sui-intern 0.1.3

String interning for the sui Nix evaluator — Symbol(u32) handles for O(1) comparison
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
//! String interning for attribute names and identifiers.
//!
//! Converts heap-allocated `String` comparisons into cheap `u32`
//! comparisons. Every unique string is stored exactly once; lookups
//! and comparisons use the [`Symbol`] handle (a `u32` index).
//!
//! # Performance Impact
//!
//! Attrset key operations (`GetAttr`, `HasAttr`, `MakeAttrs`, `UpdateAttrs`)
//! go from O(n) string comparison to O(1) integer comparison. This is
//! the single highest-ROI optimization for Nix evaluation because
//! nixpkgs is dominated by attrset operations.
//!
//! # Storage
//!
//! Strings are stored as `Rc<str>`. The forward map's key and the reverse
//! `strings` vector share the same allocation — no double-allocation on
//! intern, and `resolve_rc` returns a cheap `Rc::clone` instead of a
//! full `String::from` copy. Hashing uses `FxHashMap` (rustc-hash) —
//! ~2x faster than SipHash for the short strings typical of Nix keys
//! and identifiers.
//!
//! # Thread-Local Helpers
//!
//! For convenience in single-threaded evaluation, this crate provides
//! [`intern()`] and [`resolve()`] free functions that operate on a
//! thread-local [`Interner`] instance. [`prewarm()`] pre-interns a
//! curated set of hot nixpkgs symbols so common names get low indices
//! and the hashmap's initial resize cost is paid upfront.

use std::cell::RefCell;
use std::fmt;
use std::rc::Rc;

use rustc_hash::FxHashMap;

/// An interned string handle — a cheap, copyable, comparable token.
///
/// Two `Symbol`s are equal if and only if they refer to the same
/// interned string. Comparison is a single `u32 ==` operation.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Symbol(u32);

impl Symbol {
    /// Return the raw index for serialization / debugging.
    #[must_use]
    pub fn index(self) -> u32 {
        self.0
    }
}

impl fmt::Debug for Symbol {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Symbol({})", self.0)
    }
}

impl fmt::Display for Symbol {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "#{}", self.0)
    }
}

/// A string interner that maps strings to [`Symbol`] handles.
///
/// Thread-local, single-owner. For a Nix evaluator this is sufficient
/// because evaluation is single-threaded.
#[derive(Clone, Default)]
pub struct Interner {
    /// Forward map: string content -> symbol. The `Rc<str>` key is
    /// shared with the reverse `strings` vector, so interning allocates
    /// the UTF-8 bytes exactly once.
    map: FxHashMap<Rc<str>, Symbol>,
    /// Reverse map: symbol index -> string content.
    strings: Vec<Rc<str>>,
}

impl Interner {
    /// Create a new, empty interner.
    #[must_use]
    pub fn new() -> Self {
        Self {
            map: FxHashMap::default(),
            strings: Vec::new(),
        }
    }

    /// Create an interner with pre-allocated capacity. Use when you
    /// know the approximate identifier count upfront — avoids hashmap
    /// resizes during the hot path.
    #[must_use]
    pub fn with_capacity(cap: usize) -> Self {
        Self {
            map: FxHashMap::with_capacity_and_hasher(cap, rustc_hash::FxBuildHasher::default()),
            strings: Vec::with_capacity(cap),
        }
    }

    /// Intern a string, returning its symbol. If the string was already
    /// interned, returns the existing symbol (O(1) amortized).
    pub fn intern(&mut self, s: &str) -> Symbol {
        if let Some(&sym) = self.map.get(s) {
            return sym;
        }
        let rc: Rc<str> = Rc::from(s);
        let sym = Symbol(u32::try_from(self.strings.len()).expect("interner overflow"));
        self.strings.push(Rc::clone(&rc));
        self.map.insert(rc, sym);
        sym
    }

