euv_core/reactive/signal/impl.rs
1use super::*;
2
3/// Manual `Clone` implementation so `Signal<T>` is always `Copy` regardless of `T`.
4impl<T> Clone for Signal<T>
5where
6 T: 'static,
7{
8 /// Copies the lightweight 8-byte signal handle.
9 ///
10 /// # Arguments
11 ///
12 /// - `&Self` - Signal handle to copy.
13 ///
14 /// # Returns
15 ///
16 /// - `Self` - Identical signal handle.
17 fn clone(&self) -> Self {
18 *self
19 }
20}
21
22/// Marker `Copy` implementation for `Signal<T>`.
23impl<T> Copy for Signal<T> where T: 'static {}
24
25/// Zero-allocation dangling `Default` handle for `Signal<T>`, used when initializing component prop descriptors.
26impl<T> Default for Signal<T>
27where
28 T: 'static,
29{
30 /// Constructs an unallocated placeholder `Signal<T>` handle with `SignalId::default()`.
31 ///
32 /// # Returns
33 ///
34 /// - `Self` - Zero-cost placeholder signal handle.
35 fn default() -> Self {
36 Self {
37 id: SignalId::default(),
38 marker: PhantomData,
39 }
40 }
41}
42
43/// Equality comparison by underlying `SignalId`.
44impl<T> PartialEq for Signal<T>
45where
46 T: 'static,
47{
48 /// Compares two signal handles by arena identifier.
49 ///
50 /// # Arguments
51 ///
52 /// - `&Self` - Left-hand signal handle.
53 /// - `&Self` - Right-hand signal handle.
54 ///
55 /// # Returns
56 ///
57 /// - `bool` - True if both handles reference the same arena slot and generation.
58 fn eq(&self, other: &Self) -> bool {
59 self.id() == other.id()
60 }
61}
62
63/// Reflexive equality for `Signal<T>`.
64impl<T> Eq for Signal<T> where T: 'static {}
65
66/// Hash implementation based on underlying `SignalId`.
67impl<T> Hash for Signal<T>
68where
69 T: 'static,
70{
71 /// Hashes the underlying arena signal identifier.
72 ///
73 /// # Arguments
74 ///
75 /// - `&Self` - Signal handle to hash.
76 /// - `&mut H` - Hasher state.
77 fn hash<H>(&self, state: &mut H)
78 where
79 H: Hasher,
80 {
81 self.id().hash(state);
82 }
83}
84
85/// Core reactive operations for `Signal<T>`.
86impl<T> Signal<T>
87where
88 T: 'static,
89{
90 /// Allocates a new reactive signal initialized with `initial_value`.
91 ///
92 /// # Arguments
93 ///
94 /// - `T` - Initial signal value.
95 ///
96 /// # Returns
97 ///
98 /// - `Self` - Copyable handle to the created signal.
99 #[must_use]
100 pub fn new(initial_value: T) -> Self {
101 let id: SignalId = with_runtime(
102 |rt: &mut ReactiveRuntime| rt.create_signal(initial_value),
103 SignalId::default(),
104 );
105 Self {
106 id,
107 marker: PhantomData,
108 }
109 }
110
111 /// Allocates a new reactive signal detached from any enclosing transient `Scope` so hub/store state survives UI rebuilds.
112 ///
113 /// # Arguments
114 ///
115 /// - `T` - Initial signal value.
116 ///
117 /// # Returns
118 ///
119 /// - `Self` - Copyable handle to the created detached signal.
120 #[must_use]
121 pub fn new_detached(initial_value: T) -> Self {
122 let id: SignalId = with_runtime(
123 |rt: &mut ReactiveRuntime| rt.create_detached_signal(initial_value),
124 SignalId::default(),
125 );
126 Self {
127 id,
128 marker: PhantomData,
129 }
130 }
131
132 /// Reconstructs a typed `Signal<T>` handle from an arena `SignalId`.
133 ///
134 /// # Arguments
135 ///
136 /// - `SignalId` - Arena signal identifier.
137 ///
138 /// # Returns
139 ///
140 /// - `Self` - Lightweight copyable signal handle.
141 #[must_use]
142 pub(crate) fn from_raw_id(id: SignalId) -> Self {
143 Self {
144 id,
145 marker: PhantomData,
146 }
147 }
148
149 /// Returns the underlying `SignalId`.
150 ///
151 /// # Arguments
152 ///
153 /// - `&Self` - Signal handle.
154 ///
155 /// # Returns
156 ///
157 /// - `SignalId` - Underlying arena identifier.
158 #[must_use]
159 #[inline(always)]
160 pub fn id(&self) -> SignalId {
161 let Self { id, .. } = *self;
162 id
163 }
164
165 /// Returns whether this signal currently has at least one active downstream subscriber.
166 ///
167 /// # Arguments
168 ///
169 /// - `&Self` - Signal handle to inspect.
170 ///
171 /// # Returns
172 ///
173 /// - `bool` - True when the signal is alive and observed by at least one memo or effect.
174 #[must_use]
175 #[inline(always)]
176 pub fn has_subscribers(&self) -> bool {
177 let id: SignalId = self.id();
178 with_runtime_ref(|rt: &ReactiveRuntime| rt.signal_has_subscribers(id), false)
179 }
180
181 /// Returns the number of active downstream subscribers observing this signal in O(1).
182 ///
183 /// # Arguments
184 ///
185 /// - `&Self` - Signal handle to inspect.
186 ///
187 /// # Returns
188 ///
189 /// - `usize` - Number of live memo or effect subscribers, or `0` if disposed.
190 #[must_use]
191 #[inline(always)]
192 pub fn subscriber_count(&self) -> usize {
193 let id: SignalId = self.id();
194 with_runtime_ref(|rt: &ReactiveRuntime| rt.signal_subscriber_count(id), 0)
195 }
196
197 /// Returns whether this live signal stores its value inline inside the 24-byte SBO buffer without heap allocation.
198 ///
199 /// # Arguments
200 ///
201 /// - `&Self` - Signal handle to inspect.
202 ///
203 /// # Returns
204 ///
205 /// - `bool` - `true` when alive and stored inline in SBO storage.
206 #[must_use]
207 #[inline(always)]
208 pub fn is_inline(&self) -> bool {
209 let id: SignalId = self.id();
210 with_runtime_ref(|rt: &ReactiveRuntime| rt.signal_is_inline(id), false)
211 }
212
213 /// Records a dependency on this signal in the active observer without cloning its value.
214 ///
215 /// # Arguments
216 ///
217 /// - `&Self` - Signal handle to track.
218 #[inline(always)]
219 pub fn track(&self) {
220 track_or_defer_dependency(DependencyId::Signal(self.id()));
221 }
222
223 /// Reads the current value by cloning and tracks the active observer dependency.
224 ///
225 /// # Arguments
226 ///
227 /// - `&Self` - Signal handle to read.
228 ///
229 /// # Returns
230 ///
231 /// - `Option<T>` - Current value if the signal is still alive.
232 #[must_use]
233 #[inline(always)]
234 pub fn try_get(&self) -> Option<T>
235 where
236 T: Clone,
237 {
238 let id: SignalId = self.id();
239 if ref_borrow_depth() > 0 || !is_tracking_active() {
240 return read_signal_with_ref::<T, _, T>(id, true, |val: &T| val.clone());
241 }
242 with_runtime(
243 |rt: &mut ReactiveRuntime| rt.read_signal_cloned::<T>(id),
244 None,
245 )
246 }
247
248 /// Reads the current value, returning `T::default()` if the signal was disposed.
249 ///
250 /// # Arguments
251 ///
252 /// - `&Self` - Signal handle to read.
253 ///
254 /// # Returns
255 ///
256 /// - `T` - Current value or default fallback.
257 #[must_use]
258 #[inline(always)]
259 pub fn get(&self) -> T
260 where
261 T: Clone + Default,
262 {
263 self.try_get().unwrap_or_default()
264 }
265
266 /// Reads the current value without tracking any reactive dependency.
267 ///
268 /// # Arguments
269 ///
270 /// - `&Self` - Signal handle to inspect.
271 ///
272 /// # Returns
273 ///
274 /// - `Option<T>` - Current value if alive.
275 #[must_use]
276 #[inline(always)]
277 pub fn try_get_untracked(&self) -> Option<T>
278 where
279 T: Clone,
280 {
281 let id: SignalId = self.id();
282 with_runtime_ref(
283 |rt: &ReactiveRuntime| rt.read_signal_untracked::<T>(id),
284 None,
285 )
286 }
287
288 /// Reads the current value untracked, returning `T::default()` if disposed.
289 ///
290 /// # Arguments
291 ///
292 /// - `&Self` - Signal handle to inspect.
293 ///
294 /// # Returns
295 ///
296 /// - `T` - Current value or default fallback.
297 #[must_use]
298 #[inline(always)]
299 pub fn get_untracked(&self) -> T
300 where
301 T: Clone + Default,
302 {
303 self.try_get_untracked().unwrap_or_default()
304 }
305
306 /// Applies `f` directly to a shared borrowed `&T` inside the arena without cloning, returning `None` if disposed or mutably borrowed.
307 ///
308 /// # Arguments
309 ///
310 /// - `&Self` - Signal handle to borrow.
311 /// - `impl FnOnce(&T) -> R` - Read-only closure receiving `&T` (nested `with_ref` calls are supported).
312 ///
313 /// # Returns
314 ///
315 /// - `Option<R>` - Closure return value when the signal is alive and readable.
316 #[inline]
317 pub fn try_with_ref<R>(&self, f: impl FnOnce(&T) -> R) -> Option<R> {
318 read_signal_with_ref::<T, _, R>(self.id(), true, f)
319 }
320
321 /// Applies `f` directly to a shared borrowed `&T` without tracking dependencies or cloning, returning `None` if disposed or mutably borrowed.
322 ///
323 /// # Arguments
324 ///
325 /// - `&Self` - Signal handle to borrow untracked.
326 /// - `impl FnOnce(&T) -> R` - Read-only closure receiving `&T`.
327 ///
328 /// # Returns
329 ///
330 /// - `Option<R>` - Closure return value when the signal is alive and readable.
331 #[inline]
332 pub fn try_with_ref_untracked<R>(&self, f: impl FnOnce(&T) -> R) -> Option<R> {
333 read_signal_with_ref::<T, _, R>(self.id(), false, f)
334 }
335
336 /// Applies `f` directly to a shared borrowed `&T` inside the arena without cloning and tracks the active observer dependency.
337 ///
338 /// # Arguments
339 ///
340 /// - `&Self` - Signal handle to borrow.
341 /// - `impl FnOnce(&T) -> R` - Read-only closure receiving `&T` (nested read-only `with_ref` calls are supported; do not mutate signals inside `f`).
342 ///
343 /// # Returns
344 ///
345 /// - `R` - Value returned by `f`.
346 #[inline]
347 pub fn with_ref<R>(&self, f: impl FnOnce(&T) -> R) -> R {
348 self.try_with_ref(f).unwrap()
349 }
350
351 /// Applies `reader` to a cloned snapshot outside any `RefCell` borrow so re-entrant mutating callbacks remain safe.
352 ///
353 /// # Arguments
354 ///
355 /// - `&Self` - Signal handle to read.
356 /// - `F` - Reader closure receiving `&T`.
357 ///
358 /// # Returns
359 ///
360 /// - `Option<R>` - Closure return value if the signal is alive.
361 #[inline]
362 pub fn with<F, R>(&self, reader: F) -> Option<R>
363 where
364 T: Clone,
365 F: FnOnce(&T) -> R,
366 {
367 let snapshot: T = self.try_get()?;
368 Some(reader(&snapshot))
369 }
370
371 /// Replaces the stored value and flushes downstream reactive effects.
372 ///
373 /// # Arguments
374 ///
375 /// - `&Self` - Signal handle to write.
376 /// - `T` - Replacement value.
377 ///
378 /// # Returns
379 ///
380 /// - `bool` - True when the signal was alive and updated.
381 #[inline(always)]
382 pub fn set(&self, value: T) -> bool {
383 let id: SignalId = self.id();
384 let (updated, should_flush): (bool, bool) = with_runtime(
385 |rt: &mut ReactiveRuntime| rt.write_signal(id, value),
386 (false, false),
387 );
388 if should_flush {
389 flush_effects();
390 }
391 updated
392 }
393
394 /// Replaces the stored value only when `value` differs from the current stored value.
395 ///
396 /// # Arguments
397 ///
398 /// - `&Self` - Signal handle to write.
399 /// - `T` - Candidate value.
400 ///
401 /// # Returns
402 ///
403 /// - `bool` - True when the value changed and downstream effects were scheduled.
404 #[inline(always)]
405 pub fn set_if_changed(&self, value: T) -> bool
406 where
407 T: PartialEq,
408 {
409 let id: SignalId = self.id();
410 let (updated, should_flush): (bool, bool) = with_runtime(
411 |rt: &mut ReactiveRuntime| rt.write_signal_if_changed(id, value),
412 (false, false),
413 );
414 if should_flush {
415 flush_effects();
416 }
417 updated
418 }
419
420 /// Mutates the signal value in place outside the runtime borrow without cloning and flushes effects.
421 ///
422 /// # Arguments
423 ///
424 /// - `&Self` - Signal handle to update.
425 /// - `F` - Mutation closure receiving `&mut T`.
426 ///
427 /// # Returns
428 ///
429 /// - `bool` - True when the signal was alive and updated.
430 #[inline]
431 pub fn update<F>(&self, updater: F) -> bool
432 where
433 T: Clone,
434 F: FnOnce(&mut T),
435 {
436 let id: SignalId = self.id();
437 let Some(mut slot) = with_runtime(
438 |rt: &mut ReactiveRuntime| rt.take_signal_slot::<T>(id),
439 None,
440 ) else {
441 return false;
442 };
443 if let Some(current) = slot.downcast_mut::<T>() {
444 updater(current);
445 }
446 let (updated, should_flush): (bool, bool) = with_runtime(
447 |rt: &mut ReactiveRuntime| rt.commit_signal_slot(id, slot),
448 (false, false),
449 );
450 if should_flush {
451 flush_effects();
452 }
453 updated
454 }
455
456 /// Disposes this signal, unlinks its edges in O(deg), and drops its payload outside the runtime borrow.
457 ///
458 /// # Arguments
459 ///
460 /// - `&Self` - Signal handle to dispose.
461 pub fn dispose(&self) {
462 let id: SignalId = self.id();
463 let dropped: SignalSlot = with_runtime(
464 |rt: &mut ReactiveRuntime| rt.dispose_signal(id),
465 SignalSlot::empty(),
466 );
467 drop(dropped);
468 }
469}