Skip to main content

af_price_updates/
str_interner.rs

1//! Process-lifetime interning for UTF-8 strings.
2
3use crate::leaking_arena::LeakingArena;
4use rustc_hash::{FxBuildHasher, FxHashSet};
5use std::sync::RwLock;
6
7/// Interns strings as canonical references with program-long lifetimes.
8///
9/// The [`str`] counterpart of [`SliceInterner<u8>`]: equal non-empty strings share the same
10/// allocation, allowing returned references to be compared by address. New non-empty values are
11/// copied into a [`LeakingArena`], so their storage is intentionally never reclaimed. Lookup and
12/// insertion are safe to perform concurrently.
13///
14/// UTF-8 is validated once, when a new string is copied into the arena. The interner stores the
15/// resulting `&'static str`, so lookups return it without converting from bytes again.
16///
17/// Strings returned by the same [`StrInterner`] are canonical, so wrapper types can implement
18/// [`Eq`] and [`Hash`] by comparing and hashing string pointers.
19///
20/// [`SliceInterner<u8>`]: crate::slice_interner::SliceInterner
21#[derive(Debug)]
22pub struct StrInterner {
23    empty: &'static str,
24    inner: RwLock<StrInternerInner>,
25}
26
27#[derive(Debug)]
28struct StrInternerInner {
29    arena: LeakingArena<u8>,
30    set: FxHashSet<&'static str>,
31}
32
33impl StrInterner {
34    /// Creates an empty interner with the given arena chunk capacity bounds.
35    ///
36    /// The first chunk has at least `min_capacity` bytes. Later chunks grow geometrically up to
37    /// `max_capacity`, unless one value requires a larger chunk.
38    pub const fn new(min_capacity: usize, max_capacity: usize) -> Self {
39        Self {
40            empty: "",
41            inner: RwLock::new(StrInternerInner::new(min_capacity, max_capacity)),
42        }
43    }
44    /// Returns the canonical reference for `value`.
45    ///
46    /// Non-empty strings are returned only if they have been interned. Empty strings always return
47    /// this interner's canonical empty string.
48    pub fn find(&self, value: &str) -> Option<&'static str> {
49        if value.is_empty() {
50            return Some(self.empty);
51        }
52        self.inner
53            .read()
54            .expect("StrInterner lock is poisoned")
55            .find(value)
56    }
57    /// Returns the canonical reference for `value`, interning a copy if needed.
58    ///
59    /// Empty strings return this interner's canonical empty string without locking or adding a set
60    /// entry.
61    pub fn get(&self, value: &str) -> &'static str {
62        if let Some(value) = self.find(value) {
63            return value;
64        }
65        self.inner
66            .write()
67            .expect("StrInterner lock is poisoned")
68            .get(value)
69    }
70}
71
72impl StrInternerInner {
73    const fn new(min_capacity: usize, max_capacity: usize) -> Self {
74        Self {
75            arena: LeakingArena::new(min_capacity, max_capacity),
76            set: FxHashSet::with_hasher(FxBuildHasher),
77        }
78    }
79    fn find(&self, value: &str) -> Option<&'static str> {
80        self.set.get(value).copied()
81    }
82    fn get(&mut self, value: &str) -> &'static str {
83        if let Some(value) = self.find(value) {
84            return value;
85        }
86        let result: &'static str = self.arena.write_copy_of_str(value);
87        self.set.insert(result);
88        result
89    }
90}
91
92#[cfg(test)]
93mod tests {
94    use super::*;
95
96    #[test]
97    fn interns_equal_strings() {
98        let interner = StrInterner::new(4, 8);
99
100        let first = interner.get("BTC/USD");
101        let second = interner.get(&String::from("BTC/USD"));
102
103        assert_eq!(first.as_ptr(), second.as_ptr());
104        assert_eq!(interner.find("BTC/USD"), Some(first));
105        assert_eq!(interner.find("ETH/USD"), None);
106    }
107
108    #[test]
109    fn interns_empty_string() {
110        let interner = StrInterner::new(4, 8);
111
112        let found = interner.find("").unwrap();
113        let empty = interner.get("");
114
115        assert!(empty.is_empty());
116        assert!(std::ptr::addr_eq(found, empty));
117        assert_eq!(interner.find(""), Some(empty));
118        assert_eq!(interner.inner.read().unwrap().set.len(), 0);
119    }
120
121    #[test]
122    fn interns_non_ascii_strings() {
123        let interner = StrInterner::new(4, 8);
124
125        let value = interner.get("BTC/μUSD");
126
127        assert_eq!(value, "BTC/μUSD");
128        assert_eq!(
129            interner.find("BTC/μUSD").map(str::as_ptr),
130            Some(value.as_ptr())
131        );
132    }
133
134    #[test]
135    #[expect(
136        clippy::needless_collect,
137        reason = "spawn every thread before joining any"
138    )]
139    fn interns_concurrently() {
140        let interner = std::sync::Arc::new(StrInterner::new(4, 8));
141        let handles = (0..4)
142            .map(|_| {
143                let interner = interner.clone();
144                std::thread::spawn(move || interner.get("BTC/USD").as_ptr() as usize)
145            })
146            .collect::<Vec<_>>();
147        let pointers = handles
148            .into_iter()
149            .map(|handle| handle.join().unwrap())
150            .collect::<Vec<_>>();
151
152        assert!(pointers.windows(2).all(|pair| pair[0] == pair[1]));
153        assert_eq!(interner.inner.read().unwrap().set.len(), 1);
154    }
155}