predicator_rs/map.rs
1//! The crate's own map, over a `BTreeMap`, and its key.
2
3use crate::Value;
4use std::collections::BTreeMap;
5
6/// A map key: one of the four kinds the reference's instruction-set text
7/// lets index a map, a string, an integer, a boolean or undefined. (`null`
8/// is not one of the four; a lookup by `null` is a miss, not an error.)
9///
10/// Keys are totally ordered: undefined first, then `false` and `true`, then
11/// integers in numeric order, then strings in codepoint order. A map keeps
12/// its keys in this order.
13///
14/// ```
15/// use predicator_rs::Key;
16///
17/// let mut keys = vec![Key::from("a"), Key::from(2), Key::from(true), Key::Undefined];
18/// keys.sort();
19/// assert_eq!(keys, [Key::Undefined, Key::from(true), Key::from(2), Key::from("a")]);
20/// assert_eq!(format!("{:?}", keys), r#"[Undefined, true, 2, "a"]"#);
21/// ```
22#[non_exhaustive]
23#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
24pub enum Key {
25 /// The undefined key.
26 Undefined,
27 /// `false` or `true`.
28 Bool(bool),
29 /// An integer.
30 Integer(i64),
31 /// A string.
32 String(String),
33}
34
35impl std::fmt::Debug for Key {
36 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37 match self {
38 Key::Undefined => f.write_str("Undefined"),
39 Key::Bool(flag) => write!(f, "{flag}"),
40 Key::Integer(number) => write!(f, "{number}"),
41 Key::String(text) => write!(f, "{text:?}"),
42 }
43 }
44}
45
46impl From<&str> for Key {
47 fn from(text: &str) -> Key {
48 Key::String(text.to_owned())
49 }
50}
51
52impl From<String> for Key {
53 fn from(text: String) -> Key {
54 Key::String(text)
55 }
56}
57
58impl From<i64> for Key {
59 fn from(number: i64) -> Key {
60 Key::Integer(number)
61 }
62}
63
64impl From<bool> for Key {
65 fn from(flag: bool) -> Key {
66 Key::Bool(flag)
67 }
68}
69
70/// A predicator map: [`Key`]s, each with a [`Value`], kept in key order.
71///
72/// ```
73/// use predicator_rs::{Key, Map, Value};
74///
75/// let mut map = Map::new();
76/// map.insert("b", Value::Integer(2));
77/// map.insert("a", Value::Integer(1));
78/// map.insert(true, Value::Null);
79/// assert_eq!(map.len(), 3);
80/// assert_eq!(map.get(&"a".into()), Some(&Value::Integer(1)));
81/// assert_eq!(map.get(&Key::Integer(1)), None);
82/// assert_eq!(
83/// map.keys().collect::<Vec<_>>(),
84/// [&Key::from(true), &Key::from("a"), &Key::from("b")]
85/// );
86/// ```
87#[derive(Clone, Default, PartialEq)]
88pub struct Map {
89 pub(crate) entries: BTreeMap<Key, Value>,
90}
91
92impl Map {
93 /// An empty map.
94 ///
95 /// ```
96 /// use predicator_rs::Map;
97 ///
98 /// assert!(Map::new().is_empty());
99 /// ```
100 pub fn new() -> Map {
101 Map::default()
102 }
103
104 /// How many keys the map holds.
105 ///
106 /// ```
107 /// use predicator_rs::{Map, Value};
108 ///
109 /// let map: Map = [("a", Value::Null), ("b", Value::Null)].into_iter().collect();
110 /// assert_eq!(map.len(), 2);
111 /// ```
112 pub fn len(&self) -> usize {
113 self.entries.len()
114 }
115
116 /// Whether the map holds no keys.
117 ///
118 /// ```
119 /// use predicator_rs::{Map, Value};
120 ///
121 /// let mut map = Map::new();
122 /// assert!(map.is_empty());
123 /// map.insert("a", Value::Null);
124 /// assert!(!map.is_empty());
125 /// ```
126 pub fn is_empty(&self) -> bool {
127 self.entries.is_empty()
128 }
129
130 /// The value at `key`, if the map holds it.
131 ///
132 /// ```
133 /// use predicator_rs::{Key, Map, Value};
134 ///
135 /// let map: Map = [(1, Value::from("x"))].into_iter().collect();
136 /// assert_eq!(map.get(&Key::from(1)), Some(&Value::from("x")));
137 /// assert_eq!(map.get(&Key::from("1")), None);
138 /// ```
139 pub fn get(&self, key: &Key) -> Option<&Value> {
140 self.entries.get(key)
141 }
142
143 /// The value at `key`, mutably, if the map holds it.
144 ///
145 /// ```
146 /// use predicator_rs::{Key, Map, Value};
147 ///
148 /// let mut map: Map = [("a", Value::from(1))].into_iter().collect();
149 /// if let Some(value) = map.get_mut(&Key::from("a")) {
150 /// *value = Value::from(2);
151 /// }
152 /// assert_eq!(map.get(&Key::from("a")), Some(&Value::from(2)));
153 /// ```
154 pub fn get_mut(&mut self, key: &Key) -> Option<&mut Value> {
155 self.entries.get_mut(key)
156 }
157
158 /// Whether the map holds `key`.
159 ///
160 /// ```
161 /// use predicator_rs::{Key, Map, Value};
162 ///
163 /// let map: Map = [(true, Value::Null)].into_iter().collect();
164 /// assert!(map.contains_key(&Key::from(true)));
165 /// assert!(!map.contains_key(&Key::from(false)));
166 /// ```
167 pub fn contains_key(&self, key: &Key) -> bool {
168 self.entries.contains_key(key)
169 }
170
171 /// Puts `value` at `key`, answering the value it replaces.
172 ///
173 /// ```
174 /// use predicator_rs::{Map, Value};
175 ///
176 /// let mut map = Map::new();
177 /// assert_eq!(map.insert("a", Value::from(1)), None);
178 /// assert_eq!(map.insert("a", Value::from(2)), Some(Value::from(1)));
179 /// ```
180 pub fn insert(&mut self, key: impl Into<Key>, value: Value) -> Option<Value> {
181 self.entries.insert(key.into(), value)
182 }
183
184 /// Takes the value at `key` out of the map.
185 ///
186 /// ```
187 /// use predicator_rs::{Key, Map, Value};
188 ///
189 /// let mut map: Map = [("a", Value::from(1))].into_iter().collect();
190 /// assert_eq!(map.remove(&Key::from("a")), Some(Value::from(1)));
191 /// assert_eq!(map.remove(&Key::from("a")), None);
192 /// ```
193 pub fn remove(&mut self, key: &Key) -> Option<Value> {
194 self.entries.remove(key)
195 }
196
197 /// The keys and values, in key order.
198 ///
199 /// ```
200 /// use predicator_rs::{Key, Map, Value};
201 ///
202 /// let map: Map = [("b", Value::from(2)), ("a", Value::from(1))].into_iter().collect();
203 /// let pairs: Vec<_> = map.iter().collect();
204 /// assert_eq!(pairs[0], (&Key::from("a"), &Value::from(1)));
205 /// ```
206 pub fn iter(&self) -> impl Iterator<Item = (&Key, &Value)> {
207 self.entries.iter()
208 }
209
210 /// The keys, in order.
211 ///
212 /// ```
213 /// use predicator_rs::{Key, Map, Value};
214 ///
215 /// let map: Map = [(Key::from("a"), Value::Null), (Key::from(2), Value::Null)]
216 /// .into_iter()
217 /// .collect();
218 /// assert_eq!(map.keys().collect::<Vec<_>>(), [&Key::from(2), &Key::from("a")]);
219 /// ```
220 pub fn keys(&self) -> impl Iterator<Item = &Key> {
221 self.entries.keys()
222 }
223
224 /// The values, in key order.
225 ///
226 /// ```
227 /// use predicator_rs::{Map, Value};
228 ///
229 /// let map: Map = [("b", Value::from(2)), ("a", Value::from(1))].into_iter().collect();
230 /// assert_eq!(map.values().collect::<Vec<_>>(), [&Value::from(1), &Value::from(2)]);
231 /// ```
232 pub fn values(&self) -> impl Iterator<Item = &Value> {
233 self.entries.values()
234 }
235
236 /// The value at the string key `key`.
237 pub(crate) fn get_str(&self, key: &str) -> Option<&Value> {
238 self.entries.get(&Key::String(key.to_owned()))
239 }
240}
241
242impl std::fmt::Debug for Map {
243 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
244 f.debug_map().entries(self.entries.iter()).finish()
245 }
246}
247
248impl<K: Into<Key>> FromIterator<(K, Value)> for Map {
249 /// A map of the pairs; a key given twice keeps its last value.
250 fn from_iter<I: IntoIterator<Item = (K, Value)>>(pairs: I) -> Map {
251 Map {
252 entries: pairs
253 .into_iter()
254 .map(|(key, value)| (key.into(), value))
255 .collect(),
256 }
257 }
258}
259
260impl IntoIterator for Map {
261 type Item = (Key, Value);
262 type IntoIter = std::collections::btree_map::IntoIter<Key, Value>;
263
264 /// The keys and values, by value, in key order.
265 fn into_iter(self) -> Self::IntoIter {
266 self.entries.into_iter()
267 }
268}
269
270#[cfg(test)]
271mod tests {
272 use super::*;
273
274 // Sabotage: with Map::remove answering None without removing, this
275 // test fails.
276 #[test]
277 fn a_map_keeps_its_keys_in_key_order() {
278 let mut map: Map = [("é", Value::Null), ("z", Value::Null), ("a", Value::Null)]
279 .into_iter()
280 .collect();
281 map.insert(Key::Undefined, Value::Null);
282 map.insert(-3, Value::Null);
283 map.insert(false, Value::Null);
284 assert_eq!(
285 map.keys().collect::<Vec<_>>(),
286 [
287 &Key::Undefined,
288 &Key::from(false),
289 &Key::from(-3),
290 &Key::from("a"),
291 &Key::from("z"),
292 &Key::from("é")
293 ]
294 );
295 assert!(!map.is_empty());
296 assert!(map.contains_key(&"z".into()));
297 assert!(!map.contains_key(&Key::from(true)));
298 assert_eq!(map.insert("a", Value::Bool(true)), Some(Value::Null));
299 *map.get_mut(&"z".into()).unwrap() = Value::Integer(1);
300 assert_eq!(map.get_str("z"), Some(&Value::Integer(1)));
301 assert_eq!(map.get_str("q"), None);
302 assert_eq!(map.remove(&"é".into()), Some(Value::Null));
303 assert_eq!(map.remove(&"é".into()), None);
304 for key in [Key::Undefined, Key::from(false), Key::from(-3)] {
305 map.remove(&key);
306 }
307 assert_eq!(
308 map.iter().collect::<Vec<_>>(),
309 [
310 (&Key::from("a"), &Value::Bool(true)),
311 (&Key::from("z"), &Value::Integer(1))
312 ]
313 );
314 assert_eq!(map.values().count(), 2);
315 assert_eq!(format!("{map:?}"), r#"{"a": Bool(true), "z": Integer(1)}"#);
316 let owned: Vec<(Key, Value)> = map.into_iter().collect();
317 assert_eq!(owned.len(), 2);
318 assert!(Map::new().is_empty());
319 }
320
321 // Sabotage: with Key's variants declared strings first, this test fails.
322 #[test]
323 fn keys_order_undefined_booleans_integers_then_strings() {
324 let mut keys = vec![
325 Key::from("b"),
326 Key::from(i64::MAX),
327 Key::from("A"),
328 Key::from(true),
329 Key::from(i64::MIN),
330 Key::Undefined,
331 Key::from(false),
332 Key::from(String::from("a")),
333 ];
334 keys.sort();
335 assert_eq!(
336 format!("{keys:?}"),
337 format!(
338 r#"[Undefined, false, true, {}, {}, "A", "a", "b"]"#,
339 i64::MIN,
340 i64::MAX
341 )
342 );
343 }
344}