Skip to main content

velox_engine/arena/
str_ref.rs

1//! 零拷贝文本引用 `StrRef<'a>` 与帧内格式化宏 `fmt!`。
2
3use core::ops::Deref;
4
5/// 零堆分配文本引用:同时支持 Flash 静态字符串与 `ScratchArena` 帧内动态格式化文本。
6#[derive(Copy, Clone, Eq, Debug)]
7pub enum StrRef<'a> {
8    /// 编译期静态字符串切片。
9    Static(&'static str),
10    /// 分配在当前帧 `ScratchArena` 中的瞬态字符串切片。
11    Scratch(&'a str),
12}
13
14impl<'a> StrRef<'a> {
15    /// 获取底层 `&'a str` 切片。
16    #[inline(always)]
17    pub const fn as_str(&self) -> &'a str {
18        match *self {
19            StrRef::Static(s) => s,
20            StrRef::Scratch(s) => s,
21        }
22    }
23}
24
25impl<'a> PartialEq for StrRef<'a> {
26    #[inline]
27    fn eq(&self, other: &Self) -> bool {
28        self.as_str() == other.as_str()
29    }
30}
31
32impl<'a> Deref for StrRef<'a> {
33    type Target = str;
34    #[inline]
35    fn deref(&self) -> &Self::Target {
36        self.as_str()
37    }
38}
39
40impl<'a> core::fmt::Display for StrRef<'a> {
41    #[inline]
42    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
43        f.write_str(self.as_str())
44    }
45}
46
47impl<'a> From<&'a str> for StrRef<'a> {
48    #[inline(always)]
49    fn from(s: &'a str) -> Self {
50        StrRef::Scratch(s)
51    }
52}
53
54/// 帧内零堆分配格式化宏:直接将 `format_args!` 字节流写入 `ScratchArena` 当前游标处。
55#[macro_export]
56macro_rules! fmt {
57    ($cx:expr, $($arg:tt)*) => {
58        $cx.arena().alloc_fmt(core::format_args!($($arg)*))
59    };
60}