rustate/
context.rs

1use serde::{Deserialize, Serialize};
2use std::fmt;
3
4/// Represents the extended state (context) for a state machine
5#[derive(Clone, Debug, Default, Serialize, Deserialize)]
6pub struct Context {
7    /// The context data
8    pub data: serde_json::Value,
9}
10
11impl Context {
12    /// Create a new empty context
13    pub fn new() -> Self {
14        Self {
15            data: serde_json::json!({}),
16        }
17    }
18
19    /// Create a new context with data
20    pub fn with_data(data: impl Into<serde_json::Value>) -> Self {
21        Self { data: data.into() }
22    }
23
24    /// Set a value in the context
25    pub fn set<T: Serialize>(&mut self, key: &str, value: T) -> Result<(), serde_json::Error> {
26        match &mut self.data {
27            serde_json::Value::Object(map) => {
28                map.insert(key.to_string(), serde_json::to_value(value)?);
29                Ok(())
30            }
31            _ => {
32                self.data = serde_json::json!({ key: value });
33                Ok(())
34            }
35        }
36    }
37
38    /// Get a value from the context
39    pub fn get<T: for<'de> Deserialize<'de>>(&self, key: &str) -> Option<T> {
40        match &self.data {
41            serde_json::Value::Object(map) => map
42                .get(key)
43                .and_then(|val| serde_json::from_value(val.clone()).ok()),
44            _ => None,
45        }
46    }
47
48    /// Check if a key exists in the context
49    pub fn contains_key(&self, key: &str) -> bool {
50        match &self.data {
51            serde_json::Value::Object(map) => map.contains_key(key),
52            _ => false,
53        }
54    }
55
56    /// Remove a key from the context
57    pub fn remove(&mut self, key: &str) -> Option<serde_json::Value> {
58        match &mut self.data {
59            serde_json::Value::Object(map) => map.remove(key),
60            _ => None,
61        }
62    }
63}
64
65impl fmt::Display for Context {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        write!(f, "{}", self.data)
68    }
69}