From ab6656eb3e319e9b464061ec3c948796c2799270 Mon Sep 17 00:00:00 2001 From: ad hoc Date: Sat, 23 Sep 2023 10:15:07 +0200 Subject: [PATCH] impl From> for Bytes --- src/bytes.rs | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/bytes.rs b/src/bytes.rs index 0404a72db..c51f2940d 100644 --- a/src/bytes.rs +++ b/src/bytes.rs @@ -871,6 +871,36 @@ impl From> for Bytes { } } +impl From> 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 for Bytes { fn from(s: String) -> Bytes { Bytes::from(s.into_bytes())