Skip to content

Commit

Permalink
impl From<Box<[u8; _]>> for Bytes
Browse files Browse the repository at this point in the history
  • Loading branch information
MarinPostma committed Sep 23, 2023
1 parent a14ef46 commit ab6656e
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -871,6 +871,36 @@ impl From<Box<[u8]>> for Bytes {
}
}

impl<const N: usize> From<Box<[u8; N]>> for Bytes {
fn from(slice: Box<[u8; N]>) -> Self {
// Box<[u8]> doesn't contain a heap allocation for empty slices,
// so the pointer isn't aligned enough for the KIND_VEC stashing to
// work.
if slice.is_empty() {
return Bytes::new();
}

let ptr = Box::into_raw(slice) as *mut u8;

if ptr as usize & 0x1 == 0 {
let data = ptr_map(ptr, |addr| addr | KIND_VEC);
Bytes {
ptr,
len: N,
data: AtomicPtr::new(data.cast()),
vtable: &PROMOTABLE_EVEN_VTABLE,
}
} else {
Bytes {
ptr,
len: N,
data: AtomicPtr::new(ptr.cast()),
vtable: &PROMOTABLE_ODD_VTABLE,
}
}
}
}

impl From<String> for Bytes {
fn from(s: String) -> Bytes {
Bytes::from(s.into_bytes())
Expand Down

0 comments on commit ab6656e

Please sign in to comment.