Skip to content

Commit

Permalink
Make From only for static slices to Bytes
Browse files Browse the repository at this point in the history
  • Loading branch information
Douman committed Aug 27, 2019
1 parent b6cb346 commit ae9991f
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 11 deletions.
23 changes: 14 additions & 9 deletions src/bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -499,6 +499,11 @@ impl Bytes {
self.inner.is_inline()
}

///Creates `Bytes` instance from slice, by copying it.
pub fn copy_from_slice(data: &[u8]) -> Self {
BytesMut::from(data).freeze()
}

/// Returns a slice of self for the provided range.
///
/// This will increment the reference count for the underlying memory and
Expand Down Expand Up @@ -542,7 +547,7 @@ impl Bytes {
assert!(end <= len);

if end - begin <= INLINE_CAP {
return Bytes::from(&self[begin..end]);
return Bytes::copy_from_slice(&self[begin..end]);
}

let mut ret = self.clone();
Expand Down Expand Up @@ -729,7 +734,7 @@ impl Bytes {
/// ```
/// use bytes::Bytes;
///
/// let a = Bytes::from(&b"Mary had a little lamb, little lamb, little lamb..."[..]);
/// let a = Bytes::copy_from_slice(&b"Mary had a little lamb, little lamb, little lamb..."[..]);
///
/// // Create a shallow clone
/// let b = a.clone();
Expand Down Expand Up @@ -759,7 +764,7 @@ impl Bytes {
/// Clones the data if it is not already owned.
pub fn to_mut(&mut self) -> &mut BytesMut {
if !self.inner.is_mut_safe() {
let new = Bytes::from(&self[..]);
let new = Self::copy_from_slice(&self[..]);
*self = new;
}
unsafe { &mut *(self as *mut Bytes as *mut BytesMut) }
Expand Down Expand Up @@ -922,15 +927,15 @@ impl From<String> for Bytes {
}
}

impl<'a> From<&'a [u8]> for Bytes {
fn from(src: &'a [u8]) -> Bytes {
BytesMut::from(src).freeze()
impl From<&'static [u8]> for Bytes {
fn from(src: &'static [u8]) -> Bytes {
Bytes::from_static(src)
}
}

impl<'a> From<&'a str> for Bytes {
fn from(src: &'a str) -> Bytes {
BytesMut::from(src).freeze()
impl From<&'static str> for Bytes {
fn from(src: &'static str) -> Bytes {
Bytes::from_static(src.as_bytes())
}
}

Expand Down
4 changes: 2 additions & 2 deletions tests/test_bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -528,7 +528,7 @@ fn stress() {

for i in 0..ITERS {
let data = [i as u8; 256];
let buf = Arc::new(Bytes::from(&data[..]));
let buf = Arc::new(Bytes::copy_from_slice(&data[..]));

let barrier = Arc::new(Barrier::new(THREADS));
let mut joins = Vec::with_capacity(THREADS);
Expand Down Expand Up @@ -888,7 +888,7 @@ fn slice_ref_catches_not_an_empty_subset() {
#[test]
#[should_panic]
fn empty_slice_ref_catches_not_an_empty_subset() {
let bytes = Bytes::from(&b""[..]);
let bytes = Bytes::copy_from_slice(&b""[..]);
let slice = &b""[0..0];

bytes.slice_ref(slice);
Expand Down

0 comments on commit ae9991f

Please sign in to comment.