mirror of
https://github.com/tokio-rs/bytes.git
synced 2026-08-07 00:00:13 +02:00
<Arc<T>>::make_mut returns a &mut T, such an API is doable for Bytes too and thus we should reserve Bytes::make_mut for that. Furthermore, it would be helpful to use From<Bytes> as a trait bound in some cases with other traits such as Hyper's body trait, where Hyper gives you Bytes values. Finally, making it impl From<Bytes> for BytesMut means the API is more easily discoverable as it appears on both Bytes and BytesMut.
This commit is contained in:
+23
-21
@@ -525,32 +525,12 @@ impl Bytes {
|
||||
/// ```
|
||||
pub fn try_into_mut(self) -> Result<BytesMut, Bytes> {
|
||||
if self.is_unique() {
|
||||
Ok(self.make_mut())
|
||||
Ok(self.into())
|
||||
} else {
|
||||
Err(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert self into `BytesMut`.
|
||||
///
|
||||
/// If `self` is unique for the entire original buffer, this will return a
|
||||
/// `BytesMut` with the contents of `self` without copying.
|
||||
/// If `self` is not unique for the entire original buffer, this will make
|
||||
/// a copy of `self` subset of the original buffer in a new `BytesMut`.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use bytes::{Bytes, BytesMut};
|
||||
///
|
||||
/// let bytes = Bytes::from(b"hello".to_vec());
|
||||
/// assert_eq!(bytes.make_mut(), BytesMut::from(&b"hello"[..]));
|
||||
/// ```
|
||||
pub fn make_mut(self) -> BytesMut {
|
||||
let bytes = ManuallyDrop::new(self);
|
||||
unsafe { (bytes.vtable.to_mut)(&bytes.data, bytes.ptr, bytes.len) }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) unsafe fn with_vtable(
|
||||
ptr: *const u8,
|
||||
@@ -932,6 +912,28 @@ impl From<Box<[u8]>> for Bytes {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Bytes> for BytesMut {
|
||||
/// Convert self into `BytesMut`.
|
||||
///
|
||||
/// If `bytes` is unique for the entire original buffer, this will return a
|
||||
/// `BytesMut` with the contents of `bytes` without copying.
|
||||
/// If `bytes` is not unique for the entire original buffer, this will make
|
||||
/// a copy of `bytes` subset of the original buffer in a new `BytesMut`.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use bytes::{Bytes, BytesMut};
|
||||
///
|
||||
/// let bytes = Bytes::from(b"hello".to_vec());
|
||||
/// assert_eq!(BytesMut::from(bytes), BytesMut::from(&b"hello"[..]));
|
||||
/// ```
|
||||
fn from(bytes: Bytes) -> Self {
|
||||
let bytes = ManuallyDrop::new(bytes);
|
||||
unsafe { (bytes.vtable.to_mut)(&bytes.data, bytes.ptr, bytes.len) }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for Bytes {
|
||||
fn from(s: String) -> Bytes {
|
||||
Bytes::from(s.into_bytes())
|
||||
|
||||
Reference in New Issue
Block a user