Skip to main content

systemprompt_models/agui/
json_patch.rs

1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3
4#[derive(Debug, Clone, Serialize, Deserialize)]
5#[serde(tag = "op", rename_all = "lowercase")]
6pub enum JsonPatchOperation {
7    Add { path: String, value: Value },
8    Remove { path: String },
9    Replace { path: String, value: Value },
10    Move { from: String, path: String },
11    Copy { from: String, path: String },
12    Test { path: String, value: Value },
13}
14
15impl JsonPatchOperation {
16    pub fn add(path: impl Into<String>, value: Value) -> Self {
17        Self::Add {
18            path: path.into(),
19            value,
20        }
21    }
22
23    pub fn remove(path: impl Into<String>) -> Self {
24        Self::Remove { path: path.into() }
25    }
26
27    pub fn replace(path: impl Into<String>, value: Value) -> Self {
28        Self::Replace {
29            path: path.into(),
30            value,
31        }
32    }
33
34    pub fn move_op(from: impl Into<String>, path: impl Into<String>) -> Self {
35        Self::Move {
36            from: from.into(),
37            path: path.into(),
38        }
39    }
40
41    pub fn copy(from: impl Into<String>, path: impl Into<String>) -> Self {
42        Self::Copy {
43            from: from.into(),
44            path: path.into(),
45        }
46    }
47
48    pub fn test(path: impl Into<String>, value: Value) -> Self {
49        Self::Test {
50            path: path.into(),
51            value,
52        }
53    }
54}
55
56#[derive(Debug)]
57pub struct StateDeltaBuilder {
58    operations: Vec<JsonPatchOperation>,
59}
60
61impl StateDeltaBuilder {
62    pub const fn new() -> Self {
63        Self {
64            operations: Vec::new(),
65        }
66    }
67
68    pub fn add(mut self, path: &str, value: Value) -> Self {
69        self.operations.push(JsonPatchOperation::add(path, value));
70        self
71    }
72
73    pub fn replace(mut self, path: &str, value: Value) -> Self {
74        self.operations
75            .push(JsonPatchOperation::replace(path, value));
76        self
77    }
78
79    pub fn remove(mut self, path: &str) -> Self {
80        self.operations.push(JsonPatchOperation::remove(path));
81        self
82    }
83
84    pub fn build(self) -> Vec<JsonPatchOperation> {
85        self.operations
86    }
87}
88
89impl Default for StateDeltaBuilder {
90    fn default() -> Self {
91        Self::new()
92    }
93}