Skip to main content

mitsuami_core/
any_value.rs

1//! Type-erased values that can travel through commands and events.
2//!
3//! Commands stay comparable and printable (for logs, snapshots and the
4//! mirror check) even when they carry app-defined data: [`AnyValue`] keeps
5//! the value's own `PartialEq` and `Debug`, and [`Opaque`] is for payloads
6//! that have neither, like a native view factory.
7
8use std::any::Any;
9use std::fmt;
10use std::rc::Rc;
11
12trait DynValue: Any {
13    fn dyn_eq(&self, other: &dyn DynValue) -> bool;
14    fn dyn_fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result;
15    fn as_any(&self) -> &dyn Any;
16}
17
18impl<T: Any + PartialEq + fmt::Debug> DynValue for T {
19    fn dyn_eq(&self, other: &dyn DynValue) -> bool {
20        other.as_any().downcast_ref::<T>() == Some(self)
21    }
22
23    fn dyn_fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24        fmt::Debug::fmt(self, f)
25    }
26
27    fn as_any(&self) -> &dyn Any {
28        self
29    }
30}
31
32/// Any comparable, printable value: custom widget props and events.
33#[derive(Clone)]
34pub struct AnyValue(Rc<dyn DynValue>);
35
36impl AnyValue {
37    pub fn new<T: Any + PartialEq + fmt::Debug>(value: T) -> AnyValue {
38        AnyValue(Rc::new(value))
39    }
40
41    pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
42        self.0.as_any().downcast_ref()
43    }
44
45    pub fn is<T: Any>(&self) -> bool {
46        self.0.as_any().is::<T>()
47    }
48}
49
50impl PartialEq for AnyValue {
51    fn eq(&self, other: &AnyValue) -> bool {
52        self.0.dyn_eq(&*other.0)
53    }
54}
55
56impl fmt::Debug for AnyValue {
57    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58        self.0.dyn_fmt(f)
59    }
60}
61
62/// A platform-specific payload the core passes through without looking
63/// inside: a native render, a native view factory. Equal only to itself;
64/// printed as its label.
65#[derive(Clone)]
66pub struct Opaque {
67    label: &'static str,
68    value: Rc<dyn Any>,
69}
70
71impl Opaque {
72    pub fn new<T: Any>(label: &'static str, value: T) -> Opaque {
73        Opaque { label, value: Rc::new(value) }
74    }
75
76    pub fn label(&self) -> &'static str {
77        self.label
78    }
79
80    pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
81        self.value.downcast_ref()
82    }
83}
84
85impl PartialEq for Opaque {
86    fn eq(&self, other: &Opaque) -> bool {
87        Rc::ptr_eq(&self.value, &other.value)
88    }
89}
90
91impl fmt::Debug for Opaque {
92    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93        write!(f, "<{}>", self.label)
94    }
95}