    /// Resolve a symbol back to its string content.
    ///
    /// # Panics
    ///
    /// Panics if the symbol was not produced by this interner.
    #[must_use]
    pub fn resolve(&self, sym: Symbol) -> &str {
        &self.strings[sym.0 as usize]
    }

    /// Resolve a symbol to its shared `Rc<str>` handle. Cheap to clone
    /// and pass around; prefer this over `resolve(...).to_string()` in
    /// hot paths.
    ///
    /// # Panics
    ///
    /// Panics if the symbol was not produced by this interner.
    #[must_use]
    pub fn resolve_rc(&self, sym: Symbol) -> Rc<str> {
        Rc::clone(&self.strings[sym.0 as usize])
    }

    /// Try to resolve a symbol, returning `None` if invalid.
    #[must_use]
    pub fn try_resolve(&self, sym: Symbol) -> Option<&str> {
        self.strings.get(sym.0 as usize).map(AsRef::as_ref)
    }

    /// Look up a symbol for a string without interning it.
    #[must_use]
    pub fn lookup(&self, s: &str) -> Option<Symbol> {
        self.map.get(s).copied()
    }

    /// Return the number of interned strings.
    #[must_use]
    pub fn len(&self) -> usize {
        self.strings.len()
    }

    /// Whether the interner is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.strings.is_empty()
    }
}

impl fmt::Debug for Interner {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Interner({} strings)", self.strings.len())
    }
}

// -- Thread-local interner helpers --

thread_local! {
    static GLOBAL_INTERNER: RefCell<Interner> = RefCell::new(Interner::with_capacity(512));
}

/// Intern a string using the thread-local interner.
pub fn intern(s: &str) -> Symbol {
    GLOBAL_INTERNER.with(|i| i.borrow_mut().intern(s))
}

/// Resolve a symbol using the thread-local interner.
///
/// Allocates a fresh `String`. Prefer [`resolve_rc`] or [`with_resolved`]
/// in hot paths — `Rc::clone` is ~20x cheaper than `String::from` for
/// typical identifier lengths.
#[must_use]
pub fn resolve(sym: Symbol) -> String {
    GLOBAL_INTERNER.with(|i| i.borrow().resolve(sym).to_string())
}

/// Resolve a symbol to a shared `Rc<str>` handle. Zero-copy.
#[must_use]
pub fn resolve_rc(sym: Symbol) -> Rc<str> {
    GLOBAL_INTERNER.with(|i| i.borrow().resolve_rc(sym))
}

/// Borrow the resolved string inside a closure without allocating.
/// The thread-local interner stays locked for the duration of `f`.
pub fn with_resolved<F, R>(sym: Symbol, f: F) -> R
where
    F: FnOnce(&str) -> R,
{
    GLOBAL_INTERNER.with(|i| f(i.borrow().resolve(sym)))
}

/// Look up a symbol for a string in the thread-local interner without
/// interning it.
#[must_use]
pub fn lookup(s: &str) -> Option<Symbol> {
    GLOBAL_INTERNER.with(|i| i.borrow().lookup(s))
}

/// Intern the hot nixpkgs/flake/stdenv symbol set so they get low
/// `Symbol` indices and the thread-local hashmap pays its first few
/// resizes upfront instead of on the eval hot path.
///
/// Call this once per thread before the first eval. Idempotent —
/// re-running is cheap because every symbol is a hashmap hit after
/// the first pass.
///
/// The curated list covers the identifiers that dominate nixpkgs
/// attribute access: derivation fields (`name`, `src`, `buildInputs`
/// …), module-system glue (`config`, `options`, `mkOption`, `mkIf`
/// …), flake schema (`inputs`, `outputs`, `description` …), meta
/// (`meta`, `platforms`, `license` …), and the empty string used by
/// string context machinery.
pub fn prewarm() {
    GLOBAL_INTERNER.with(|i| {
        let mut guard = i.borrow_mut();
        for s in HOT_SYMBOLS {
            guard.intern(s);
        }
    });
}

