Skip to main content

Map

Struct Map 

Source
pub struct Map<T> { /* private fields */ }
Expand description

A map implemented as a radix trie.

Keys are split into sequences of 4 bits, which are used to place elements in 16-entry arrays which are nested to form a tree structure. Inserted elements are placed as close to the top of the tree as possible. The most significant bits of the key are used to assign the key to a node/bucket in the first layer. If there are no other elements keyed by the same 4 bits in the first layer, a leaf node will be created in the first layer. When keys coincide, the next 4 bits are used to assign the node to a bucket in the next layer, with this process continuing until an empty spot is found or there are no more bits left in the key. As a result, the maximum depth using 32-bit usize keys is 8. The worst collisions occur for very small numbers. For example, 1 and 2 are identical in all but their least significant 4 bits. If both numbers are used as keys, a chain of maximum length will be created to differentiate them.

§Examples

let mut map = trie::Map::new();
map.insert(27, "Olaf");
map.insert(1, "Edgar");
map.insert(13, "Ruth");
map.insert(1, "Martin");

assert_eq!(map.len(), 3);
assert_eq!(map.get(&1), Some(&"Martin"));

if !map.contains_key(&90) {
    println!("Nobody is keyed 90");
}

// Update a key
match map.get_mut(&1) {
    Some(value) => *value = "Olga",
    None => (),
}

map.remove(&13);
assert_eq!(map.len(), 2);

// Print the key value pairs, ordered by key.
for (key, value) in map.iter() {
    // Prints `1: Olga` then `27: Olaf`
    println!("{}: {}", key, value);
}

map.clear();
assert!(map.is_empty());

Implementations§

Source§

impl<T> Map<T>

Source

pub fn new() -> Map<T>

Creates an empty map.

§Examples
let mut map: trie::Map<&str> = trie::Map::new();
Source

