Skip to main content

velox_engine/signal/
handles.rs

1//! 强类型 4 字节零堆响应式句柄:`Signal<T>`、`Computed<T>` 与 `Effect`。
2
3use core::marker::PhantomData;
4
5use crate::pod::{ActionScope, FrameScope};
6
7use super::runtime::{
8    ensure_computed_fresh, notify_signal_changed, record_computed_read, record_signal_read,
9    run_effect_slot,
10};
11use super::table::{with_table, NodeKind, NodeState};
12use super::table::{ComputedSlot, SignalSlot};
13use super::storage::{default_eq_fn, InlineFnStorage, InlineValueStorage, NO_EDGE};
14use super::storage::TRACKER_INDEX_MASK;
15use super::MAX_EFFECTS;
16
17/// NSH 风格细粒度响应式信号句柄(4 字节 `Copy`,含 `generation` 代号校验)。
18///
19/// 支持 `T: Copy + 'static`(尺寸 `<= 16` 字节,对齐 `<= 8` 字节,零堆分配)。
20#[repr(C)]
21pub struct Signal<T: Copy + 'static> {
22    id: u16,
23    generation: u16,
24    _marker: PhantomData<T>,
25}
26
27impl<T: Copy + 'static> Copy for Signal<T> {}
28impl<T: Copy + 'static> Clone for Signal<T> {
29    #[inline(always)]
30    fn clone(&self) -> Self {
31        *self
32    }
33}
34
35impl<T: Copy + 'static> PartialEq for Signal<T> {
36    #[inline(always)]
37    fn eq(&self, other: &Self) -> bool {
38        self.id == other.id && self.generation == other.generation
39    }
40}
41impl<T: Copy + 'static> Eq for Signal<T> {}
42
43impl<T: Copy + 'static> core::fmt::Debug for Signal<T> {
44    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
45        f.debug_struct("Signal")
46            .field("id", &self.id)
47            .field("generation", &self.generation)
48            .finish()
49    }
50}
51
52impl<T: Copy + core::fmt::Display + 'static> core::fmt::Display for Signal<T> {
53    #[inline]
54    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
55        core::fmt::Display::fmt(&self.get(), f)
56    }
57}
58
59impl<T: Copy + core::fmt::Binary + 'static> core::fmt::Binary for Signal<T> {
60    #[inline]
61    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
62        core::fmt::Binary::fmt(&self.get(), f)
63    }
64}
65
66impl<T: Copy + core::fmt::LowerHex + 'static> core::fmt::LowerHex for Signal<T> {
67    #[inline]
68    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
69        core::fmt::LowerHex::fmt(&self.get(), f)
70    }
71}
72
73impl<T: Copy + core::fmt::UpperHex + 'static> core::fmt::UpperHex for Signal<T> {
74    #[inline]
75    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
76        core::fmt::UpperHex::fmt(&self.get(), f)
77    }
78}
79
80impl<T: Copy + PartialEq + 'static> PartialEq<T> for Signal<T> {
81    #[inline(always)]
82    fn eq(&self, other: &T) -> bool {
83        self.get() == *other
84    }
85}
86
87impl<T: Copy + PartialOrd + 'static> PartialOrd<T> for Signal<T> {
88    #[inline(always)]
89    fn partial_cmp(&self, other: &T) -> Option<core::cmp::Ordering> {
90        self.get().partial_cmp(other)
91    }
92}
93
94impl<T: Copy + core::ops::AddAssign<Rhs> + 'static, Rhs> core::ops::AddAssign<Rhs> for Signal<T> {
95    #[inline]
96    fn add_assign(&mut self, rhs: Rhs) {
97        self.update(|v| *v += rhs);
98    }
99}
100
101impl<T: Copy + core::ops::SubAssign<Rhs> + 'static, Rhs> core::ops::SubAssign<Rhs> for Signal<T> {
102    #[inline]
103    fn sub_assign(&mut self, rhs: Rhs) {
104        self.update(|v| *v -= rhs);
105    }
106}
107
108impl<T: Copy + core::ops::BitOrAssign<Rhs> + 'static, Rhs> core::ops::BitOrAssign<Rhs>
109    for Signal<T>
110{
111    #[inline]
112    fn bitor_assign(&mut self, rhs: Rhs) {
113        self.update(|v| *v |= rhs);
114    }
115}
116
117impl<T: Copy + core::ops::BitXorAssign<Rhs> + 'static, Rhs> core::ops::BitXorAssign<Rhs>
118    for Signal<T>
119{
120    #[inline]
121    fn bitxor_assign(&mut self, rhs: Rhs) {
122        self.update(|v| *v ^= rhs);
123    }
124}
125
126/// 创建一个新的响应式信号 [`Signal<T>`]。
127#[inline]
128pub fn signal<T: Copy + 'static>(initial: T) -> Signal<T> {
129    Signal::new(initial)
130}
131
132impl<T: Copy + 'static> Signal<T> {
133    /// 分配并初始化一个响应式信号(`std` 下自动扩容;若槽位回收则强制递增 `generation` 保证类型安全)。
134    pub fn new(initial: T) -> Self {
135        with_table(|tbl| {
136            let idx = if let Some(free_idx) = tbl.signals.iter().position(|s| !s.occupied) {
137                free_idx
138            } else {
139                if tbl.signals.len() < (TRACKER_INDEX_MASK as usize) {
140                    let new_idx = tbl.signals.len();
141                    tbl.signals.push(SignalSlot::empty());
142                    new_idx
143                } else {
144                    let cap = tbl.signals.len().max(1);
145                    let start = tbl.recycle_cursor % cap;
146                    (0..cap)
147                        .map(|off| (start + off) % cap)
148                        .find(|&i| !tbl.signals[i].has_any_subscribers())
149                        .unwrap_or_else(|| {
150                            let i = tbl.recycle_cursor % cap;
151                            tbl.recycle_cursor = tbl.recycle_cursor.wrapping_add(1);
152                            i
153                        })
154                }
155            };
156            tbl.recycle_cursor = idx.wrapping_add(1);
157            if tbl.signals[idx].occupied {
158                tbl.unlink_all_subs(NodeKind::Signal, idx as u16);
159                tbl.signals[idx].generation = tbl.signals[idx].generation.wrapping_add(1);
160            }
161            let slot = &mut tbl.signals[idx];
162            unsafe {
163                slot.storage.write(initial);
164            }
165            slot.version = 1;
166            slot.clear_all_subscribers();
167            slot.first_sub = NO_EDGE;
168            slot.owner_pool = 0;
169            slot.occupied = true;
170            Self {
171                id: idx as u16,
172                generation: slot.generation,
173                _marker: PhantomData,
174            }
175        })
176    }
177
178    /// 读取信号当前值;若处于 `View::render`、`Computed` 或 `Effect` 上下文中,自动注册依赖订阅。
179    #[inline]
180    pub fn get(self) -> T {
181        let (val, ver) = with_table(|tbl| {
182            let slot = tbl
183                .signals
184                .get(self.id as usize)
185                .expect("Attempted to read an out-of-range Signal");
186            assert!(
187                slot.occupied && slot.generation == self.generation,
188                "Attempted to read a disposed Signal"
189            );
190            let v = unsafe { slot.storage.read::<T>() };
191            (v, slot.version)
192        });
193        record_signal_read(self.id, self.generation, ver);
194        val
195    }
196
197    /// 在给定 [`FrameScope`] 中读取信号当前值,并显式将 `cx.current_pod()` 注册为订阅者。
198    #[inline]
199    pub fn get_in(self, cx: &FrameScope) -> T {
200        let pod_idx = cx.current_pod().0;
201        let (val, ver) = with_table(|tbl| {
202            let slot = tbl
203                .signals
204                .get_mut(self.id as usize)
205                .expect("Attempted to read an out-of-range Signal");
206            assert!(
207                slot.occupied && slot.generation == self.generation,
208                "Attempted to read a disposed Signal"
209            );
210            slot.add_subscriber(pod_idx);
211            let v = unsafe { slot.storage.read::<T>() };
212            (v, slot.version)
213        });
214        record_signal_read(self.id, self.generation, ver);
215        val
216    }
217
218    /// 读取信号当前值但不触发依赖追踪。
219    #[inline]
220    pub fn get_untracked(self) -> T {
221        with_table(|tbl| {
222            let slot = tbl
223                .signals
224                .get(self.id as usize)
225                .expect("Attempted to read an out-of-range Signal");
226            assert!(
227                slot.occupied && slot.generation == self.generation,
228                "Attempted to read a disposed Signal"
229            );
230            unsafe { slot.storage.read::<T>() }
231        })
232    }
233
234    /// 写入新值,递增信号版本号,通过三色 Push-Pull 图传播脏状态并自动通知订阅视图与 `Effect`。
235    #[inline]
236    pub fn set(self, val: T) {
237        let notify_info = with_table(|tbl| {
238            let idx = self.id as usize;
239            let slot = tbl.signals.get_mut(idx)?;
240            if !slot.occupied || slot.generation != self.generation {
241                return None;
242            }
243            unsafe {
244                slot.storage.write(val);
245            }
246            slot.version = slot.version.wrapping_add(1).max(1);
247            Some(tbl.push_dirty_from_signal(idx))
248        });
249        if let Some((has_subs, eff_mask)) = notify_info {
250            notify_signal_changed(has_subs, eff_mask);
251        }
252    }
253
254    /// 当新值与旧值不相等时才写入并通知订阅者(返回 `true` 表示发生了实际变更)。
255    #[inline]
256    pub fn set_if_changed(self, val: T) -> bool
257    where
258        T: PartialEq,
259    {
260        if self.get_untracked() != val {
261            self.set(val);
262            true
263        } else {
264            false
265        }
266    }
267
268    /// 原地修改信号值,递增版本号并自动通知所有订阅该信号的 `PodId`、`Computed` 与 `Effect`(闭包执行期间不持有全局表可变借用,100% 重入安全)。
269    #[inline]
270    pub fn update(self, f: impl FnOnce(&mut T)) {
271        let cur_opt = with_table(|tbl| {
272            let slot = tbl.signals.get(self.id as usize)?;
273            if !slot.occupied || slot.generation != self.generation {
274                return None;
275            }
276            Some(unsafe { slot.storage.read::<T>() })
277        });
278        let Some(mut cur_val) = cur_opt else {
279            return;
280        };
281        f(&mut cur_val);
282        let notify_info = with_table(|tbl| {
283            let idx = self.id as usize;
284            let slot = tbl.signals.get_mut(idx)?;
285            if !slot.occupied || slot.generation != self.generation {
286                return None;
287            }
288            unsafe {
289                slot.storage.write(cur_val);
290            }
291            slot.version = slot.version.wrapping_add(1).max(1);
292            Some(tbl.push_dirty_from_signal(idx))
293        });
294        if let Some((has_subs, eff_mask)) = notify_info {
295            notify_signal_changed(has_subs, eff_mask);
296        }
297    }
298
299    /// 在事件回调 [`ActionScope`] 中写入新值,并立即将所有订阅该信号的 `PodId` 标记到 `acx.pool` 脏队列中。
300    #[inline]
301    pub fn set_in(self, acx: &mut ActionScope, val: T) {
302        self.set(val);
303        acx.flush_signal_dirty_pods();
304    }
305
306    /// 在事件回调 [`ActionScope`] 中原地更新信号值,并立即将所有订阅该信号的 `PodId` 标记到 `acx.pool` 脏队列中。
307    #[inline]
308    pub fn update_in(self, acx: &mut ActionScope, f: impl FnOnce(&mut T)) {
309        self.update(f);
310        acx.flush_signal_dirty_pods();
311    }
312
313    /// 获取该信号当前的单调版本号。
314    #[inline]
315    pub fn version(self) -> u32 {
316        with_table(|tbl| {
317            tbl.signals
318                .get(self.id as usize)
319                .filter(|s| s.occupied && s.generation == self.generation)
320                .map(|s| s.version)
321                .unwrap_or(0)
322        })
323    }
324
325    /// 获取当前订阅了该信号的 `PodId` 位掩码(`bit i == 1` 表示 `PodId(i)` 依赖该信号)。
326    #[inline]
327    pub fn subscribers_mask(self) -> u64 {
328        with_table(|tbl| {
329            tbl.signals
330                .get(self.id as usize)
331                .filter(|s| s.occupied && s.generation == self.generation)
332                .map(|s| s.subscribers_mask)
333                .unwrap_or(0)
334        })
335    }
336
337    /// 销毁释放该信号槽位、回收其全部下游依赖边并递增 `generation`(防止 ABA 悬垂引用)。
338    pub fn dispose(self) -> bool {
339        with_table(|tbl| {
340            let idx = self.id as usize;
341            let valid = tbl
342                .signals
343                .get(idx)
344                .map(|s| s.occupied && s.generation == self.generation)
345                .unwrap_or(false);
346            if !valid {
347                return false;
348            }
349            tbl.unlink_all_subs(NodeKind::Signal, self.id);
350            let slot = &mut tbl.signals[idx];
351            slot.occupied = false;
352            slot.clear_all_subscribers();
353            slot.first_sub = NO_EDGE;
354            slot.generation = slot.generation.wrapping_add(1);
355            true
356        })
357    }
358}
359
360/// 三色 Push-Pull 惰性记忆化派生计算句柄(4 字节 `Copy`)。
361///
362/// 支持任意深度 `Signal -> Computed -> Computed -> Effect` 链与菱形依赖无 Glitch,
363/// 当上游重算结果与缓存值相同时自动触发 Early Cutoff 剪枝,跳过全部下游冗余计算。
364#[repr(C)]
365pub struct Computed<T: Copy + 'static> {
366    id: u16,
367    generation: u16,
368    _marker: PhantomData<T>,
369}
370
371impl<T: Copy + 'static> Copy for Computed<T> {}
372impl<T: Copy + 'static> Clone for Computed<T> {
373    #[inline(always)]
374    fn clone(&self) -> Self {
375        *self
376    }
377}
378
379/// 创建一个新的惰性记忆化派生计算节点 [`Computed<T>`](支持捕获 [`Signal`] / [`Computed`] 句柄的闭包,零堆分配)。
380///
381/// 对于内置标量与短元组(`bool`/`i*`/`u*`/`f32`/`f64`/`char` 等),自动启用 Early Cutoff 剪枝;
382/// 若自定义结构体需启用 Early Cutoff,可使用 [`computed_eq`]。
383#[inline]
384pub fn computed<T: Copy + 'static, F: Fn() -> T + Copy + 'static>(f: F) -> Computed<T> {
385    Computed::new(f)
386}
387
388/// 创建一个带有显式 `PartialEq` Early Cutoff 剪枝比较器的派生计算节点 [`Computed<T>`]。
389#[inline]
390pub fn computed_eq<T: Copy + PartialEq + 'static, F: Fn() -> T + Copy + 'static>(
391    f: F,
392) -> Computed<T> {
393    Computed::new_eq(f)
394}
395
396impl<T: Copy + 'static> Computed<T> {
397    /// 使用闭包或函数指针创建 `#![no_std]` 零分配派生计算节点。
398    pub fn new<F: Fn() -> T + Copy + 'static>(f: F) -> Self {
399        Self::new_with_eq(f, default_eq_fn::<T>())
400    }
401
402    /// 使用显式 `PartialEq` 比较器创建派生计算节点,当结果相等时阻止版本号递增以触发 Early Cutoff 剪枝。
403    pub fn new_eq<F: Fn() -> T + Copy + 'static>(f: F) -> Self
404    where
405        T: PartialEq,
406    {
407        unsafe fn eq_trampoline<T: Copy + PartialEq>(
408            a: *const InlineValueStorage,
409            b: *const InlineValueStorage,
410        ) -> bool {
411            let va = unsafe { (*a).read::<T>() };
412            let vb = unsafe { (*b).read::<T>() };
413            va == vb
414        }
415        Self::new_with_eq(f, Some(eq_trampoline::<T>))
416    }
417
418    fn new_with_eq<F: Fn() -> T + Copy + 'static>(
419        f: F,
420        eq_fn: Option<unsafe fn(*const InlineValueStorage, *const InlineValueStorage) -> bool>,
421    ) -> Self {
422        unsafe fn trampoline<T: Copy + 'static, F: Fn() -> T + Copy + 'static>(
423            fn_ptr: *const InlineFnStorage,
424            out: *mut InlineValueStorage,
425        ) {
426            let func = unsafe { &*(fn_ptr as *const F) };
427            let val = func();
428            unsafe {
429                (*out).write(val);
430            }
431        }
432
433        with_table(|tbl| {
434            let idx = if let Some(free_idx) = tbl.computeds.iter().position(|c| !c.occupied) {
435                free_idx
436            } else {
437                if tbl.computeds.len() < (TRACKER_INDEX_MASK as usize) {
438                    let new_idx = tbl.computeds.len();
439                    tbl.computeds.push(ComputedSlot::EMPTY);
440                    new_idx
441                } else {
442                    let i = tbl.computed_cursor % tbl.computeds.len().max(1);
443                    tbl.computed_cursor = tbl.computed_cursor.wrapping_add(1);
444                    i
445                }
446            };
447            if tbl.computeds[idx].occupied {
448                tbl.unlink_all_deps(NodeKind::Computed, idx as u16);
449                tbl.unlink_all_subs(NodeKind::Computed, idx as u16);
450                tbl.computeds[idx].generation = tbl.computeds[idx].generation.wrapping_add(1);
451            }
452            let slot = &mut tbl.computeds[idx];
453            unsafe {
454                slot.fn_storage.write(f);
455            }
456            slot.compute_fn = Some(trampoline::<T, F>);
457            slot.eq_fn = eq_fn;
458            slot.first_dep = NO_EDGE;
459            slot.first_sub = NO_EDGE;
460            slot.version = 0;
461            slot.eval_count = 0;
462            slot.state = NodeState::Dirty;
463            slot.initialized = false;
464            slot.occupied = true;
465            slot.computing = false;
466            Self {
467                id: idx as u16,
468                generation: slot.generation,
469                _marker: PhantomData,
470            }
471        })
472    }
473
474    /// 读取派生计算值:
475    /// - `Clean` 时 $O(1)$ 直接返回缓存;
476    /// - `Check` 时先递归验证上游(命中 Early Cutoff 则零重算直接恢复 `Clean`);
477    /// - 若处于外层 `Computed`、`Effect` 或 `View::render` 期间,自动建立依赖边并传递底层源信号订阅。
478    pub fn get(self) -> T {
479        let idx = self.id as usize;
480        let Some(ver) = ensure_computed_fresh(idx, self.generation) else {
481            panic!("Attempted to read a disposed or out-of-range Computed");
482        };
483        let val = with_table(|tbl| {
484            let slot = tbl
485                .computeds
486                .get(idx)
487                .expect("Attempted to read an out-of-range Computed");
488            assert!(
489                slot.occupied && slot.generation == self.generation,
490                "Attempted to read a disposed Computed"
491            );
492            unsafe { slot.cached.read::<T>() }
493        });
494        record_computed_read(self.id, self.generation, ver);
495        val
496    }
497
498    /// 获取该派生计算节点当前的内容版本号(仅当重算结果实质变化时递增)。
499    #[inline]
500    pub fn version(self) -> u32 {
501        with_table(|tbl| {
502            tbl.computeds
503                .get(self.id as usize)
504                .filter(|c| c.occupied && c.generation == self.generation)
505                .map(|c| c.version)
506                .unwrap_or(0)
507        })
508    }
509
510    /// 获取该派生计算节点实际执行计算函数的累计次数(用于验证记忆化缓存与 Early Cutoff 命中)。
511    #[inline]
512    pub fn eval_count(self) -> u32 {
513        with_table(|tbl| {
514            tbl.computeds
515                .get(self.id as usize)
516                .filter(|c| c.occupied && c.generation == self.generation)
517                .map(|c| c.eval_count)
518                .unwrap_or(0)
519        })
520    }
521
522    /// 销毁释放该派生计算节点并回收全部上下游依赖边(递增 `generation` 防 ABA)。
523    pub fn dispose(self) -> bool {
524        with_table(|tbl| {
525            let idx = self.id as usize;
526            let valid = tbl
527                .computeds
528                .get(idx)
529                .map(|c| c.occupied && c.generation == self.generation)
530                .unwrap_or(false);
531            if !valid {
532                return false;
533            }
534            tbl.unlink_all_deps(NodeKind::Computed, self.id);
535            tbl.unlink_all_subs(NodeKind::Computed, self.id);
536            let slot = &mut tbl.computeds[idx];
537            slot.occupied = false;
538            slot.initialized = false;
539            slot.computing = false;
540            slot.first_dep = NO_EDGE;
541            slot.first_sub = NO_EDGE;
542            slot.generation = slot.generation.wrapping_add(1);
543            true
544        })
545    }
546}
547
548/// NSH 风格响应式副作用观察器句柄(4 字节 `Copy`)。
549#[repr(C)]
550#[derive(Copy, Clone, PartialEq, Eq, Debug)]
551pub struct Effect {
552    id: u16,
553    generation: u16,
554}
555
556/// 创建并立即执行一次响应式副作用观察器 [`Effect`],当其读取的任何 [`Signal`] / [`Computed`] 发生实质变更时自动重跑。
557#[inline]
558pub fn effect<F: Fn() + Copy + 'static>(f: F) -> Effect {
559    Effect::new(f)
560}
561
562impl Effect {
563    /// 创建并立即执行一次响应式副作用观察器。
564    pub fn new<F: Fn() + Copy + 'static>(f: F) -> Self {
565        unsafe fn trampoline<F: Fn() + Copy + 'static>(fn_ptr: *const InlineFnStorage) {
566            let func = unsafe { &*(fn_ptr as *const F) };
567            func();
568        }
569
570        let (idx, generation) = with_table(|tbl| {
571            let idx = tbl
572                .effects
573                .iter()
574                .position(|e| !e.occupied)
575                .unwrap_or_else(|| {
576                    let i = tbl.effect_cursor % MAX_EFFECTS;
577                    tbl.effect_cursor = tbl.effect_cursor.wrapping_add(1);
578                    i
579                });
580            if tbl.effects[idx].occupied {
581                tbl.unlink_all_deps(NodeKind::Effect, idx as u16);
582                tbl.effects[idx].generation = tbl.effects[idx].generation.wrapping_add(1);
583            }
584            let slot = &mut tbl.effects[idx];
585            unsafe {
586                slot.fn_storage.write(f);
587            }
588            slot.run_fn = Some(trampoline::<F>);
589            slot.first_dep = NO_EDGE;
590            slot.run_count = 0;
591            slot.occupied = true;
592            slot.running = false;
593            (idx, slot.generation)
594        });
595
596        run_effect_slot(idx);
597
598        Self {
599            id: idx as u16,
600            generation,
601        }
602    }
603
604    /// 获取该副作用观察器累计执行的次数。
605    #[inline]
606    pub fn run_count(self) -> u32 {
607        with_table(|tbl| {
608            tbl.effects
609                .get(self.id as usize)
610                .filter(|e| e.occupied && e.generation == self.generation)
611                .map(|e| e.run_count)
612                .unwrap_or(0)
613        })
614    }
615
616    /// 停止并销毁该副作用观察器,并 $O(\text{deps})$ 精确回收其全部上游依赖边。
617    pub fn dispose(self) -> bool {
618        let idx = self.id as usize;
619        with_table(|tbl| {
620            let valid = tbl
621                .effects
622                .get(idx)
623                .map(|e| e.occupied && e.generation == self.generation)
624                .unwrap_or(false);
625            if !valid {
626                return false;
627            }
628            tbl.unlink_all_deps(NodeKind::Effect, self.id);
629            let slot = &mut tbl.effects[idx];
630            slot.occupied = false;
631            slot.first_dep = NO_EDGE;
632            slot.generation = slot.generation.wrapping_add(1);
633            true
634        })
635    }
636}