pub struct TreeMap<K, V, const PREFIX_LEN: usize = DEFAULT_PREFIX_LEN> { /* private fields */ }
Expand description
An ordered map based on an adaptive radix tree.
Implementations§
Source§impl<K, V> TreeMap<K, V>
impl<K, V> TreeMap<K, V>
Sourcepub fn new() -> Self
pub fn new() -> Self
Create a new, empty crate::TreeMap
with the default number of prefix
bytes (16).
This function will not pre-allocate anything.
§Examples
Source§impl<K, V, const PREFIX_LEN: usize> TreeMap<K, V, PREFIX_LEN>
impl<K, V, const PREFIX_LEN: usize> TreeMap<K, V, PREFIX_LEN>
Sourcepub fn with_prefix_len() -> Self
pub fn with_prefix_len() -> Self
Sourcepub fn into_raw(tree: Self) -> Option<OpaqueNodePtr<K, V, PREFIX_LEN>>
pub fn into_raw(tree: Self) -> Option<OpaqueNodePtr<K, V, PREFIX_LEN>>
Consume the tree, returning a raw pointer to the root node.
If the results is None
, this means the tree is empty.
§Examples
use blart::TreeMap;
let mut map = TreeMap::<Box<[u8]>, char>::new();
map.try_insert(Box::new([1, 2, 3]), 'a').unwrap();
assert_eq!(map.len(), 1);
let root = TreeMap::into_raw(map);
assert!(root.is_some());
// SAFETY: The root pointer came directly from the `into_raw` result.
let _map = unsafe { TreeMap::from_raw(root) }.unwrap();
Sourcepub unsafe fn from_raw(
root: Option<OpaqueNodePtr<K, V, PREFIX_LEN>>,
) -> Result<Self, MalformedTreeError<K, V, PREFIX_LEN>>where
K: AsBytes,
pub unsafe fn from_raw(
root: Option<OpaqueNodePtr<K, V, PREFIX_LEN>>,
) -> Result<Self, MalformedTreeError<K, V, PREFIX_LEN>>where
K: AsBytes,
Constructs a TreeMap
from a raw node pointer.
§Safety
The raw pointer must have been previously returned by a call to
TreeMap::into_raw
.
This function also requires that this the given root
pointer is
unique, and that there are no other pointers into the tree.
§Errors
This function runs a series of checks to ensure that the returned tree
is well-formed. See WellFormedChecker
for details on the
requirements.
§Examples
use blart::TreeMap;
let mut map = TreeMap::<Box<[u8]>, char>::new();
map.try_insert(Box::new([1, 2, 3]), 'a').unwrap();
assert_eq!(map.len(), 1);
let root = TreeMap::into_raw(map);
assert!(root.is_some());
// SAFETY: The root pointer came directly from the `into_raw` result.
let _map = unsafe { TreeMap::from_raw(root) }.unwrap();
Sourcepub fn get<Q>(&self, key: &Q) -> Option<&V>
pub fn get<Q>(&self, key: &Q) -> Option<&V>
Returns a reference to the value corresponding to the key.
§Examples
Sourcepub fn get_key_value<Q>(&self, key: &Q) -> Option<(&K, &V)>
pub fn get_key_value<Q>(&self, key: &Q) -> Option<(&K, &V)>
Returns the key-value pair corresponding to the supplied key.
§Examples
Sourcepub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
Returns a mutable reference to the value corresponding to the key.
§Examples
use blart::TreeMap;
let mut map = TreeMap::<Box<[u8]>, char>::new();
map.try_insert(Box::new([1, 2, 3]), 'a').unwrap();
assert_eq!(map[[1, 2, 3].as_ref()], 'a');
*map.get_mut([1, 2, 3].as_ref()).unwrap() = 'b';
assert_eq!(map[[1, 2, 3].as_ref()], 'b');
While an element from the tree is mutably referenced, no other operation on the tree can happen.
use blart::TreeMap;
let mut map = TreeMap::<Box<[u8]>, char>::new();
map.try_insert(Box::new([1, 2, 3]), 'a').unwrap();
let value = map.get_mut(&[1, 2, 3]).unwrap();
assert_eq!(*value, 'a');
assert_eq!(*map[[1, 2, 3].as_ref()], 'a');
*value = 'b';
drop(value);
Sourcepub fn fuzzy<'a, 'b, Q>(
&'a self,
key: &'b Q,
max_edit_dist: usize,
) -> Fuzzy<'a, 'b, K, V, PREFIX_LEN> ⓘ
pub fn fuzzy<'a, 'b, Q>( &'a self, key: &'b Q, max_edit_dist: usize, ) -> Fuzzy<'a, 'b, K, V, PREFIX_LEN> ⓘ
Makes a fuzzy search in the tree by key
,
returning all keys and values that are
less than or equal to max_edit_dist
.
This is done by using Levenshtein distance
§Examples
Sourcepub fn fuzzy_mut<'a, 'b, Q>(
&'a mut self,
key: &'b Q,
max_edit_dist: usize,
) -> FuzzyMut<'a, 'b, K, V, PREFIX_LEN> ⓘ
pub fn fuzzy_mut<'a, 'b, Q>( &'a mut self, key: &'b Q, max_edit_dist: usize, ) -> FuzzyMut<'a, 'b, K, V, PREFIX_LEN> ⓘ
Makes a fuzzy search in the tree by key
,
returning all keys and values that are
less than or equal to max_edit_dist
.
This is done by using Levenshtein distance
§Examples
Sourcepub fn contains_key<Q>(&self, key: &Q) -> bool
pub fn contains_key<Q>(&self, key: &Q) -> bool
Returns true if the map contains a value for the specified key.
§Examples
Sourcepub fn first_key_value(&self) -> Option<(&K, &V)>
pub fn first_key_value(&self) -> Option<(&K, &V)>
Returns the first key-value pair in the map. The key in this pair is the minimum key in the map.
If the tree is empty, returns None.
§Examples
Sourcepub fn pop_first(&mut self) -> Option<(K, V)>
pub fn pop_first(&mut self) -> Option<(K, V)>
Removes and returns the first element in the map. The key of this element is the minimum key that was in the map.
If the tree is empty, returns None.
§Examples
Sourcepub fn last_key_value(&self) -> Option<(&K, &V)>
pub fn last_key_value(&self) -> Option<(&K, &V)>
Returns the last key-value pair in the map. The key in this pair is the maximum key in the map.
If the tree is empty, returns None.
§Examples
Sourcepub fn pop_last(&mut self) -> Option<(K, V)>
pub fn pop_last(&mut self) -> Option<(K, V)>
Removes and returns the last element in the map. The key of this element is the maximum key that was in the map.
If the tree is empty, returns None.
§Examples
Sourcepub fn insert(&mut self, key: K, value: V) -> Option<V>where
K: NoPrefixesBytes,
pub fn insert(&mut self, key: K, value: V) -> Option<V>where
K: NoPrefixesBytes,
Insert a key-value pair into the map.
If the map did not have this key present, Ok(None) is returned.
If the map did have this key present, the value is updated, and the old value is returned.
Unlike try_insert
, this function will
not return an error, because the contract of the NoPrefixesBytes
ensures that the given key type will never be a prefix of an existing
value.
§Examples
Sourcepub fn try_insert(
&mut self,
key: K,
value: V,
) -> Result<Option<V>, InsertPrefixError>where
K: AsBytes,
pub fn try_insert(
&mut self,
key: K,
value: V,
) -> Result<Option<V>, InsertPrefixError>where
K: AsBytes,
Inserts a key-value pair into the map.
If the map did not have this key present, Ok(None) is returned.
If the map did have this key present, the value is updated, and the old value is returned.
§Errors
- If the map has an existing key, such that the new key is a prefix of the existing key or vice versa, then it returns an error.
§Examples
use blart::TreeMap;
let mut map = TreeMap::<Box<[u8]>, char>::new();
assert!(map.try_insert(Box::new([1, 2, 3]), 'a').unwrap().is_none());
assert!(map.try_insert(Box::new([2, 3, 4]), 'b').unwrap().is_none());
// This function call errors because the key is a prefix of the existing key
assert!(map.try_insert(Box::new([2, 3, 4, 5]), 'c').is_err());
assert_eq!(map.try_insert(Box::new([2, 3, 4]), 'd').unwrap(), Some('b'));
assert_eq!(map.len(), 2);
Sourcepub fn remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V)>
pub fn remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V)>
Removes a key from the map, returning the stored key and value if the key was previously in the map.
§Examples
Sourcepub fn remove<Q>(&mut self, key: &Q) -> Option<V>
pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
Removes a key from the map, returning the value at the key if the key was previously in the map.
§Examples
Sourcepub fn range<Q, R>(&self, range: R) -> Range<'_, K, V, PREFIX_LEN> ⓘ
pub fn range<Q, R>(&self, range: R) -> Range<'_, K, V, PREFIX_LEN> ⓘ
Constructs a double-ended iterator over a sub-range of elements in the map.
The simplest way is to use the range syntax min..max
, thus
range(min..max)
will yield elements from min (inclusive) to max
(exclusive). The range may also be entered as (Bound<T>, Bound<T>)
, so
for example range((Excluded(4), Included(10)))
will yield a
left-exclusive, right-inclusive range from 4 to 10.
§Examples
use blart::TreeMap;
use std::ops::Bound::Included;
let mut map = TreeMap::<u8, _>::new();
map.try_insert(3, "a").unwrap();
map.try_insert(5, "b").unwrap();
map.try_insert(8, "c").unwrap();
for (key, &value) in map.range((Included(&4), Included(&8))) {
println!("{key:?}: {value}");
}
assert_eq!(map.range(&4..).next(), Some((&5, &"b")));
Sourcepub fn range_mut<Q, R>(&mut self, range: R) -> RangeMut<'_, K, V, PREFIX_LEN> ⓘ
pub fn range_mut<Q, R>(&mut self, range: R) -> RangeMut<'_, K, V, PREFIX_LEN> ⓘ
Constructs a mutable double-ended iterator over a sub-range of elements in the map.
The simplest way is to use the range syntax min..max
, thus
range_mut(min..max)
will yield elements from min (inclusive) to max
(exclusive). The range may also be entered as (Bound<T>, Bound<T>)
, so
for example range_mut((Excluded(4), Included(10)))
will yield a
left-exclusive, right-inclusive range from 4 to 10.
§Examples
use blart::TreeMap;
let mut map: TreeMap<_, i32> = TreeMap::new();
for (key, value) in [("Alice", 0), ("Bob", 0), ("Carol", 0), ("Cheryl", 0)] {
let _ = map.try_insert(key, value).unwrap();
}
for (name, balance) in map.range_mut("B"..="Cheryl") {
*balance += 100;
if name.starts_with('C') {
*balance *= 2;
}
}
for (name, balance) in &map {
println!("{name} => {balance}");
}
assert_eq!(map["Alice"], 0);
assert_eq!(map["Bob"], 100);
assert_eq!(map["Carol"], 200);
assert_eq!(map["Cheryl"], 200);
Sourcepub fn into_keys(self) -> IntoKeys<K, V, PREFIX_LEN> ⓘ
pub fn into_keys(self) -> IntoKeys<K, V, PREFIX_LEN> ⓘ
Creates a consuming iterator visiting all the keys, in sorted order. The
map cannot be used after calling this. The iterator element type is K
.
§Examples
use blart::TreeMap;
let map: TreeMap<_, char> = ['d', 'c', 'b', 'a', 'z'].into_iter()
.enumerate()
.collect();
let mut iter = map.into_keys();
assert_eq!(iter.next().unwrap(), 0);
assert_eq!(iter.next().unwrap(), 1);
assert_eq!(iter.next().unwrap(), 2);
assert_eq!(iter.next().unwrap(), 3);
assert_eq!(iter.next().unwrap(), 4);
assert_eq!(iter.next(), None);
Sourcepub fn into_values(self) -> IntoValues<K, V, PREFIX_LEN> ⓘ
pub fn into_values(self) -> IntoValues<K, V, PREFIX_LEN> ⓘ
Creates a consuming iterator visiting all the values, in order by key.
The map cannot be used after calling this. The iterator element type is
V
.
§Examples
use blart::TreeMap;
let map: TreeMap<_, char> = ['d', 'c', 'b', 'a', 'z'].into_iter()
.enumerate()
.collect();
let mut iter = map.into_values();
assert_eq!(iter.next().unwrap(), 'd');
assert_eq!(iter.next().unwrap(), 'c');
assert_eq!(iter.next().unwrap(), 'b');
assert_eq!(iter.next().unwrap(), 'a');
assert_eq!(iter.next().unwrap(), 'z');
assert_eq!(iter.next(), None);
Sourcepub fn iter(&self) -> Iter<'_, K, V, PREFIX_LEN> ⓘ
pub fn iter(&self) -> Iter<'_, K, V, PREFIX_LEN> ⓘ
Gets an iterator over the entries of the map, sorted by key.
§Examples
use blart::TreeMap;
let map: TreeMap<_, char> = ['d', 'c', 'b', 'a', 'z'].into_iter()
.enumerate()
.collect();
let mut iter = map.iter();
assert_eq!(iter.next().unwrap(), (&0, &'d'));
assert_eq!(iter.next().unwrap(), (&1, &'c'));
assert_eq!(iter.next().unwrap(), (&2, &'b'));
assert_eq!(iter.next().unwrap(), (&3, &'a'));
assert_eq!(iter.next().unwrap(), (&4, &'z'));
assert_eq!(iter.next(), None);
Sourcepub fn iter_mut(&mut self) -> IterMut<'_, K, V, PREFIX_LEN> ⓘ
pub fn iter_mut(&mut self) -> IterMut<'_, K, V, PREFIX_LEN> ⓘ
Gets a mutable iterator over the entries of the map, sorted by key.
§Examples
use blart::TreeMap;
let mut map: TreeMap<_, char> = ['d', 'c', 'b', 'a', 'z'].into_iter()
.enumerate()
.collect();
for (_key, value) in map.iter_mut() {
value.make_ascii_uppercase();
}
assert_eq!(map[&0], 'D');
assert_eq!(map[&1], 'C');
assert_eq!(map[&2], 'B');
assert_eq!(map[&3], 'A');
assert_eq!(map[&4], 'Z');
Sourcepub fn keys(&self) -> Keys<'_, K, V, PREFIX_LEN> ⓘ
pub fn keys(&self) -> Keys<'_, K, V, PREFIX_LEN> ⓘ
Gets an iterator over the keys of the map, in sorted order.
§Examples
use blart::TreeMap;
let map: TreeMap<_, char> = ['d', 'c', 'b', 'a', 'z'].into_iter()
.enumerate()
.collect();
let mut iter = map.keys();
assert_eq!(iter.next().unwrap(), &0);
assert_eq!(iter.next().unwrap(), &1);
assert_eq!(iter.next().unwrap(), &2);
assert_eq!(iter.next().unwrap(), &3);
assert_eq!(iter.next().unwrap(), &4);
assert_eq!(iter.next(), None);
Sourcepub fn values(&self) -> Values<'_, K, V, PREFIX_LEN> ⓘ
pub fn values(&self) -> Values<'_, K, V, PREFIX_LEN> ⓘ
Gets an iterator over the values of the map, in order by key.
§Examples
use blart::TreeMap;
let map: TreeMap<_, char> = ['d', 'c', 'b', 'a', 'z'].into_iter()
.enumerate()
.collect();
let mut iter = map.values();
assert_eq!(iter.next().unwrap(), &'d');
assert_eq!(iter.next().unwrap(), &'c');
assert_eq!(iter.next().unwrap(), &'b');
assert_eq!(iter.next().unwrap(), &'a');
assert_eq!(iter.next().unwrap(), &'z');
assert_eq!(iter.next(), None);
Sourcepub fn values_mut(&mut self) -> ValuesMut<'_, K, V, PREFIX_LEN> ⓘ
pub fn values_mut(&mut self) -> ValuesMut<'_, K, V, PREFIX_LEN> ⓘ
Gets a mutable iterator over the values of the map, in order by key.
§Examples
use blart::TreeMap;
let mut map: TreeMap<_, char> = ['d', 'c', 'b', 'a', 'z'].into_iter()
.enumerate()
.collect();
for value in map.values_mut() {
value.make_ascii_uppercase();
}
assert_eq!(map[&0], 'D');
assert_eq!(map[&1], 'C');
assert_eq!(map[&2], 'B');
assert_eq!(map[&3], 'A');
assert_eq!(map[&4], 'Z');
Sourcepub fn prefix(&self, prefix: &[u8]) -> Prefix<'_, K, V, PREFIX_LEN> ⓘwhere
K: AsBytes,
pub fn prefix(&self, prefix: &[u8]) -> Prefix<'_, K, V, PREFIX_LEN> ⓘwhere
K: AsBytes,
Gets an iterator over the entries of the map that start with prefix
§Examples
use blart::TreeMap;
let mut map = TreeMap::new();
map.insert(c"abcde", 0);
map.insert(c"abcdexxx", 0);
map.insert(c"abcdexxy", 0);
map.insert(c"abcdx", 0);
map.insert(c"abcx", 0);
map.insert(c"bx", 0);
let p: Vec<_> = map.prefix(c"abcde".to_bytes()).collect();
assert_eq!(p, vec![(&c"abcde", &0), (&c"abcdexxx", &0), (&c"abcdexxy", &0)]);
Sourcepub fn prefix_mut(&mut self, prefix: &[u8]) -> PrefixMut<'_, K, V, PREFIX_LEN> ⓘwhere
K: AsBytes,
pub fn prefix_mut(&mut self, prefix: &[u8]) -> PrefixMut<'_, K, V, PREFIX_LEN> ⓘwhere
K: AsBytes,
Gets a mutable iterator over the entries of the map that start with
prefix
§Examples
use blart::TreeMap;
let mut map = TreeMap::new();
map.insert(c"abcde", 0);
map.insert(c"abcdexxx", 0);
map.insert(c"abcdexxy", 0);
map.insert(c"abcdx", 0);
map.insert(c"abcx", 0);
map.insert(c"bx", 0);
let p: Vec<_> = map.prefix_mut(c"abcde".to_bytes()).collect();
assert_eq!(p, vec![(&c"abcde", &mut 0), (&c"abcdexxx", &mut 0), (&c"abcdexxy", &mut 0)]);
Source§impl<K, V, const PREFIX_LEN: usize> TreeMap<K, V, PREFIX_LEN>
impl<K, V, const PREFIX_LEN: usize> TreeMap<K, V, PREFIX_LEN>
Sourcepub fn try_entry(
&mut self,
key: K,
) -> Result<Entry<'_, K, V, PREFIX_LEN>, InsertPrefixError>where
K: AsBytes,
pub fn try_entry(
&mut self,
key: K,
) -> Result<Entry<'_, K, V, PREFIX_LEN>, InsertPrefixError>where
K: AsBytes,
Tries to get the given key’s corresponding entry in the map for in-place manipulation.
Sourcepub fn try_entry_ref<'a, 'b, Q>(
&'a mut self,
key: &'b Q,
) -> Result<EntryRef<'a, 'b, K, V, Q, PREFIX_LEN>, InsertPrefixError>
pub fn try_entry_ref<'a, 'b, Q>( &'a mut self, key: &'b Q, ) -> Result<EntryRef<'a, 'b, K, V, Q, PREFIX_LEN>, InsertPrefixError>
Tries to get the given key’s corresponding entry in the map for in-place manipulation.
Sourcepub fn entry(&mut self, key: K) -> Entry<'_, K, V, PREFIX_LEN>where
K: NoPrefixesBytes,
pub fn entry(&mut self, key: K) -> Entry<'_, K, V, PREFIX_LEN>where
K: NoPrefixesBytes,
Gets the given key’s corresponding entry in the map for in-place manipulation.
Trait Implementations§
Source§impl<'a, K, V, const PREFIX_LEN: usize> Extend<(&'a K, &'a V)> for TreeMap<K, V, PREFIX_LEN>
impl<'a, K, V, const PREFIX_LEN: usize> Extend<(&'a K, &'a V)> for TreeMap<K, V, PREFIX_LEN>
Source§fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T)
fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T)
Source§fn extend_one(&mut self, item: A)
fn extend_one(&mut self, item: A)
extend_one
)Source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one
)Source§impl<K, V, const PREFIX_LEN: usize> Extend<(K, V)> for TreeMap<K, V, PREFIX_LEN>where
K: NoPrefixesBytes,
impl<K, V, const PREFIX_LEN: usize> Extend<(K, V)> for TreeMap<K, V, PREFIX_LEN>where
K: NoPrefixesBytes,
Source§fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T)
fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T)
Source§fn extend_one(&mut self, item: A)
fn extend_one(&mut self, item: A)
extend_one
)Source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one
)