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 bytes::{BytesMut, BufMut};

let mut buf = BytesMut::with_capacity(64);

buf.put_u8(b'h');
buf.put_u8(b'e');
buf.put(&b"llo"[..]);

assert_eq!(&buf[..], b"hello");

// 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!(&a[..], b"hello");
assert_eq!(&b[..], b"hello");

Implementations

impl BytesMut

fn with_capacity(capacity: usize) -> BytesMut

Creates a new BytesMut with the specified capacity.

The returned BytesMut will be able to hold at least capacity bytes 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 bytes::{BytesMut, BufMut};

let mut bytes = BytesMut::with_capacity(64);

// `bytes` contains no data, even though there is capacity
assert_eq!(bytes.len(), 0);

bytes.put(&b"hello world"[..]);

assert_eq!(&bytes[..], b"hello world");
fn new() -> BytesMut

Creates a new BytesMut with default capacity.

Resulting object has length 0 and unspecified capacity. This function does not allocate.

Examples

use bytes::{BytesMut, BufMut};

let mut bytes = BytesMut::new();

assert_eq!(0, bytes.len());

bytes.reserve(2);
bytes.put_slice(b"xy");

assert_eq!(&b"xy"[..], &bytes[..]);
fn len(self: &Self) -> usize

Returns the number of bytes contained in this BytesMut.

Examples

use bytes::BytesMut;

let b = BytesMut::from(&b"hello"[..]);
assert_eq!(b.len(), 5);
fn is_empty(self: &Self) -> bool

Returns true if the BytesMut has a length of 0.

Examples

use bytes::BytesMut;

let b = BytesMut::with_capacity(64);
assert!(b.is_empty());
fn capacity(self: &Self) -> usize

Returns the number of bytes the BytesMut can hold without reallocating.

Examples

use bytes::BytesMut;

let b = BytesMut::with_capacity(64);
assert_eq!(b.capacity(), 64);
fn freeze(self: Self) -> Bytes

Converts self into an immutable Bytes.

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) -> BytesMut

Creates a new BytesMut containing len zeros.

The resulting object has a length of len and a capacity greater than or equal to len. 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 bytes::BytesMut;

let zeros = BytesMut::zeroed(42);

assert!(zeros.capacity() >= 42);
assert_eq!(zeros.len(), 42);
zeros.into_iter().for_each(|x| assert_eq!(x, 0));
fn split_off(self: &mut Self, at: usize) -> BytesMut

Splits the bytes into two at the given index.

Afterwards self contains elements [0, at), and the returned BytesMut contains elements [at, capacity). It's guaranteed that the memory does not move, that is, the address of self does not change, and the address of the returned slice is at bytes after that.

This is an O(1) operation that just increases the reference count and sets a few indices.

Examples

use bytes::BytesMut;

let mut a = BytesMut::from(&b"hello world"[..]);
let mut b = a.split_off(5);

a[0] = b'j';
b[0] = b'!';

assert_eq!(&a[..], b"jello");
assert_eq!(&b[..], b"!world");

Panics

Panics if at > capacity.

fn split(self: &mut Self) -> BytesMut

Removes the bytes from the current view, returning them in a new BytesMut handle.

Afterwards, self will be empty, but will retain any additional capacity that it had before the operation. This is identical to self.split_to(self.len()).

This is an O(1) operation that just increases the reference count and sets a few indices.

Examples

use bytes::{BytesMut, BufMut};

let mut buf = BytesMut::with_capacity(1024);
buf.put(&b"hello world"[..]);

let other = buf.split();

assert!(buf.is_empty());
assert_eq!(1013, buf.capacity());

assert_eq!(other, b"hello world"[..]);
fn split_to(self: &mut Self, at: usize) -> BytesMut

Splits the buffer into two at the given index.

Afterwards self contains elements [at, len), and the returned BytesMut contains elements [0, at).

This is an O(1) operation that just increases the reference count and sets a few indices.

Examples

use bytes::BytesMut;

let mut a = BytesMut::from(&b"hello world"[..]);
let mut b = a.split_to(5);

a[0] = b'!';
b[0] = b'j';

assert_eq!(&a[..], b"!world");
assert_eq!(&b[..], b"jello");

Panics

Panics if at > len.

fn truncate(self: &mut Self, len: usize)

Shortens the buffer, keeping the first len bytes and dropping the rest.

If len is 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 bytes::BytesMut;

let mut buf = BytesMut::from(&b"hello world"[..]);
buf.truncate(5);
assert_eq!(buf, b"hello"[..]);
fn clear(self: &mut Self)

Clears the buffer, removing all data. Existing capacity is preserved.

Examples

use bytes::BytesMut;

let mut buf = BytesMut::from(&b"hello world"[..]);
buf.clear();
assert!(buf.is_empty());
fn resize(self: &mut Self, new_len: usize, value: u8)

Resizes the buffer so that len is equal to new_len.

If new_len is greater than len, the buffer is extended by the difference with each additional byte set to value. If new_len is less than len, the buffer is simply truncated.

Examples

use bytes::BytesMut;

let mut buf = BytesMut::new();

buf.resize(3, 0x1);
assert_eq!(&buf[..], &[0x1, 0x1, 0x1]);

