xmachines_runtime/
event.rs1use std::borrow::Cow;
2
3use serde::de::DeserializeOwned;
4use serde::Serialize;
5use serde_json::{Map, Value};
6
7pub trait EventType: Clone + Serialize + DeserializeOwned + 'static {
13 fn event_type(&self) -> &str;
15
16 fn field(&self, key: &str) -> Option<Value> {
19 match serde_json::to_value(self) {
20 Ok(Value::Object(mut map)) => map.remove(key).map(|mut v| {
21 js_numbers(&mut v);
22 v
23 }),
24 _ => None,
25 }
26 }
27
28 fn to_json(&self) -> Value {
30 let mut v = serde_json::to_value(self).unwrap_or(Value::Null);
31 js_numbers(&mut v);
32 v
33 }
34
35 fn from_json(value: Value) -> Result<Self, Value> {
38 match Self::deserialize(&value) {
39 Ok(event) => Ok(event),
40 Err(_) => Err(value),
41 }
42 }
43}
44
45pub fn js_numbers(value: &mut Value) {
48 const MAX_SAFE: f64 = 9_007_199_254_740_991.0;
49 match value {
50 Value::Number(n) if n.is_f64() => {
51 let f = n.as_f64().unwrap_or(f64::NAN);
52 if f.fract() == 0.0 && f.abs() <= MAX_SAFE {
53 *value = Value::from(f as i64);
54 }
55 }
56 Value::Array(items) => items.iter_mut().for_each(js_numbers),
57 Value::Object(map) => map.values_mut().for_each(js_numbers),
58 _ => {}
59 }
60}
61
62pub(crate) fn needs_js_numbers(value: &Value) -> bool {
64 const MAX_SAFE: f64 = 9_007_199_254_740_991.0;
65 match value {
66 Value::Number(n) if n.is_f64() => {
67 let f = n.as_f64().unwrap_or(f64::NAN);
68 f.fract() == 0.0 && f.abs() <= MAX_SAFE
69 }
70 Value::Array(items) => items.iter().any(needs_js_numbers),
71 Value::Object(map) => map.values().any(needs_js_numbers),
72 _ => false,
73 }
74}
75
76impl EventType for Value {
77 fn event_type(&self) -> &str {
78 self.get("type").and_then(Value::as_str).unwrap_or("")
79 }
80
81 fn field(&self, key: &str) -> Option<Value> {
82 self.get(key).cloned()
83 }
84
85 fn to_json(&self) -> Value {
86 self.clone()
87 }
88
89 fn from_json(value: Value) -> Result<Self, Value> {
90 if value.get("type").and_then(Value::as_str).is_some() {
91 Ok(value)
92 } else {
93 Err(value)
94 }
95 }
96}
97
98pub(crate) const INIT: &str = "xstate.init";
99pub(crate) const DONE_STATE: &str = "xstate.done.state";
100pub(crate) const AFTER: &str = "xstate.after";
101
102#[derive(Debug, Clone, PartialEq)]
106pub enum Ev<E> {
107 Init,
108 User(E),
109 Internal { event_type: Cow<'static, str>, data: Map<String, Value> },
110}
111
112impl<E: EventType> Ev<E> {
113 pub fn event_type(&self) -> &str {
114 match self {
115 Ev::Init => INIT,
116 Ev::User(e) => e.event_type(),
117 Ev::Internal { event_type, .. } => event_type,
118 }
119 }
120
121 pub fn field(&self, key: &str) -> Option<Value> {
123 match self {
124 Ev::Init => None,
125 Ev::User(e) => e.field(key),
126 Ev::Internal { data, .. } => data.get(key).cloned(),
127 }
128 }
129
130 pub fn to_json(&self) -> Value {
131 match self {
132 Ev::Init => serde_json::json!({ "type": INIT }),
133 Ev::User(e) => e.to_json(),
134 Ev::Internal { event_type, data } => {
135 let mut map = Map::with_capacity(data.len() + 1);
136 map.insert("type".into(), Value::String(event_type.to_string()));
137 for (k, v) in data {
138 map.insert(k.clone(), v.clone());
139 }
140 Value::Object(map)
141 }
142 }
143 }
144
145 pub fn from_json(value: Value) -> Option<Self> {
148 match E::from_json(value) {
149 Ok(e) => Some(Ev::User(e)),
150 Err(Value::Object(mut map)) => {
151 let event_type = match map.remove("type") {
152 Some(Value::String(t)) => t,
153 _ => return None,
154 };
155 if event_type == INIT {
156 return Some(Ev::Init);
157 }
158 Some(Ev::Internal { event_type: Cow::Owned(event_type), data: map })
159 }
160 Err(_) => None,
161 }
162 }
163
164 pub fn output(&self) -> Option<Value> {
166 self.field("output")
167 }
168}
169
170pub(crate) fn matches_descriptor(event_type: &str, descriptor: &str) -> bool {
173 if descriptor == event_type || descriptor == "*" {
174 return true;
175 }
176 if !descriptor.ends_with(".*") {
177 return false;
178 }
179 let mut event_tokens = event_type.split('.');
180 let mut partial_tokens = descriptor.split('.').peekable();
181 while let Some(partial) = partial_tokens.next() {
182 let event_token = event_tokens.next();
183 if partial == "*" {
184 return partial_tokens.peek().is_none();
185 }
186 if Some(partial) != event_token {
187 return false;
188 }
189 }
190 true
191}
192
193#[cfg(test)]
194mod tests {
195 use super::*;
196
197 #[test]
198 fn descriptors() {
199 assert!(matches_descriptor("a", "a"));
200 assert!(matches_descriptor("a.b", "*"));
201 assert!(matches_descriptor("a.b", "a.*"));
202 assert!(matches_descriptor("a.b.c", "a.*"));
203 assert!(matches_descriptor("a", "a.*"));
204 assert!(!matches_descriptor("ab", "a.*"));
205 assert!(!matches_descriptor("b.a", "a.*"));
206 assert!(!matches_descriptor("a.b.c", "a.*.c"));
207 assert!(!matches_descriptor("ab", "a*"));
208 }
209
210 #[test]
211 fn numbers_as_javascript_writes_them() {
212 let mut v = serde_json::json!({ "a": 1.0, "b": [2.5, -0.0, 3.0], "c": 7 });
213 js_numbers(&mut v);
214 assert_eq!(v.to_string(), r#"{"a":1,"b":[2.5,0,3],"c":7}"#);
215 }
216}