Skip to main content

glory_ui/
buffer.rs

1//! One empty spare per stream. Payloads are dropped before borrowing the pool.
2use std::cell::RefCell;
3use std::ops::{Deref, DerefMut};
4
5// Large bursts must not permanently reserve their peak in every idle stream.
6const MAX_BYTES: usize = 1024 * 1024;
7
8pub(crate) struct Pool<T>(RefCell<Vec<T>>);
9impl<T> Default for Pool<T> {
10    fn default() -> Self {
11        Self(RefCell::new(Vec::new()))
12    }
13}
14impl<T> Pool<T> {
15    pub(crate) fn take(&self) -> Batch<'_, T> {
16        Batch {
17            pool: self,
18            items: std::mem::take(&mut *self.0.borrow_mut()),
19        }
20    }
21    pub(crate) fn capacity(&self) -> usize {
22        self.0.borrow().capacity()
23    }
24}
25
26pub(crate) struct Batch<'a, T> {
27    pool: &'a Pool<T>,
28    items: Vec<T>,
29}
30impl<T> Deref for Batch<'_, T> {
31    type Target = Vec<T>;
32    fn deref(&self) -> &Self::Target {
33        &self.items
34    }
35}
36impl<T> DerefMut for Batch<'_, T> {
37    fn deref_mut(&mut self) -> &mut Self::Target {
38        &mut self.items
39    }
40}
41impl<T> Drop for Batch<'_, T> {
42    fn drop(&mut self) {
43        // A destructor can reenter and use the pool. No pool/Present borrow is
44        // held, and only empty capacity may be returned after it finishes.
45        self.items.clear();
46        if self.items.capacity().saturating_mul(size_of::<T>()) > MAX_BYTES {
47            return;
48        }
49        if let Ok(mut spare) = self.pool.0.try_borrow_mut()
50            && self.items.capacity() > spare.capacity()
51        {
52            std::mem::swap(&mut *spare, &mut self.items);
53        }
54        // Discarded capacity drops after the RefMut, including during unwind.
55    }
56}
57
58/// Queue and idle-spare capacities, sampled between host turns.
59/// Counts slots/bytes, excludes in-flight batches, and does not measure RSS.
60#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
61pub struct BufferStats {
62    pub commands: usize,
63    pub actions: usize,
64    pub listeners: usize,
65    pub inputs: usize,
66    pub bytes: usize,
67}
68
69#[cfg(test)]
70mod tests {
71    use super::*;
72    use std::{cell::Cell, rc::Rc};
73
74    #[test]
75    fn unwind_releases_payloads_but_returns_bounded_empty_storage() {
76        struct Payload(Rc<Cell<usize>>);
77        impl Drop for Payload {
78            fn drop(&mut self) {
79                self.0.set(self.0.get() + 1);
80            }
81        }
82        let pool = Pool::default();
83        let drops = Rc::new(Cell::new(0));
84        assert!(
85            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
86                let mut batch = pool.take();
87                batch.reserve(16);
88                batch.push(Payload(drops.clone()));
89                panic!("rollback");
90            }))
91            .is_err()
92        );
93        assert_eq!(drops.get(), 1);
94        let batch = pool.take();
95        assert!(batch.is_empty());
96        assert!(batch.capacity() >= 16);
97    }
98
99    #[test]
100    fn payload_drop_may_reenter_and_nested_returns_keep_one_empty_spare() {
101        struct Payload(Rc<Pool<Payload>>, Rc<Cell<bool>>);
102        impl Drop for Payload {
103            fn drop(&mut self) {
104                let mut nested = self.0.take();
105                assert!(nested.is_empty());
106                nested.reserve(8);
107                self.1.set(true);
108            }
109        }
110        let pool = Rc::new(Pool::default());
111        let entered = Rc::new(Cell::new(false));
112        let mut batch = pool.take();
113        batch.reserve(32);
114        batch.push(Payload(pool.clone(), entered.clone()));
115        drop(batch);
116        assert!(entered.get());
117        assert!(pool.capacity() >= 32);
118        assert!(pool.take().is_empty());
119        assert_eq!(Rc::strong_count(&pool), 1);
120    }
121
122    #[test]
123    fn oversized_bursts_are_not_kept_and_failed_return_does_not_panic() {
124        let pool = Pool::<u8>::default();
125        let mut huge = pool.take();
126        huge.reserve(MAX_BYTES + 1);
127        drop(huge);
128        assert_eq!(pool.capacity(), 0);
129        let mut batch = pool.take();
130        batch.reserve(8);
131        let borrow = pool.0.borrow_mut();
132        drop(batch);
133        drop(borrow);
134        assert_eq!(pool.capacity(), 0);
135    }
136}