Skip to main content

xtce_model/
intern.rs

1//! String interning.
2//!
3//! XTCE documents repeat the same identifiers many times: a parameter name appears in
4//! `<Parameter>`, in every `<ParameterRefEntry>` that references it, and in every
5//! `<Comparison>` that tests it. Interning collapses those to a single `u32`, which keeps
6//! the IR small, makes equality a register compare, and lets the decoder key lookups on an
7//! integer instead of a string.
8
9use std::collections::HashMap;
10use std::fmt;
11use std::hash::{BuildHasherDefault, Hasher};
12
13/// A handle to an interned string.
14///
15/// Equality on `NameId` is exactly string equality for strings from the same [`Interner`],
16/// because interning is canonical.
17#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
18pub struct NameId(u32);
19
20impl NameId {
21    /// The first handle any interner hands out. Useful as a placeholder; it resolves to
22    /// whatever string was interned first, so never rely on its text.
23    pub const ZERO: Self = Self(0);
24
25    /// The numeric index, for use as a dense array key.
26    #[inline]
27    #[must_use]
28    pub const fn index(self) -> usize {
29        self.0 as usize
30    }
31}
32
33impl fmt::Debug for NameId {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        write!(f, "NameId({})", self.0)
36    }
37}
38
39/// An append-only string arena that hands out [`NameId`]s.
40///
41/// Strings are concatenated into one `String` and addressed by `(start, len)`, so `N` names
42/// cost one amortised allocation rather than `N`.
43///
44/// # Why not `HashMap<Box<str>, NameId>`
45///
46/// The obvious implementation allocates a `Box<str>` for every unique name and stores the
47/// text twice. Loading the 1.6 MB CTIM database interns about nineteen thousand names, so
48/// that is nineteen thousand allocations and a few hundred kilobytes of duplication on a
49/// path whose whole purpose is to be fast.
50///
51/// This is an open-addressing table whose entries are `NameId`s. A probe compares against
52/// the text already in the arena, so nothing is stored twice and a hash collision resolves
53/// correctly rather than merging two distinct names — which is the failure mode of the
54/// tempting "just key the map on the hash" shortcut.
55#[derive(Default)]
56pub struct Interner {
57    blob: String,
58    spans: Vec<(u32, u32)>,
59    /// `id + 1` for an occupied bucket, `0` for an empty one. Length is a power of two.
60    buckets: Vec<u32>,
61}
62
63/// Grow when the table is this full, as a fraction of capacity: `len * 8 >= capacity * 5`.
64///
65/// Linear probing degrades sharply as the table fills, and the names in a mission database
66/// are anything but random — CTIM's are nine thousand variations on `CTIM__XACT_`.
67const LOAD_NUMERATOR: usize = 5;
68const LOAD_DENOMINATOR: usize = 8;
69
70impl Interner {
71    /// Creates an interner with capacity for roughly `names` entries and `bytes` of text.
72    #[must_use]
73    pub fn with_capacity(names: usize, bytes: usize) -> Self {
74        let mut interner = Self {
75            blob: String::with_capacity(bytes),
76            spans: Vec::with_capacity(names),
77            buckets: Vec::new(),
78        };
79        interner.resize_buckets(names.saturating_mul(2).max(16).next_power_of_two());
80        interner
81    }
82
83    /// Interns `s`, returning its handle. Repeated calls with equal strings return the
84    /// same handle, and nothing is allocated per name.
85    pub fn intern(&mut self, s: &str) -> NameId {
86        if self.buckets.is_empty() {
87            self.resize_buckets(16);
88        }
89        if self.spans.len() * LOAD_DENOMINATOR >= self.buckets.len() * LOAD_NUMERATOR {
90            self.resize_buckets(self.buckets.len() * 2);
91        }
92
93        let hash = hash_str(s);
94        let mask = self.buckets.len() - 1;
95        let mut index = (hash as usize) & mask;
96        loop {
97            match self.buckets.get(index).copied() {
98                None | Some(0) => break,
99                Some(slot) => {
100                    let id = NameId(slot - 1);
101                    if self.resolve(id) == s {
102                        return id;
103                    }
104                    index = (index + 1) & mask;
105                }
106            }
107        }
108
109        let start = u32::try_from(self.blob.len()).unwrap_or(u32::MAX);
110        let len = u32::try_from(s.len()).unwrap_or(u32::MAX);
111        self.blob.push_str(s);
112        let id = NameId(u32::try_from(self.spans.len()).unwrap_or(u32::MAX));
113        self.spans.push((start, len));
114        if let Some(slot) = self.buckets.get_mut(index) {
115            *slot = id.0 + 1;
116        }
117        id
118    }
119
120    /// Returns the handle for `s` if it has been interned, without interning it.
121    #[must_use]
122    pub fn get(&self, s: &str) -> Option<NameId> {
123        if self.buckets.is_empty() {
124            return None;
125        }
126        let hash = hash_str(s);
127        let mask = self.buckets.len() - 1;
128        let mut index = (hash as usize) & mask;
129        loop {
130            match self.buckets.get(index).copied() {
131                None | Some(0) => return None,
132                Some(slot) => {
133                    let id = NameId(slot - 1);
134                    if self.resolve(id) == s {
135                        return Some(id);
136                    }
137                    index = (index + 1) & mask;
138                }
139            }
140        }
141    }
142
143    /// Resolves a handle back to its string.
144    ///
145    /// Returns `""` for a handle minted by a different interner, which cannot happen for
146    /// handles obtained through the public API of a single [`crate::XtceDb`].
147    #[must_use]
148    pub fn resolve(&self, id: NameId) -> &str {
149        match self.spans.get(id.index()) {
150            Some(&(start, len)) => {
151                let (start, end) = (start as usize, start as usize + len as usize);
152                self.blob.get(start..end).unwrap_or_default()
153            }
154            None => "",
155        }
156    }
157
158    /// Number of distinct interned strings.
159    #[must_use]
160    pub fn len(&self) -> usize {
161        self.spans.len()
162    }
163
164    /// Whether nothing has been interned yet.
165    #[must_use]
166    pub fn is_empty(&self) -> bool {
167        self.spans.is_empty()
168    }
169
170    /// Total bytes of unique string data held.
171    #[must_use]
172    pub fn bytes(&self) -> usize {
173        self.blob.len()
174    }
175
176    /// Rebuilds the bucket table at `capacity`, which must be a power of two.
177    fn resize_buckets(&mut self, capacity: usize) {
178        let capacity = capacity.max(16).next_power_of_two();
179        let mut buckets = vec![0u32; capacity];
180        let mask = capacity - 1;
181        for (index, &(start, len)) in self.spans.iter().enumerate() {
182            let (from, to) = (start as usize, start as usize + len as usize);
183            let text = self.blob.get(from..to).unwrap_or_default();
184            let mut slot = (hash_str(text) as usize) & mask;
185            while buckets.get(slot).copied().unwrap_or(0) != 0 {
186                slot = (slot + 1) & mask;
187            }
188            if let Some(bucket) = buckets.get_mut(slot) {
189                *bucket = u32::try_from(index).unwrap_or(u32::MAX) + 1;
190            }
191        }
192        self.buckets = buckets;
193    }
194}
195
196fn hash_str(s: &str) -> u64 {
197    let mut hasher = FxHasher::default();
198    hasher.write(s.as_bytes());
199    mix(hasher.finish())
200}
201
202/// The `splitmix64` finalizer.
203///
204/// [`FxHasher`] is fast but its low bits carry little entropy, and a bucket index is exactly
205/// the low bits. XTCE names share long prefixes — every parameter in the CTIM database
206/// starts `CTIM__` — so without this the table clusters badly enough to cost more than the
207/// allocations it was meant to save. Measured on that file: 16.5 ms without, 9.4 ms with.
208#[inline]
209const fn mix(mut hash: u64) -> u64 {
210    hash ^= hash >> 33;
211    hash = hash.wrapping_mul(0xff51_afd7_ed55_8ccd);
212    hash ^= hash >> 33;
213    hash = hash.wrapping_mul(0xc4ce_b9fe_1a85_ec53);
214    hash ^ (hash >> 33)
215}
216
217impl fmt::Debug for Interner {
218    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219        f.debug_struct("Interner")
220            .field("names", &self.spans.len())
221            .field("bytes", &self.blob.len())
222            // The blob is megabytes of XTCE identifiers; summarising is the only useful
223            // thing to print.
224            .finish_non_exhaustive()
225    }
226}
227
228/// The hash used by `rustc` itself: a multiply-xor-rotate mixer.
229///
230/// `SipHash` costs roughly 1 ns per short key and interning is the hottest loop in loading,
231/// so the default hasher measurably dominates parse time. These keys are XTCE identifiers
232/// from a file the caller chose to load, not adversarial input, so `HashDoS` resistance buys
233/// nothing here.
234#[derive(Default)]
235pub struct FxHasher {
236    hash: u64,
237}
238
239impl FxHasher {
240    const SEED: u64 = 0x51_7c_c1_b7_27_22_0a_95;
241
242    #[inline]
243    fn add(&mut self, word: u64) {
244        self.hash = (self.hash.rotate_left(5) ^ word).wrapping_mul(Self::SEED);
245    }
246}
247
248impl Hasher for FxHasher {
249    #[inline]
250    fn write(&mut self, bytes: &[u8]) {
251        let mut chunks = bytes.chunks_exact(8);
252        for chunk in &mut chunks {
253            // `chunks_exact(8)` guarantees the length, so the conversion cannot fail.
254            let word = u64::from_ne_bytes(chunk.try_into().unwrap_or([0; 8]));
255            self.add(word);
256        }
257        let rest = chunks.remainder();
258        if !rest.is_empty() {
259            let mut buf = [0u8; 8];
260            if let Some(slot) = buf.get_mut(..rest.len()) {
261                slot.copy_from_slice(rest);
262            }
263            self.add(u64::from_ne_bytes(buf));
264        }
265        // Mix the length so that "ab" and "ab\0" differ.
266        self.add(bytes.len() as u64);
267    }
268
269    #[inline]
270    fn write_u8(&mut self, i: u8) {
271        self.add(u64::from(i));
272    }
273
274    #[inline]
275    fn write_u32(&mut self, i: u32) {
276        self.add(u64::from(i));
277    }
278
279    #[inline]
280    fn write_u64(&mut self, i: u64) {
281        self.add(i);
282    }
283
284    #[inline]
285    fn write_usize(&mut self, i: usize) {
286        self.add(i as u64);
287    }
288
289    #[inline]
290    fn finish(&self) -> u64 {
291        self.hash
292    }
293}
294
295/// A `HashMap` using [`FxHasher`].
296pub type FxHashMap<K, V> = HashMap<K, V, BuildHasherDefault<FxHasher>>;
297
298#[cfg(test)]
299mod tests {
300    use super::*;
301
302    #[test]
303    fn interning_is_canonical() {
304        let mut interner = Interner::default();
305        let a = interner.intern("PKT_APID");
306        let b = interner.intern("VERSION");
307        let c = interner.intern("PKT_APID");
308        assert_eq!(a, c);
309        assert_ne!(a, b);
310        assert_eq!(interner.len(), 2);
311        assert_eq!(interner.resolve(a), "PKT_APID");
312        assert_eq!(interner.resolve(b), "VERSION");
313    }
314
315    #[test]
316    fn get_does_not_intern() {
317        let mut interner = Interner::default();
318        assert_eq!(interner.get("nope"), None);
319        let id = interner.intern("nope");
320        assert_eq!(interner.get("nope"), Some(id));
321        assert_eq!(interner.len(), 1);
322    }
323
324    #[test]
325    fn empty_string_round_trips() {
326        let mut interner = Interner::default();
327        let id = interner.intern("");
328        assert_eq!(interner.resolve(id), "");
329        assert_eq!(interner.intern(""), id);
330    }
331
332    #[test]
333    fn resolve_rejects_foreign_handle() {
334        let mut a = Interner::default();
335        let id = a.intern("x");
336        let b = Interner::default();
337        assert_eq!(b.resolve(id), "");
338    }
339
340    #[test]
341    fn survives_growth_with_adversarial_names() {
342        // Long shared prefixes are the realistic worst case for a hand-rolled table: every
343        // parameter in a mission database looks like its neighbours. This also forces
344        // several rehashes, which is where an off-by-one in the resize would show up.
345        let mut interner = Interner::with_capacity(4, 16);
346        let names: Vec<String> = (0..5_000)
347            .map(|index| format!("CTIM__XACT_SUBSYSTEM_CHANNEL_{index:05}"))
348            .collect();
349
350        let ids: Vec<NameId> = names.iter().map(|name| interner.intern(name)).collect();
351        assert_eq!(interner.len(), names.len());
352
353        for (name, id) in names.iter().zip(&ids) {
354            assert_eq!(interner.resolve(*id), name.as_str());
355            assert_eq!(interner.get(name), Some(*id));
356            assert_eq!(interner.intern(name), *id);
357        }
358        assert_eq!(
359            interner.len(),
360            names.len(),
361            "re-interning must not add entries"
362        );
363
364        // Every handle must be distinct.
365        let mut sorted = ids.clone();
366        sorted.sort_unstable();
367        sorted.dedup();
368        assert_eq!(sorted.len(), ids.len());
369
370        assert_eq!(interner.get("CTIM__XACT_SUBSYSTEM_CHANNEL_99999"), None);
371    }
372
373    #[test]
374    fn distinguishes_names_that_differ_only_at_the_end() {
375        let mut interner = Interner::default();
376        let a = interner.intern("PARAM_0000000000000001");
377        let b = interner.intern("PARAM_0000000000000002");
378        assert_ne!(a, b);
379        assert_eq!(interner.resolve(a), "PARAM_0000000000000001");
380        assert_eq!(interner.resolve(b), "PARAM_0000000000000002");
381    }
382
383    #[test]
384    fn hashing_distinguishes_length() {
385        use std::hash::Hash;
386        let hash_of = |s: &str| {
387            let mut h = FxHasher::default();
388            s.hash(&mut h);
389            h.finish()
390        };
391        assert_ne!(hash_of("ab"), hash_of("ab\0"));
392        assert_eq!(hash_of("abcdefghij"), hash_of("abcdefghij"));
393    }
394}