SBTreeMap

Struct SBTreeMap 

Source
pub struct SBTreeMap<K: StableType + AsFixedSizeBytes + Ord, V: StableType + AsFixedSizeBytes> { /* private fields */ }
Expand description

Right-biased B-plus tree based map data structure

Entries are stored in ascending order of their keys. Use std::cmp::Reverse or a custom std::cmp::Ord impl, to differ the order.

B is 8. This implementation is optimized to perform as few stable memory (de)allocations as possible. Also, this data structure implements several non-conventional functions in order to share code with other data structures, based on this one.

This is an “infinite” data structure - it can handle up to u64::MAX key-value entries.

Both K and V have to implement StableType and AsFixedSizeBytes traits. SBTreeMap also implements these trait, so you can nest it in other stable structures.

Implementations§

Source§

impl<K: StableType + AsFixedSizeBytes + Ord, V: StableType + AsFixedSizeBytes> SBTreeMap<K, V>

Source

pub fn new() -> Self

Creates a new SBTreeMap

Does not allocate any heap or stable memory.

Source

pub fn insert(&mut self, key: K, value: V) -> Result<Option<V>, (K, V)>

Inserts the provided key-value pair into this SBTreeMap

May allocate stable and heap memory. If your canister is out of stable memory, will return Err with the key-value pair that was about to get inserted.

If the insertion is successful, returns Option with a value, that was previously stored under this key.

§Example
let mut map = SBTreeMap::new();

match map.insert(10u64, 100u64) {
    Ok(prev) => println!("Success! Previous value == {prev:?}"),
    Err((k, v)) => println!("Out of memory. Unable to insert pair: {k}, {v}"),
};
Source

pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
where K: Borrow<Q>, Q: Ord + ?Sized,

Removes a key-value pair by the provided key

Returns None if no pair was found by this key. May release some of stable memory occupied by this stable structure.

§Examples
let mut map = SBTreeMap::new();

map.insert(1, 10).expect("Out of memory");

assert_eq!(map.remove(&1).unwrap(), 10);

Borrowed type is also accepted. If your key type is, for example, [SBox] of String, then you can remove the pair by String.

let mut map = SBTreeMap::new();

let str_key = String::from("The key");
let key = SBox::new(str_key.clone()).expect("Out of memory");

map.insert(key, 10).expect("Out of memory");

assert_eq!(map.remove(&str_key).unwrap(), 10);
Source

pub fn get<Q>(&self, key: &Q) -> Option<SRef<'_, V>>
where K: Borrow<Q>, Q: Ord + ?Sized,

Returns an immutable reference SRef to a value stored by the key

See also SBTreeMap::get_mut.

If no such key-value pair is found, returns None

Borrowed type is also accepted. If your key type is, for example, [SBox] of String, then you can get the value by String.

§Example
let mut map = SBTreeMap::new();

let str_key = String::from("The key");
let key = SBox::new(str_key.clone()).expect("Out of memory");

map.insert(key, 10).expect("Out of memory");

assert_eq!(*map.get(&str_key).unwrap(), 10);
Source

pub fn get_random_key(&self, seed: u32) -> Option<SRef<'_, K>>

Returns a random key, deterministically deriving the randomness from the seed. This function is usefull, when you have a source of real randomness.

If the collection is empty, returns None.

Same seed on the same collection leads to the same returned key. Same seed on a modified collection may still lead to the same returned key. You can use [utils::math::shuffle_bits] function to pseudo-randomly generate more seeds.

Source

pub fn get_mut<Q>(&mut self, key: &Q) -> Option<SRefMut<'_, V>>
where K: Borrow<Q>, Q: Ord + ?Sized,

Returns a mutable reference SRefMut to a value stored by the key

See also SBTreeMap::get.

If no such key-value pair is found, returns None

Borrowed type is also accepted. If your key type is, for example, [SBox] of String, then you can get the value by String.

Source

pub fn contains_key<Q>(&self, key: &Q) -> bool
where K: Borrow<Q>, Q: Ord + ?Sized,

Returns true if there exists a key-value pair stored by the provided key

Borrowed type is also accepted. If your key type is, for example, [SBox] of String, then you can get the value by String.

Source

pub fn iter(&self) -> SBTreeMapIter<'_, K, V>

Returns an iterator over entries of this SBTreeMap

Elements of this iterator are presented in ascending order.

§Example
let mut map = SBTreeMap::new();

for i in 0..100 {
    map.insert(i, i).expect("Out of memory");
}

let mut i = 0;
for (k, v) in map.iter() {
    assert_eq!(*k, i);
    assert_eq!(*v, i);

    i += 1;
}

assert_eq!(i, 100);

One can use .rev() to get elements in reverse order.

§Example
let mut map = SBTreeMap::new();

for i in 0..100 {
    map.insert(i, i).expect("Out of memory");
}

let mut i = 100;
for (k, v) in map.iter().rev() {
    i -= 1;

    assert_eq!(*k, i);
    assert_eq!(*v, i);
}

assert_eq!(i, 0);
Source

pub fn len(&self) -> u64

Returns the length of this SBTreeMap

Source

pub fn is_empty(&self) -> bool

Returns true if the length of this SBTreeMap is 0

Source

pub fn clear(&mut self)

Removes all key-value pairs from this collection, releasing all occupied stable memory

Source§

impl<K: StableType + AsFixedSizeBytes + Ord + Debug, V: StableType + AsFixedSizeBytes + Debug> SBTreeMap<K, V>

Source

pub fn debug_print_stack(&self)

Source

pub fn debug_print(&self)

Trait Implementations§

Source§

impl<K: StableType + AsFixedSizeBytes + Ord, V: StableType + AsFixedSizeBytes> AsFixedSizeBytes for SBTreeMap<K, V>

Source§

const SIZE: usize = 16usize

Size of self when encoded
Source§

type Buf = [u8; 16]

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(buf: &[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<K: StableType + AsFixedSizeBytes + Ord + Debug, V: StableType + AsFixedSizeBytes + Debug> Debug for SBTreeMap<K, V>

Source§

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

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

impl<K: StableType + AsFixedSizeBytes + Ord, V: StableType + AsFixedSizeBytes> Default for SBTreeMap<K, V>

Source§

fn default() -> Self

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

impl<K: StableType + AsFixedSizeBytes + Ord, V: StableType + AsFixedSizeBytes> Drop for SBTreeMap<K, V>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl<K: StableType + AsFixedSizeBytes + Ord, V: StableType + AsFixedSizeBytes> StableType for SBTreeMap<K, V>

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<K, V> Freeze for SBTreeMap<K, V>

§

impl<K, V> RefUnwindSafe for SBTreeMap<K, V>

§

impl<K, V> Send for SBTreeMap<K, V>
where K: Send, V: Send,

§

impl<K, V> Sync for SBTreeMap<K, V>
where K: Sync, V: Sync,

§

impl<K, V> Unpin for SBTreeMap<K, V>
where K: Unpin, V: Unpin,

§

impl<K, V> UnwindSafe for SBTreeMap<K, V>
where K: UnwindSafe, V: 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.