Overview
Soroban provides two types for working with byte arrays:Bytes: A growable byte array (similar toVec<u8>)BytesN<N>: A fixed-size byte array of exactlyNbytes
Bytes
Bytes is a contiguous growable array type containing u8s.
Creating Bytes
new()
Create an empty Bytes.
from_array()
Create from an array.
from_slice()
Create from a slice.
bytes!() Macro
Convenient macro for creating Bytes:
Accessing Elements
get()
Returns the byte at position or None if out-of-bounds.
get_unchecked()
Returns the byte at position without bounds checking.
first() / last()
Returns the first or last byte, or None if empty.
first_unchecked() / last_unchecked()
Returns the first or last byte without checking if empty.
Modifying Bytes
set()
Sets the byte at position.
push_back()
Adds a byte to the back.
pop_back()
Removes and returns the last byte, or None if empty.
pop_back_unchecked()
Removes and returns the last byte without checking if empty.
insert()
Inserts a byte at position.
remove()
Removes the byte at position.
remove_unchecked()
Removes the byte at position without bounds checking.
Appending and Extending
append()
Appends another Bytes.
extend_from_array() / extend_from_slice()
Extends with bytes from an array or slice.
insert_from_bytes() / insert_from_slice()
Inserts bytes at position.
Copying Data
copy_from_slice()
Copies bytes from a slice to the specified position.
copy_into_slice()
Copies bytes into a slice.
Slicing
slice()
Returns a subset of bytes.
Query Methods
len()
Returns the number of bytes.
is_empty()
Returns true if empty.
Iteration
iter()
Returns an iterator over the bytes.
Conversion
to_buffer()
Copies bytes into a fixed-size buffer.
to_alloc_vec() (with alloc feature)
Copies bytes into a Vec<u8>.
to_string()
Converts bytes to a String.
BytesN
BytesN<N> is a fixed-size byte array of exactly N bytes.
Creating BytesN
from_array()
Create from an array.
bytesn!() Macro
Conversion Between Bytes and BytesN
Bytes → BytesN
BytesN → Bytes
BytesN → Array
BytesN Methods
BytesN supports most read-only methods from Bytes:get(),get_unchecked()first(),first_unchecked(),last(),last_unchecked()len(),is_empty()iter()to_array(),copy_into_slice()env(),as_val(),to_val()
set() to modify individual bytes.
Common Use Cases
Hash Storage
Binary Data Processing
Converting Between Types
Traits
BothBytes and BytesN<N> implement:
CloneDebugEq,PartialEqOrd,PartialOrdIntoIterator