buf.resize(2, 0x2);
assert_eq!(&buf[..], &[0x1, 0x1]);

buf.resize(4, 0x3);
assert_eq!(&buf[..], &[0x1, 0x1, 0x3, 0x3]);
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 bytes::BytesMut;

let mut b = BytesMut::from(&b"hello world"[..]);

unsafe {
    b.set_len(5);
}

assert_eq!(&b[..], b"hello");

unsafe {
    b.set_len(11);
}

assert_eq!(&b[..], b"hello world");
fn reserve(self: &mut Self, additional: usize)

Reserves capacity for at least additional more bytes to be inserted into the given BytesMut.

More than additional bytes may be reserved in order to avoid frequent reallocations. A call to reserve may 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 bytes::BytesMut;

let mut buf = BytesMut::from(&b"hello"[..]);
buf.reserve(64);
assert!(buf.capacity() >= 69);

In the following example, the existing buffer is reclaimed.

use bytes::{BytesMut, BufMut};

let mut buf = BytesMut::with_capacity(128);
buf.put(&[0; 64][..]);

let ptr = buf.as_ptr();
let other = buf.split();

assert!(buf.is_empty());
assert_eq!(buf.capacity(), 64);

drop(other);
buf.reserve(128);

assert_eq!(buf.capacity(), 128);
assert_eq!(buf.as_ptr(), ptr);

Panics

Panics if the new capacity overflows usize.

fn try_reclaim(self: &mut Self, additional: usize) -> bool

Attempts to cheaply reclaim already allocated capacity for at least additional more bytes to be inserted into the given BytesMut and returns true if it succeeded.

try_reclaim behaves exactly like reserve, except that it never allocates new storage and returns a bool indicating whether it was successful in doing so:

try_reclaim returns false under these conditions:

  • The spare capacity left is less than additional bytes AND
  • The existing allocation cannot be reclaimed cheaply or it was less than additional bytes in size

Reclaiming the allocation cheaply is possible if the BytesMut has no outstanding references through other BytesMuts or Bytes which point to the same underlying storage.

Examples

use bytes::BytesMut;

let mut buf = BytesMut::with_capacity(64);
assert_eq!(true, buf.try_reclaim(64));
assert_eq!(64, buf.capacity());

buf.extend_from_slice(b"abcd");
let mut split = buf.split();
assert_eq!(60, buf.capacity());
assert_eq!(4, split.capacity());
assert_eq!(false, split.try_reclaim(64));
assert_eq!(false, buf.try_reclaim(64));
// The split buffer is filled with "abcd"
assert_eq!(false, split.try_reclaim(4));
// buf is empty and has capacity for 60 bytes
assert_eq!(true, buf.try_reclaim(60));

drop(buf);
assert_eq!(false, split.try_reclaim(64));

split.clear();
assert_eq!(4, split.capacity());
assert_eq!(true, split.try_reclaim(64));
assert_eq!(64, split.capacity());
fn extend_from_slice(self: &mut Self, extend: &[u8])

Appends given bytes to this BytesMut.

If this BytesMut object does not have enough capacity, it is resized first.

Examples

use bytes::BytesMut;

let mut buf = BytesMut::with_capacity(0);
buf.extend_from_slice(b"aaabbb");
buf.extend_from_slice(b"cccddd");

assert_eq!(b"aaabbbcccddd", &buf[..]);
fn unsplit(self: &mut Self, other: BytesMut)

Absorbs a BytesMut that was previously split off.

If the two BytesMut objects were previously contiguous and not mutated in a way that causes re-allocation i.e., if other was created by calling split_off on this BytesMut, then this is an O(1) operation that just decreases a reference count and sets a few indices. Otherwise this method degenerates to self.extend_from_slice(other.as_ref()).

Examples

use bytes::BytesMut;

let mut buf = BytesMut::with_capacity(64);
buf.extend_from_slice(b"aaabbbcccddd");

let split = buf.split_off(6);
assert_eq!(b"aaabbb", &buf[..]);
assert_eq!(b"cccddd", &split[..]);

buf.unsplit(split);
assert_eq!(b"aaabbbcccddd", &buf[..]);
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_len method.

Examples

use bytes::BytesMut;

// Allocate buffer big enough for 10 bytes.
let mut buf = BytesMut::with_capacity(10);

// Fill in the first 3 elements.
let uninit = buf.spare_capacity_mut();
uninit[0].write(0);
uninit[1].write(1);
uninit[2].write(2);

// Mark the first 3 bytes of the buffer as being initialized.
unsafe {
    buf.set_len(3);
}

assert_eq!(&buf[..], &[0, 1, 2]);

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) -> usize
fn 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) -> usize
unsafe fn advance_mut(self: &mut Self, cnt: usize)
fn chunk_mut(self: &mut Self) -> &mut UninitSlice
fn put<T: Buf>(self: &mut Self, src: T)
where
    Self: Sized
fn 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) -> Self

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"[..]));

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) -> Result
fn 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) -> T

Returns the argument unchanged.

impl<T> ToOwned for BytesMut

fn to_owned(self: &Self) -> T
fn clone_into(self: &Self, target: &mut T)

impl<T, U> Into for BytesMut

fn into(self: Self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of [From]<T> for U chooses 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>