SVec

Struct SVec 

Source
pub struct SVec<T: StableType + AsFixedSizeBytes> { /* private fields */ }
Expand description

Stable analog of Vec

May reallocate on inserts. In this case will copy the underlying data to a new location.

This is a “finite” data structure, it can only holp up to u32::MAX / T::SIZE elements. Putting more elements inside will panic.

T has to implement both StableType and AsFixedSizeBytes. SVec itself implements these traits and can be nested inside other stable data structures.

When SVec is stable-dropped, its elements are also stable-dropped but in reverse order.

Implementations§

Source§

impl<T: StableType + AsFixedSizeBytes> SVec<T>

Source

pub fn new() -> Self

Creates a SVec of capacity equal to 4 elements.

Does not allocate any heap or stable memory.

§Example
// won't allocate until you insert something in it
let mut numbers = SVec::<u64>::new();
Source

pub fn new_with_capacity(capacity: usize) -> Result<Self, OutOfMemory>

Creates a SVec of requested capacity.

Does allocate stable memory, returning OutOfMemory if there is not enough of it. If this function returns Ok, you are guaranteed to have enough stable memory to store at least capacity elements in it.

§Example
let mut at_least_10_numbers = SVec::<u64>::new_with_capacity(10)
    .expect("Out of memory");
Source

pub fn capacity(&self) -> usize

Returns the capacity of this SVec

Source

pub fn len(&self) -> usize

Returns the length of this SVec

Source

pub fn is_empty(&self) -> bool

Returns true if the length of this SVec is 0

Source

pub const fn max_capacity() -> usize

Returns the maximum possible capacity of this SVec

Source

pub fn push(&mut self, element: T) -> Result<(), T>

Inserts a new element at the end of this SVec

Will try to reallocate if capacity == length. If the canister is out of stable memory, will return Err with the element that was about to get inserted.

Source

pub fn pop(&mut self) -> Option<T>

Removes the last element of the SVec

If the SVec is empty, returns None.

Source

pub fn get(&self, idx: usize) -> Option<SRef<'_, T>>

Returns a SRef pointing to the element at requested index

See also SVec::get_mut.

If out of bounds, returns None

§Example
let mut vec = SVec::<u64>::new();
vec.push(20).expect("Out of memory");

let elem = vec.get(0).unwrap();

assert_eq!(*elem, 20);
Source

pub fn get_mut(&mut self, idx: usize) -> Option<SRefMut<'_, T>>

Returns SRefMut pointing to the element at requested index

See also SVec::get.

If out of bounds, returns None

§Example
let mut vec = SVec::<u64>::new();
vec.push(20).expect("Out of memory");

let mut elem = vec.get_mut(0).unwrap();
*elem = 100;
Source

pub fn replace(&mut self, idx: usize, element: T) -> T

Replaces an element at requested index with a provided value

§Panics

Panics if out of bounds.

§Example
let mut vec = SVec::<u64>::new();
vec.push(10).expect("Out of memory");

let prev = vec.replace(0, 20);

assert_eq!(prev, 10);
assert_eq!(*vec.get(0).unwrap(), 20);
Source

pub fn insert(&mut self, idx: usize, element: T) -> Result<(), T>

Inserts a new element at the requested index, forward-shifting all elements after it

Will try to reallocate, if capacity == length. If the canister is out of stable memory, will return Err with the element that was about to get inserted.

§Panics

Panics if out of bounds.

Source

pub fn remove(&mut self, idx: usize) -> T

Removes element at the requested index, back-shifting all elements after it

§Panics

Panics if out of bounds.

Source

pub fn swap(&mut self, idx1: usize, idx2: usize)

Swaps elements at requested indices with each other

§Panics

Panics if idx1 == idx2 or if any of indices are out of bounds.

Source

pub fn clear(&mut self)

Clears the SVec from elements

Does not reallocate or shrink the underlying memory block.

Source

pub fn binary_search_by<FN>(&self, f: FN) -> Result<usize, usize>
where FN: FnMut(&T) -> Ordering,

Performs binary search on a sorted SVec, using the provided lambda

Works the same way as in Vec.

§Example
let mut vec = SVec::new_with_capacity(100).expect("Out of memory");

for i in 0..100 {
    vec.push(i);
}

let idx = vec.binary_search_by(|it| it.cmp(&10)).unwrap();

assert_eq!(idx, 10);
Source

pub fn iter(&self) -> SVecIter<'_, T>

Returns an immutable iterator over this collection

§Example
let mut vec = SVec::new_with_capacity(100).expect("Out of memory");

for i in 0..100 {
    vec.push(i);
}

for elem in vec.iter() {
    println!("{}", *elem); // will print '0, 1, 2, 3, 4, ...'
}
Source

pub fn debug_print(&self)

Prints byte representation of this collection

Useful for tests

Trait Implementations§

Source§

impl<T: StableType + AsFixedSizeBytes> AsFixedSizeBytes for SVec<T>

Source§

const SIZE: usize = 24usize

Size of self when encoded
Source§

type Buf = [u8; 24]

Buffer that is used to encode this value into
Source§

fn as_fixed_size_bytes(&self, buf: &mut [u8])

Encodes itself into a slice of bytes. Read more
Source§

fn from_fixed_size_bytes(arr: &[u8]) -> Self

Decodes itself from a slice of bytes. Read more
Source§

fn as_new_fixed_size_bytes(&self) -> Self::Buf

Encodes itself into a new Self::Buf of size == Self::SIZE
Source§

impl<T: StableType + AsFixedSizeBytes + Debug> Debug for SVec<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: StableType + AsFixedSizeBytes> Default for SVec<T>

Source§

fn default() -> Self

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

impl<T: StableType + AsFixedSizeBytes> Drop for SVec<T>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl<T: StableType + AsFixedSizeBytes> StableType for SVec<T>

Source§

unsafe fn stable_drop_flag_off(&mut self)

Sets stable drop flag to off position, if it is applicable Read more
Source§

unsafe fn stable_drop_flag_on(&mut self)

Should set stable drop flag to on position, if it is applicable Read more
Source§

fn should_stable_drop(&self) -> bool

Should return the value of the stable drop flag
Source§

unsafe fn stable_drop(&mut self)

Performs stable drop, releasing all underlying stable memory of this data structure Read more

Auto Trait Implementations§

§

impl<T> Freeze for SVec<T>

§

impl<T> RefUnwindSafe for SVec<T>
where T: RefUnwindSafe,

§

impl<T> Send for SVec<T>
where T: Send,

§

impl<T> Sync for SVec<T>
where T: Sync,

§

impl<T> Unpin for SVec<T>
where T: Unpin,

§

impl<T> UnwindSafe for SVec<T>
where T: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> AsDynSizeBytes for T

Source§

fn as_dyn_size_bytes(&self) -> Vec<u8>

Encodes self into vector of bytes Read more
Source§

fn from_dyn_size_bytes(buf: &[u8]) -> T

Decodes self from a slice of bytes. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.