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

Add support for Box<[u8]> and Vec<u8> to safer_ffi::bytes::Bytes #216

Merged
merged 2 commits into from
May 29, 2024
Merged
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
45 changes: 42 additions & 3 deletions src/bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,16 @@ impl<T: AsRef<[u8]>> PartialEq<T> for Bytes<'_> {
}
}
impl Eq for Bytes<'_> {}
impl<T: AsRef<[u8]>> PartialOrd<T> for Bytes<'_> {
fn partial_cmp(&self, other: &T) -> Option<core::cmp::Ordering> {
self.as_slice().partial_cmp(other.as_ref())
}
}
impl Ord for Bytes<'_> {
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
self.as_slice().cmp(other)
}
}
impl<'a> From<&'a [u8]> for Bytes<'a> {
fn from(data: &'a [u8]) -> Self {
static VT: BytesVt = BytesVt {
Expand Down Expand Up @@ -265,19 +275,48 @@ impl<'a, T: Sized + AsRef<[u8]> + Send + Sync + 'a> From<Arc<T>> for Bytes<'a> {
}
}
#[cfg(feature = "alloc")]
impl From<alloc::boxed::Box<[u8]>> for Bytes<'_> {
fn from(value: alloc::boxed::Box<[u8]>) -> Self {
unsafe extern "C" fn release(this: *const (), capacity: usize) {
core::mem::drop(alloc::boxed::Box::from_raw(
core::ptr::slice_from_raw_parts_mut(this.cast::<u8>().cast_mut(), capacity),
))
}
let data: &[u8] = value.as_ref();
Bytes {
start: core::ptr::NonNull::<[u8]>::from(data.as_ref()).cast(),
len: data.len(),
capacity: data.len(),
data: alloc::boxed::Box::into_raw(value) as *const (),
vtable: &BytesVt {
release: Some(release),
retain: None,
},
}
}
}
#[cfg(feature = "alloc")]
impl From<alloc::vec::Vec<u8>> for Bytes<'_> {
fn from(value: alloc::vec::Vec<u8>) -> Self {
alloc::boxed::Box::<[u8]>::from(value).into()
}
}
#[cfg(feature = "alloc")]
unsafe impl<'a> Send for Bytes<'a>
where
&'a [u8]: Send,
Arc<[u8]>: Send,
alloc::boxed::Box<[u8]>: Sync,
Arc<dyn 'a + AsRef<[u8]> + Send + Sync>: Send,
{
}
#[cfg(feature = "alloc")]
unsafe impl<'a> Sync for Bytes<'a>
where
&'a [u8]: Send,
Arc<[u8]>: Send,
Arc<dyn 'a + AsRef<[u8]> + Send + Sync>: Send,
&'a [u8]: Sync,
Arc<[u8]>: Sync,
alloc::boxed::Box<[u8]>: Sync,
Arc<dyn 'a + AsRef<[u8]> + Send + Sync>: Sync,
{
}

Expand Down
Loading