Skip to main content

tilo_resource/
map.rs

1//! A map from string keys whose clones share it chunk by chunk: [`Map`],
2//! for a state field keyed by name (where the reader is in each book, the
3//! pictures a notebook shows by digest).
4
5use std::any::Any;
6use std::collections::BTreeMap;
7use std::fmt;
8
9use crate::chunk_map::ChunkMap;
10use crate::model::{ModelError, leaf_paths};
11use crate::path::{Edit, EditOp, Path, Segment, Settable};
12use crate::table::{MapEntries, MapIn, ModelTable};
13use crate::{Model, Shape};
14
15/// A map from string keys, sorted by key, stored and merged as a
16/// `BTreeMap<String, V>` is: one document map, reconciled key by key.
17///
18/// Clones share the entries in chunks of a few dozen: a copy costs a pointer
19/// per chunk, and a change copies only the chunk it touches while another
20/// clone still holds it. A state a view holds therefore costs the next
21/// change to the map one chunk, and a change elsewhere in the state none.
22#[derive(Clone)]
23pub struct Map<V> {
24    entries: ChunkMap<V>,
25}
26
27impl<V> Default for Map<V> {
28    fn default() -> Self {
29        Self {
30            entries: ChunkMap::default(),
31        }
32    }
33}
34
35impl<V: fmt::Debug> fmt::Debug for Map<V> {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        self.entries.fmt(f)
38    }
39}
40
41impl<V: PartialEq> PartialEq for Map<V> {
42    fn eq(&self, other: &Self) -> bool {
43        self.entries == other.entries
44    }
45}
46
47impl<V: Eq> Eq for Map<V> {}
48
49impl<V> Map<V> {
50    #[must_use]
51    pub fn new() -> Self {
52        Self::default()
53    }
54
55    #[must_use]
56    pub fn len(&self) -> usize {
57        self.entries.len()
58    }
59
60    #[must_use]
61    pub fn is_empty(&self) -> bool {
62        self.entries.is_empty()
63    }
64
65    /// The value at `key`.
66    #[must_use]
67    pub fn get(&self, key: &str) -> Option<&V> {
68        self.entries.get(key)
69    }
70
71    #[must_use]
72    pub fn contains_key(&self, key: &str) -> bool {
73        self.entries.contains_key(key)
74    }
75
76    /// The entries in key order.
77    pub fn iter(&self) -> impl Iterator<Item = (&String, &V)> {
78        self.entries.iter()
79    }
80
81    /// The keys in order.
82    pub fn keys(&self) -> impl Iterator<Item = &String> {
83        self.entries.iter().map(|(key, _)| key)
84    }
85
86    /// The values in key order.
87    pub fn values(&self) -> impl ExactSizeIterator<Item = &V> {
88        self.entries.values()
89    }
90
91    /// The value at `key`, to change. When a clone still shares its chunk,
92    /// the chunk is copied first, so the clone keeps seeing it as it was.
93    pub fn get_mut(&mut self, key: &str) -> Option<&mut V> {
94        self.entries.get_mut(key)
95    }
96
97    /// Put `value` at `key`; returns the value it replaced.
98    pub fn insert(&mut self, key: impl Into<String>, value: V) -> Option<V> {
99        self.entries.insert(key.into(), value)
100    }
101
102    /// Take the entry `key` out; returns its value.
103    pub fn remove(&mut self, key: &str) -> Option<V> {
104        self.entries.remove(key)
105    }
106
107    pub fn clear(&mut self) {
108        self.entries.clear();
109    }
110}
111
112impl<V> From<BTreeMap<String, V>> for Map<V> {
113    fn from(entries: BTreeMap<String, V>) -> Self {
114        Self {
115            entries: ChunkMap::from(entries),
116        }
117    }
118}
119
120impl<V: Clone> From<&Map<V>> for BTreeMap<String, V> {
121    fn from(map: &Map<V>) -> Self {
122        map.iter()
123            .map(|(key, value)| (key.clone(), value.clone()))
124            .collect()
125    }
126}
127
128impl<K: Into<String>, V> FromIterator<(K, V)> for Map<V> {
129    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
130        let sorted: BTreeMap<String, V> = iter
131            .into_iter()
132            .map(|(key, value)| (key.into(), value))
133            .collect();
134        Self::from(sorted)
135    }
136}
137
138impl<K: Into<String>, V> Extend<(K, V)> for Map<V> {
139    fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
140        for (key, value) in iter {
141            self.insert(key, value);
142        }
143    }
144}
145
146impl<T: 'static> MapEntries for Map<T> {
147    fn count(&self) -> usize {
148        self.entries.count()
149    }
150
151    fn each(&self, visit: &mut dyn FnMut(&str, &dyn Any)) {
152        self.entries.each(visit);
153    }
154
155    fn value(&self, key: &str) -> Option<&dyn Any> {
156        self.entries.value(key)
157    }
158
159    fn value_mut(&mut self, key: &str) -> Option<&mut dyn Any> {
160        self.entries.value_mut(key)
161    }
162
163    fn remove_key(&mut self, key: &str) {
164        self.entries.remove_key(key);
165    }
166
167    fn insert_filled(
168        &mut self,
169        key: String,
170        fill: &mut dyn FnMut(&mut dyn Any) -> Result<(), ModelError>,
171    ) -> Result<(), ModelError> {
172        self.entries.insert_filled(key, fill)
173    }
174
175    fn insert_moved(&mut self, key: String, staged: &mut dyn Any) -> Result<(), ModelError> {
176        self.entries.insert_moved(key, staged)
177    }
178
179    /// The keys of the chunks `self` and `before` do not share: a map
180    /// changed since it was cloned from `before` differs only there.
181    fn differing_keys<'a>(&'a self, before: &'a dyn Any) -> Option<Vec<&'a str>> {
182        let before = before.downcast_ref::<Self>()?;
183        Some(self.entries.differing_keys(&before.entries))
184    }
185}
186
187/// A map reconciled key by key, as a `BTreeMap<String, T>` is.
188impl<T: Model> Settable for Map<T> {}
189impl<T: Model> Model for Map<T> {
190    const SHAPE: Shape = Shape::Map(&T::SHAPE);
191    fn value_schema() -> serde_json::Value {
192        serde_json::json!({"type": "object"})
193    }
194    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
195        crate::FieldType::Map(Box::new(T::field_type(types)))
196    }
197    const CHECKS: bool = T::CHECKS;
198    const OPS: bool = T::OPS;
199    // Run by the functions of every map of string keys, over `T`'s table.
200    const TABLE: &'static ModelTable = &MapIn::<T, Self>::TABLE;
201    leaf_paths!();
202    crate::__table_functions!();
203    fn missing() -> Result<Self, ModelError> {
204        Ok(Self::new())
205    }
206}
207
208impl<R, T: Model> Path<R, Map<T>> {
209    /// The entry `key`, its own paths rooted here.
210    #[must_use]
211    pub fn key(&self, key: impl Into<String>) -> T::Paths<R> {
212        T::paths_at(self.child(Segment::Key(key.into())))
213    }
214
215    /// Remove the entry `key`.
216    #[must_use]
217    pub fn remove(&self, key: impl Into<String>) -> Edit<R> {
218        self.edit(EditOp::RemoveKey { key: key.into() })
219    }
220}