Skip to main content

af_price_updates/
leaking_arena.rs

1//! Append-only arena storage used by the interner helpers.
2
3/// An append-only arena that intentionally leaks allocations.
4///
5/// Values are stored in heap-allocated chunks that grow as needed. Earlier chunks are never
6/// deallocated, so values written to the arena remain valid for the remainder of the program and
7/// are returned as `&'static mut T`.
8///
9/// `min_capacity` controls the first chunk size; subsequent chunks grow geometrically, up to
10/// `max_capacity`.
11#[derive(Debug)]
12pub struct LeakingArena<T: 'static> {
13    min_capacity: usize,
14    max_capacity: usize,
15    last_capacity: usize,
16    current: &'static mut [std::mem::MaybeUninit<T>],
17}
18
19impl<T> LeakingArena<T> {
20    /// Creates an empty arena; no chunk is allocated until the first write.
21    pub const fn new(min_capacity: usize, max_capacity: usize) -> Self {
22        Self {
23            min_capacity,
24            max_capacity,
25            last_capacity: 0,
26            current: &mut [],
27        }
28    }
29    fn allocate_space(&mut self, requested_size: usize) {
30        if self.last_capacity < self.min_capacity {
31            self.last_capacity = self.min_capacity;
32        } else {
33            self.last_capacity = self.last_capacity.saturating_mul(2).min(self.max_capacity);
34        }
35        self.last_capacity = self.last_capacity.max(requested_size.next_power_of_two());
36        self.current = Box::leak(Box::new_uninit_slice(self.last_capacity));
37    }
38    /// Moves `value` into the arena. It is never dropped.
39    pub fn write(&mut self, value: T) -> &'static mut T {
40        if self.current.is_empty() {
41            self.allocate_space(1);
42        }
43        let place = self.current.split_off_first_mut().expect("allocated above");
44        place.write(value)
45    }
46    /// Copies `slice` into the arena, contiguously.
47    pub fn write_copy_of_slice(&mut self, slice: &[T]) -> &'static mut [T]
48    where
49        T: Copy,
50    {
51        if slice.len() > self.current.len() {
52            self.allocate_space(slice.len());
53        }
54        let place = self
55            .current
56            .split_off_mut(..slice.len())
57            .expect("allocated above");
58        place.write_copy_of_slice(slice)
59    }
60}
61
62impl LeakingArena<u8> {
63    /// Copies `value` into the arena as a string.
64    ///
65    /// The copied bytes are validated as UTF-8 here, so callers can keep the returned
66    /// `&'static str` and never convert from bytes again.
67    pub fn write_copy_of_str(&mut self, value: &str) -> &'static mut str {
68        std::str::from_utf8_mut(self.write_copy_of_slice(value.as_bytes()))
69            .expect("copied from a str")
70    }
71}
72
73#[cfg(test)]
74mod tests {
75    use super::*;
76
77    #[test]
78    fn writes_slices_into_exactly_fitting_chunk() {
79        let mut arena = LeakingArena::new(4, 8);
80
81        let first = arena.write_copy_of_slice(&[1, 2]);
82        let second = arena.write_copy_of_slice(&[3, 4]);
83
84        assert_eq!(first, &[1, 2]);
85        assert_eq!(second, &[3, 4]);
86        assert_eq!(first.as_ptr().wrapping_add(first.len()), second.as_ptr());
87    }
88
89    #[test]
90    fn writes_empty_values() {
91        let mut arena = LeakingArena::<u8>::new(4, 8);
92
93        assert!(arena.write_copy_of_slice(&[]).is_empty());
94    }
95
96    #[test]
97    fn writes_strings_into_exactly_fitting_chunk() {
98        let mut arena = LeakingArena::new(4, 8);
99
100        let first = arena.write_copy_of_str("ab");
101        let second = arena.write_copy_of_str("cd");
102
103        assert_eq!(first, "ab");
104        assert_eq!(second, "cd");
105        assert_eq!(first.as_ptr().wrapping_add(first.len()), second.as_ptr());
106    }
107
108    #[test]
109    fn writes_empty_and_non_ascii_strings() {
110        let mut arena = LeakingArena::new(4, 8);
111
112        assert!(arena.write_copy_of_str("").is_empty());
113        assert_eq!(arena.write_copy_of_str("BTC/μUSD"), "BTC/μUSD");
114    }
115}