acme_graphs/grad/
store.rs

1/*
2    Appellation: gradient <module>
3    Contrib: FL03 <jo3mccain@icloud.com>
4*/
5use crate::NodeIndex;
6use acme::prelude::Store;
7use std::any::Any;
8use std::collections::btree_map::{BTreeMap, Entry};
9use std::ops::{Index, IndexMut};
10
11pub struct GradientStore<K = NodeIndex, V = Box<dyn Any>> {
12    store: BTreeMap<K, V>,
13}
14
15impl<K, V> Default for GradientStore<K, V>
16where
17    K: Ord,
18{
19    fn default() -> Self {
20        Self::new()
21    }
22}
23
24impl<K, V> GradientStore<K, V>
25where
26    K: Ord,
27{
28    pub fn new() -> Self {
29        Self {
30            store: BTreeMap::new(),
31        }
32    }
33
34    pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
35        self.store.entry(key)
36    }
37
38    pub fn or_insert(&mut self, key: K, value: V) -> &mut V {
39        self.store.entry(key).or_insert(value)
40    }
41}
42
43impl<K, T> Store<K, T> for GradientStore<K, T>
44where
45    K: Ord,
46{
47    fn get(&self, key: &K) -> Option<&T> {
48        self.store.get(key)
49    }
50
51    fn get_mut(&mut self, key: &K) -> Option<&mut T> {
52        self.store.get_mut(key)
53    }
54
55    fn insert(&mut self, key: K, value: T) -> Option<T> {
56        self.store.insert(key, value)
57    }
58
59    fn remove(&mut self, key: &K) -> Option<T> {
60        self.store.remove(key)
61    }
62}
63
64impl<K, T> Index<K> for GradientStore<K, T>
65where
66    K: Ord,
67{
68    type Output = T;
69
70    fn index(&self, key: K) -> &Self::Output {
71        self.store.get(&key).expect("Key not found")
72    }
73}
74
75impl<K, T> IndexMut<K> for GradientStore<K, T>
76where
77    K: Ord,
78{
79    fn index_mut(&mut self, key: K) -> &mut Self::Output {
80        self.store.get_mut(&key).expect("Key not found")
81    }
82}