jsonld_syntax/intern.rs
1//! Process-wide string interner used by [`crate::context::definition::Key`].
2//!
3//! Backed by [`lasso::ThreadedRodeo`]. Interned strings live for the lifetime
4//! of the program and are **never freed**.
5//!
6//! # Untrusted input
7//!
8//! Every term key of every parsed `@context` is interned, so the interner's
9//! memory usage grows with the number of *distinct* context keys the process
10//! ever parses — a quantity that is attacker-controlled when parsing
11//! untrusted documents. A long-running service accepting arbitrary JSON-LD
12//! should bound the size of the documents it accepts (for example via
13//! [`Options::max_document_size`] on the `reqwest` loader of the main crate,
14//! or an equivalent limit at the transport layer) to keep this growth
15//! proportional to the traffic it chooses to serve.
16//!
17//! [`Options::max_document_size`]: https://docs.rs/jsonld/latest/jsonld/loader/reqwest/struct.Options.html
18
19use lasso::ThreadedRodeo;
20use std::sync::OnceLock;
21
22pub use lasso::Spur;
23
24/// Returns the global interner, initializing it on first call.
25pub fn interner() -> &'static ThreadedRodeo {
26 static INTERNER: OnceLock<ThreadedRodeo> = OnceLock::new();
27 INTERNER.get_or_init(ThreadedRodeo::new)
28}
29
30/// Interns the given string and returns its [`Spur`].
31///
32/// # Panics
33///
34/// Panics if the interner's key space overflows (more than `u32::MAX - 1`
35/// distinct strings interned over the process lifetime).
36#[inline]
37#[must_use]
38pub fn intern(s: &str) -> Spur {
39 interner().get_or_intern(s)
40}
41
42/// Resolves a [`Spur`] back to its `&'static str`.
43///
44/// # Panics
45///
46/// Panics if `spur` was not produced by [`intern`]: `Spur` values can be
47/// forged via [`lasso::Key::try_from_usize`], and resolving a forged key that
48/// was never handed out is a caller bug. Use [`try_resolve`] to get `None`
49/// instead.
50#[inline]
51#[must_use]
52pub fn resolve(spur: Spur) -> &'static str {
53 interner().resolve(&spur)
54}
55
56/// Resolves a [`Spur`] back to its `&'static str`, returning `None` if the
57/// key was never handed out by [`intern`] (e.g. forged via
58/// [`lasso::Key::try_from_usize`]).
59#[inline]
60#[must_use]
61pub fn try_resolve(spur: Spur) -> Option<&'static str> {
62 interner().try_resolve(&spur)
63}
64
65/// Interns the given string and returns the canonical `&'static str` directly.
66///
67/// # Panics
68///
69/// Panics if the interner's key space overflows (more than `u32::MAX - 1`
70/// distinct strings interned over the process lifetime).
71#[inline]
72#[must_use]
73pub fn intern_static(s: &str) -> &'static str {
74 let interner = interner();
75 let spur = interner.get_or_intern(s);
76 interner.resolve(&spur)
77}