From da13fccbb1e02e6fa412f9f833e954540c6f5d7c Mon Sep 17 00:00:00 2001 From: Pierre Avital Date: Wed, 29 May 2024 21:35:09 +0200 Subject: [PATCH] Add support for Box<[u8]> and Vec to safer_ffi::bytes::Bytes (#216) * Add support for Box<[u8]> and Vec to safer_ffi::bytes::Bytes * Address PR comments --- src/bytes.rs | 48 +++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 45 insertions(+), 3 deletions(-) diff --git a/src/bytes.rs b/src/bytes.rs index 70e98d0136..3bc43c3c55 100644 --- a/src/bytes.rs +++ b/src/bytes.rs @@ -198,6 +198,16 @@ impl> PartialEq for Bytes<'_> { } } impl Eq for Bytes<'_> {} +impl> PartialOrd for Bytes<'_> { + fn partial_cmp(&self, other: &T) -> Option { + 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 { @@ -265,19 +275,51 @@ impl<'a, T: Sized + AsRef<[u8]> + Send + Sync + 'a> From> for Bytes<'a> { } } #[cfg(feature = "alloc")] +impl From> for Bytes<'_> { + fn from(value: alloc::boxed::Box<[u8]>) -> Self { + unsafe extern "C" fn release_box_bytes(this: *const (), capacity: usize) { + core::mem::drop(alloc::boxed::Box::from_raw( + core::ptr::slice_from_raw_parts_mut(this.cast::().cast_mut(), capacity), + )) + } + let bytes: &[u8] = &*value; + let len = bytes.len(); + let start = core::ptr::NonNull::<[u8]>::from(bytes).cast(); + let data = alloc::boxed::Box::into_raw(value).cast::<()>(); + Bytes { + start, + len, + capacity: len, + data, + vtable: &BytesVt { + release: Some(release_box_bytes), + retain: None, + }, + } + } +} +#[cfg(feature = "alloc")] +impl From> for Bytes<'_> { + fn from(value: alloc::vec::Vec) -> 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]>: Send, Arc + Send + Sync>: Send, { } #[cfg(feature = "alloc")] unsafe impl<'a> Sync for Bytes<'a> where - &'a [u8]: Send, - Arc<[u8]>: Send, - Arc + Send + Sync>: Send, + &'a [u8]: Sync, + Arc<[u8]>: Sync, + alloc::boxed::Box<[u8]>: Sync, + Arc + Send + Sync>: Sync, { }