1#![no_std]
4#![forbid(unsafe_code)]
5extern crate alloc;
6#[cfg(feature = "observability")]
9extern crate std;
10
11use alloc::rc::Rc;
12use core::{
13 any::TypeId,
14 cell::RefCell,
15 hash::{Hash, Hasher},
16 panic::Location,
17};
18
19use crate::watcher::{Context, WatcherGuard};
20
21#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
23pub struct SignalIdentity(usize);
24
25impl SignalIdentity {
26 #[must_use]
31 pub fn from_rc<T>(value: &Rc<T>) -> Self {
32 Self::from_ptr(Rc::as_ptr(value))
33 }
34
35 #[must_use]
41 pub fn from_ptr<T>(value: *const T) -> Self {
42 let value = value.cast::<()>() as usize;
43 assert!(value != 0, "signal identity pointer must not be null");
44 Self(value)
45 }
46
47 #[must_use]
49 pub const fn raw(self) -> usize {
50 self.0
51 }
52
53 #[must_use]
55 pub const fn with_discriminator(self, discriminator: usize) -> Self {
56 Self(
57 self.0.wrapping_mul(0x9E37_79B9usize).rotate_left(7)
58 ^ discriminator.wrapping_add(0x517C_C1B7usize),
59 )
60 }
61
62 #[must_use]
64 pub const fn combine(self, other: Self) -> Self {
65 self.with_discriminator(other.0)
66 }
67
68 #[must_use]
70 pub fn call_site_discriminator<T: 'static>(caller: &'static Location<'static>) -> usize {
71 let mut hasher = IdentityDiscriminatorHasher::new();
72 TypeId::of::<T>().hash(&mut hasher);
73 caller.file().hash(&mut hasher);
74 caller.line().hash(&mut hasher);
75 caller.column().hash(&mut hasher);
76 hasher.value()
77 }
78}
79
80struct IdentityDiscriminatorHasher(usize);
81
82impl IdentityDiscriminatorHasher {
83 const OFFSET: usize = 0x811C_9DC5;
84 const PRIME: usize = 0x0100_0193;
85
86 const fn new() -> Self {
87 Self(Self::OFFSET)
88 }
89
90 const fn value(&self) -> usize {
91 self.0
92 }
93}
94
95impl Hasher for IdentityDiscriminatorHasher {
96 fn finish(&self) -> u64 {
97 self.0 as u64
98 }
99
100 fn write(&mut self, bytes: &[u8]) {
101 for byte in bytes {
102 self.0 ^= usize::from(*byte);
103 self.0 = self.0.wrapping_mul(Self::PRIME);
104 self.0 = self.0.rotate_left(5);
105 }
106 }
107}
108
109pub mod collection;
111pub mod dictionary;
112pub mod id;
113pub mod observe;
114pub mod watcher;
115
116pub use id::{Identifiable, IdentifiableExt, SelfId, UseId};
117
118#[diagnostic::on_unimplemented(
123 message = "`{Self}` is not a nami `Signal`",
124 label = "expected a `Signal` implementation",
125 note = "`Signal` is nami's reactive read trait; wrap a value in `nami::Binding` or `nami::Computed`, or create a fixed one with `nami::constant(value)`"
126)]
127pub trait Signal: Clone + 'static {
128 type Output: 'static;
130 type Guard: WatcherGuard;
132
133 fn snapshot(&self) -> Self::Output;
141
142 fn with_ref<R>(&self, f: impl FnOnce(&Self::Output) -> R) -> R {
153 f(&self.snapshot())
154 }
155
156 fn identity(&self) -> Option<SignalIdentity> {
161 None
162 }
163
164 #[must_use = "the watcher stops when its guard is dropped"]
168 fn watch(&self, watcher: impl Fn(Context<Self::Output>) + 'static) -> Self::Guard;
169}
170
171pub trait CustomBinding: Signal {
176 fn set(&self, value: Self::Output);
180}
181
182#[macro_export]
187macro_rules! impl_constant {
188 ($($ty:ty),*) => {
189 $(
190 impl $crate::Signal for $ty {
191 type Output = Self;
192 type Guard = ();
193
194 fn snapshot(&self) -> Self::Output {
195 self.clone()
196 }
197
198 fn with_ref<R>(&self, f: impl FnOnce(&Self::Output) -> R) -> R {
199 f(self)
200 }
201
202 fn watch(
203 &self,
204 _watcher: impl Fn($crate::watcher::Context<Self::Output>)+'static,
205 ) {
206
207 }
208 }
209 )*
210 };
211
212}
213
214macro_rules! impl_generic_constant {
215
216 ( $($ty:ident < $($param:ident),* >),* $(,)? ) => {
217 $(
218 impl<$($param: Clone + 'static),*> $crate::Signal for $ty<$($param),*> {
219 type Output = Self;
220 type Guard = ();
221
222 fn snapshot(&self) -> Self::Output {
223 self.clone()
224 }
225
226 fn with_ref<R>(&self, f: impl FnOnce(&Self::Output) -> R) -> R {
227 f(self)
228 }
229
230 fn watch(
231 &self,
232 _watcher: impl Fn($crate::watcher::Context<Self::Output>)+'static,
233 ) {
234
235 }
236 }
237 )*
238 };
239
240
241
242
243}
244
245mod impl_constant {
246 use alloc::borrow::Cow;
247 use alloc::collections::{BTreeMap, BTreeSet};
248 use core::time::Duration;
249
250 use crate::Signal;
251 use alloc::string::String;
252 use alloc::vec::Vec;
253 impl_constant!(
254 &'static str,
255 u8,
256 u16,
257 u32,
258 u64,
259 usize,
260 i8,
261 i16,
262 i32,
263 i64,
264 isize,
265 f32,
266 f64,
267 bool,
268 char,
269 Duration,
270 String,
271 Cow<'static, str>
272 );
273
274 impl_generic_constant!(Vec<T>,BTreeMap<K,V>,BTreeSet<T>);
275
276 impl<T: 'static> Signal for &'static [T] {
277 type Output = &'static [T];
278 type Guard = ();
279 fn snapshot(&self) -> Self::Output {
280 self
281 }
282 fn with_ref<R>(&self, f: impl FnOnce(&Self::Output) -> R) -> R {
283 f(self)
284 }
285 fn watch(&self, _watcher: impl Fn(crate::watcher::Context<Self::Output>) + 'static) {}
286 }
287
288 impl<T: Clone + 'static, const N: usize> Signal for [T; N] {
292 type Output = Self;
293 type Guard = ();
294 fn snapshot(&self) -> Self::Output {
295 self.clone()
296 }
297 fn with_ref<R>(&self, f: impl FnOnce(&Self::Output) -> R) -> R {
298 f(self)
299 }
300 fn watch(&self, _watcher: impl Fn(crate::watcher::Context<Self::Output>) + 'static) {}
301 }
302}
303
304#[cfg(feature = "kurbo")]
309mod impl_kurbo_constant {
310 use kurbo::{
311 Affine, Arc, BezPath, Circle, CircleSegment, CubicBez, Ellipse, Insets, Line, PathEl,
312 Point, QuadBez, Rect, RoundedRect, RoundedRectRadii, Size, Stroke, Vec2,
313 };
314
315 impl_constant!(
316 Affine,
317 Arc,
318 BezPath,
319 Circle,
320 CircleSegment,
321 CubicBez,
322 Ellipse,
323 Insets,
324 Line,
325 PathEl,
326 Point,
327 QuadBez,
328 Rect,
329 RoundedRect,
330 RoundedRectRadii,
331 Size,
332 Stroke,
333 Vec2
334 );
335
336 #[cfg(test)]
337 mod tests {
338 use kurbo::Affine;
339
340 use crate::Signal;
341
342 #[test]
343 fn plain_affine_is_a_constant_signal() {
344 let affine = Affine::translate((1.0, 2.0));
345 assert_eq!(affine.snapshot(), affine);
346 let () = affine.watch(|_| unreachable!("a constant never notifies"));
347 }
348 }
349}
350
351impl<T: Signal> Signal for Option<T> {
352 type Output = Option<T::Output>;
353 type Guard = Option<T::Guard>;
354 fn snapshot(&self) -> Self::Output {
355 self.as_ref().map(Signal::snapshot)
356 }
357 fn identity(&self) -> Option<SignalIdentity> {
358 self.as_ref().and_then(Signal::identity)
359 }
360 fn watch(&self, watcher: impl Fn(Context<Self::Output>) + 'static) -> Self::Guard {
361 self.as_ref()
362 .map(|s| s.watch(move |context| watcher(context.map(Some))))
363 }
364}
365
366impl<T: Signal, E: Signal> Signal for Result<T, E> {
367 type Output = Result<T::Output, E::Output>;
368 type Guard = Result<T::Guard, E::Guard>;
369 fn snapshot(&self) -> Self::Output {
370 match &self {
371 Ok(s) => Ok(s.snapshot()),
372 Err(e) => Err(e.snapshot()),
373 }
374 }
375 fn identity(&self) -> Option<SignalIdentity> {
376 match &self {
377 Ok(s) => s.identity(),
378 Err(e) => e.identity(),
379 }
380 }
381 fn watch(&self, watcher: impl Fn(Context<Self::Output>) + 'static) -> Self::Guard {
382 match &self {
383 Ok(s) => Ok(s.watch(move |context| watcher(context.map(Ok)))),
384 Err(e) => Err(e.watch(move |context| watcher(context.map(Err)))),
385 }
386 }
387}
388
389struct TupleWatchState<L, R, W> {
390 latest_left: RefCell<L>,
391 latest_right: RefCell<R>,
392 watcher: W,
393}
394
395impl<T, U> Signal for (T, U)
396where
397 T: Signal,
398 U: Signal,
399 T::Output: Clone,
400 U::Output: Clone,
401{
402 type Output = (T::Output, U::Output);
403 type Guard = (T::Guard, U::Guard);
404
405 fn snapshot(&self) -> Self::Output {
406 (self.0.snapshot(), self.1.snapshot())
407 }
408
409 fn watch(&self, watcher: impl Fn(Context<Self::Output>) + 'static) -> Self::Guard {
410 let state = Rc::new(TupleWatchState {
411 latest_left: RefCell::new(self.0.snapshot()),
412 latest_right: RefCell::new(self.1.snapshot()),
413 watcher,
414 });
415
416 let left_guard = {
417 let state = Rc::clone(&state);
418 self.0.watch(move |ctx: Context<T::Output>| {
419 let updated_left = ctx.value().clone();
420 *state.latest_left.borrow_mut() = updated_left;
421 let right = state.latest_right.borrow().clone();
422 (state.watcher)(ctx.map(|left| (left, right)));
423 })
424 };
425
426 let right_guard = self.1.watch(move |ctx: Context<U::Output>| {
427 let updated_right = ctx.value().clone();
428 *state.latest_right.borrow_mut() = updated_right;
429 let left = state.latest_left.borrow().clone();
430 (state.watcher)(ctx.map(|right| (left, right)));
431 });
432
433 (left_guard, right_guard)
434 }
435}
436
437#[cfg(test)]
438mod tests {
439 use alloc::{rc::Rc, vec, vec::Vec};
440 use core::cell::RefCell;
441
442 use crate::{Signal, watcher::Context};
443
444 #[derive(Clone)]
445 struct TestSignal<T> {
446 value: Rc<RefCell<T>>,
447 watchers: Rc<RefCell<Vec<Watcher<T>>>>,
448 }
449
450 type Watcher<T> = Rc<dyn Fn(Context<T>)>;
451
452 impl<T: Clone + 'static> TestSignal<T> {
453 fn new(value: T) -> Self {
454 Self {
455 value: Rc::new(RefCell::new(value)),
456 watchers: Rc::new(RefCell::new(Vec::new())),
457 }
458 }
459
460 fn set(&self, value: T) {
461 *self.value.borrow_mut() = value.clone();
462 for watcher in self.watchers.borrow().iter() {
463 watcher(Context::from(value.clone()));
464 }
465 }
466 }
467
468 impl<T: Clone + 'static> Signal for TestSignal<T> {
469 type Output = T;
470 type Guard = ();
471
472 fn snapshot(&self) -> Self::Output {
473 self.value.borrow().clone()
474 }
475
476 fn watch(&self, watcher: impl Fn(Context<Self::Output>) + 'static) -> Self::Guard {
477 self.watchers.borrow_mut().push(Rc::new(watcher));
478 }
479 }
480
481 #[test]
482 fn tuple_signal_tracks_both_inputs() {
483 let left = TestSignal::new(1_i32);
484 let right = TestSignal::new(2_i32);
485 let pair = (left.clone(), right.clone());
486 let updates = Rc::new(RefCell::new(Vec::new()));
487
488 let _ = pair.watch({
489 let updates = updates.clone();
490 move |ctx| {
491 updates.borrow_mut().push(ctx.into_value());
492 }
493 });
494
495 left.set(3);
496 right.set(4);
497
498 assert_eq!(pair.snapshot(), (3, 4));
499 assert_eq!(*updates.borrow(), vec![(3, 2), (3, 4)]);
500 }
501}