diff --git a/src/bytes.rs b/src/bytes.rs index b1b35ea83..d0be0d276 100644 --- a/src/bytes.rs +++ b/src/bytes.rs @@ -797,14 +797,20 @@ impl From<&'static str> for Bytes { impl From> for Bytes { fn from(vec: Vec) -> Bytes { - // into_boxed_slice doesn't return a heap allocation for empty vectors, + let slice = vec.into_boxed_slice(); + slice.into() + } +} + +impl From> for Bytes { + fn from(slice: Box<[u8]>) -> Bytes { + // 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 vec.is_empty() { + if slice.is_empty() { return Bytes::new(); } - let slice = vec.into_boxed_slice(); let len = slice.len(); let ptr = Box::into_raw(slice) as *mut u8; diff --git a/tests/test_bytes.rs b/tests/test_bytes.rs index 0914155b9..f0cae9990 100644 --- a/tests/test_bytes.rs +++ b/tests/test_bytes.rs @@ -994,3 +994,11 @@ fn bytes_put_bytes() { bytes.put_bytes(19, 2); assert_eq!([17, 19, 19], bytes.as_ref()); } + +#[test] +fn box_slice_empty() { + // See https://github.com/tokio-rs/bytes/issues/340 + let empty: Box<[u8]> = Default::default(); + let b = Bytes::from(empty); + assert!(b.is_empty()); +}