Skip to main content

latexml_core/common/
arena.rs

1//! An arena for interning strings
2//!  (global, mutable, single thread only)
3//!
4//! Note: works under the assumption of a single threaded, short-lived process,
5//! where memory starvation will not be an issue. It would need a hard reset if the same process
6//! does multiple conversions, and a different implementation if one needs a thread-local arena.
7//!
8//! ## Borrow safety
9//!
10//! A lend ([`with`] and its siblings) holds a shared `RefCell` borrow of the arena for the closure's duration, so the
11//! buffer it lends from cannot move under it. A string interned while a lend is live cannot grow that buffer: it goes
12//! to the overflow page, its own `Rc<str>` under a symbol at or above `OVERFLOW_BASE`. One string has one symbol across
13//! both tiers until a [`reset`]: every intern probes the buffer first, then the page, and only a string neither holds
14//! is added (to the buffer outside a lend, to the page under one).
15
16use std::{
17  cell::{Cell, RefCell},
18  hash::BuildHasherDefault,
19  ops::Deref,
20  rc::Rc,
21};
22
23use rustc_hash::{FxHashMap, FxHasher};
24use string_interner::{StringInterner, Symbol, backend::BufferBackend};
25
26pub mod data;
27pub use data::{SymHashMap, SymStr};
28
29type Interner = StringInterner<BufferBackend, BuildHasherDefault<FxHasher>>;
30
31thread_root! {
32fn arena_root() -> RefCell<Interner> = {
33  // 131,072 = 2^17 — sized to absorb the latex.dump (109,863 entries)
34  // plus a typical conversion's content (~15k more), so the hot path
35  // hits no reallocation. Profiled 2026-05-12: a representative
36  // `\usepackage{glossaries}` + math conversion ends at ~125,628
37  // strings allocated.
38  //
39  // Cost: ~2-3 MB extra startup memory vs the prior 32,768. Worth it
40  // when running batched conversions over a corpus (one fewer
41  // BufferBackend Vec realloc + HashMap rehash per process startup);
42  // negligible on a single short-lived run.
43  RefCell::new(new_interner())
44};
45}
46
47fn new_interner() -> Interner {
48  StringInterner::with_capacity_and_hasher(131_072, BuildHasherDefault::<FxHasher>::default())
49}
50
51/// The overflow page's symbols: the top of the `SymbolU32` range (a `NonZeroU32` holding index + 1, so the largest
52/// index is `u32::MAX - 1`). Measured peaks: 392 strings (2308.04512), 222 (2604.01119), 56 (a 3,952-page book).
53const OVERFLOW_SLOTS: usize = 1 << 24;
54/// The first overflow symbol: the arena's own symbols are byte offsets into its buffer, kept below it, so the buffer
55/// holds ~4 GiB as in 0.7.6 (issue 1011: a 26,000-page book passed the former 2 GiB).
56const OVERFLOW_BASE: usize = u32::MAX as usize - OVERFLOW_SLOTS;
57
58thread_local! {
59  /// The bytes the buffer holds. A new string's symbol is this offset cast `as u32`, unchecked (string-interner 0.20
60  /// `buffer.rs:81`, `symbol.rs:79`), so [`push`] keeps it at most `OVERFLOW_BASE`.
61  static BUFFER_LEN: Cell<usize> = const { Cell::new(0) };
62}
63
64/// The strings interned while a lend was live, which the arena's buffer could not take without moving.
65#[derive(Default)]
66struct Overflow {
67  texts:   Vec<Rc<str>>,
68  symbols: FxHashMap<Rc<str>, SymStr>,
69  /// New strings since [`take_overflow_interns`] last read the count.
70  fresh:   usize,
71}
72
73thread_root! {
74fn overflow_root() -> RefCell<Overflow> = RefCell::default();
75}
76
77/// The overflow page's symbol for `text`, if the page holds it.
78#[inline(never)]
79fn page_symbol(text: &str) -> Option<SymStr> { overflow_root().borrow().symbols.get(text).copied() }
80
81/// A symbol of the arena's buffer, never one of the overflow page's: [`push`] keeps the buffer below them.
82#[inline]
83fn in_buffer(sym: SymStr) -> SymStr {
84  assert!(
85    sym.to_usize() < OVERFLOW_BASE,
86    "a symbol of the string arena's buffer reached the overflow page's"
87  );
88  sym
89}
90
91/// Add a new string to the buffer, outside any lend; refused, the buffer unchanged, when it would end past
92/// `OVERFLOW_BASE`.
93#[inline]
94fn push(arena: &mut Interner, text: &str) -> SymStr {
95  let start = BUFFER_LEN.get();
96  let Some(end) = buffer_end(start, text.len()) else {
97    buffer_full()
98  };
99  let sym = arena.get_or_intern(text);
100  debug_assert_eq!(
101    sym.to_usize(),
102    start,
103    "the buffer's length went out of step"
104  );
105  BUFFER_LEN.set(end);
106  sym
107}
108
109/// Where a string of `len` bytes added at `start` ends: after its length, 7 bits a byte (string-interner 0.20
110/// `buffer.rs:139-148, 208-226`), and its text; `None` past `OVERFLOW_BASE`.
111#[inline]
112fn buffer_end(start: usize, len: usize) -> Option<usize> {
113  let prefix = (usize::BITS - len.leading_zeros()).div_ceil(7).max(1) as usize;
114  Some(start.saturating_add(prefix).saturating_add(len)).filter(|end| *end <= OVERFLOW_BASE)
115}
116
117#[cold]
118#[inline(never)]
119fn buffer_full() -> ! {
120  panic!(
121    "the string arena is full: this conversion interned about 4 GiB of distinct strings (names, labels, file paths, \
122     numbers), the most one run can hold"
123  )
124}
125
126#[inline]
127fn intern(text: &str) -> SymStr {
128  if let Ok(mut arena) = arena_root().try_borrow_mut() {
129    if let Some(sym) = arena.get(text) {
130      return in_buffer(sym);
131    }
132    // A string first interned under a lend keeps its overflow symbol.
133    return page_symbol(text).unwrap_or_else(|| push(&mut arena, text));
134  }
135  intern_cold(text)
136}
137
138/// [`intern`] while a lend is live: a string either tier holds keeps its symbol (the buffer probed first, as most
139/// interns find their string); a new one goes to the overflow page.
140#[cold]
141#[inline(never)]
142fn intern_cold(text: &str) -> SymStr {
143  if let Some(sym) = arena_root().borrow().get(text) {
144    return in_buffer(sym);
145  }
146  let mut overflow = overflow_root().borrow_mut();
147  if let Some(&sym) = overflow.symbols.get(text) {
148    return sym;
149  }
150  let sym = page_slot(overflow.texts.len());
151  let text: Rc<str> = Rc::from(text);
152  overflow.texts.push(Rc::clone(&text));
153  overflow.symbols.insert(text, sym);
154  overflow.fresh += 1;
155  sym
156}
157
158/// The overflow page's symbol for its `index`th string. (`try_from_usize` truncates past `u32::MAX`: the count is
159/// checked first.)
160fn page_slot(index: usize) -> SymStr {
161  assert!(index < OVERFLOW_SLOTS, "the arena's overflow page is full");
162  SymStr::try_from_usize(OVERFLOW_BASE + index).expect("an overflow symbol is a SymbolU32")
163}
164
165/// A symbol's text, from the arena's buffer (under the caller's borrow) or the overflow page (its own `Rc`).
166enum Text<'a> {
167  Buffer(&'a str),
168  Page(Rc<str>),
169}
170
171impl Deref for Text<'_> {
172  type Target = str;
173  #[inline]
174  fn deref(&self) -> &str {
175    match self {
176      Text::Buffer(text) => text,
177      Text::Page(text) => text,
178    }
179  }
180}
181
182#[inline]
183fn text(arena: &Interner, sym: SymStr) -> Text<'_> {
184  if is_paged(sym) {
185    Text::Page(page_text(sym))
186  } else {
187    Text::Buffer(buffer_text(arena, sym))
188  }
189}
190
191#[inline]
192fn is_paged(sym: SymStr) -> bool { sym.to_usize() >= OVERFLOW_BASE }
193
194/// The text of a symbol of the buffer (the callers' test of [`is_paged`] lets the compiler drop this one's).
195#[inline]
196fn buffer_text(arena: &Interner, sym: SymStr) -> &str {
197  assert!(
198    !is_paged(sym),
199    "an overflow symbol resolved in the arena's buffer"
200  );
201  // SAFETY: `resolve_unchecked` skips the bounds and UTF-8 checks. Every symbol below `OVERFLOW_BASE` came from
202  // the buffer's `get_or_intern` of a `&str` at its true offset (`push` refuses one that would wrap), and the buffer is append-only between `reset`s, so the symbol names a
203  // whole UTF-8 string in it. Callgrind measured the validating `resolve` at ~3% of total Ir (`str::from_utf8`).
204  unsafe { arena.resolve_unchecked(sym) }
205}
206
207#[cold]
208#[inline(never)]
209fn page_text(sym: SymStr) -> Rc<str> {
210  Rc::clone(&overflow_root().borrow().texts[sym.to_usize() - OVERFLOW_BASE])
211}
212
213/// Assign a static str into the arena, returning a unique symbol.
214pub fn pin_static(text: &'static str) -> SymStr { intern(text) }
215
216thread_static! {
217  /// The [`pin!`] call sites that cached a symbol on this thread: [`reset`]
218  /// replaces the arena and clears each, so a cached symbol never indexes the
219  /// replaced arena. A site registers on its first (cold) pin, so the hot path
220  /// stays one thread-local load.
221  static PINNED_SITES: RefCell<Vec<&'static std::thread::LocalKey<Cell<Option<SymStr>>>>> =
222    RefCell::new(Vec::new());
223}
224
225/// A [`pin!`] call site's first pin after a [`reset`] (the cold path): pin the
226/// literal, cache it in the site and register the site for the next reset.
227#[doc(hidden)]
228#[cold]
229#[inline(never)]
230pub fn pin_site(
231  site: &'static std::thread::LocalKey<Cell<Option<SymStr>>>,
232  text: &'static str,
233) -> SymStr {
234  let sym = pin_static(text);
235  site.with(|c| c.set(Some(sym)));
236  PINNED_SITES.borrow_mut().push(site);
237  sym
238}
239
240/// Call-site-cached interning for string literals — the first call on
241/// a thread (after an arena [`reset`]) pins the literal via `pin_static`,
242/// later calls return the cached `SymStr` directly (a thread-local load,
243/// no arena access). Use this from hot state-key lookup sites so you can keep
244/// writing string literals at the call site and still skip the per-call
245/// `pin()` hash probe:
246///
247/// ```ignore
248/// if state::lookup_bool_sym(pin!("groupNonBoxing")) { ... }
249/// ```
250///
251/// Each call site gets its own thread-local cache (no dedicated pub-static
252/// constant per key), so there is no ergonomic cost beyond typing the macro
253/// name; a site registers in `PINNED_SITES` on its first pin so that
254/// [`reset`] can clear it.
255///
256/// Note: the macro `pin!` and the runtime-string function
257/// `arena::pin(s)` share a name but occupy different namespaces in
258/// Rust — `pin!(…)` is the macro, `pin(…)` is the function — so both
259/// remain callable.
260#[macro_export]
261macro_rules! pin {
262  ($s:literal) => {{
263    std::thread_local! {
264      static CACHED: std::cell::Cell<Option<$crate::common::arena::SymStr>> =
265        const { std::cell::Cell::new(None) };
266    }
267    match CACHED.with(std::cell::Cell::get) {
268      Some(sym) => sym,
269      None => $crate::common::arena::pin_site(&CACHED, $s),
270    }
271  }};
272  (concat!($($part:literal),+ $(,)?)) => {{
273    std::thread_local! {
274      static CACHED: std::cell::Cell<Option<$crate::common::arena::SymStr>> =
275        const { std::cell::Cell::new(None) };
276    }
277    match CACHED.with(std::cell::Cell::get) {
278      Some(sym) => sym,
279      None => $crate::common::arena::pin_site(&CACHED, concat!($($part),+)),
280    }
281  }};
282}
283
284/// Assign a string into the arena, returning a unique symbol.
285///
286/// No overflow guard below the buffer's ~4 GiB (`OVERFLOW_BASE`): the main-level wall-clock watchdog (watchdog.rs) catches genuinely runaway loops
287/// long before any real-world workload approaches it. Earlier versions had both a call-count and a distinct-symbol
288/// sentinel; the call-count one false-fired on dedup-heavy hot loops, and the distinct-symbol one added a per-call
289/// `arena.len()` read on a hot path (~350k calls per doc). Neither cost was paying for itself.
290pub fn pin<S: AsRef<str>>(text: S) -> SymStr { intern(text.as_ref()) }
291
292/// Probe-only lookup: the symbol for `text` if it was ever interned, without
293/// interning it. For existence-style checks (e.g. `install_definition`'s
294/// `"{cs}:locked"` gate) a `None` here proves the key cannot be bound in any
295/// state table — and skipping the intern avoids permanently growing the arena
296/// with one probe-key twin per defined control sequence (2026-08-23 audit R6).
297pub fn get<S: AsRef<str>>(text: S) -> Option<SymStr> {
298  let text = text.as_ref();
299  let found = arena_root().borrow().get(text).map(in_buffer);
300  found.or_else(|| page_symbol(text))
301}
302
303thread_static! {
304  /// The buffer [`get_suffixed`] and [`pin_qname`] spell their key in. Freed by [`reset`], as a leaked per-thread static has no
305  /// destructor.
306  static SUFFIXED_KEY: RefCell<String> = RefCell::new(String::new());
307}
308
309/// [`get`] of `name` with `suffix` appended, without formatting a string: every definition asks this of its side keys
310/// (`"{cs}:locked"`, `"{cs}:error@stub"`), and almost none of them exists.
311pub fn get_suffixed(name: &str, suffix: &str) -> Option<SymStr> {
312  let mut key = SUFFIXED_KEY.borrow_mut();
313  key.clear();
314  key.push_str(name);
315  key.push_str(suffix);
316  get(key.as_str())
317}
318
319/// [`pin`] of `prefix:local`, spelled in a reused buffer rather than a new `String`: `get_node_qname` asks it of every
320/// element and attribute it names.
321pub fn pin_qname(prefix: &str, local: &str) -> SymStr {
322  let mut key = SUFFIXED_KEY.borrow_mut();
323  key.clear();
324  key.push_str(prefix);
325  key.push(':');
326  key.push_str(local);
327  pin(key.as_str())
328}
329
330thread_static! {
331  /// ASCII char-pin cache: every unique ASCII byte resolves to a single
332  /// SymStr for the lifetime of the thread's arena (append-only between
333  /// [`reset`]s, which clears the cache with it). Cache entries use `u32::MAX` as the "not yet pinned"
334  /// sentinel — every symbol value, the overflow page's included, is strictly below that.
335  /// Called from `lookup_catcode` / `assign_catcode` on every token,
336  /// so the RefCell + hashmap overhead on `pin` is a measurable cost
337  /// (1.4% Ir per callgrind on siunitx-heavy fixtures). The fast path
338  /// avoids the arena entirely for the common ASCII case.
339  static ASCII_CHAR_SYM: [Cell<u32>; 128] = [const { Cell::new(u32::MAX) }; 128];
340}
341
342pub fn pin_char(c: char) -> SymStr {
343  let code = c as u32;
344  if code < 128 {
345    let cached = ASCII_CHAR_SYM[code as usize].get();
346    if cached != u32::MAX {
347      // (a prior `pin` below cached it, and `reset` clears the cache with the arena)
348      return SymStr::try_from_usize(cached as usize).expect("invalid cached ASCII SymStr");
349    }
350  }
351  let sym = {
352    let mut tmp = [0u8; 4];
353    let s = c.encode_utf8(&mut tmp);
354    pin(s)
355  };
356  if code < 128 {
357    ASCII_CHAR_SYM[code as usize].set(sym.to_usize() as u32);
358  }
359  sym
360}
361
362/// Resolve a symbol and call the closure with a `&str` reference. The closure may intern (`pin()`, `pin_char()`, …):
363/// the text is lent under a shared borrow of the arena, so a string new during the lend goes to the overflow page
364/// instead of growing (and moving) the buffer the text lives in (string-interner 0.20 `buffer.rs:144`).
365/// An overflow symbol's lend holds the borrow too, so every lend is one where a [`reset`] panics.
366#[inline]
367pub fn with<R, FnR>(sym: SymStr, caller: FnR) -> R
368where FnR: FnOnce(&str) -> R {
369  let arena = arena_root().borrow();
370  // (one branch, not `text()`'s two: the hottest lend)
371  let page;
372  let text = if is_paged(sym) {
373    page = page_text(sym);
374    &*page
375  } else {
376    buffer_text(&arena, sym)
377  };
378  caller(text)
379}
380
381/// The first `N` bytes of `sym`'s text, if it has as many, for a test by name on a hot path.
382#[inline]
383pub fn first_bytes<const N: usize>(sym: SymStr) -> Option<[u8; N]> {
384  with(sym, |text| text.as_bytes().first_chunk().copied())
385}
386
387pub fn with2<R, FnR>(sym1: SymStr, sym2: SymStr, caller: FnR) -> R
388where FnR: FnOnce(&str, &str) -> R {
389  let arena = arena_root().borrow();
390  caller(&text(&arena, sym1), &text(&arena, sym2))
391}
392
393pub fn with3<R, FnR>(sym1: SymStr, sym2: SymStr, sym3: SymStr, caller: FnR) -> R
394where FnR: FnOnce(&str, &str, &str) -> R {
395  let arena = arena_root().borrow();
396  caller(
397    &text(&arena, sym1),
398    &text(&arena, sym2),
399    &text(&arena, sym3),
400  )
401}
402
403pub fn with_many<R, FnR>(syms: &[SymStr], caller: FnR) -> R
404where FnR: FnOnce(Vec<&str>) -> R {
405  let arena = arena_root().borrow();
406  let texts: Vec<Text> = syms.iter().map(|sym| text(&arena, *sym)).collect();
407  caller(texts.iter().map(|text| &**text).collect())
408}
409
410pub fn to_string(sym: SymStr) -> String { with(sym, str::to_owned) }
411
412pub fn join(syms: &[SymStr], sep: &str) -> String { with_many(syms, |strs| strs.join(sep)) }
413
414pub fn len() -> usize { arena_root().borrow().len() + overflow_root().borrow().texts.len() }
415
416/// The number of strings the overflow page took (interned while a lend was live) since the last call: every conversion
417/// entry point takes it at its start, and the conversion's end reports it as a Debug line.
418pub fn take_overflow_interns() -> usize { std::mem::take(&mut overflow_root().borrow_mut().fresh) }
419
420/// Free every interned string on this thread, returning the arena to a
421/// fresh, empty state.
422///
423/// **Danger:** this invalidates *every* outstanding [`SymStr`] on the
424/// thread — they become dangling indices that may resolve to unrelated
425/// strings after re-interning. It is only sound when **nothing on the
426/// thread will read a pre-reset `SymStr` again**: i.e. between fully
427/// independent conversions in a reused process (the test harness, where
428/// each test has already serialized its output to owned `String`s and
429/// the thread is about to exit or be re-initialized) or a future daemon
430/// that re-initializes the engine afterward. The single-conversion
431/// `latexml_oxide` binary never calls this — it exits instead.
432///
433/// Needed because the engine's roots are leaked per-thread
434/// statics (`thread_root!`/`thread_static!`), which (unlike a plain `thread_local!` value) do **not** run
435/// destructors on thread exit. Without an explicit reset, every reused
436/// thread leaks its interner (~tens of MB for a full document). See
437/// `latexml_core::reset_thread_engine`.
438pub fn reset() {
439  // A lend holds a shared borrow until its closure returns, so a reset from inside one finds the arena borrowed.
440  *arena_root()
441    .try_borrow_mut()
442    .expect("arena::reset inside a lend (`arena::with`): the lent text would dangle") =
443    new_interner();
444  *overflow_root().borrow_mut() = Overflow::default();
445  BUFFER_LEN.set(0);
446  // The cached symbols index the replaced arena: a character or literal first
447  // pinned mid-document would otherwise resolve to another string in the next
448  // conversion on this thread.
449  for cached in &*ASCII_CHAR_SYM {
450    cached.set(u32::MAX);
451  }
452  for site in PINNED_SITES.borrow_mut().drain(..) {
453    site.with(|c| c.set(None));
454  }
455  *SUFFIXED_KEY.borrow_mut() = String::new();
456}
457
458/// [`reset`] to a zero-capacity interner, for a thread about to exit (`latexml_core::shrink_thread_engine`): the
459/// arena is a leaked root, so a 2^17-slot interner left in it would outlive the thread.
460pub fn shrink() {
461  reset();
462  *arena_root().borrow_mut() =
463    StringInterner::with_hasher(BuildHasherDefault::<FxHasher>::default());
464  // `reset` drains the `pin!` site list but keeps its capacity, a slot per site the thread reached.
465  *PINNED_SITES.borrow_mut() = Vec::new();
466}
467
468/// The bytes the buffer holds, for a test of what a mechanism costs the arena.
469#[cfg(test)]
470pub(crate) fn buffer_len() -> usize { BUFFER_LEN.get() }
471
472/// Eagerly initialize this thread's per-thread `ARENA` root.
473///
474/// `ARENA` is the *leaf* of the engine's thread-local dependency graph:
475/// every other root's initializer interns symbols via [`pin`], so it
476/// reaches into `ARENA`. Calling this at conversion entry (see
477/// `Core::new`), before any other root is touched, guarantees those later
478/// initializers find a fully-constructed `ARENA` instead of triggering its
479/// initialization *re-entrantly from within their own*. That re-entrant
480/// cross-root initialization is benign on Linux/ELF TLS but is
481/// the documented macOS hazard (rust-lang/rust#29594) behind the macOS
482/// worker-thread memory corruption in issue #217. `ARENA`'s own initializer
483/// touches no other thread-local, so forcing it first is always safe.
484/// No behavioral change on Linux.
485pub(crate) fn force_init() { arena_root(); }
486
487#[cfg(test)]
488mod tests {
489  use super::*;
490
491  #[test]
492  fn pin_literal_cache_follows_an_arena_reset() {
493    fn cached() -> SymStr { pin!("a literal pinned at a call site") }
494    assert_eq!(to_string(cached()), "a literal pinned at a call site");
495    reset();
496    // A string interned first in the new arena takes the slot the literal had.
497    pin("another string");
498    assert_eq!(to_string(cached()), "a literal pinned at a call site");
499  }
500
501  #[test]
502  fn pin_char_cache_follows_an_arena_reset() {
503    assert_eq!(to_string(pin_char('~')), "~");
504    reset();
505    // A string interned first in the new arena takes the slot `~` had.
506    pin("not a tilde");
507    assert_eq!(to_string(pin_char('~')), "~");
508  }
509
510  #[test]
511  fn pin_dedups_equal_strings() {
512    let a = pin("arena_test_foo");
513    let b = pin("arena_test_foo");
514    assert_eq!(a, b, "equal strings must return the same SymStr");
515  }
516
517  #[test]
518  fn pin_distinguishes_different_strings() {
519    let a = pin("arena_test_bar");
520    let b = pin("arena_test_baz");
521    assert_ne!(a, b);
522  }
523
524  #[test]
525  fn pin_static_matches_pin() {
526    let a = pin_static("arena_test_qux");
527    let b = pin("arena_test_qux");
528    assert_eq!(a, b, "pin_static and pin should intern to the same SymStr");
529  }
530
531  #[test]
532  fn to_string_roundtrips() {
533    let sym = pin("arena_test_quux");
534    assert_eq!(to_string(sym), "arena_test_quux");
535  }
536
537  #[test]
538  fn with_borrows_without_allocating() {
539    let sym = pin("arena_test_corge");
540    let len = with(sym, |s| s.len());
541    assert_eq!(len, "arena_test_corge".len());
542  }
543
544  #[test]
545  fn with_predicate_returns_bool() {
546    let sym = pin("arena_test_predicate");
547    let starts_with = with(sym, |s| s.starts_with("arena"));
548    assert!(starts_with);
549  }
550
551  #[test]
552  fn reset_empties_interner_and_stays_usable() {
553    // Each `#[test]` runs on its own thread, so this thread's arena
554    // starts empty and the reset is isolated from sibling tests.
555    let _ = pin("arena_reset_alpha");
556    let _ = pin("arena_reset_beta");
557    assert!(len() >= 2, "expected the two pins to be interned");
558    reset();
559    assert_eq!(len(), 0, "reset must return the interner to empty");
560    // Interning still works after a reset (fresh backend installed).
561    let s = pin("arena_reset_gamma");
562    assert_eq!(to_string(s), "arena_reset_gamma");
563  }
564
565  #[test]
566  fn pin_char_ascii_roundtrips() {
567    let sym = pin_char('a');
568    assert_eq!(to_string(sym), "a");
569    let sym2 = pin_char('a');
570    assert_eq!(sym, sym2, "ASCII char pin is cached");
571  }
572
573  #[test]
574  fn pin_char_distinct_chars_distinct_syms() {
575    assert_ne!(pin_char('a'), pin_char('b'));
576    assert_ne!(pin_char('0'), pin_char('1'));
577  }
578
579  #[test]
580  fn pin_char_unicode_roundtrips() {
581    // Non-ASCII chars go through the general arena path.
582    let sym = pin_char('π');
583    assert_eq!(to_string(sym), "π");
584  }
585
586  #[test]
587  fn join_concatenates_with_separator() {
588    let a = pin("arena_test_alpha");
589    let b = pin("arena_test_beta");
590    let c = pin("arena_test_gamma");
591    let out = join(&[a, b, c], ",");
592    assert_eq!(out, "arena_test_alpha,arena_test_beta,arena_test_gamma");
593  }
594
595  #[test]
596  fn pin_macro_caches_per_site() {
597    // The `pin!` macro returns a cached SymStr per call site. Two
598    // call sites with identical strings cache independently but
599    // intern to the same underlying symbol.
600    let a = pin!("arena_test_literal");
601    let b = pin!("arena_test_literal");
602    assert_eq!(a, b, "same literal at different call sites → same SymStr");
603  }
604
605  /// A closure lent a text may intern: 3000 new strings must not move the lent text (the use-after-free of the former
606  /// re-entrant `&mut` path, which grew the buffer under the lend; Miri flags it at the first new string).
607  #[test]
608  fn lend_survives_interning_many_new_strings() {
609    // (counts are absolute: a test thread that converted, or ran another test, before must not shift them)
610    reset();
611    let lent = pin("arena_lend_text");
612    let read = with(lent, |text| {
613      for i in 0..3000 {
614        pin(format!("arena_lend_new_{i}"));
615      }
616      text.to_owned()
617    });
618    assert_eq!(read, "arena_lend_text");
619    for i in [0, 1499, 2999] {
620      let sym = get(format!("arena_lend_new_{i}")).expect("interned under the lend");
621      assert_eq!(to_string(sym), format!("arena_lend_new_{i}"));
622    }
623    assert_eq!(take_overflow_interns(), 3000);
624    assert_eq!(take_overflow_interns(), 0, "the count is read once");
625  }
626
627  /// The same with more new bytes than the buffer's whole capacity (131,072 × 13 bytes, string-interner 0.20
628  /// `buffer.rs:161-169`), interned inside a lend: every one goes to the overflow page (the count is the guard), and
629  /// the lent text still reads. Guards the current arena only (red under Miri on the old one: the test above). A
630  /// native test: its 1.7 MB take Miri 2 min under Stacked and 13 under Tree Borrows.
631  #[test]
632  #[cfg_attr(miri, ignore)]
633  fn lend_survives_more_new_bytes_than_the_buffer_holds() {
634    reset();
635    let lent = pin("arena_move_text");
636    let filler = "x".repeat(1 << 15);
637    let count = 131_072 * 13 / filler.len() + 2;
638    let (read, unmoved) = with(lent, |text| {
639      let at = text.as_ptr();
640      for i in 0..count {
641        pin(format!("{i}{filler}"));
642      }
643      (text.to_owned(), with(lent, |again| again.as_ptr()) == at)
644    });
645    assert_eq!(read, "arena_move_text");
646    assert!(unmoved, "the buffer moved under the lend");
647    assert_eq!(
648      to_string(pin(format!("{}{filler}", count - 1))).len(),
649      filler.len() + 2
650    );
651    assert_eq!(take_overflow_interns(), count);
652  }
653
654  /// Nested lends, and a pin of a string the buffer already holds, which keeps its buffer symbol.
655  #[test]
656  fn nested_lends_and_a_pin_of_an_existing_string() {
657    let outer = pin("arena_nest_outer");
658    let inner = pin("arena_nest_inner");
659    let joined = with(outer, |o| {
660      with2(inner, outer, |i, o2| {
661        assert_eq!(
662          pin("arena_nest_inner"),
663          inner,
664          "an existing string keeps its symbol under a lend"
665        );
666        format!("{o}/{i}/{o2}/{}", to_string(inner))
667      })
668    });
669    assert_eq!(
670      joined,
671      "arena_nest_outer/arena_nest_inner/arena_nest_outer/arena_nest_inner"
672    );
673    assert_eq!(take_overflow_interns(), 0, "no string was new");
674  }
675
676  /// `get` under a lend sees both tiers and interns nothing.
677  #[test]
678  fn get_under_a_lend() {
679    let lent = pin("arena_get_lent");
680    let before = len();
681    let (buffered, paged, absent) = with(lent, |_| {
682      let paged = pin("arena_get_paged");
683      (
684        get("arena_get_lent"),
685        (paged, get("arena_get_paged")),
686        get("arena_get_absent"),
687      )
688    });
689    assert_eq!(buffered, Some(lent));
690    assert_eq!(paged.1, Some(paged.0));
691    assert_eq!(absent, None);
692    assert_eq!(len(), before + 1);
693  }
694
695  /// A string first interned under a lend keeps its overflow symbol when pinned again outside any lend, and its text
696  /// reads the same through every entry point.
697  #[test]
698  fn an_overflow_string_dedups_across_tiers() {
699    reset();
700    let lent = pin("arena_dedup_lent");
701    let paged = with(lent, |_| pin("arena_dedup_paged"));
702    assert_eq!(
703      pin("arena_dedup_paged"),
704      paged,
705      "the later pin outside the lend finds the overflow string"
706    );
707    assert_eq!(pin_static("arena_dedup_paged"), paged);
708    assert_eq!(get("arena_dedup_paged"), Some(paged));
709    assert_eq!(to_string(paged), "arena_dedup_paged");
710    assert_eq!(first_bytes::<3>(paged), Some(*b"are"));
711    assert_eq!(
712      with3(lent, paged, lent, |a, b, c| format!("{a}{b}{c}")),
713      "arena_dedup_lentarena_dedup_pagedarena_dedup_lent"
714    );
715    assert_eq!(
716      join(&[paged, lent], ","),
717      "arena_dedup_paged,arena_dedup_lent"
718    );
719    // Outside a lend with the overflow page in use, a new string still goes to the buffer.
720    let buffered = pin("arena_dedup_after");
721    assert!(!is_paged(buffered));
722    assert_eq!(to_string(buffered), "arena_dedup_after");
723    assert_eq!(take_overflow_interns(), 1);
724  }
725
726  /// `reset` empties both tiers; the overflow page's symbols start over.
727  #[test]
728  fn reset_clears_the_overflow_page() {
729    reset();
730    let lent = pin("arena_reset_lent");
731    let paged = with(lent, |_| pin("arena_reset_paged"));
732    assert_eq!(len(), 2);
733    reset();
734    assert_eq!(len(), 0);
735    assert_eq!(get("arena_reset_paged"), None);
736    assert_eq!(take_overflow_interns(), 0);
737    let lent = pin("arena_reset_lent2");
738    assert_eq!(
739      with(lent, |_| pin("arena_reset_paged2")),
740      paged,
741      "the first overflow symbol again"
742    );
743    assert_eq!(to_string(paged), "arena_reset_paged2");
744  }
745
746  /// The buffer's symbols reach past 2 GiB, up to the overflow page at the top of the u32 range (issue 1011: a 26,000-page
747  /// book's buffer passed 2 GiB, which 0.7.6 took).
748  #[test]
749  fn buffer_symbols_reach_past_2_gib() {
750    for at in [1 << 31, OVERFLOW_BASE - 1] {
751      let sym = SymStr::try_from_usize(at).unwrap();
752      assert_eq!(in_buffer(sym), sym);
753      assert!(!is_paged(sym), "{at} is a buffer symbol");
754    }
755    assert_eq!(
756      OVERFLOW_BASE,
757      (1 << 32) - 1 - (1 << 24),
758      "the buffer's ceiling is near 4 GiB"
759    );
760    assert!(is_paged(SymStr::try_from_usize(OVERFLOW_BASE).unwrap()));
761    // The page's last symbol is the largest a `SymbolU32` holds.
762    let last = SymStr::try_from_usize(u32::MAX as usize - 1).unwrap();
763    assert!(is_paged(last));
764    assert_eq!(SymStr::try_from_usize(u32::MAX as usize), None);
765  }
766
767  /// The overflow page numbers its symbols from its base, and each resolves to its text.
768  #[test]
769  fn overflow_symbols_start_at_the_page_base() {
770    reset();
771    let lent = pin("arena_base_lent");
772    let [first, second] = with(lent, |_| {
773      [pin("arena_base_first"), pin("arena_base_second")]
774    });
775    assert_eq!(
776      (first.to_usize(), second.to_usize()),
777      (OVERFLOW_BASE, OVERFLOW_BASE + 1)
778    );
779    assert!(first.to_usize() > 1 << 31);
780    assert_eq!(to_string(first), "arena_base_first");
781    assert_eq!(with(second, str::to_owned), "arena_base_second");
782    let buffered = pin("arena_base_buffered");
783    assert!(buffered.to_usize() < OVERFLOW_BASE);
784    assert_eq!(to_string(buffered), "arena_base_buffered");
785  }
786
787  /// A new string is refused when it would end past `OVERFLOW_BASE`, and the buffer does not take it; the strings it
788  /// holds still read, and under a lend a new string still goes to the overflow page.
789  #[test]
790  fn a_full_buffer_refuses_a_new_string() {
791    reset();
792    let held = pin("arena_full_held");
793    // 15 bytes of text and 1 of length, with 15 left
794    BUFFER_LEN.set(OVERFLOW_BASE - 15);
795    let refused =
796      std::panic::catch_unwind(|| pin("arena_full_new0")).expect_err("the buffer is full");
797    assert!(
798      refused
799        .downcast_ref::<&str>()
800        .is_some_and(|m| m.starts_with("the string arena is full"))
801    );
802    assert_eq!(get("arena_full_new0"), None);
803    assert_eq!(BUFFER_LEN.get(), OVERFLOW_BASE - 15);
804    assert_eq!(pin("arena_full_held"), held);
805    assert_eq!(to_string(held), "arena_full_held");
806    let paged = with(held, |_| pin("arena_full_paged"));
807    assert!(is_paged(paged));
808    assert_eq!(to_string(paged), "arena_full_paged");
809    reset();
810  }
811
812  /// A string may end exactly at `OVERFLOW_BASE`, not a byte past it: the next one would start at a symbol that is
813  /// the page's (and, 2^24 further, one that wraps).
814  #[test]
815  fn the_buffer_ends_at_the_overflow_base() {
816    assert_eq!(buffer_end(OVERFLOW_BASE - 15, 14), Some(OVERFLOW_BASE));
817    assert_eq!(buffer_end(OVERFLOW_BASE - 15, 15), None);
818    assert_eq!(buffer_end(OVERFLOW_BASE - 1, 0), Some(OVERFLOW_BASE));
819    assert_eq!(buffer_end(OVERFLOW_BASE, 0), None);
820    // one string of 16 MiB, the page's width, cannot cross it either
821    assert_eq!(buffer_end(OVERFLOW_BASE - 100, OVERFLOW_SLOTS), None);
822    assert_eq!(buffer_end(usize::MAX - 1, 5), None);
823  }
824
825  /// The buffer's length follows every string it takes: a symbol is the offset after its predecessor's length prefix
826  /// (one byte per 7 bits) and text.
827  #[test]
828  fn the_buffer_length_follows_its_strings() {
829    reset();
830    for (len, prefix) in [
831      (0, 1),
832      (1, 1),
833      (127, 1),
834      (128, 2),
835      (16_383, 2),
836      (16_384, 3),
837      (70_000, 3),
838    ] {
839      let start = BUFFER_LEN.get();
840      assert_eq!(pin("y".repeat(len)).to_usize(), start);
841      assert_eq!(BUFFER_LEN.get(), start + prefix + len);
842    }
843    let end = BUFFER_LEN.get();
844    assert_eq!(pin("arena_len_next").to_usize(), end);
845  }
846
847  /// The page's first and last slots are the base and the largest `SymbolU32`; one more is refused, not wrapped.
848  #[test]
849  fn the_overflow_page_ends_at_the_largest_symbol() {
850    assert_eq!(page_slot(0).to_usize(), OVERFLOW_BASE);
851    assert_eq!(
852      page_slot(OVERFLOW_SLOTS - 1).to_usize(),
853      u32::MAX as usize - 1
854    );
855    let full =
856      std::panic::catch_unwind(|| page_slot(OVERFLOW_SLOTS)).expect_err("the page is full");
857    assert_eq!(
858      full.downcast_ref::<&str>(),
859      Some(&"the arena's overflow page is full")
860    );
861  }
862
863  /// `reset` inside a lend would leave the lent text dangling: it refuses.
864  #[test]
865  #[should_panic(expected = "arena::reset inside a lend")]
866  fn reset_inside_a_lend_panics() {
867    let lent = pin("arena_reset_inside");
868    with(lent, |_| reset());
869  }
870
871  /// So does `reset` inside the lend of an overflow symbol, whose text is its own `Rc`: every lend borrows the arena.
872  #[test]
873  #[should_panic(expected = "arena::reset inside a lend")]
874  fn reset_inside_an_overflow_lend_panics() {
875    let lent = pin("arena_reset_inside_page");
876    let paged = with(lent, |_| pin("arena_reset_inside_paged"));
877    with(paged, |_| reset());
878  }
879}