Skip to main content

ftui_core/
arena.rs

1#![forbid(unsafe_code)]
2
3//! Per-frame bump arena allocation.
4//!
5//! Provides [`FrameArena`], a thin wrapper around [`bumpalo::Bump`] for
6//! per-frame temporary allocations. The arena is reset at frame boundaries,
7//! eliminating allocator churn on the hot render path.
8//!
9//! # Usage
10//!
11//! ```
12//! use ftui_core::arena::FrameArena;
13//!
14//! let mut arena = FrameArena::new(256 * 1024); // 256 KB initial capacity
15//! let s = arena.alloc_str("hello");
16//! assert_eq!(s, "hello");
17//!
18//! let slice = arena.alloc_slice(&[1u32, 2, 3]);
19//! assert_eq!(slice, &[1, 2, 3]);
20//!
21//! arena.reset(); // O(1) — reclaims all memory for reuse
22//! ```
23//!
24//! # Safety
25//!
26//! This module uses only safe code. `bumpalo::Bump` provides a safe bump
27//! allocator with automatic growth. `reset()` is safe and frees all
28//! allocations, making the memory available for reuse.
29
30use bumpalo::Bump;
31
32/// A growable vector allocated in the bump arena.
33///
34/// Use this for scratch collections that need `push()` during rendering.
35/// The memory is reclaimed when the arena is reset at frame boundaries.
36pub type BumpVec<'a, T> = bumpalo::collections::Vec<'a, T>;
37
38/// A growable UTF-8 string allocated in the bump arena.
39///
40/// The memory is reclaimed when the arena is reset at frame boundaries.
41pub type BumpString<'a> = bumpalo::collections::String<'a>;
42
43/// Default initial capacity for the frame arena (256 KB).
44pub const DEFAULT_ARENA_CAPACITY: usize = 256 * 1024;
45
46/// A per-frame bump allocator for temporary render-path allocations.
47///
48/// `FrameArena` wraps [`bumpalo::Bump`] with a focused API for the common
49/// allocation patterns in the render pipeline: strings, slices, and
50/// single values. All allocations are invalidated on [`reset()`](Self::reset),
51/// which should be called at frame boundaries.
52///
53/// # Drop semantics
54///
55/// `bumpalo` intentionally does not run `Drop` for values allocated in the arena
56/// when calling [`reset()`](Self::reset) or when the arena itself is dropped.
57/// Only allocate short-lived scratch values that do not require destructor logic.
58///
59/// # Capacity
60///
61/// The arena starts with an initial capacity and grows automatically when
62/// exhausted. Growth allocates new chunks from the global allocator but
63/// never moves existing allocations.
64#[derive(Debug)]
65pub struct FrameArena {
66    bump: Bump,
67}
68
69impl FrameArena {
70    /// Create a new arena with the given initial capacity in bytes.
71    ///
72    /// # Panics
73    ///
74    /// Panics if the system allocator cannot fulfill the initial allocation.
75    pub fn new(capacity: usize) -> Self {
76        Self {
77            bump: Bump::with_capacity(capacity),
78        }
79    }
80
81    /// Create a new arena with the default capacity (256 KB).
82    pub fn with_default_capacity() -> Self {
83        Self::new(DEFAULT_ARENA_CAPACITY)
84    }
85
86    /// Reset the arena, reclaiming all memory for reuse.
87    ///
88    /// This is an O(1) operation. All previously allocated references
89    /// are invalidated. The arena retains its allocated chunks for
90    /// future allocations, avoiding repeated system allocator calls.
91    pub fn reset(&mut self) {
92        self.bump.reset();
93    }
94
95    /// Allocate a string slice in the arena.
96    ///
97    /// Returns a reference to the arena-allocated copy of `s`.
98    /// The returned reference is valid until the next [`reset()`](Self::reset).
99    pub fn alloc_str(&self, s: &str) -> &str {
100        self.bump.alloc_str(s)
101    }
102
103    /// Format a string directly into the arena, avoiding an intermediate heap `String`.
104    ///
105    /// This is the arena equivalent of `format!()`. The formatted text is
106    /// written into a bump-backed string and returned as an arena-allocated `&str`.
107    pub fn alloc_fmt(&self, args: std::fmt::Arguments<'_>) -> &str {
108        use core::fmt::Write;
109        let mut s = bumpalo::collections::String::new_in(&self.bump);
110        s.write_fmt(args).expect("formatting into arena string");
111        s.into_bump_str()
112    }
113
114    /// Allocate a copy of a slice in the arena.
115    ///
116    /// Returns a reference to the arena-allocated copy of `slice`.
117    /// The returned reference is valid until the next [`reset()`](Self::reset).
118    pub fn alloc_slice<T: Copy>(&self, slice: &[T]) -> &[T] {
119        self.bump.alloc_slice_copy(slice)
120    }
121
122    /// Allocate a single value in the arena, constructed by `f`.
123    ///
124    /// Returns a mutable reference to the arena-allocated value.
125    /// The returned reference is valid until the next [`reset()`](Self::reset).
126    pub fn alloc_with<T, F: FnOnce() -> T>(&self, f: F) -> &mut T {
127        self.bump.alloc_with(f)
128    }
129
130    /// Allocate a single value in the arena.
131    ///
132    /// Returns a mutable reference to the arena-allocated value.
133    /// The returned reference is valid until the next [`reset()`](Self::reset).
134    ///
135    /// NOTE: destructors are NEVER run for bump allocations — neither on
136    /// `reset()` nor on arena drop (pinned by test). Allocating a `Drop`
137    /// type (Rc, String, Vec, file handles…) leaks whatever the destructor
138    /// would have released; use arena allocation for plain data only.
139    pub fn alloc<T>(&self, val: T) -> &mut T {
140        self.bump.alloc(val)
141    }
142
143    /// Collect an iterator into an arena-allocated slice.
144    ///
145    /// This is the arena equivalent of `.collect::<Vec<T>>()` — it avoids
146    /// a heap allocation by writing elements directly into bump memory.
147    pub fn alloc_iter<T, I>(&self, iter: I) -> &mut [T]
148    where
149        I: IntoIterator<Item = T>,
150    {
151        let mut vec = bumpalo::collections::Vec::new_in(&self.bump);
152        vec.extend(iter);
153        vec.into_bump_slice_mut()
154    }
155
156    /// Create a new growable vector backed by this arena.
157    ///
158    /// Use this for scratch collections that grow via `push()` during
159    /// rendering. The vector's memory is reclaimed on arena reset.
160    pub fn new_vec<T>(&self) -> BumpVec<'_, T> {
161        bumpalo::collections::Vec::new_in(&self.bump)
162    }
163
164    /// Create a new growable vector with the given capacity.
165    pub fn new_vec_with_capacity<T>(&self, capacity: usize) -> BumpVec<'_, T> {
166        bumpalo::collections::Vec::with_capacity_in(capacity, &self.bump)
167    }
168
169    /// Create a new growable string backed by this arena.
170    pub fn new_string(&self) -> BumpString<'_> {
171        bumpalo::collections::String::new_in(&self.bump)
172    }
173
174    /// Create a new growable string with the given capacity.
175    pub fn new_string_with_capacity(&self, capacity: usize) -> BumpString<'_> {
176        bumpalo::collections::String::with_capacity_in(capacity, &self.bump)
177    }
178
179    /// Returns the total bytes allocated in the arena (across all chunks).
180    ///
181    /// IMPORTANT: after [`reset()`](Self::reset) this reports the RETAINED
182    /// chunk capacity (bumpalo keeps its largest chunk for reuse), not live
183    /// allocation usage — it never decreases on its own. Treating it as a
184    /// "current usage" signal creates ratchet-and-stick behavior: this
185    /// exact misreading made the frame guardrails' emergency verdict
186    /// permanent (fixed by rebuilding the arena on the drop path). To
187    /// actually release memory, drop and recreate the arena.
188    pub fn allocated_bytes(&self) -> usize {
189        self.bump.allocated_bytes()
190    }
191
192    /// Returns total allocated bytes including allocator metadata.
193    ///
194    /// This reflects chunk footprint, not currently live allocation usage.
195    /// Chunk memory is retained across [`reset()`](Self::reset) for reuse.
196    pub fn allocated_bytes_including_metadata(&self) -> usize {
197        self.bump.allocated_bytes_including_metadata()
198    }
199
200    /// Returns a reference to the underlying [`Bump`] allocator.
201    ///
202    /// Use this for advanced allocation patterns not covered by the
203    /// convenience methods.
204    pub fn as_bump(&self) -> &Bump {
205        &self.bump
206    }
207}
208
209impl Default for FrameArena {
210    fn default() -> Self {
211        Self::with_default_capacity()
212    }
213}
214
215#[cfg(test)]
216mod tests {
217    use super::*;
218
219    #[test]
220    fn core_arena_alloc_and_reset() {
221        let mut arena = FrameArena::new(4096);
222        let s = arena.alloc_str("ftui-core arena");
223        assert_eq!(s, "ftui-core arena");
224        let v = arena.alloc_slice(&[10u32, 20, 30]);
225        assert_eq!(v, &[10, 20, 30]);
226        arena.reset();
227        let s2 = arena.alloc_str("reused");
228        assert_eq!(s2, "reused");
229    }
230}