/// Hot symbols pre-interned by [`prewarm`]. Order is load-bearing —
/// the first entry gets Symbol(0), the second Symbol(1), etc.  Leave
/// the empty string first so `Symbol(0)` means "empty" by convention.
const HOT_SYMBOLS: &[&str] = &[
    // Sentinels
    "",
    // Derivation fields
    "name",
    "pname",
    "version",
    "src",
    "system",
    "builder",
    "args",
    "outputs",
    "out",
    "dev",
    "bin",
    "man",
    "doc",
    "outputHash",
    "outputHashAlgo",
    "outputHashMode",
    "passAsFile",
    "preferLocalBuild",
    "allowSubstitutes",
    // Build dependencies
    "buildInputs",
    "nativeBuildInputs",
    "propagatedBuildInputs",
    "propagatedNativeBuildInputs",
    "checkInputs",
    "nativeCheckInputs",
    "buildPhase",
    "installPhase",
    "configurePhase",
    "patchPhase",
    "unpackPhase",
    // Module system
    "config",
    "options",
    "imports",
    "_module",
    "mkOption",
    "mkDefault",
    "mkForce",
    "mkIf",
    "mkMerge",
    "mkOverride",
    "type",
    "default",
    "description",
    "example",
    "visible",
    "internal",
    "readOnly",
    // Flake schema
    "inputs",
    "url",
    "flake",
    "follows",
    "packages",
    "devShells",
    "apps",
    "overlays",
    "nixosModules",
    "nixosConfigurations",
    "darwinModules",
    "darwinConfigurations",
    "homeModules",
    "homeConfigurations",
    "templates",
    "checks",
    "formatter",
    "legacyPackages",
    // nixpkgs conventions
    "nixpkgs",
    "pkgs",
    "stdenv",
    "lib",
    "hostPlatform",
    "buildPlatform",
    "targetPlatform",
    "isDarwin",
    "isLinux",
    "x86_64-linux",
    "aarch64-linux",
    "x86_64-darwin",
    "aarch64-darwin",
    // Meta
    "meta",
    "platforms",
    "homepage",
    "license",
    "maintainers",
    "mainProgram",
    "available",
    "broken",
    "insecure",
    "unsupported",
    // String context + laziness helpers
    "recurseIntoAttrs",
    "__functor",
    "__toString",
    "__ignoreNulls",
    "outPath",
    "drvPath",
    "attrs",
    "outputName",
    // Common value identifiers
    "true",
    "false",
    "null",
];

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn intern_returns_same_symbol() {
        let mut interner = Interner::new();
        let s1 = interner.intern("hello");
        let s2 = interner.intern("hello");
        assert_eq!(s1, s2);
    }

    #[test]
    fn different_strings_different_symbols() {
        let mut interner = Interner::new();
        let s1 = interner.intern("hello");
        let s2 = interner.intern("world");
        assert_ne!(s1, s2);
    }

    #[test]
    fn resolve_roundtrip() {
        let mut interner = Interner::new();
        let sym = interner.intern("foo");
        assert_eq!(interner.resolve(sym), "foo");
    }

    #[test]
    fn resolve_rc_shares_allocation() {
        let mut interner = Interner::new();
        let sym = interner.intern("shared");
        let a = interner.resolve_rc(sym);
        let b = interner.resolve_rc(sym);
        assert_eq!(&*a, "shared");
        assert_eq!(&*b, "shared");
        // Two handles point at the same allocation.
        assert!(Rc::ptr_eq(&a, &b));
    }

    #[test]
    fn lookup_existing() {
        let mut interner = Interner::new();
        let sym = interner.intern("bar");
        assert_eq!(interner.lookup("bar"), Some(sym));
    }

    #[test]
    fn lookup_missing() {
        let interner = Interner::new();
        assert_eq!(interner.lookup("missing"), None);
    }

    #[test]
    fn len_and_empty() {
        let mut interner = Interner::new();
        assert!(interner.is_empty());
        assert_eq!(interner.len(), 0);
        interner.intern("a");
        interner.intern("b");
        interner.intern("a"); // duplicate
        assert_eq!(interner.len(), 2);
        assert!(!interner.is_empty());
    }

    #[test]
    fn symbol_ordering() {
        let mut interner = Interner::new();
        let s1 = interner.intern("alpha");
        let s2 = interner.intern("beta");
        // Symbols are ordered by insertion order, not alphabetically.
        assert!(s1 < s2);
    }

    #[test]
    fn try_resolve_valid() {
        let mut interner = Interner::new();
        let sym = interner.intern("test");
        assert_eq!(interner.try_resolve(sym), Some("test"));
    }

    #[test]
    fn try_resolve_invalid() {
        let interner = Interner::new();
        assert_eq!(interner.try_resolve(Symbol(999)), None);
    }

    #[test]
    fn clone_interner() {
        let mut interner = Interner::new();
        let s1 = interner.intern("hello");
        let cloned = interner.clone();
        assert_eq!(cloned.resolve(s1), "hello");
        assert_eq!(cloned.len(), 1);
    }

    #[test]
    fn with_capacity_preallocates() {
        let interner = Interner::with_capacity(256);
        assert!(interner.is_empty());
        // capacity is not exposed on FxHashMap publicly but len should be 0
        assert_eq!(interner.len(), 0);
    }

    // Thread-local helpers run inside `std::thread::spawn` so they
    // can't collide with each other or with tests in sibling crates
    // that already touched the global interner.
    #[test]
    fn thread_local_intern_resolve() {
        std::thread::spawn(|| {
            let sym = intern("thread_local_test");
            let resolved = resolve(sym);
            assert_eq!(resolved, "thread_local_test");
        })
        .join()
        .unwrap();
    }

    #[test]
    fn thread_local_intern_dedup() {
        std::thread::spawn(|| {
            let s1 = intern("dedup");
            let s2 = intern("dedup");
            assert_eq!(s1, s2);
        })
        .join()
        .unwrap();
    }

    #[test]
    fn thread_local_resolve_rc_zero_copy() {
        std::thread::spawn(|| {
            let sym = intern("tl_rc");
            let a = resolve_rc(sym);
            let b = resolve_rc(sym);
            assert!(Rc::ptr_eq(&a, &b));
        })
        .join()
        .unwrap();
    }

    #[test]
    fn thread_local_with_resolved_no_alloc() {
        std::thread::spawn(|| {
            let sym = intern("borrowed");
            let len = with_resolved(sym, str::len);
            assert_eq!(len, "borrowed".len());
        })
        .join()
        .unwrap();
    }

    #[test]
    fn thread_local_lookup() {
        std::thread::spawn(|| {
            assert_eq!(lookup("never_interned_here"), None);
            let sym = intern("findme");
            assert_eq!(lookup("findme"), Some(sym));
        })
        .join()
        .unwrap();
    }

    #[test]
    fn prewarm_populates_hot_set() {
        std::thread::spawn(|| {
            // Fresh thread — interner starts empty, then prewarm fills it.
            prewarm();
            for &s in HOT_SYMBOLS {
                assert!(
                    lookup(s).is_some(),
                    "prewarm should have interned {s:?}"
                );
            }
            // Idempotent — second call shouldn't grow the interner.
            let before = HOT_SYMBOLS.len();
            prewarm();
            // The thread-local state isn't directly inspectable here;
            // instead, check that every hot symbol still resolves to
            // the same index it got the first time.
            let sym_first = lookup("name").expect("name interned by prewarm");
            assert!(sym_first.index() < u32::try_from(before).unwrap());
        })
        .join()
        .unwrap();
    }

    #[test]
    fn hot_symbols_unique() {
        // Sanity: no duplicates in the curated list, otherwise the
        // "this symbol has the N-th index" reasoning breaks.
        let mut seen = std::collections::HashSet::new();
        for &s in HOT_SYMBOLS {
            assert!(seen.insert(s), "HOT_SYMBOLS contains duplicate {s:?}");
        }
    }
}