Skip to content

Commit

Permalink
impl From<Box<[u8]>> for Bytes (#504)
Browse files Browse the repository at this point in the history
  • Loading branch information
ijackson authored Aug 24, 2021
1 parent ee24be7 commit 0e9fa0b
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
12 changes: 9 additions & 3 deletions src/bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -797,14 +797,20 @@ impl From<&'static str> for Bytes {

impl From<Vec<u8>> for Bytes {
fn from(vec: Vec<u8>) -> Bytes {
// into_boxed_slice doesn't return a heap allocation for empty vectors,
let slice = vec.into_boxed_slice();
slice.into()
}
}

impl From<Box<[u8]>> 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;

Expand Down
8 changes: 8 additions & 0 deletions tests/test_bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}

0 comments on commit 0e9fa0b

Please sign in to comment.