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