Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement the Buffer trait #908

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 94 additions & 0 deletions src/buffer.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
//! Code for handling buffers to write into.

#![allow(unsafe_code)]

use core::mem::MaybeUninit;
use core::slice;

/// A buffer that the system can write into.
pub unsafe trait Buffer<T: AnyBitPattern>: Sized {
/// The result of the process operation.
type Result;

/// Convert this buffer into a pointer to a buffer and its capacity.
fn as_buffer(&mut self) -> (*mut T, usize);

/// Convert a finished buffer pointer into its result.
unsafe fn finish(self, len: usize) -> Self::Result;
}

unsafe impl<T: AnyBitPattern> Buffer<T> for &mut [T] {
type Result = usize;

#[inline]
fn as_buffer(&mut self) -> (*mut T, usize) {
(self.as_mut_ptr(), self.len())
}

#[inline]
unsafe fn finish(self, len: usize) -> Self::Result {
len
}
}

unsafe impl<'a, T: AnyBitPattern> Buffer<T> for &'a mut [MaybeUninit<T>] {
type Result = (&'a mut [T], &'a mut [MaybeUninit<T>]);

#[inline]
fn as_buffer(&mut self) -> (*mut T, usize) {
(self.as_mut_ptr().cast(), self.len())
}

#[inline]
unsafe fn finish(self, len: usize) -> Self::Result {
let (init, uninit) = self.split_at_mut(len);

// SAFETY: The user asserts that the slice is now initialized.
let init = slice::from_raw_parts_mut(
init.as_mut_ptr().cast(),
init.len()
);

(init, uninit)
}
}

/// Implements [`Buffer`] around the `Vec` type.
///
/// This implementation fills the buffer with data and sets the length.
#[cfg(feature = "alloc")]
unsafe impl<T: AnyBitPattern> Buffer<T> for alloc::vec::Vec<T> {
type Result = alloc::vec::Vec<T>;

#[inline]
fn as_buffer(&mut self) -> (*mut T, usize) {
(self.as_mut_ptr(), self.len())
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you could get away with using self.capacity() here rather than just self.len(), which would make this approach more attractive because one could pass in a Vec::with_capacity(n) and read into it without initializing it first, or take an existing Vec, clear() it, and then reuse the existing memory directly.

Another option would be to use .spare_capacity_mut().as_buffer(), and say the behavior here is to append elements to the Vec rather than rewriting the whole Vec. That seems nice for read_to_end kinds of use cases. On the other hand, I wonder if that's too subtle. Given a v: Vec<T>, passing in v would append, while &mut v would start from the beginning. And passing &v to write would still start from the beginning.

}

#[inline]
unsafe fn finish(mut self, len: usize) -> Self::Result {
self.set_len(len);
self
}
}

/// Types made up of plain-old-data.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So this is supposed to be equivalent to requirements of the AnyBitPattern type in bytemuck, but avoids adding that as a dependency?

Bytemuck distinguishes that from its Pod trait which has slightly different requirements.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A secondary goal for this trait is to act as a buffer for epoll and kqueue events, which can have uninitialized bytes (IIRC). Which is why I'm denoting it like this.

///
/// # Safety
///
/// - The OS can write any byte pattern to this structure.
/// - This type does not implement `Drop`.
pub unsafe trait AnyBitPattern {}

macro_rules! impl_pod {
($($ty:ty),*) => {
$(
unsafe impl AnyBitPattern for $ty {}
)*
}
}

impl_pod! {
u8, i8, u16, i16, u32, i32, u64, i64,
usize, isize
}
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,7 @@ pub mod fd {
}

// The public API modules.
pub mod buffer;
#[cfg(feature = "event")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "event")))]
pub mod event;
Expand Down
Loading