eure_document/
map.rs

1use indexmap::IndexMap;
2
3use crate::prelude_internal::*;
4
5// TODO: Remove `pub`
6#[derive(Debug, Clone, Plural)]
7#[plural(len, is_empty, iter, into_iter, into_iter_ref, new)]
8pub struct Map<K, V>(pub IndexMap<K, V>);
9
10impl<K: Eq + std::hash::Hash, V: Eq> Eq for Map<K, V> {}
11impl<K: Eq + std::hash::Hash, V: PartialEq> PartialEq for Map<K, V> {
12    fn eq(&self, other: &Self) -> bool {
13        self.0 == other.0
14    }
15}
16
17impl<K: Eq + std::hash::Hash, V> FromIterator<(K, V)> for Map<K, V> {
18    fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
19        Self(IndexMap::from_iter(iter))
20    }
21}
22
23impl<K, V> Default for Map<K, V> {
24    fn default() -> Self {
25        Self(IndexMap::new())
26    }
27}
28
29impl<K: std::hash::Hash + Eq, V> Map<K, V> {
30    pub fn get(&self, key: &K) -> Option<&V> {
31        self.0.get(key)
32    }
33
34    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
35        self.0.insert(key, value)
36    }
37
38    /// O(1) removal, may reorder remaining keys.
39    /// Use when order doesn't matter (e.g., batch processing).
40    pub fn remove_fast(&mut self, key: &K) -> Option<V> {
41        self.0.swap_remove(key)
42    }
43
44    /// O(n) removal, preserves document order.
45    /// Use when order must be maintained.
46    pub fn remove_ordered(&mut self, key: &K) -> Option<V> {
47        self.0.shift_remove(key)
48    }
49
50    pub fn contains_key(&self, key: &K) -> bool {
51        self.0.contains_key(key)
52    }
53}
54
55impl Map<ObjectKey, NodeId> {
56    pub fn add(&mut self, key: ObjectKey, value: NodeId) -> Result<(), InsertErrorKind> {
57        match self.0.entry(key) {
58            indexmap::map::Entry::Occupied(e) => Err(InsertErrorKind::AlreadyAssigned {
59                key: e.key().clone(),
60            }),
61            indexmap::map::Entry::Vacant(e) => {
62                e.insert(value);
63                Ok(())
64            }
65        }
66    }
67
68    pub fn get_node_id(&self, key: &ObjectKey) -> Option<NodeId> {
69        self.0.get(key).copied()
70    }
71}