Skip to main content

semantic_operators/
state.rs

1//! Validated text and JSON state.
2use crate::{Error, ErrorKind};
3use serde_json::Value;
4/// State passed to a provider. Debug output intentionally omits its contents.
5#[derive(Clone, PartialEq, serde::Serialize, serde::Deserialize)]
6#[serde(try_from = "Value", into = "Value")]
7pub struct State(Value);
8impl State {
9    /// Construct text state, including empty text.
10    pub fn text(text: impl Into<String>) -> Self {
11        Self(Value::String(text.into()))
12    }
13    /// Borrow the original JSON representation.
14    pub fn as_value(&self) -> &Value {
15        &self.0
16    }
17    /// Consume this state into its original JSON representation.
18    pub fn into_value(self) -> Value {
19        self.0
20    }
21}
22impl TryFrom<Value> for State {
23    type Error = Error;
24    /// Preserve text, objects, and arrays as provider state.
25    ///
26    /// # Errors
27    /// Returns `InvalidState` for a top-level null, Boolean, or number.
28    fn try_from(value: Value) -> Result<Self, Error> {
29        match value {
30            Value::String(_) | Value::Object(_) | Value::Array(_) => Ok(Self(value)),
31            _ => Err(Error::new(
32                ErrorKind::InvalidState,
33                "state must be text, a JSON object, or an array",
34            )),
35        }
36    }
37}
38impl std::fmt::Debug for State {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        f.write_str("State(<private>)")
41    }
42}
43
44impl From<State> for Value {
45    fn from(state: State) -> Value {
46        state.0
47    }
48}