Skip to main content

latexml_core/common/arena/
data.rs

1use std::{
2  any::type_name,
3  collections::hash_map::{Entry, IntoIter, Iter, IterMut, Keys},
4  fmt,
5  iter::IntoIterator,
6  ops::Index,
7};
8
9use rustc_hash::FxHashMap as HashMap;
10use string_interner::{Symbol, symbol::SymbolU32};
11
12use crate::common::arena;
13
14pub type SymStr = SymbolU32;
15
16// TODO: Are we heading in the right direction with this interface...
17// is there performance overhead from the extra wrap? It seems borderline usable...
18
19/// A convenience abstraction over a String-keyed HashMap
20///
21/// typically used for `HashMap<String,Stored>` states.
22/// The goal is to support both a string interface, as well as the interned tickets interface,
23/// while avoiding String allocations internally.
24#[derive(Clone)]
25pub struct SymHashMap<T>(pub HashMap<SymStr, T>);
26
27impl<T> Default for SymHashMap<T> {
28  fn default() -> Self { SymHashMap(HashMap::default()) }
29}
30
31impl<T> SymHashMap<T> {
32  #[inline]
33  pub fn len(&self) -> usize { self.0.len() }
34  #[inline]
35  pub fn is_empty(&self) -> bool { self.0.is_empty() }
36  #[inline]
37  // The `&str` PROBES (`get`/`get_mut`/`contains_key`/`remove`) resolve the
38  // key with `arena::get`, which does not intern: a key that was never
39  // interned cannot be in the map (every entry was minted through
40  // `insert`/`entry`, which still pin), so a negative probe leaves the arena
41  // unchanged instead of permanently growing it (handoff 2026-09-03 ยง2.3;
42  // the same invariant `state.rs` uses for the `:locked` twin).
43  pub fn get(&self, key: &str) -> Option<&T> {
44    let sym = arena::get(key)?;
45    self.0.get(&sym)
46  }
47  #[inline]
48  pub fn get_sym(&self, key: SymStr) -> Option<&T> { self.0.get(&key) }
49  #[inline]
50  pub fn get_mut(&mut self, key: &str) -> Option<&mut T> {
51    let sym = arena::get(key)?;
52    self.0.get_mut(&sym)
53  }
54  #[inline]
55  pub fn get_mut_sym(&mut self, key: SymStr) -> Option<&mut T> { self.0.get_mut(&key) }
56  #[inline]
57  pub fn contains_key(&self, key: &str) -> bool {
58    arena::get(key).is_some_and(|sym| self.0.contains_key(&sym))
59  }
60  #[inline]
61  pub fn contains_key_sym(&self, key: &SymStr) -> bool { self.0.contains_key(key) }
62  #[inline]
63  pub fn insert(&mut self, key: &str, value: T) { self.0.insert(arena::pin(key), value); }
64  #[inline]
65  pub fn insert_sym(&mut self, key: SymStr, value: T) { self.0.insert(key, value); }
66  #[inline]
67  pub fn remove(&mut self, key: &str) {
68    if let Some(sym) = arena::get(key) {
69      self.0.remove(&sym);
70    }
71  }
72  #[inline]
73  pub fn remove_sym(&mut self, key: SymStr) { self.0.remove(&key); }
74  #[inline]
75  pub fn keys(&self) -> Keys<'_, SymStr, T> { self.0.keys() }
76  #[inline]
77  pub fn entry(&mut self, key: &str) -> Entry<'_, SymStr, T> { self.0.entry(arena::pin(key)) }
78  #[inline]
79  pub fn entry_sym(&mut self, key: SymStr) -> Entry<'_, SymStr, T> { self.0.entry(key) }
80  #[inline]
81  pub fn iter(&self) -> Iter<'_, SymStr, T> { self.0.iter() }
82}
83
84impl<'a, T> IntoIterator for &'a SymHashMap<T> {
85  type Item = (&'a SymStr, &'a T);
86  type IntoIter = Iter<'a, SymStr, T>;
87
88  #[inline]
89  fn into_iter(self) -> Iter<'a, SymStr, T> { self.0.iter() }
90}
91
92impl<'a, T> IntoIterator for &'a mut SymHashMap<T> {
93  type Item = (&'a SymStr, &'a mut T);
94  type IntoIter = IterMut<'a, SymStr, T>;
95
96  #[inline]
97  fn into_iter(self) -> IterMut<'a, SymStr, T> { self.0.iter_mut() }
98}
99impl<T> IntoIterator for SymHashMap<T> {
100  type Item = (SymStr, T);
101  type IntoIter = IntoIter<SymStr, T>;
102  #[inline]
103  fn into_iter(self) -> Self::IntoIter { self.0.into_iter() }
104}
105
106impl<T: fmt::Debug> fmt::Debug for SymHashMap<T> {
107  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
108    write!(f, "SymHashMap[")?;
109    let mut init = true;
110    for (k, v) in self {
111      if init {
112        init = false;
113      } else {
114        write!(f, ", ")?;
115      }
116      arena::with(*k, |key| write!(f, "{key}"))?;
117      // very temporary hack to get the full trace
118      if type_name::<T>() == "string_interner::symbol::SymbolU32" {
119        let symstr = format!("{:?}", v);
120        // "SymbolU32 { value: 28104 }"
121        let mut symiter = symstr.split(' ');
122        symiter.next();
123        symiter.next();
124        symiter.next();
125        let sym_v_str = symiter.next().unwrap();
126        let sym_val = sym_v_str.parse::<usize>().unwrap();
127        let sym = Symbol::try_from_usize(sym_val - 1).unwrap();
128        let vstr = arena::to_string(sym);
129        write!(f, ": {vstr}")?;
130      } else {
131        write!(f, ": [{:?}]", v)?;
132      }
133      // write!(f,": {:?}",v)?;
134    }
135    write!(f, "]")
136  }
137}
138
139impl<T> Index<&SymStr> for SymHashMap<T> {
140  type Output = T;
141  /// Returns a reference to the value corresponding to the supplied key.
142  ///
143  /// # Panics
144  ///
145  /// Panics if the key is not present in the `HashMap`.
146  #[inline]
147  fn index(&self, key: &SymStr) -> &T { &self.0[key] }
148}
149
150#[cfg(test)]
151mod negative_probe_tests {
152  use super::*;
153
154  /// A negative `&str` probe must not grow the interner; the positive path
155  /// (insert then get) still works.
156  #[test]
157  fn negative_probes_do_not_intern() {
158    let mut map: SymHashMap<u8> = SymHashMap::default();
159    let before = arena::len();
160    assert!(map.get("zz-never-interned-probe-1").is_none());
161    assert!(!map.contains_key("zz-never-interned-probe-2"));
162    assert!(map.get_mut("zz-never-interned-probe-3").is_none());
163    map.remove("zz-never-interned-probe-4");
164    assert_eq!(arena::len(), before, "a negative probe interned its key");
165    map.insert("zz-inserted-key", 7);
166    assert_eq!(map.get("zz-inserted-key"), Some(&7));
167    assert!(map.contains_key("zz-inserted-key"));
168  }
169}