Skip to main content

neo_types/
map.rs

1use std::vec::Vec;
2
3#[cfg(feature = "serde")]
4use serde::{Deserialize, Serialize};
5
6/// Neo N3 Map type
7#[derive(Debug, Clone, PartialEq, Eq)]
8#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9#[cfg_attr(
10    feature = "serde",
11    serde(bound(
12        serialize = "K: Serialize + Eq, V: Serialize",
13        deserialize = "K: Deserialize<'de> + Eq, V: Deserialize<'de>"
14    ))
15)]
16pub struct NeoMap<K, V> {
17    data: Vec<(K, V)>,
18}
19
20impl<K, V> NeoMap<K, V> {
21    pub fn new() -> Self {
22        Self { data: Vec::new() }
23    }
24
25    pub fn insert(&mut self, key: K, value: V) -> Option<V>
26    where
27        K: PartialEq,
28    {
29        for (k, v) in &mut self.data {
30            if *k == key {
31                return Some(core::mem::replace(v, value));
32            }
33        }
34        self.data.push((key, value));
35        None
36    }
37
38    /// Gets a reference to the value associated with the given key.
39    ///
40    /// # Performance
41    /// This operation is O(n) as it performs a linear search.
42    /// Consider using a HashMap for O(1) lookups if performance is critical.
43    pub fn get(&self, key: &K) -> Option<&V>
44    where
45        K: PartialEq,
46    {
47        self.data.iter().find(|(k, _)| k == key).map(|(_, v)| v)
48    }
49
50    /// Gets a mutable reference to the value associated with the given key.
51    ///
52    /// # Performance
53    /// This operation is O(n) as it performs a linear search.
54    pub fn get_mut(&mut self, key: &K) -> Option<&mut V>
55    where
56        K: PartialEq,
57    {
58        self.data.iter_mut().find(|(k, _)| k == key).map(|(_, v)| v)
59    }
60
61    /// Removes the key-value pair associated with the given key.
62    ///
63    /// # Performance
64    /// This operation is O(n) due to the element removal.
65    pub fn remove(&mut self, key: &K) -> Option<V>
66    where
67        K: PartialEq,
68    {
69        self.data
70            .iter()
71            .position(|(k, _)| k == key)
72            .map(|i| self.data.swap_remove(i).1)
73    }
74
75    pub fn len(&self) -> usize {
76        self.data.len()
77    }
78
79    pub fn is_empty(&self) -> bool {
80        self.data.is_empty()
81    }
82
83    pub fn iter(&self) -> impl Iterator<Item = (&K, &V)> {
84        self.data.iter().map(|(k, v)| (k, v))
85    }
86
87    /// Returns an iterator over the keys of the map
88    pub fn keys(&self) -> impl Iterator<Item = &K> {
89        self.data.iter().map(|(k, _)| k)
90    }
91
92    /// Returns an iterator over the values of the map
93    pub fn values(&self) -> impl Iterator<Item = &V> {
94        self.data.iter().map(|(_, v)| v)
95    }
96}
97
98impl<K, V> Default for NeoMap<K, V> {
99    fn default() -> Self {
100        Self::new()
101    }
102}