Skip to main content

af_price_updates/
slice_interner.rs

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