Skip to content

Commit 0e9fa0b

Browse files
authored
impl From<Box<[u8]>> for Bytes (#504)
1 parent ee24be7 commit 0e9fa0b

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

src/bytes.rs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -797,14 +797,20 @@ impl From<&'static str> for Bytes {
797797

798798
impl From<Vec<u8>> for Bytes {
799799
fn from(vec: Vec<u8>) -> Bytes {
800-
// into_boxed_slice doesn't return a heap allocation for empty vectors,
800+
let slice = vec.into_boxed_slice();
801+
slice.into()
802+
}
803+
}
804+
805+
impl From<Box<[u8]>> for Bytes {
806+
fn from(slice: Box<[u8]>) -> Bytes {
807+
// Box<[u8]> doesn't contain a heap allocation for empty slices,
801808
// so the pointer isn't aligned enough for the KIND_VEC stashing to
802809
// work.
803-
if vec.is_empty() {
810+
if slice.is_empty() {
804811
return Bytes::new();
805812
}
806813

807-
let slice = vec.into_boxed_slice();
808814
let len = slice.len();
809815
let ptr = Box::into_raw(slice) as *mut u8;
810816

tests/test_bytes.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -994,3 +994,11 @@ fn bytes_put_bytes() {
994994
bytes.put_bytes(19, 2);
995995
assert_eq!([17, 19, 19], bytes.as_ref());
996996
}
997+
998+
#[test]
999+
fn box_slice_empty() {
1000+
// See https://github.com/tokio-rs/bytes/issues/340
1001+
let empty: Box<[u8]> = Default::default();
1002+
let b = Bytes::from(empty);
1003+
assert!(b.is_empty());
1004+
}

0 commit comments

Comments
 (0)