pub fn each_reverse<'a, F>(&'a self, f: F) -> bool
where F: FnMut(&usize, &'a T) -> bool,

Visits all key-value pairs in reverse order. Aborts traversal when f returns false. Returns true if f returns true for all elements.

§Examples
let map: trie::Map<&str> = [(1, "a"), (2, "b"), (3, "c")].iter().cloned().collect();

let mut vec = vec![];
assert_eq!(true, map.each_reverse(|&key, &value| { vec.push((key, value)); true }));
assert_eq!(vec, [(3, "c"), (2, "b"), (1, "a")]);

// Stop when we reach 2
let mut vec = vec![];
assert_eq!(false, map.each_reverse(|&key, &value| { vec.push(value); key != 2 }));
assert_eq!(vec, ["c", "b"]);
Source

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

Gets an iterator visiting all keys in ascending order by the keys. The iterator’s element type is usize.

Source

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

Gets an iterator visiting all values in ascending order by the keys. The iterator’s element type is &'r T.

Source

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

Gets an iterator over the key-value pairs in the map, ordered by keys.

§Examples
let map: trie::Map<&str> = [(3, "c"), (1, "a"), (2, "b")].iter().cloned().collect();

for (key, value) in map.iter() {
    println!("{}: {}", key, value);
}
Source

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

Gets an iterator over the key-value pairs in the map, with the ability to mutate the values.

§Examples
let mut map: trie::Map<i32> = [(1, 2), (2, 4), (3, 6)].iter().cloned().collect();

for (key, value) in map.iter_mut() {
    *value = -(key as i32);
}

assert_eq!(map.get(&1), Some(&-1));
assert_eq!(map.get(&2), Some(&-2));
assert_eq!(map.get(&3), Some(&-3));
Source

pub fn len(&self) -> usize

Return the number of elements in the map.

§Examples
let mut a = trie::Map::new();
assert_eq!(a.len(), 0);
a.insert(1, "a");
assert_eq!(a.len(), 1);
Source

pub fn is_empty(&self) -> bool

Return true if the map contains no elements.

§Examples
let mut a = trie::Map::new();
assert!(a.is_empty());
a.insert(1, "a");
assert!(!a.is_empty());
Source

pub fn clear(&mut self)

Clears the map, removing all values.

§Examples
let mut a = trie::Map::new();
a.insert(1, "a");
a.clear();
assert!(a.is_empty());
Source

pub fn get(&self, key: &usize) -> Option<&T>

Returns a reference to the value corresponding to the key.

§Examples
let mut map = trie::Map::new();
map.insert(1, "a");
assert_eq!(map.get(&1), Some(&"a"));
assert_eq!(map.get(&2), None);
Source

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

Returns true if the map contains a value for the specified key.

§Examples
let mut map = trie::Map::new();
map.insert(1, "a");
assert_eq!(map.contains_key(&1), true);
assert_eq!(map.contains_key(&2), false);
Source

pub fn get_mut(&mut self, key: &usize) -> Option<&mut T>

Returns a mutable reference to the value corresponding to the key.

§Examples
let mut map = trie::Map::new();
map.insert(1, "a");
match map.get_mut(&1) {
    Some(x) => *x = "b",
    None => (),
}
assert_eq!(map[&1], "b");
Source

pub fn insert(&mut self, key: usize, value: T) -> Option<T>

Inserts a key-value pair from the map. If the key already had a value present in the map, that value is returned. Otherwise, None is returned.

§Examples
let mut map = trie::Map::new();
assert_eq!(map.insert(37, "a"), None);
assert_eq!(map.is_empty(), false);

map.insert(37, "b");
assert_eq!(map.insert(37, "c"), Some("b"));
assert_eq!(map[&37], "c");
Source

pub fn remove(&mut self, key: &usize) -> Option<T>

Removes a key from the map, returning the value at the key if the key was previously in the map.

§Examples
let mut map = trie::Map::new();
map.insert(1, "a");
assert_eq!(map.remove(&1), Some("a"));
assert_eq!(map.remove(&1), None);
Source§

impl<T> Map<T>

Source

pub fn lower_bound(&self, key: usize) -> Range<'_, T>

Gets an iterator pointing to the first key-value pair whose key is not less than key. If all keys in the map are less than key an empty iterator is returned.

§Examples
let map: trie::Map<&str> = [(2, "a"), (4, "b"), (6, "c")].iter().cloned().collect();

assert_eq!(map.lower_bound(4).next(), Some((4, &"b")));
assert_eq!(map.lower_bound(5).next(), Some((6, &"c")));
assert_eq!(map.lower_bound(10).next(), None);
Source

pub fn upper_bound(&self, key: usize) -> Range<'_, T>

Gets an iterator pointing to the first key-value pair whose key is greater than key. If all keys in the map are not greater than key an empty iterator is returned.

§Examples
let map: trie::Map<&str> = [(2, "a"), (4, "b"), (6, "c")].iter().cloned().collect();

assert_eq!(map.upper_bound(4).next(), Some((6, &"c")));
assert_eq!(map.upper_bound(5).next(), Some((6, &"c")));
assert_eq!(map.upper_bound(10).next(), None);
Source

pub fn lower_bound_mut(&mut self, key: usize) -> RangeMut<'_, T>

Gets an iterator pointing to the first key-value pair whose key is not less than key. If all keys in the map are less than key an empty iterator is returned.

§Examples
let mut map: trie::Map<&str> = [(2, "a"), (4, "b"), (6, "c")].iter().cloned().collect();

assert_eq!(map.lower_bound_mut(4).next(), Some((4, &mut "b")));
assert_eq!(map.lower_bound_mut(5).next(), Some((6, &mut "c")));
assert_eq!(map.lower_bound_mut(10).next(), None);

for (key, value) in map.lower_bound_mut(4) {
    *value = "changed";
}

assert_eq!(map.get(&2), Some(&"a"));
assert_eq!(map.get(&4), Some(&"changed"));
assert_eq!(map.get(&6), Some(&"changed"));
Source

pub fn upper_bound_mut(&mut self, key: usize) -> RangeMut<'_, T>

Gets an iterator pointing to the first key-value pair whose key is greater than key. If all keys in the map are not greater than key an empty iterator is returned.

§Examples
let mut map: trie::Map<&str> = [(2, "a"), (4, "b"), (6, "c")].iter().cloned().collect();

assert_eq!(map.upper_bound_mut(4).next(), Some((6, &mut "c")));
assert_eq!(map.upper_bound_mut(5).next(), Some((6, &mut "c")));
assert_eq!(map.upper_bound_mut(10).next(), None);

for (key, value) in map.upper_bound_mut(4) {
    *value = "changed";
}

assert_eq!(map.get(&2), Some(&"a"));
assert_eq!(map.get(&4), Some(&"b"));
assert_eq!(map.get(&6), Some(&"changed"));
Source§

impl<T> Map<T>

Source

pub fn entry(&mut self, key: usize) -> Entry<'_, T>

Gets the given key’s corresponding entry in the map for in-place manipulation.

Trait Implementations§

Source§

impl<T: Clone> Clone for Map<T>

Source§

fn clone(&self) -> Map<T>

Returns a duplicate 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<T: Debug> Debug for Map<T>

Source§

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

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

impl<T> Default for Map<T>

Source§

fn default() -> Map<T>

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

impl<T> Extend<(usize, T)> for Map<T>

Source§

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

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<T> FromIterator<(usize, T)> for Map<T>

Source§

fn from_iter<I: IntoIterator<Item = (usize, T)>>(iter: I) -> Map<T>

Creates a value from an iterator. Read more
Source§

impl<T: Hash> Hash for Map<T>

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

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

impl<'a, T> Index<&'a usize> for Map<T>

Source§

type Output = T

The returned type after indexing.
Source§

fn index(&self, i: &'a usize) -> &T

Performs the indexing (container[index]) operation. Read more
Source§

impl<'a, T> IndexMut<&'a usize> for Map<T>

Source§

fn index_mut(&mut self, i: &'a usize) -> &mut T

Performs the mutable indexing (container[index]) operation. Read more
Source§

impl<'a, T> IntoIterator for &'a Map<T>

Source§

type Item = (usize, &'a T)

The type of the elements being iterated over.
Source§

type IntoIter = Iter<'a, T>

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

fn into_iter(self) -> Iter<'a, T>

Creates an iterator from a value. Read more
Source§

impl<'a, T> IntoIterator for &'a mut Map<T>

Source§

type Item = (usize, &'a mut T)

The type of the elements being iterated over.
Source§

type IntoIter = IterMut<'a, T>

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

fn into_iter(self) -> IterMut<'a, T>

Creates an iterator from a value. Read more
Source§

impl<T: Ord> Ord for Map<T>

Source§

fn cmp(&self, other: &Map<T>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl<T: PartialEq> PartialEq for Map<T>

Source§

fn eq(&self, other: &Map<T>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<T: PartialOrd> PartialOrd for Map<T>

Source§

fn partial_cmp(&self, other: &Map<T>) -> Option<Ordering>

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

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<T: Eq> Eq for Map<T>

Auto Trait Implementations§

§

impl<T> Freeze for Map<T>
where T: Freeze,

§

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

§

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

§

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

§

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

§

impl<T> UnsafeUnpin for Map<T>
where T: UnsafeUnpin,

§

impl<T> UnwindSafe for Map<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> 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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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.