livesplit_core/util/
ordered_map.rs

1//! An ordered [`Map`] is a map where the iteration order of the key-value pairs is
2//! based on the order the pairs were inserted into the map.
3
4use crate::{platform::prelude::*, util::PopulateString};
5use core::{fmt, marker::PhantomData};
6use serde::{
7    de::{MapAccess, Visitor},
8    ser::SerializeMap,
9    Deserialize, Deserializer, Serialize, Serializer,
10};
11
12/// An ordered [`Map`] is a map where the iteration order of the key-value pairs is
13/// based on the order the pairs were inserted into the map.
14#[derive(Default, Clone, Debug, PartialEq, Eq)]
15pub struct Map<V>(Vec<(Box<str>, V)>);
16
17/// An iterator over the entries of the [`Map`].
18pub struct Iter<'a, V>(core::slice::Iter<'a, (Box<str>, V)>);
19
20impl<V> Map<V> {
21    /// Insert a key-value pair in the [`Map`].
22    pub fn insert<K>(&mut self, key: K, value: V)
23    where
24        K: PopulateString,
25    {
26        let as_str = key.as_str();
27        if let Some(index) = self.0.iter().position(|(k, _)| &**k == as_str) {
28            self.0[index].1 = value;
29        } else {
30            self.0.push((key.into_string().into(), value));
31        }
32    }
33
34    /// Return a reference to the value stored for key, if it is present, else [`None`].
35    pub fn get(&self, key: &str) -> Option<&V> {
36        if let Some(index) = self.0.iter().position(|(k, _)| &**k == key) {
37            Some(&self.0[index].1)
38        } else {
39            None
40        }
41    }
42
43    /// Get the given key’s corresponding entry in the [`Map`] for insertion
44    /// and/or in-place manipulation.
45    pub fn entry<K>(&mut self, key: K) -> Entry<'_, K, V>
46    where
47        K: PopulateString,
48    {
49        let as_str = key.as_str();
50        Entry {
51            index: self.0.iter().position(|(k, _)| &**k == as_str),
52            map: self,
53            key,
54        }
55    }
56
57    /// Remove the key-value pair equivalent to key.
58    pub fn shift_remove(&mut self, key: &str) {
59        if let Some(index) = self.0.iter().position(|(k, _)| &**k == key) {
60            self.0.remove(index);
61        }
62    }
63
64    /// Return an iterator over the key-value pairs of the [`Map`], in their order.
65    pub fn iter(&self) -> Iter<'_, V> {
66        Iter(self.0.iter())
67    }
68
69    /// Remove all key-value pairs in the [`Map`], while preserving its capacity.
70    pub fn clear(&mut self) {
71        self.0.clear();
72    }
73}
74
75/// Entry for an existing key-value pair or a vacant location to insert one.
76pub struct Entry<'a, K, V> {
77    map: &'a mut Map<V>,
78    index: Option<usize>,
79    key: K,
80}
81
82impl<'a, K, V> Entry<'a, K, V> {
83    /// Inserts a default-constructed value in the entry if it is vacant and
84    /// returns a mutable reference to it. Otherwise a mutable reference to
85    /// an already existent value is returned.
86    pub fn or_default(self) -> &'a mut V
87    where
88        K: PopulateString,
89        V: Default,
90    {
91        if let Some(index) = self.index {
92            &mut self.map.0[index].1
93        } else {
94            self.map
95                .0
96                .push((self.key.into_string().into(), Default::default()));
97            &mut self.map.0.last_mut().unwrap().1
98        }
99    }
100}
101
102impl<'a, V> Iterator for Iter<'a, V> {
103    type Item = (&'a str, &'a V);
104    fn next(&mut self) -> Option<Self::Item> {
105        self.0.next().map(|(a, b)| (&**a, b))
106    }
107}
108
109impl<V> Serialize for Map<V>
110where
111    V: Serialize,
112{
113    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
114    where
115        S: Serializer,
116    {
117        let mut map = serializer.serialize_map(Some(self.0.len()))?;
118        for (k, v) in self.iter() {
119            map.serialize_entry(k, v)?;
120        }
121        map.end()
122    }
123}
124
125impl<'de, V> Deserialize<'de> for Map<V>
126where
127    V: Deserialize<'de>,
128{
129    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
130    where
131        D: Deserializer<'de>,
132    {
133        deserializer.deserialize_map(IndexMapVisitor::new())
134    }
135}
136
137struct IndexMapVisitor<V> {
138    marker: PhantomData<fn() -> Map<V>>,
139}
140
141impl<V> IndexMapVisitor<V> {
142    fn new() -> Self {
143        IndexMapVisitor {
144            marker: PhantomData,
145        }
146    }
147}
148
149impl<'de, V> Visitor<'de> for IndexMapVisitor<V>
150where
151    V: Deserialize<'de>,
152{
153    type Value = Map<V>;
154
155    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
156        formatter.write_str("a map")
157    }
158
159    fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
160    where
161        M: MapAccess<'de>,
162    {
163        let mut map = Map(Vec::with_capacity(access.size_hint().unwrap_or(0)));
164
165        while let Some((key, value)) = access.next_entry::<String, _>()? {
166            map.insert(key, value);
167        }
168
169        Ok(map)
170    }
171}