Struct heapless_bytes::Bytes[][src]

pub struct Bytes<const N: usize> { /* fields omitted */ }

Implementations

Construct a new, empty Bytes<N>.

Wrap existing bytes in a Bytes<N>.

Unwraps the Vec<u8, N>, same as into_vec.

Unwraps the Vec<u8, N>, same as into_inner.

Returns an immutable slice view.

Returns a mutable slice view.

Low-noise conversion between lengths.

We can’t implement TryInto since it would clash with blanket implementations.

Some APIs offer an interface of the form f(&mut [u8]) -> Result<usize, E>, with the contract that the Ok-value signals how many bytes were written.

This constructor allows wrapping such interfaces in a more ergonomic way, returning a Bytes willed using f.

It seems it’s not possible to do this as an actual TryFrom implementation.

Fallible conversion into differently sized byte buffer.

Methods from Deref<Target = Vec<u8, N>>

Extracts a slice containing the entire vector.

Equivalent to &s[..].

Examples

use heapless::Vec;
let buffer: Vec<u8, 5> = Vec::from_slice(&[1, 2, 3, 5, 8]).unwrap();
assert_eq!(buffer.as_slice(), &[1, 2, 3, 5, 8]);

Returns the maximum number of elements the vector can hold.

Clears the vector, removing all values.

Extends the vec from an iterator.

Panic

Panics if the vec cannot hold all elements of the iterator.

Clones and appends all elements in a slice to the Vec.

Iterates over the slice other, clones each element, and then appends it to this Vec. The other vector is traversed in-order.

Examples

use heapless::Vec;

let mut vec = Vec::<u8, 8>::new();
vec.push(1).unwrap();
vec.extend_from_slice(&[2, 3, 4]).unwrap();
assert_eq!(*vec, [1, 2, 3, 4]);

Removes the last element from a vector and returns it, or None if it’s empty

Appends an item to the back of the collection

Returns back the item if the vector is full

Appends an item to the back of the collection

Safety

This assumes the vec is not full.

Shortens the vector, keeping the first len elements and dropping the rest.

Resizes the Vec in-place so that len is equal to new_len.

If new_len is greater than len, the Vec is extended by the difference, with each additional slot filled with value. If new_len is less than len, the Vec is simply truncated.

See also resize_default.

Resizes the Vec in-place so that len is equal to new_len.

If new_len is greater than len, the Vec is extended by the difference, with each additional slot filled with Default::default(). If new_len is less than len, the Vec is simply truncated.

See also resize.

Forces the length of the vector to new_len.

This is a low-level operation that maintains none of the normal invariants of the type. Normally changing the length of a vector is done using one of the safe operations instead, such as truncate, resize, extend, or clear.

Safety

  • new_len must be less than or equal to capacity().
  • The elements at old_len..new_len must be initialized.

Examples

This method can be useful for situations in which the vector is serving as a buffer for other code, particularly over FFI:

use heapless::Vec;

pub fn get_dictionary(&self) -> Option<Vec<u8, 32768>> {
    // Per the FFI method's docs, "32768 bytes is always enough".
    let mut dict = Vec::new();
    let mut dict_length = 0;
    // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
    // 1. `dict_length` elements were initialized.
    // 2. `dict_length` <= the capacity (32_768)
    // which makes `set_len` safe to call.
    unsafe {
        // Make the FFI call...
        let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
        if r == Z_OK {
            // ...and update the length to what was initialized.
            dict.set_len(dict_length);
            Some(dict)
        } else {
            None
        }
    }
}

While the following example is sound, there is a memory leak since the inner vectors were not freed prior to the set_len call:

use core::iter::FromIterator;
use heapless::Vec;

let mut vec = Vec::<Vec<u8, 3>, 3>::from_iter(
    [
        Vec::from_iter([1, 0, 0].iter().cloned()),
        Vec::from_iter([0, 1, 0].iter().cloned()),
        Vec::from_iter([0, 0, 1].iter().cloned()),
    ]
    .iter()
    .cloned()
);
// SAFETY:
// 1. `old_len..0` is empty so no elements need to be initialized.
// 2. `0 <= capacity` always holds whatever `capacity` is.
unsafe {
    vec.set_len(0);
}

Normally, here, one would use clear instead to correctly drop the contents and thus not leak memory.

Removes an element from the vector and returns it.

The removed element is replaced by the last element of the vector.

This does not preserve ordering, but is O(1).

Panics

Panics if index is out of bounds.

Examples

use heapless::Vec;

let mut v: Vec<_, 8> = Vec::new();
v.push("foo").unwrap();
v.push("bar").unwrap();
v.push("baz").unwrap();
v.push("qux").unwrap();

assert_eq!(v.swap_remove(1), "bar");
assert_eq!(&*v, ["foo", "qux", "baz"]);

assert_eq!(v.swap_remove(0), "foo");
assert_eq!(&*v, ["baz", "qux"]);

Removes an element from the vector and returns it.

The removed element is replaced by the last element of the vector.

This does not preserve ordering, but is O(1).

Safety

Assumes index within bounds.

Examples

use heapless::Vec;

let mut v: Vec<_, 8> = Vec::new();
v.push("foo").unwrap();
v.push("bar").unwrap();
v.push("baz").unwrap();
v.push("qux").unwrap();

assert_eq!(unsafe { v.swap_remove_unchecked(1) }, "bar");
assert_eq!(&*v, ["foo", "qux", "baz"]);

assert_eq!(unsafe { v.swap_remove_unchecked(0) }, "foo");
assert_eq!(&*v, ["baz", "qux"]);

Returns true if the vec is full

Returns true if needle is a prefix of the Vec.

Always returns true if needle is an empty slice.

Examples

use heapless::Vec;

let v: Vec<_, 8> = Vec::from_slice(b"abc").unwrap();
assert_eq!(v.starts_with(b""), true);
assert_eq!(v.starts_with(b"ab"), true);
assert_eq!(v.starts_with(b"bc"), false);

Returns true if needle is a suffix of the Vec.

Always returns true if needle is an empty slice.

Examples

use heapless::Vec;

let v: Vec<_, 8> = Vec::from_slice(b"abc").unwrap();
assert_eq!(v.ends_with(b""), true);
assert_eq!(v.ends_with(b"ab"), false);
assert_eq!(v.ends_with(b"bc"), true);

Trait Implementations

Performs the conversion.

Performs the conversion.

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

Returns the “default value” for a type. Read more

The resulting type after dereferencing.

Dereferences the value.

Mutably dereferences the value.

Deserialize this value from the given Serde deserializer. Read more

Performs the conversion.

Feeds this value into the given Hasher. Read more

Feeds a slice of this type into the given Hasher. Read more

The type of the elements being iterated over.

Which kind of iterator are we turning this into?

Creates an iterator from a value. Read more

The type of the elements being iterated over.

Which kind of iterator are we turning this into?

Creates an iterator from a value. Read more

The type of the elements being iterated over.

Which kind of iterator are we turning this into?

Creates an iterator from a value. Read more

This method tests for self and other values to be equal, and is used by ==. Read more

This method tests for !=.

This method returns an ordering between self and other values if one exists. Read more

This method tests less than (for self and other) and is used by the < operator. Read more

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more

This method tests greater than (for self and other) and is used by the > operator. Read more

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

Performs the conversion.

Should always be Self

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.