mitsuami_core/
any_value.rs1use 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#[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#[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}