Skip to main content

jev/
state.rs

1//! `State`: the state a decision is made about, matching the schema's
2//! `anyOf: [string, object, array]`.
3
4use serde::{Deserialize, Serialize};
5use serde_json::Value;
6
7use crate::error::Error;
8
9/// The state a [`crate::Question`] set is evaluated against.
10///
11/// State is never logged: it may contain PII. See the crate-level docs for the
12/// full logging policy.
13///
14/// # Examples
15///
16/// ```
17/// use jev::State;
18///
19/// let from_str: State = "a plain-text ticket body".into();
20/// assert!(matches!(from_str, State::Text(_)));
21///
22/// #[derive(serde::Serialize)]
23/// struct Ticket { subject: String }
24/// let from_struct = State::json(&Ticket { subject: "billing issue".into() }).unwrap();
25/// assert!(matches!(from_struct, State::Json(_)));
26/// ```
27#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
28#[serde(untagged)]
29pub enum State {
30    /// Plain-text state.
31    Text(String),
32    /// Structured (object or array) state.
33    Json(Value),
34}
35
36impl State {
37    /// Serializes any [`serde::Serialize`] value into a JSON [`State`].
38    ///
39    /// This is the common case for domain structs: `State::json(&ticket)` instead of
40    /// hand-building a `serde_json::Value`.
41    ///
42    /// # Errors
43    ///
44    /// Returns [`Error::Invalid`] when `value` cannot be serialized to JSON.
45    pub fn json<T: Serialize>(value: &T) -> Result<Self, Error> {
46        serde_json::to_value(value)
47            .map(State::Json)
48            .map_err(|e| Error::Invalid {
49                field: "state".to_string(),
50                reason: e.to_string(),
51            })
52    }
53
54    /// The serialized byte length, used for the pre-flight context-size estimate.
55    #[must_use]
56    pub fn byte_len(&self) -> usize {
57        match self {
58            State::Text(s) => s.len(),
59            State::Json(v) => serde_json::to_string(v).map_or(usize::MAX, |s| s.len()),
60        }
61    }
62}
63
64impl From<&str> for State {
65    fn from(s: &str) -> Self {
66        State::Text(s.to_string())
67    }
68}
69
70impl From<String> for State {
71    fn from(s: String) -> Self {
72        State::Text(s)
73    }
74}
75
76impl From<Value> for State {
77    fn from(v: Value) -> Self {
78        State::Json(v)
79    }
80}
81
82#[cfg(test)]
83mod tests {
84    use serde_json::json;
85
86    use super::*;
87
88    #[derive(Serialize)]
89    struct Ticket {
90        subject: String,
91    }
92
93    #[test]
94    fn test_should_convert_str_and_string_into_text_state() {
95        let a: State = "hi".into();
96        let b: State = String::from("hi").into();
97        assert_eq!(a, State::Text("hi".to_string()));
98        assert_eq!(b, State::Text("hi".to_string()));
99    }
100
101    #[test]
102    fn test_should_convert_value_into_json_state() {
103        let v = json!({"a": 1});
104        let s: State = v.clone().into();
105        assert_eq!(s, State::Json(v));
106    }
107
108    #[test]
109    fn test_should_serialize_domain_struct_via_state_json() {
110        let ticket = Ticket {
111            subject: "billing".to_string(),
112        };
113        let state = State::json(&ticket).unwrap();
114        assert_eq!(state, State::Json(json!({"subject": "billing"})));
115    }
116
117    #[test]
118    fn test_should_round_trip_serde_for_each_variant() {
119        for s in [State::Text("hi".to_string()), State::Json(json!(["a", 1]))] {
120            let encoded = serde_json::to_string(&s).unwrap();
121            let decoded: State = serde_json::from_str(&encoded).unwrap();
122            assert_eq!(s, decoded);
123        }
124    }
125
126    #[test]
127    fn test_should_report_byte_len_for_text_and_json() {
128        assert_eq!(State::Text("abcd".to_string()).byte_len(), 4);
129        assert_eq!(State::Json(json!({})).byte_len(), 2); // "{}"
130    }
131}