Skip to main content

velox_engine/arena/
scratch.rs

1//! `ScratchArena` 瞬态帧内存池。
2
3use core::cell::Cell;
4use core::fmt;
5use core::mem::{align_of, size_of};
6
7use super::StrRef;
8
9/// 单帧瞬态竞技场默认容量(依托虚拟列表按需挂载与布局树水位线即时回收)。
10pub const SCRATCH_CAPACITY: usize = 4992;
11
12/// 基于 `bumpalo::Bump` 的帧级瞬态内存池,帧末 `rewind()` 零分配复用。
13pub struct ScratchArena<const CAP: usize = SCRATCH_CAPACITY> {
14    inner: bumpalo::Bump,
15    used: Cell<usize>,
16    peak_used: Cell<usize>,
17    truncation_count: Cell<u32>,
18}
19
20impl<const CAP: usize> Default for ScratchArena<CAP> {
21    fn default() -> Self {
22        Self::new()
23    }
24}
25
26impl<const CAP: usize> ScratchArena<CAP> {
27    /// 创建一个新的瞬态帧内存池。
28    #[inline]
29    pub fn new() -> Self {
30        Self {
31            inner: bumpalo::Bump::with_capacity(CAP),
32            used: Cell::new(0),
33            peak_used: Cell::new(0),
34            truncation_count: Cell::new(0),
35        }
36    }
37
38    #[inline(always)]
39    fn set_used_std(&self, next: usize) {
40        self.used.set(next);
41        if next > self.peak_used.get() {
42            self.peak_used.set(next);
43        }
44    }
45
46    /// 尝试在帧池中无 panic 分配单个对象。
47    #[inline]
48    pub fn try_alloc<'a, T>(&'a self, val: T) -> Option<&'a mut T> {
49        let align = align_of::<T>().max(1);
50        let size = size_of::<T>();
51        let cur = (self.used.get() + align - 1) & !(align - 1);
52        self.set_used_std(cur + size);
53        Some(self.inner.alloc(val))
54    }
55
56    /// 在帧池中分配单个节点或事件闭包(返回 `'a` 可变引用,彻底消除 `Box` 堆分配)。
57    #[inline(always)]
58    pub fn alloc<'a, T>(&'a self, val: T) -> &'a mut T {
59        self.try_alloc(val).expect("ScratchArena overflow")
60    }
61
62    /// 尝试在帧池中无 panic 分配临时树节点。
63    #[inline]
64    pub fn try_alloc_temp<'a, T>(&'a self, val: T) -> Option<&'a mut T> {
65        self.try_alloc(val)
66    }
67
68    /// 分配仅在布局求解阶段存活的临时树节点(`ElementNode` / `Element` / `DivVisual`)。
69    #[inline(always)]
70    pub fn alloc_temp<'a, T>(&'a self, val: T) -> &'a mut T {
71        self.try_alloc_temp(val)
72            .expect("ScratchArena temp overflow")
73    }
74
75    /// 回收临时元素树节点。
76    ///
77    /// # Safety
78    /// 调用此函数后,此前通过 `alloc_temp` 获得的引用不得再被解引用。
79    #[inline(always)]
80    pub(crate) unsafe fn reset_temp(&self) {
81    }
82
83    /// 获取当前临时区水位线(用于保留 `LayoutNode` 树以供 Pass-4 快路径跨帧复用)。
84    #[inline(always)]
85    pub(crate) fn save_temp_mark(&self) -> usize {
86        CAP
87    }
88
89    /// 恢复临时区水位线至指定位置。
90    #[inline(always)]
91    pub(crate) fn restore_temp_mark(&mut self, mark: usize) {
92        let _ = mark;
93    }
94
95    /// 回滚本帧试探性分配的水位线(仅供求解器内部试探失败时回退刚分配的临时节点)。
96    #[inline(always)]
97    pub(crate) unsafe fn rollback_speculative_marks(&self, mark: usize, temp_mark: usize) {
98        let _ = temp_mark;
99        if mark <= self.used.get() {
100            self.used.set(mark);
101        }
102    }
103
104    /// 检查给定指针是否仍位于当前竞技场尚未被 `rewind` / `reset_temp` 回收的有效临时树区间内。
105    #[inline(always)]
106    pub(crate) fn contains_temp_ptr(&self, ptr: *const u8) -> bool {
107        if ptr.is_null() {
108            return false;
109        }
110        self.used.get() > 0
111    }
112
113    /// 在帧池中分配长度为 `len` 的对齐字节切片 `&'a mut [u8]`。
114    #[inline(always)]
115    pub fn alloc_bytes<'a>(&'a self, len: usize) -> &'a mut [u8] {
116        if len == 0 {
117            return &mut [];
118        }
119        self.set_used_std(self.used.get() + len);
120        self.inner.alloc_slice_fill_copy(len, 0u8)
121    }
122
123    /// 无需 `Vec` 中转,直接将任意迭代器原地展开为连续内存切片 `&'a mut [T]`。
124    pub fn alloc_iter<'a, T, I>(&'a self, iter: I) -> &'a mut [T]
125    where
126        I: IntoIterator<Item = T>,
127    {
128        let mut iter = iter.into_iter();
129        let (lower, upper) = iter.size_hint();
130
131        let size = size_of::<T>();
132        if Some(lower) == upper {
133            let count = lower;
134            if count == 0 || size == 0 {
135                return &mut [];
136            }
137            self.set_used_std(self.used.get() + count.saturating_mul(size));
138            return self.inner.alloc_slice_fill_with(count, |_| {
139                iter.next().expect("Exact size_hint mismatch")
140            });
141        }
142        let mut vec = bumpalo::collections::Vec::with_capacity_in(lower, &self.inner);
143        for item in iter {
144            vec.push(item);
145        }
146        self.set_used_std(self.used.get() + vec.len().saturating_mul(size));
147        vec.into_bump_slice_mut()
148    }
149
150    /// 将任意临时字符串切片 `s` 拷贝至当前 `ScratchArena`,返回 `StrRef<'a>`。
151    #[inline]
152    pub fn alloc_str<'a>(&'a self, s: &str) -> StrRef<'a> {
153        if s.is_empty() {
154            return StrRef::Static("");
155        }
156        let copied = self.inner.alloc_str(s);
157        self.set_used_std(self.used.get() + copied.len());
158        StrRef::Scratch(copied)
159    }
160
161    /// 将 `format_args!` 字节流直接写入当前 `ScratchArena`,返回 `StrRef<'a>`。
162    pub fn alloc_fmt<'a>(&'a self, args: fmt::Arguments<'_>) -> StrRef<'a> {
163        if let Some(static_str) = args.as_str() {
164            return StrRef::Static(static_str);
165        }
166        let mut s = bumpalo::collections::String::new_in(&self.inner);
167        let _ = fmt::write(&mut s, args);
168        self.set_used_std(self.used.get() + s.len());
169        StrRef::Scratch(s.into_bump_str())
170    }
171
172    /// 重置帧内存池游标与本帧水位遥测,实现零分配跨帧复用。
173    #[inline(always)]
174    pub fn rewind(&mut self) {
175        self.used.set(0);
176        self.peak_used.set(0);
177        self.truncation_count.set(0);
178        self.inner.reset();
179    }
180
181    /// 保存当前竞技场游标水位线(用于阶段性临时数据分时复用回收)。
182    #[inline(always)]
183    pub fn save_mark(&self) -> usize {
184        self.used_bytes()
185    }
186
187    /// 恢复竞技场游标至指定水位线(需要可变引用 `&mut self`,静态保证此前分配的借用生命周期已结束)。
188    #[inline(always)]
189    pub fn restore_mark(&mut self, mark: usize) {
190        if mark <= self.used.get() {
191            self.used.set(mark);
192        }
193    }
194
195    /// 返回当前帧已使用的逻辑字节数。
196    #[inline(always)]
197    pub fn used_bytes(&self) -> usize {
198        self.used.get()
199    }
200
201    /// 返回当前周期内瞬态内存池触及的真实峰值字节数(`#![no_std]` 双端池计入 `cursor + (CAP - temp_cursor)`)。
202    #[inline(always)]
203    pub fn peak_used_bytes(&self) -> usize {
204        self.peak_used.get()
205    }
206
207    /// 返回当前周期内发生静默字符串截断(`alloc_str` / `alloc_fmt`)或临时切片空降级(`alloc_temp_iter_exact`)的累计次数。
208    #[inline(always)]
209    pub fn truncation_count(&self) -> u32 {
210        self.truncation_count.get()
211    }
212
213    /// 取出并清零当前周期内累计的静默截断次数(供 `VeloxEngine` 帧末汇总并透传至 `FlushReport`)。
214    #[inline(always)]
215    pub(crate) fn take_truncation_count(&self) -> u32 {
216        self.truncation_count.replace(0)
217    }
218
219    /// 将峰值水位基线重置为当前实时占用字节数(用于保留子树未调用 `rewind()` 的增量帧统计单帧真实高水位)。
220    #[inline(always)]
221    pub(crate) fn reset_peak_to_current(&self) {
222        self.peak_used.set(self.used.get());
223    }
224
225    /// 返回底层实际驻留字节数(`bumpalo::Bump::allocated_bytes()`,用于真实水位上限回收)。
226    #[inline(always)]
227    pub(crate) fn real_allocated_bytes(&self) -> usize {
228        self.inner.allocated_bytes()
229    }
230
231    /// 检查当前竞技场剩余空间是否足以容纳 `count` 个连续的 `T` 元素。
232    #[inline(always)]
233    pub fn can_alloc_slice<T>(&self, count: usize) -> bool {
234        let _ = count;
235        true
236    }
237
238    /// 检查当前竞技场临时区是否足以分配 `count` 个 `T` 元素。
239    #[inline(always)]
240    pub fn can_alloc_temp_slice<T>(&self, count: usize) -> bool {
241        let _ = count;
242        true
243    }
244
245    /// 批量分配由固定长度迭代器产生的连续切片 `&'a mut [T]`(供布局求解器构建 `LayoutNode` 子树使用)。
246    pub fn alloc_temp_iter_exact<'a, T, I>(&'a self, count: usize, iter: I) -> &'a mut [T]
247    where
248        I: IntoIterator<Item = T>,
249    {
250        if count == 0 || size_of::<T>() == 0 {
251            return &mut [];
252        }
253        self.alloc_iter(iter.into_iter().take(count))
254    }
255}