Skip to main content

yomi_core/value/
map.rs

1//! The contents of a `map` (`MapData`). Insertion order and an index, sharing and copy on write, and incremental tracking
2//! of the total size.
3
4use super::*;
5use hashbrown::HashTable;
6
7/// The contents of a `map`. Holds pairs of keys and values in insertion order, with an index for looking up keys (key →
8/// where the pair is stored).
9///
10/// - Lookup, update, insertion and removal take time proportional to the size of the key (not a linear search). Keys are
11///   compared and hashed as values, without converting them to strings.
12/// - Removal only empties the slot of the pair, without shifting the pairs after it. When the holes exceed the number of
13///   pairs, they are compacted at once (amortized constant time per removal). [`MapData::entries`] goes through the pairs
14///   in insertion order, skipping holes.
15/// - Cloning only shares the `Arc` (the first update after cloning copies the contents). Reading a huge `map` does not
16///   mean copying the whole thing every time. A clone is independent of the original (value semantics).
17/// - The index is not saved. It is rebuilt on restore (`From<Vec<_>>`, `Deserialize`).
18/// - Keeps the total size of the pairs (the estimate of [`Value::approx_bytes`]) incrementally, so checking value sizes is
19///   not proportional to the size of the `map`. When a value inside nesting is updated, the outer side reports it with
20///   `adjust_bytes` (within the crate).
21/// - `==` does not compare insertion order (equal if they have the same values for the same keys).
22#[derive(Clone, Default)]
23pub struct MapData(Arc<MapInner>);
24
25/// Shows only the sequence of pairs (`[(key, value), …]`), without the index or holes (so the output is stable).
26impl std::fmt::Debug for MapData {
27    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
28        f.debug_list().entries(self.entries()).finish()
29    }
30}
31
32/// The contents of a `map` (pairs, index, total size).
33#[derive(Clone, Default)]
34pub(super) struct MapInner {
35    /// The slots of pairs (in insertion order). Removed slots stay as `None`, and are compacted when holes exceed `live`.
36    /// The last slot is never a hole (it shrinks when a removal empties the end).
37    slots: Vec<Option<Slot>>,
38    /// Key hash → index into `slots`. The key itself lives only in `slots`.
39    index: HashTable<usize>,
40    /// The number of pairs (the number of `Some` in `slots`).
41    live: usize,
42    /// The total size of the pairs (the sum of [`Value::approx_bytes`] of keys and values, not including the 24 of the `map`
43    /// itself). On each update, only the change is added or subtracted (no recounting).
44    bytes: usize,
45}
46
47#[derive(Clone)]
48struct Slot {
49    pair: (Value, Value),
50    /// The hash of the key. Kept so keys need not be rehashed when compacting.
51    hash: u64,
52}
53
54/// The iterator returned by [`MapData::entries`] that goes through the pairs in insertion order (skipping holes left by
55/// removals).
56#[derive(Clone)]
57pub struct MapEntries<'a> {
58    slots: std::slice::Iter<'a, Option<Slot>>,
59    remaining: usize,
60}
61
62impl<'a> Iterator for MapEntries<'a> {
63    type Item = &'a (Value, Value);
64    fn next(&mut self) -> Option<Self::Item> {
65        let e = self.slots.by_ref().flatten().next()?;
66        self.remaining -= 1;
67        Some(&e.pair)
68    }
69    fn size_hint(&self) -> (usize, Option<usize>) {
70        (self.remaining, Some(self.remaining))
71    }
72}
73
74impl DoubleEndedIterator for MapEntries<'_> {
75    fn next_back(&mut self) -> Option<Self::Item> {
76        let e = self.slots.by_ref().rev().flatten().next()?;
77        self.remaining -= 1;
78        Some(&e.pair)
79    }
80}
81
82impl ExactSizeIterator for MapEntries<'_> {}
83
84impl std::iter::FusedIterator for MapEntries<'_> {}
85
86/// Shows the sequence of remaining pairs.
87impl std::fmt::Debug for MapEntries<'_> {
88    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89        f.debug_list().entries(self.clone()).finish()
90    }
91}
92
93impl MapData {
94    /// An empty `map`.
95    pub fn new() -> Self {
96        Self::default()
97    }
98
99    /// Makes one from a sequence of pairs. If a key repeats, the later value updates it (the position stays the first one).
100    pub fn from_pairs(pairs: Vec<(Value, Value)>) -> Self {
101        let mut inner = MapInner {
102            slots: Vec::with_capacity(pairs.len()),
103            index: HashTable::with_capacity(pairs.len()),
104            live: 0,
105            bytes: 0,
106        };
107        for (k, v) in pairs {
108            inner.upsert(k, v);
109        }
110        Self(Arc::new(inner))
111    }
112
113    /// Goes through the pairs in insertion order.
114    pub fn entries(&self) -> MapEntries<'_> {
115        MapEntries {
116            slots: self.0.slots.iter(),
117            remaining: self.0.live,
118        }
119    }
120
121    /// Goes through the pairs in insertion order (same as [`MapData::entries`]).
122    pub fn iter(&self) -> MapEntries<'_> {
123        self.entries()
124    }
125
126    /// The number of pairs.
127    pub fn len(&self) -> usize {
128        self.0.live
129    }
130
131    /// Whether there are no pairs.
132    pub fn is_empty(&self) -> bool {
133        self.0.live == 0
134    }
135
136    /// Takes the pairs out (in insertion order). Does not copy the pairs if not shared.
137    pub fn into_entries(self) -> Vec<(Value, Value)> {
138        match Arc::try_unwrap(self.0) {
139            Ok(inner) => inner.slots.into_iter().flatten().map(|s| s.pair).collect(),
140            Err(shared) => shared
141                .slots
142                .iter()
143                .flatten()
144                .map(|s| s.pair.clone())
145                .collect(),
146        }
147    }
148
149    /// Whether the key exists.
150    pub fn contains_key(&self, key: &Value) -> bool {
151        self.slot(key).is_some()
152    }
153
154    /// The value of the key.
155    pub fn get(&self, key: &Value) -> Option<&Value> {
156        self.slot(key).map(|i| &self.0.entry(i).1)
157    }
158
159    /// The slot of the key's pair (passed to `value_mut` and `remove_at`; it may change on insertion and removal).
160    pub(crate) fn slot(&self, key: &Value) -> Option<usize> {
161        self.0.find(hash_of(key), key)
162    }
163
164    /// The slot of the key's pair. If missing, returns the hash of the key (passed to [`MapData::push_hashed`], so the hash is
165    /// not computed twice).
166    pub(crate) fn slot_or_hash(&self, key: &Value) -> Result<usize, u64> {
167        let hash = hash_of(key);
168        self.0.find(hash, key).ok_or(hash)
169    }
170
171    /// Compacts the holes left by removals, if any (copies the contents first if shared). Used for the copy that a `for`
172    /// iterates. After compacting, slots match positions in insertion order, so positions do not change across save and load.
173    pub(crate) fn compact_for_iteration(&mut self) {
174        if self.0.live != self.0.slots.len() {
175            Arc::make_mut(&mut self.0).compact();
176        }
177    }
178
179    /// The pair in slot `i` (`None` if out of range or a hole left by a removal).
180    pub(crate) fn entry_at(&self, i: usize) -> Option<&(Value, Value)> {
181        self.0.slots.get(i)?.as_ref().map(|s| &s.pair)
182    }
183
184    /// Appends a pair to the end when `slot_or_hash` returned a hash (the key is missing).
185    pub(crate) fn push_hashed(&mut self, hash: u64, key: Value, value: Value) {
186        Arc::make_mut(&mut self.0).push_entry(hash, key, value);
187    }
188
189    /// Returns the value in slot `i` in a mutable form (copies the contents first if shared).
190    pub(crate) fn value_mut(&mut self, i: usize) -> &mut Value {
191        &mut Arc::make_mut(&mut self.0).slots[i]
192            .as_mut()
193            .expect("組がある")
194            .pair
195            .1
196    }
197
198    /// If the key is missing, appends it and returns `true`; otherwise does nothing and returns `false`.
199    pub(crate) fn push_new(&mut self, key: Value, value: Value) -> bool {
200        let hash = hash_of(&key);
201        if self.0.find(hash, &key).is_some() {
202            return false;
203        }
204        Arc::make_mut(&mut self.0).push_entry(hash, key, value);
205        true
206    }
207
208    /// The total size of the pairs (not including the 24 of the `map` itself).
209    pub(crate) fn content_bytes(&self) -> usize {
210        self.0.bytes
211    }
212
213    /// After updating a value inside (modified via `value_mut`), corrects the total size of the pairs as having decreased by
214    /// `shrink` and increased by `grow`.
215    pub(crate) fn adjust_bytes(&mut self, shrink: usize, grow: usize) {
216        let inner = Arc::make_mut(&mut self.0);
217        inner.bytes = (inner.bytes + grow).saturating_sub(shrink);
218    }
219
220    /// Removes the pair in slot `i` (makes it a hole; compacts when there are too many holes).
221    pub(crate) fn remove_at(&mut self, i: usize) -> (Value, Value) {
222        let inner = Arc::make_mut(&mut self.0);
223        let Slot { pair: (k, v), hash } = inner.slots[i].take().expect("組がある");
224        inner.live -= 1;
225        inner.bytes = inner
226            .bytes
227            .saturating_sub(k.approx_bytes() + v.approx_bytes());
228        inner
229            .index
230            .find_entry(hash, |&j| j == i)
231            .expect("索引にある")
232            .remove();
233        while matches!(inner.slots.last(), Some(None)) {
234            inner.slots.pop();
235        }
236        if inner.slots.len() - inner.live > inner.live.max(COMPACT_MIN) {
237            inner.compact();
238        }
239        (k, v)
240    }
241
242    /// Whether it shares the same `Arc` (to confirm that a clone did not copy the contents; for tests).
243    #[doc(hidden)]
244    pub fn shares_storage_with(&self, other: &Self) -> bool {
245        Arc::ptr_eq(&self.0, &other.0)
246    }
247
248    /// Empties it.
249    pub(crate) fn clear(&mut self) {
250        self.0 = Arc::new(MapInner::default());
251    }
252
253    /// Whether the index, the order and the total size are consistent (for tests).
254    #[doc(hidden)]
255    pub fn is_consistent(&self) -> bool {
256        let inner = &*self.0;
257        let holes = inner.slots.len() - inner.live;
258        inner.bytes
259            == self
260                .entries()
261                .map(|(k, v)| k.approx_bytes() + v.approx_bytes())
262                .sum::<usize>()
263            && inner.slots.iter().flatten().count() == inner.live
264            && inner.index.len() == inner.live
265            && !matches!(inner.slots.last(), Some(None))
266            && holes <= inner.live.max(COMPACT_MIN)
267            && inner.slots.iter().enumerate().all(|(i, e)| {
268                e.as_ref()
269                    .is_none_or(|s| s.hash == hash_of(&s.pair.0) && self.slot(&s.pair.0) == Some(i))
270            })
271    }
272}
273
274/// With fewer holes than this, do not compact even if there are few pairs (so small `map`s do not compact repeatedly).
275const COMPACT_MIN: usize = 8;
276
277impl MapInner {
278    fn entry(&self, i: usize) -> &(Value, Value) {
279        &self.slots[i].as_ref().expect("組がある").pair
280    }
281
282    fn find(&self, hash: u64, key: &Value) -> Option<usize> {
283        let slots = &self.slots;
284        self.index
285            .find(hash, |&i| {
286                slots[i]
287                    .as_ref()
288                    .is_some_and(|s| s.hash == hash && key_eq(&s.pair.0, key))
289            })
290            .copied()
291    }
292
293    /// If the key exists, replaces the value; otherwise appends it (also updates the total size).
294    fn upsert(&mut self, key: Value, value: Value) {
295        let hash = hash_of(&key);
296        match self.find(hash, &key) {
297            Some(i) => {
298                let slot = &mut self.slots[i].as_mut().expect("組がある").pair.1;
299                self.bytes =
300                    (self.bytes + value.approx_bytes()).saturating_sub(slot.approx_bytes());
301                *slot = value;
302            }
303            None => self.push_entry(hash, key, value),
304        }
305    }
306
307    /// Appends the pair of a new key to the end (the caller makes sure the key is missing).
308    fn push_entry(&mut self, hash: u64, key: Value, value: Value) {
309        self.bytes += key.approx_bytes() + value.approx_bytes();
310        let slots = &self.slots;
311        self.index.insert_unique(hash, slots.len(), |&i| {
312            slots[i].as_ref().expect("組がある").hash
313        });
314        self.slots.push(Some(Slot {
315            pair: (key, value),
316            hash,
317        }));
318        self.live += 1;
319    }
320
321    /// Compacts the holes and rebuilds the index (keeps the order; uses the stored hashes without rehashing keys).
322    fn compact(&mut self) {
323        self.slots.retain(Option::is_some);
324        self.index.clear();
325        let slots = &self.slots;
326        for (i, s) in slots.iter().flatten().enumerate() {
327            self.index
328                .insert_unique(s.hash, i, |&j| slots[j].as_ref().expect("組がある").hash);
329        }
330    }
331}
332
333fn hash_of(key: &Value) -> u64 {
334    use std::hash::{BuildHasher, Hasher};
335    let mut h = rustc_hash::FxBuildHasher.build_hasher();
336    hash_key(key, &mut h);
337    h.finish()
338}
339
340/// The hash of a key. Keys that are equal by [`key_eq`] have the same hash.
341fn hash_key<H: std::hash::Hasher>(v: &Value, h: &mut H) {
342    use std::hash::Hash;
343    match v {
344        Value::Int(n) => (0u8, n).hash(h),
345        Value::Bool(b) => (1u8, b).hash(h),
346        Value::Str(t) => (2u8, &**t).hash(h),
347        Value::Identity(i) => (3u8, &i.id, &i.name).hash(h),
348        Value::Struct(st) => {
349            (4u8, &*st.ty, st.fields.len()).hash(h);
350            for (_, f) in st.fields.iter() {
351                hash_key(f, h);
352            }
353        }
354        Value::Enum(e) => {
355            (5u8, &*e.ty, &*e.variant, e.args.len()).hash(h);
356            for a in e.args.iter() {
357                hash_key(a, h);
358            }
359        }
360        // Types that cannot be keys (rejected by type checking). Uses the same equivalence as `key_repr`
361        other => (6u8, other.key_repr()).hash(h),
362    }
363}
364
365/// Whether two keys are equal (the same as equal `key_repr`; for `struct`s, field names are not compared).
366fn key_eq(a: &Value, b: &Value) -> bool {
367    match (a, b) {
368        (Value::Int(x), Value::Int(y)) => x == y,
369        (Value::Bool(x), Value::Bool(y)) => x == y,
370        (Value::Str(x), Value::Str(y)) => x == y,
371        (Value::Identity(x), Value::Identity(y)) => x.id == y.id && x.name == y.name,
372        (Value::Struct(s1), Value::Struct(s2)) => {
373            s1.ty == s2.ty
374                && s1.fields.len() == s2.fields.len()
375                && s1
376                    .fields
377                    .iter()
378                    .zip(s2.fields.iter())
379                    .all(|((_, x), (_, y))| key_eq(x, y))
380        }
381        (Value::Enum(e1), Value::Enum(e2)) => {
382            e1.ty == e2.ty
383                && e1.variant == e2.variant
384                && e1.args.len() == e2.args.len()
385                && e1
386                    .args
387                    .iter()
388                    .zip(e2.args.iter())
389                    .all(|(x, y)| key_eq(x, y))
390        }
391        (
392            Value::Int(_)
393            | Value::Bool(_)
394            | Value::Str(_)
395            | Value::Identity(_)
396            | Value::Struct(_)
397            | Value::Enum(_),
398            _,
399        )
400        | (
401            _,
402            Value::Int(_)
403            | Value::Bool(_)
404            | Value::Str(_)
405            | Value::Identity(_)
406            | Value::Struct(_)
407            | Value::Enum(_),
408        ) => false,
409        _ => a.key_repr() == b.key_repr(),
410    }
411}
412
413impl<'a> IntoIterator for &'a MapData {
414    type Item = &'a (Value, Value);
415    type IntoIter = MapEntries<'a>;
416    fn into_iter(self) -> Self::IntoIter {
417        self.entries()
418    }
419}
420
421impl From<Vec<(Value, Value)>> for MapData {
422    fn from(pairs: Vec<(Value, Value)>) -> Self {
423        Self::from_pairs(pairs)
424    }
425}
426
427impl PartialEq for MapData {
428    fn eq(&self, other: &Self) -> bool {
429        if Arc::ptr_eq(&self.0, &other.0) {
430            return true;
431        }
432        // Insertion order is not compared (keys do not repeat, so they are equal if every pair of one is in the other)
433        self.len() == other.len()
434            && self
435                .iter()
436                .all(|(k, v)| other.get(k).is_some_and(|v2| v == v2))
437    }
438}
439
440impl Serialize for MapData {
441    fn serialize<S: serde::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
442        ser.collect_seq(self.entries())
443    }
444}
445
446impl<'de> Deserialize<'de> for MapData {
447    fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
448        Ok(Self::from_pairs(Vec::<(Value, Value)>::deserialize(de)?))
449    }
450}
451
452#[cfg(test)]
453mod tests {
454    use super::*;
455
456    fn keys(m: &MapData) -> Vec<Value> {
457        m.entries().map(|(k, _)| k.clone()).collect()
458    }
459
460    #[test]
461    fn iteration_and_lookup_work_in_insertion_order_after_removal() {
462        let mut m = MapData::new();
463        for i in 0..10 {
464            assert!(m.push_new(Value::Int(i), Value::Int(i * 10)));
465        }
466        for i in [0, 5, 9, 3] {
467            let p = m.slot(&Value::Int(i)).unwrap();
468            m.remove_at(p);
469            assert!(m.is_consistent());
470        }
471        assert_eq!(keys(&m), [1, 2, 4, 6, 7, 8].map(Value::Int).to_vec());
472        assert_eq!(m.len(), 6);
473        assert_eq!(m.entries().len(), 6);
474        assert_eq!(m.entries().next_back().map(|e| &e.0), Some(&Value::Int(8)));
475        assert_eq!(m.get(&Value::Int(7)), Some(&Value::Int(70)));
476        assert!(!m.contains_key(&Value::Int(5)));
477        m.push_new(Value::Int(5), Value::Int(0));
478        assert_eq!(keys(&m).last(), Some(&Value::Int(5)));
479        assert!(m.is_consistent());
480    }
481
482    #[test]
483    fn compacts_when_holes_grow() {
484        let mut m = MapData::new();
485        for i in 0..100 {
486            m.push_new(Value::Int(i), Value::Int(i));
487        }
488        for i in 0..90 {
489            let p = m.slot(&Value::Int(i)).unwrap();
490            m.remove_at(p);
491            assert!(m.is_consistent(), "{i}");
492        }
493        assert!(m.0.slots.len() <= 10 + COMPACT_MIN);
494        assert_eq!(keys(&m), (90..100).map(Value::Int).collect::<Vec<_>>());
495        for i in 90..100 {
496            let p = m.slot(&Value::Int(i)).unwrap();
497            m.remove_at(p);
498        }
499        assert!(m.is_empty() && m.0.slots.is_empty() && m.is_consistent());
500    }
501
502    #[test]
503    fn removing_from_shared_clone_does_not_affect_original() {
504        let mut a = MapData::from_pairs((0..20).map(|i| (Value::Int(i), Value::Int(i))).collect());
505        let b = a.clone();
506        let p = a.slot(&Value::Int(3)).unwrap();
507        a.remove_at(p);
508        assert_eq!(b.len(), 20);
509        assert!(b.contains_key(&Value::Int(3)) && !a.contains_key(&Value::Int(3)));
510        assert!(a.is_consistent() && b.is_consistent());
511    }
512
513    #[test]
514    fn key_equality_matches_string_representation() {
515        let s = |t: &str| Value::Str(t.into());
516        let st = |name: &str, v: i64| {
517            Value::Struct(std::sync::Arc::new(StructValue {
518                ty: "点".into(),
519                fields: vec![(name.into(), Value::Int(v))],
520            }))
521        };
522        let vals = [
523            Value::Int(1),
524            Value::Bool(true),
525            s("1"),
526            s("i1;"),
527            st("x", 1),
528            st("y", 1),
529            st("x", 2),
530            Value::Float(1.0),
531        ];
532        for a in &vals {
533            for b in &vals {
534                let same = a.key_repr() == b.key_repr();
535                assert_eq!(key_eq(a, b), same, "{a:?} と {b:?}");
536                if same {
537                    assert_eq!(hash_of(a), hash_of(b), "{a:?} と {b:?}");
538                }
539            }
540        }
541    }
542}