Struct BytesMut
struct BytesMut { ... }
A unique reference to a contiguous slice of memory.
BytesMut represents a unique view into a potentially shared memory region.
Given the uniqueness guarantee, owners of BytesMut handles are able to
mutate the memory.
BytesMut can be thought of as containing a buf: Arc<Vec<u8>>, an offset
into buf, a slice length, and a guarantee that no other BytesMut for the
same buf overlaps with its slice. That guarantee means that a write lock
is not required.
Growth
BytesMut's BufMut implementation will implicitly grow its buffer as
necessary. However, explicitly reserving the required space up-front before
a series of inserts will be more efficient.
Examples
use ;
let mut buf = with_capacity;
buf.put_u8;
buf.put_u8;
buf.put;
assert_eq!;
// Freeze the buffer so that it can be shared
let a = buf.freeze;
// This does not allocate, instead `b` points to the same memory.
let b = a.clone;
assert_eq!;
assert_eq!;
Implementations
impl BytesMut
fn with_capacity(capacity: usize) -> BytesMutCreates a new
BytesMutwith the specified capacity.The returned
BytesMutwill be able to hold at leastcapacitybytes without reallocating.It is important to note that this function does not specify the length of the returned
BytesMut, but only the capacity.Examples
use ; let mut bytes = with_capacity; // `bytes` contains no data, even though there is capacity assert_eq!; bytes.put; assert_eq!;fn new() -> BytesMutCreates a new
BytesMutwith default capacity.Resulting object has length 0 and unspecified capacity. This function does not allocate.
Examples
use ; let mut bytes = new; assert_eq!; bytes.reserve; bytes.put_slice; assert_eq!;fn len(self: &Self) -> usizeReturns the number of bytes contained in this
BytesMut.Examples
use BytesMut; let b = from; assert_eq!;fn is_empty(self: &Self) -> boolReturns true if the
BytesMuthas a length of 0.Examples
use BytesMut; let b = with_capacity; assert!;fn capacity(self: &Self) -> usizeReturns the number of bytes the
BytesMutcan hold without reallocating.Examples
use BytesMut; let b = with_capacity; assert_eq!;fn freeze(self: Self) -> BytesConverts
selfinto an immutableBytes.The conversion is zero cost and is used to indicate that the slice referenced by the handle will no longer be mutated. Once the conversion is done, the handle can be cloned and shared across threads.
Examples
use bytes::{BytesMut, BufMut}; use std::thread; let mut b = BytesMut::with_capacity(64); b.put(&b"hello world"[..]); let b1 = b.freeze(); let b2 = b1.clone(); let th = thread::spawn(move || { assert_eq!(&b1[..], b"hello world"); }); assert_eq!(&b2[..], b"hello world"); th.join().unwrap();fn zeroed(len: usize) -> BytesMutCreates a new
BytesMutcontaininglenzeros.The resulting object has a length of
lenand a capacity greater than or equal tolen. The entire length of the object will be filled with zeros.On some platforms or allocators this function may be faster than a manual implementation.
Examples
use BytesMut; let zeros = zeroed; assert!; assert_eq!; zeros.into_iter.for_each;fn split_off(self: &mut Self, at: usize) -> BytesMutSplits the bytes into two at the given index.
Afterwards
selfcontains elements[0, at), and the returnedBytesMutcontains elements[at, capacity). It's guaranteed that the memory does not move, that is, the address ofselfdoes not change, and the address of the returned slice isatbytes after that.This is an
O(1)operation that just increases the reference count and sets a few indices.Examples
use BytesMut; let mut a = from; let mut b = a.split_off; a = b'j'; b = b'!'; assert_eq!; assert_eq!;Panics
Panics if
at > capacity.fn split(self: &mut Self) -> BytesMutRemoves the bytes from the current view, returning them in a new
BytesMuthandle.Afterwards,
selfwill be empty, but will retain any additional capacity that it had before the operation. This is identical toself.split_to(self.len()).This is an
O(1)operation that just increases the reference count and sets a few indices.Examples
use ; let mut buf = with_capacity; buf.put; let other = buf.split; assert!; assert_eq!; assert_eq!;fn split_to(self: &mut Self, at: usize) -> BytesMutSplits the buffer into two at the given index.
Afterwards
selfcontains elements[at, len), and the returnedBytesMutcontains elements[0, at).This is an
O(1)operation that just increases the reference count and sets a few indices.Examples
use BytesMut; let mut a = from; let mut b = a.split_to; a = b'!'; b = b'j'; assert_eq!; assert_eq!;Panics
Panics if
at > len.fn truncate(self: &mut Self, len: usize)Shortens the buffer, keeping the first
lenbytes and dropping the rest.If
lenis greater than the buffer's current length, this has no effect.Existing underlying capacity is preserved.
The split_off method can emulate
truncate, but this causes the excess bytes to be returned instead of dropped.Examples
use BytesMut; let mut buf = from; buf.truncate; assert_eq!;fn clear(self: &mut Self)Clears the buffer, removing all data. Existing capacity is preserved.
Examples
use BytesMut; let mut buf = from; buf.clear; assert!;fn resize(self: &mut Self, new_len: usize, value: u8)Resizes the buffer so that
lenis equal tonew_len.If
new_lenis greater thanlen, the buffer is extended by the difference with each additional byte set tovalue. Ifnew_lenis less thanlen, the buffer is simply truncated.Examples
use BytesMut; let mut buf = new; buf.resize; assert_eq!; buf.resize; assert_eq!; buf.resize; assert_eq!;unsafe fn set_len(self: &mut Self, len: usize)Sets the length of the buffer.
This will explicitly set the size of the buffer without actually modifying the data, so it is up to the caller to ensure that the data has been initialized.
Examples
use BytesMut; let mut b = from; unsafe assert_eq!; unsafe assert_eq!;fn reserve(self: &mut Self, additional: usize)Reserves capacity for at least
additionalmore bytes to be inserted into the givenBytesMut.More than
additionalbytes may be reserved in order to avoid frequent reallocations. A call toreservemay result in an allocation.Before allocating new buffer space, the function will attempt to reclaim space in the existing buffer. If the current handle references a view into a larger original buffer, and all other handles referencing part of the same original buffer have been dropped, then the current view can be copied/shifted to the front of the buffer and the handle can take ownership of the full buffer, provided that the full buffer is large enough to fit the requested additional capacity.
This optimization will only happen if shifting the data from the current view to the front of the buffer is not too expensive in terms of the (amortized) time required. The precise condition is subject to change; as of now, the length of the data being shifted needs to be at least as large as the distance that it's shifted by. If the current view is empty and the original buffer is large enough to fit the requested additional capacity, then reallocations will never happen.
Examples
In the following example, a new buffer is allocated.
use BytesMut; let mut buf = from; buf.reserve; assert!;In the following example, the existing buffer is reclaimed.
use ; let mut buf = with_capacity; buf.put; let ptr = buf.as_ptr; let other = buf.split; assert!; assert_eq!; drop; buf.reserve; assert_eq!; assert_eq!;Panics
Panics if the new capacity overflows
usize.fn try_reclaim(self: &mut Self, additional: usize) -> boolAttempts to cheaply reclaim already allocated capacity for at least
additionalmore bytes to be inserted into the givenBytesMutand returnstrueif it succeeded.try_reclaimbehaves exactly likereserve, except that it never allocates new storage and returns aboolindicating whether it was successful in doing so:try_reclaimreturns false under these conditions:- The spare capacity left is less than
additionalbytes AND - The existing allocation cannot be reclaimed cheaply or it was less than
additionalbytes in size
Reclaiming the allocation cheaply is possible if the
BytesMuthas no outstanding references through otherBytesMuts orByteswhich point to the same underlying storage.Examples
use BytesMut; let mut buf = with_capacity; assert_eq!; assert_eq!; buf.extend_from_slice; let mut split = buf.split; assert_eq!; assert_eq!; assert_eq!; assert_eq!; // The split buffer is filled with "abcd" assert_eq!; // buf is empty and has capacity for 60 bytes assert_eq!; drop; assert_eq!; split.clear; assert_eq!; assert_eq!; assert_eq!;- The spare capacity left is less than
fn extend_from_slice(self: &mut Self, extend: &[u8])Appends given bytes to this
BytesMut.If this
BytesMutobject does not have enough capacity, it is resized first.Examples
use BytesMut; let mut buf = with_capacity; buf.extend_from_slice; buf.extend_from_slice; assert_eq!;fn unsplit(self: &mut Self, other: BytesMut)Absorbs a
BytesMutthat was previously split off.If the two
BytesMutobjects were previously contiguous and not mutated in a way that causes re-allocation i.e., ifotherwas created by callingsplit_offon thisBytesMut, then this is anO(1)operation that just decreases a reference count and sets a few indices. Otherwise this method degenerates toself.extend_from_slice(other.as_ref()).Examples
use BytesMut; let mut buf = with_capacity; buf.extend_from_slice; let split = buf.split_off; assert_eq!; assert_eq!; buf.unsplit; assert_eq!;fn spare_capacity_mut(self: &mut Self) -> &mut [MaybeUninit<u8>]Returns the remaining spare capacity of the buffer as a slice of
MaybeUninit<u8>.The returned slice can be used to fill the buffer with data (e.g. by reading from a file) before marking the data as initialized using the
set_lenmethod.Examples
use BytesMut; // Allocate buffer big enough for 10 bytes. let mut buf = with_capacity; // Fill in the first 3 elements. let uninit = buf.spare_capacity_mut; uninit.write; uninit.write; uninit.write; // Mark the first 3 bytes of the buffer as being initialized. unsafe assert_eq!;
impl AsMut for BytesMut
fn as_mut(self: &mut Self) -> &mut [u8]
impl AsRef for BytesMut
fn as_ref(self: &Self) -> &[u8]
impl Borrow for BytesMut
fn borrow(self: &Self) -> &[u8]
impl BorrowMut for BytesMut
fn borrow_mut(self: &mut Self) -> &mut [u8]
impl Buf for BytesMut
fn remaining(self: &Self) -> usizefn chunk(self: &Self) -> &[u8]fn advance(self: &mut Self, cnt: usize)fn copy_to_bytes(self: &mut Self, len: usize) -> Bytes
impl BufMut for BytesMut
fn remaining_mut(self: &Self) -> usizeunsafe fn advance_mut(self: &mut Self, cnt: usize)fn chunk_mut(self: &mut Self) -> &mut UninitSlicefn put<T: Buf>(self: &mut Self, src: T) where Self: Sizedfn put_slice(self: &mut Self, src: &[u8])fn put_bytes(self: &mut Self, val: u8, cnt: usize)
impl Clone for BytesMut
fn clone(self: &Self) -> BytesMut
impl Debug for BytesMut
fn fmt(self: &Self, f: &mut Formatter<'_>) -> Result
impl Default for BytesMut
fn default() -> BytesMut
impl Deref for BytesMut
fn deref(self: &Self) -> &[u8]
impl DerefMut for BytesMut
fn deref_mut(self: &mut Self) -> &mut [u8]
impl Drop for BytesMut
fn drop(self: &mut Self)
impl Eq for BytesMut
impl Extend for BytesMut
fn extend<T>(self: &mut Self, iter: T) where T: IntoIterator<Item = u8>
impl Extend for BytesMut
fn extend<T>(self: &mut Self, iter: T) where T: IntoIterator<Item = Bytes>
impl Freeze for BytesMut
impl From for BytesMut
fn from(bytes: Bytes) -> SelfConvert self into
BytesMut.If
bytesis unique for the entire original buffer, this will return aBytesMutwith the contents ofbyteswithout copying. Ifbytesis not unique for the entire original buffer, this will make a copy ofbytessubset of the original buffer in a newBytesMut.Examples
use ; let bytes = from; assert_eq!;
impl FromIterator for BytesMut
fn from_iter<T: IntoIterator<Item = u8>>(into_iter: T) -> Self
impl Hash for BytesMut
fn hash<H>(self: &Self, state: &mut H) where H: Hasher
impl IntoIterator for BytesMut
fn into_iter(self: Self) -> <Self as >::IntoIter
impl LowerHex for BytesMut
fn fmt(self: &Self, f: &mut Formatter<'_>) -> Result
impl Ord for BytesMut
fn cmp(self: &Self, other: &BytesMut) -> Ordering
impl PartialEq for BytesMut
fn eq(self: &Self, other: &Vec<u8>) -> bool
impl PartialEq for BytesMut
fn eq(self: &Self, other: &Bytes) -> bool
impl PartialEq for BytesMut
fn eq(self: &Self, other: &[u8]) -> bool
impl PartialEq for BytesMut
fn eq(self: &Self, other: &String) -> bool
impl PartialEq for BytesMut
fn eq(self: &Self, other: &BytesMut) -> bool
impl PartialEq for BytesMut
fn eq(self: &Self, other: &str) -> bool
impl PartialOrd for BytesMut
fn partial_cmp(self: &Self, other: &[u8]) -> Option<Ordering>
impl PartialOrd for BytesMut
fn partial_cmp(self: &Self, other: &String) -> Option<Ordering>
impl PartialOrd for BytesMut
fn partial_cmp(self: &Self, other: &BytesMut) -> Option<Ordering>
impl PartialOrd for BytesMut
fn partial_cmp(self: &Self, other: &str) -> Option<Ordering>
impl PartialOrd for BytesMut
fn partial_cmp(self: &Self, other: &Vec<u8>) -> Option<Ordering>
impl RefUnwindSafe for BytesMut
impl Send for BytesMut
impl Serialize for BytesMut
fn serialize<S>(self: &Self, serializer: S) -> Result<<S as >::Ok, <S as >::Error> where S: Serializer
impl Sync for BytesMut
impl Unpin for BytesMut
impl UnsafeUnpin for BytesMut
impl UnwindSafe for BytesMut
impl UpperHex for BytesMut
fn fmt(self: &Self, f: &mut Formatter<'_>) -> Result
impl Write for BytesMut
fn write_str(self: &mut Self, s: &str) -> Resultfn write_fmt(self: &mut Self, args: Arguments<'_>) -> Result
impl<'a> Extend for BytesMut
fn extend<T>(self: &mut Self, iter: T) where T: IntoIterator<Item = &'a u8>
impl<'a> From for BytesMut
fn from(src: &'a [u8]) -> BytesMut
impl<'a> From for BytesMut
fn from(src: &'a str) -> BytesMut
impl<'a> FromIterator for BytesMut
fn from_iter<T: IntoIterator<Item = &'a u8>>(into_iter: T) -> Self
impl<'a, T: ?Sized> PartialEq for BytesMut
fn eq(self: &Self, other: &&'a T) -> bool
impl<'a, T: ?Sized> PartialOrd for BytesMut
fn partial_cmp(self: &Self, other: &&'a T) -> Option<Ordering>
impl<'de> Deserialize for BytesMut
fn deserialize<D>(deserializer: D) -> Result<BytesMut, <D as >::Error> where D: Deserializer<'de>
impl<P, T> Receiver for BytesMut
impl<T> Any for BytesMut
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for BytesMut
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for BytesMut
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> CloneToUninit for BytesMut
unsafe fn clone_to_uninit(self: &Self, dest: *mut u8)
impl<T> DeserializeOwned for BytesMut
impl<T> From for BytesMut
fn from(t: T) -> TReturns the argument unchanged.
impl<T> ToOwned for BytesMut
fn to_owned(self: &Self) -> Tfn clone_into(self: &Self, target: &mut T)
impl<T, U> Into for BytesMut
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for BytesMut
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for BytesMut
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>