Struct tinymap::array_map::ArrayMap

source ·
pub struct ArrayMap<K: PartialOrd, V, const N: usize> { /* private fields */ }
Expand description

A binary tree that uses a stack-based array as storage for nodes.

Rather than using the heap to store nodes, this structure uses an ArrayVec. Note that this is nowhere near as efficient as the standard library HashMap implementation. The purpose of this structure is to offer an interface similar to HashMap to use in its place in no_std environments.

Examples

use tinymap::ArrayMap;

// Today, I'm making software for the lamp store. They want to match up a LampID to a
// Lamp. This software also needs to run on embedded hardware, where a Rust allocator
// hasn't been ported yet.

/// A representation of a lamp.
struct Lamp { wattage: u32, color: &'static str }

// The LampID is just a string that the manager uses to look up a lamp
// that the store has in stock.
let mut lamps: ArrayMap<&'static str, Lamp, 3> = ArrayMap::new();

// Let's take some of the lamps we have and put them in our map.
lamps.insert("32ZD", Lamp { wattage: 120, color: "red" });
lamps.insert("11HR", Lamp { wattage: 60, color: "gray" });
lamps.insert("2460", Lamp { wattage: 90, color: "blue" });

// The customer wants lamps #32ZD and #11HR?
assert_eq!(lamps.get(&"32ZD").unwrap().wattage, 120);
assert_eq!(lamps.get(&"11HR").unwrap().color, "gray");

// Let's add one more lamp! Nothing could go wrong!
let oops = lamps.try_insert("199K", Lamp { wattage: 80, color: "green" });
assert!(oops.is_err());
assert!(lamps.get(&"199k").is_none());

Implementations§

source§

impl<K: PartialOrd, V, const N: usize> ArrayMap<K, V, N>

source

pub fn new() -> Self

Create a new ArrayMap.

Examples
#[derive(PartialOrd, Ord, PartialEq, Eq)]
struct Foo;
struct Bar;

let my_map: ArrayMap<Foo, Bar, 1> = ArrayMap::new();
source

pub fn len(&self) -> usize

Retrieves the current number of elements within the binary tree.

Examples
#[derive(PartialOrd, Ord, PartialEq, Eq)]
struct MyIndex(u32);
struct MyData { foo: &'static str }

let mut my_map: ArrayMap<MyIndex, MyData, 3> = ArrayMap::new();
my_map.insert(MyIndex(12), MyData { foo: "Leroy" });
my_map.insert(MyIndex(13), MyData { foo: "Barbara" });
my_map.insert(MyIndex(12), MyData { foo: "Joanne" });
assert_eq!(my_map.len(), 2);
source

pub fn is_empty(&self) -> bool

Check to see if there are any elements in this map.

Examples
let my_love_life: ArrayMap<&'static str, u32, 10> = ArrayMap::new();
assert!(my_love_life.is_empty());
source

pub fn get(&self, key: &K) -> Option<&V>

Get a reference to an item stored inside of this map.

source

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

Get a mutable reference to an item stored inside of this map.

source

pub fn contains_key(&self, key: &K) -> bool

Tell whether or not this map contains a certain key.

source

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

Insert a node into this binary tree. This function will return the value previously in the key’s slot, if applicable.

Errors

If the backing array is full, this function will return back the key-value pair passed in.

Examples
/// The representation of a mattress.
#[derive(PartialOrd, Ord, PartialEq, Eq)]
struct Mattress { width: u32, height: u32, brand: &'static str }

let mut mattress_ratings: ArrayMap<Mattress, u64, 12> = ArrayMap::new();
let mut limit = 0;
loop {
    // The mattress testing robot tests more mattresses than we could ever imagine.
    // But how long until it tests too many?
    let mattress = Mattress {
        width: limit + 1,
        height: (limit + 1) * 2,
        brand: "Smith Mattresses",
    };
    let res = mattress_ratings.try_insert(mattress, 27);
    match res {
        Ok(_) => { limit += 1; },
        Err((reject, _)) => {
            assert_eq!(reject.width, 13);
            break;
        }
    }
}

assert_eq!(limit, 12);
source

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

Insert a node into this binary tree.

Panics

Unlike try_insert, this function will panic if the backing array is full.

Examples
/// Representation of a viking.
struct Viking { kill_count: u32, body_count: u32, name: &'static str }
let mut famous_vikings: ArrayMap<u32, Viking, 25> = ArrayMap::new();

for i in 0..100 {
   // D'oh! I knew I shouldn't have run my school assignment on my microwave!
   famous_vikings.insert(i, Viking { kill_count: i, body_count: i * 2, name: "John" });
}
source

pub fn remove_entry(&mut self, key: &K) -> Option<(K, V)>where K: Ord,

Remove a node entry from the binary tree. This function returns the key-value pair that was removed.

Examples
fn help_humans() { println!("Let's solve world hunger!"); }
fn kill_humans() { panic!("Kill! Kill! Kill!"); }

// My robot needs to know what to do!
let mut robot_behaviors: ArrayMap<&'static str, &dyn Fn(), 2> = ArrayMap::new();
robot_behaviors.insert("help", &help_humans);
robot_behaviors.insert("kill", &kill_humans);

// ...wait. It probably shouldn't do that.
let removed = robot_behaviors.remove_entry(&"kill").unwrap();

assert_eq!(removed.0, "kill");
source

pub fn remove(&mut self, key: &K) -> Option<V>where K: Ord,

Remove a value from the binary tree. This is similar to remove_entry, but it does not keep the value.

source

pub fn clear(&mut self)

Clear out the binary tree.

Examples
struct Album { name: &'static str }

let mut albums_by_artist: ArrayMap<&'static str, Album, 5> = ArrayMap::new();

albums_by_artist.insert("Owl City", Album { name: "Ocean Lights" });
albums_by_artist.insert("Billy Joel", Album { name: "Glass Houses" });
albums_by_artist.insert("Frank Sinatra", Album { name: "My Way" });

// You know what? I've decided I'm not really that into music anymore.
albums_by_artist.clear();

assert_eq!(albums_by_artist.len(), 0);
source

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

Iterate over the elements of this binary tree in arbitrary order.

source

pub fn iter_mut(&mut self) -> IterMut<'_, K, V>

Iterate over the elements of this binary tree in arbitrary order, mutably.

source

pub fn keys(&self) -> Keys<'_, K, V>

Iterate over the keys of this binary tree in arbitrary order.

source

pub fn values(&self) -> Values<'_, K, V>

Iterate over the values of this binary tree in arbitrary order.

source

pub fn values_mut(&mut self) -> ValuesMut<'_, K, V>

Iterate over the values of this binary tree in arbitrary order, mutably.

source

pub fn drain(&mut self) -> Drain<'_, K, V>

Drain the values from this map.

Trait Implementations§

source§

impl<K: PartialOrd + Clone, V: Clone, const N: usize> Clone for ArrayMap<K, V, N>

source§

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<K: PartialOrd + Debug, V: Debug, const N: usize> Debug for ArrayMap<K, V, N>

source§

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

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

impl<K: PartialOrd, V, const N: usize> Default for ArrayMap<K, V, N>

source§

fn default() -> Self

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

impl<K: Ord, V, const N: usize> Extend<(K, V)> for ArrayMap<K, V, N>

source§

fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T)

Extends a collection with the contents of an iterator. Read more
source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
source§

impl<K: Ord, V, const N: usize> FromIterator<(K, V)> for ArrayMap<K, V, N>

source§

fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self

Creates a value from an iterator. Read more
source§

impl<K: PartialOrd, V, const N: usize> IntoIterator for ArrayMap<K, V, N>

§

type Item = (K, V)

The type of the elements being iterated over.
§

type IntoIter = IntoIter<K, V, N>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more

Auto Trait Implementations§

§

impl<K, V, const N: usize> RefUnwindSafe for ArrayMap<K, V, N>where K: RefUnwindSafe, V: RefUnwindSafe,

§

impl<K, V, const N: usize> Send for ArrayMap<K, V, N>where K: Send, V: Send,

§

impl<K, V, const N: usize> Sync for ArrayMap<K, V, N>where K: Sync, V: Sync,

§

impl<K, V, const N: usize> Unpin for ArrayMap<K, V, N>where K: Unpin, V: Unpin,

§

impl<K, V, const N: usize> UnwindSafe for ArrayMap<K, V, N>where K: UnwindSafe, V: UnwindSafe,

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

const: unstable · source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

const: unstable · source§

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

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

const: unstable · source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

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

const: unstable · 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, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
const: unstable · source§

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

Performs the conversion.
source§

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

§

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

The type returned in the event of a conversion error.
const: unstable · source§

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

Performs the conversion.