discrimination_tree/
util.rs1use std::fmt;
2
3#[derive(Clone)]
4pub(crate) struct SortedMap<K, V> {
5 items: Vec<(K, V)>,
6}
7
8impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for SortedMap<K, V> {
9 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10 self.items.fmt(f)
11 }
12}
13
14impl<K, V> Default for SortedMap<K, V> {
15 fn default() -> Self {
16 Self { items: vec![] }
17 }
18}
19
20impl<K: Ord, V> SortedMap<K, V> {
21 pub(crate) fn get(&self, key: &K) -> Option<&V> {
22 match self.items.binary_search_by(|(k, _)| k.cmp(key)) {
23 Ok(index) => Some(&self.items[index].1),
24 Err(_) => None,
25 }
26 }
27
28 pub(crate) fn get_or_insert_with<F: FnOnce() -> V>(
29 &mut self,
30 key: K,
31 insert: F,
32 ) -> &mut V {
33 let index = match self.items.binary_search_by(|(k, _)| k.cmp(&key)) {
34 Ok(index) => index,
35 Err(index) => {
36 self.items.insert(index, (key, insert()));
37 index
38 }
39 };
40 &mut self.items[index].1
41 }
42
43 pub(crate) fn iter(&self) -> impl Iterator<Item = &(K, V)> {
44 self.items.iter()
45 }
46}