tembra_core/context_values/
value.rs1use super::{ContextDatum, ContextKind, Result, invalid};
4use crate::Id;
5use std::{any::Any, fmt, rc::Rc};
6
7#[derive(Clone, Debug, PartialEq)]
8pub enum ContextValue {
9 Text(Rc<str>),
10 Integer(i64),
11 Boolean(bool),
12 Opaque(OpaqueContextValue),
13}
14
15impl ContextValue {
16 pub fn kind(&self) -> ContextKind {
18 match self {
19 Self::Text(_) => ContextKind::Text,
20 Self::Integer(_) => ContextKind::Integer,
21 Self::Boolean(_) => ContextKind::Boolean,
22 Self::Opaque(_) => ContextKind::Opaque,
23 }
24 }
25}
26
27macro_rules! datum {
28 ($ty:ty, $kind:ident, $variant:ident) => {
29 impl ContextDatum for $ty {
30 const KIND: ContextKind = ContextKind::$kind;
31
32 fn into_value(self) -> ContextValue {
34 ContextValue::$variant(self)
35 }
36
37 fn from_value(value: ContextValue) -> Result<Self> {
39 match value {
40 ContextValue::$variant(value) => Ok(value),
41 _ => Err(invalid("context type mismatch")),
42 }
43 }
44 }
45 };
46}
47datum!(Rc<str>, Text, Text);
48
49impl ContextDatum for String {
50 const KIND: ContextKind = ContextKind::Text;
51
52 fn into_value(self) -> ContextValue {
54 ContextValue::Text(self.into())
55 }
56
57 fn from_value(value: ContextValue) -> Result<Self> {
59 match value {
60 ContextValue::Text(value) => Ok(value.to_string()),
61 _ => Err(invalid("context type mismatch")),
62 }
63 }
64}
65
66datum!(i64, Integer, Integer);
67datum!(bool, Boolean, Boolean);
68
69#[derive(Clone)]
71pub struct OpaqueContextValue {
72 pub id: Id,
73 lease: Rc<dyn Any>,
74}
75
76impl OpaqueContextValue {
77 pub fn new(id: Id, lease: impl Any) -> Self {
79 Self {
80 id,
81 lease: Rc::new(lease),
82 }
83 }
84}
85
86impl fmt::Debug for OpaqueContextValue {
87 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89 f.debug_tuple("OpaqueContextValue").field(&self.id).finish()
90 }
91}
92
93impl PartialEq for OpaqueContextValue {
94 fn eq(&self, other: &Self) -> bool {
96 self.id == other.id && Rc::ptr_eq(&self.lease, &other.lease)
97 }
98}
99
100impl ContextDatum for OpaqueContextValue {
101 const KIND: ContextKind = ContextKind::Opaque;
102
103 fn into_value(self) -> ContextValue {
105 ContextValue::Opaque(self)
106 }
107
108 fn from_value(value: ContextValue) -> Result<Self> {
110 match value {
111 ContextValue::Opaque(value) => Ok(value),
112 _ => Err(invalid("context type mismatch")),
113 }
114 }
115}