Skip to main content

velox_engine/pod/
handle.rs

1//! 状态槽位唯一标识符 `PodId` 与强类型句柄 `Handle<T>`。
2
3use core::marker::PhantomData;
4
5/// 状态槽位唯一标识符(2 字节)。
6#[repr(transparent)]
7#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Default, Hash)]
8pub struct PodId(pub u16);
9
10/// 常驻 `PodPool` 的强类型组件句柄(4 字节:2 字节 `PodId` + 2 字节代号 `generation`,防止 ABA 释放后重用旧句柄误指向新实例)。
11#[repr(C)]
12pub struct Handle<T> {
13    pub(crate) id: PodId,
14    pub(crate) generation: u16,
15    _marker: PhantomData<T>,
16}
17
18impl<T> Copy for Handle<T> {}
19impl<T> Clone for Handle<T> {
20    #[inline(always)]
21    fn clone(&self) -> Self {
22        *self
23    }
24}
25
26impl<T> PartialEq for Handle<T> {
27    #[inline(always)]
28    fn eq(&self, other: &Self) -> bool {
29        self.id == other.id && self.generation == other.generation
30    }
31}
32impl<T> Eq for Handle<T> {}
33
34impl<T> core::fmt::Debug for Handle<T> {
35    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
36        f.debug_struct("Handle")
37            .field("id", &self.id)
38            .field("generation", &self.generation)
39            .finish()
40    }
41}
42
43impl<T> Handle<T> {
44    /// 创建一个指向给定 `PodId`(默认第 0 代)的强类型句柄。
45    #[inline(always)]
46    pub const fn new(id: PodId) -> Self {
47        Self {
48            id,
49            generation: 0,
50            _marker: PhantomData,
51        }
52    }
53
54    /// 创建一个带有显式代号 `generation` 的强类型句柄。
55    #[inline(always)]
56    pub const fn with_generation(id: PodId, generation: u16) -> Self {
57        Self {
58            id,
59            generation,
60            _marker: PhantomData,
61        }
62    }
63
64    /// 获取底层 `PodId`。
65    #[inline(always)]
66    pub const fn pod_id(self) -> PodId {
67        self.id
68    }
69
70    /// 获取槽位代号 `generation`。
71    #[inline(always)]
72    pub const fn generation(self) -> u16 {
73        self.generation
74    }
75}
76
77impl<T: crate::element::View> Handle<T> {
78    /// 在前景异步协程中安全更新当前句柄指向的视图状态(与 GPUI `WeakEntity::update` 对齐)。
79    ///
80    /// 自动校验 ABA `generation`、防重入、标脏当前视图并刷新 `Signal` 依赖;若视图已卸载则安全返回 `None`。
81    #[inline]
82    pub fn update<R>(
83        self,
84        cx: &mut crate::async_rt::AsyncApp,
85        f: impl FnOnce(&mut T, &mut super::ActionScope) -> R,
86    ) -> Option<R> {
87        cx.update(self, f)
88    }
89
90    /// 在前景异步协程中只读访问当前句柄指向的视图状态(若视图已卸载则安全返回 `None`)。
91    #[inline]
92    pub fn read<R>(
93        self,
94        cx: &crate::async_rt::AsyncApp,
95        f: impl FnOnce(&T) -> R,
96    ) -> Option<R> {
97        cx.read(self, f)
98    }
99}
100