Skip to main content

acorn_diff/json_patch/
mod.rs

1//! Deterministic [RFC 6902 JSON Patch](https://www.rfc-editor.org/rfc/rfc6902) primitives.
2use alloc::{
3    collections::BTreeSet,
4    format,
5    string::{String, ToString},
6    vec::Vec,
7};
8use core::{cmp, fmt};
9use serde::{Serialize, Serializer};
10use serde_json::Value;
11
12/// Computes deterministic patches between JSON values.
13pub trait DiffValue {
14    /// Compute a patch that transforms this value into `after`.
15    fn diff(&self, after: &Self) -> JsonPatch;
16}
17trait DiffValueAt {
18    fn diff_at(&self, after: &Value, path: &str, operations: &mut Vec<Operation>);
19    fn diff_changed_at(&self, after: &Value, path: &str, operations: &mut Vec<Operation>);
20}
21/// Creates validated [RFC 6902](https://www.rfc-editor.org/rfc/rfc6902) operations.
22pub trait Rfc6902: Sized {
23    /// Creates an `add` operation.
24    fn add(path: impl Into<String>, value: Value) -> Result<Self, PointerError>;
25    /// Creates a `copy` operation.
26    fn copy(from: impl Into<String>, path: impl Into<String>) -> Result<Self, PointerError>;
27    /// Returns this operation's kind.
28    fn kind(&self) -> OperationKind;
29    /// Creates a `move` operation.
30    fn move_(from: impl Into<String>, path: impl Into<String>) -> Result<Self, PointerError>;
31    /// Creates a `remove` operation.
32    fn remove(path: impl Into<String>) -> Result<Self, PointerError>;
33    /// Creates a `replace` operation.
34    fn replace(path: impl Into<String>, value: Value) -> Result<Self, PointerError>;
35    /// Creates a `test` operation.
36    fn test(path: impl Into<String>, value: Value) -> Result<Self, PointerError>;
37}
38/// The RFC 6902 operation represented by an [`Operation`].
39#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
40#[serde(rename_all = "lowercase")]
41pub enum OperationKind {
42    /// Adds a value.
43    Add,
44    /// Copies a value.
45    Copy,
46    /// Moves a value.
47    Move,
48    /// Removes a value.
49    Remove,
50    /// Replaces a value.
51    Replace,
52    /// Tests a value.
53    Test,
54}
55#[derive(Clone, Debug, PartialEq, Serialize)]
56#[serde(tag = "op", rename_all = "lowercase")]
57enum OperationRepr {
58    Add { path: String, value: Value },
59    Copy { from: String, path: String },
60    Move { from: String, path: String },
61    Remove { path: String },
62    Replace { path: String, value: Value },
63    Test { path: String, value: Value },
64}
65/// An invalid JSON Pointer or move relationship.
66#[derive(Clone, Debug, Eq, PartialEq)]
67pub enum PointerError {
68    /// A pointer contains a `~` escape other than `~0` or `~1`.
69    InvalidEscape(String),
70    /// A pointer is not empty and does not begin with `/`.
71    MissingLeadingSlash(String),
72    /// A move destination is a child of its source.
73    MoveIntoChild {
74        /// Source pointer.
75        from: String,
76        /// Destination pointer.
77        path: String,
78    },
79}
80/// A deterministic sequence of RFC 6902 operations.
81#[derive(Clone, Debug, Default, PartialEq, Serialize)]
82#[serde(transparent)]
83pub struct JsonPatch(Vec<Operation>);
84/// A validated RFC 6902 operation.
85#[derive(Clone, Debug, PartialEq)]
86pub struct Operation(OperationRepr);
87impl JsonPatch {
88    /// Returns whether the patch has no operations.
89    #[must_use]
90    pub fn is_empty(&self) -> bool {
91        self.0.is_empty()
92    }
93    /// Returns the patch operations.
94    #[must_use]
95    pub fn operations(&self) -> &[Operation] {
96        &self.0
97    }
98}
99impl Rfc6902 for Operation {
100    fn add(path: impl Into<String>, value: Value) -> Result<Self, PointerError> {
101        validated(path.into()).map(|path| Self(OperationRepr::Add { path, value }))
102    }
103    fn copy(from: impl Into<String>, path: impl Into<String>) -> Result<Self, PointerError> {
104        validated(from.into()).and_then(|from| validated(path.into()).map(|path| Self(OperationRepr::Copy { from, path })))
105    }
106    fn kind(&self) -> OperationKind {
107        OperationKind::from(self.0.clone())
108    }
109    fn move_(from: impl Into<String>, path: impl Into<String>) -> Result<Self, PointerError> {
110        validated(from.into()).and_then(|from| {
111            validated(path.into()).and_then(|path| match is_proper_prefix(&from, &path) {
112                | true => Err(PointerError::MoveIntoChild { from, path }),
113                | false => Ok(Self(OperationRepr::Move { from, path })),
114            })
115        })
116    }
117    fn remove(path: impl Into<String>) -> Result<Self, PointerError> {
118        validated(path.into()).map(|path| Self(OperationRepr::Remove { path }))
119    }
120    fn replace(path: impl Into<String>, value: Value) -> Result<Self, PointerError> {
121        validated(path.into()).map(|path| Self(OperationRepr::Replace { path, value }))
122    }
123    fn test(path: impl Into<String>, value: Value) -> Result<Self, PointerError> {
124        validated(path.into()).map(|path| Self(OperationRepr::Test { path, value }))
125    }
126}
127impl Serialize for Operation {
128    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
129    where
130        S: Serializer,
131    {
132        self.0.serialize(serializer)
133    }
134}
135impl From<OperationRepr> for OperationKind {
136    fn from(value: OperationRepr) -> Self {
137        match value {
138            | OperationRepr::Add { .. } => Self::Add,
139            | OperationRepr::Copy { .. } => Self::Copy,
140            | OperationRepr::Move { .. } => Self::Move,
141            | OperationRepr::Remove { .. } => Self::Remove,
142            | OperationRepr::Replace { .. } => Self::Replace,
143            | OperationRepr::Test { .. } => Self::Test,
144        }
145    }
146}
147impl core::error::Error for PointerError {}
148impl fmt::Display for PointerError {
149    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
150        match self {
151            | Self::InvalidEscape(pointer) => write!(formatter, "JSON Pointer contains an invalid '~' escape: {pointer}"),
152            | Self::MissingLeadingSlash(pointer) => write!(formatter, "JSON Pointer must be empty or begin with '/': {pointer}"),
153            | Self::MoveIntoChild { from, path } => write!(formatter, "cannot move {from} into its child {path}"),
154        }
155    }
156}
157impl DiffValue for Value {
158    fn diff(&self, after: &Self) -> JsonPatch {
159        let mut operations = Vec::new();
160        self.diff_at(after, "", &mut operations);
161        JsonPatch(operations)
162    }
163}
164impl DiffValueAt for Value {
165    fn diff_at(&self, after: &Value, path: &str, operations: &mut Vec<Operation>) {
166        match self == after {
167            | true => {}
168            | false => self.diff_changed_at(after, path, operations),
169        }
170    }
171    fn diff_changed_at(&self, after: &Value, path: &str, operations: &mut Vec<Operation>) {
172        match (self, after) {
173            | (Value::Object(before), Value::Object(after)) => {
174                let before_keys = before.keys().collect::<BTreeSet<_>>();
175                let after_keys = after.keys().collect::<BTreeSet<_>>();
176                before_keys.difference(&after_keys).for_each(|key| {
177                    operations.push(Operation(OperationRepr::Remove { path: join(path, key) }));
178                });
179                before_keys.intersection(&after_keys).for_each(|key| {
180                    let before_value = &before[*key];
181                    let after_value = &after[*key];
182                    match before_value == after_value {
183                        | true => {}
184                        | false => before_value.diff_changed_at(after_value, &join(path, key), operations),
185                    }
186                });
187                after_keys.difference(&before_keys).for_each(|key| {
188                    operations.push(Operation(OperationRepr::Add {
189                        path: join(path, key),
190                        value: after[*key].clone(),
191                    }));
192                });
193            }
194            | (Value::Array(before), Value::Array(after)) => {
195                let shared = cmp::min(before.len(), after.len());
196                before
197                    .iter()
198                    .zip(after)
199                    .take(shared)
200                    .enumerate()
201                    .for_each(|(index, (before, after))| match before == after {
202                        | true => {}
203                        | false => before.diff_changed_at(after, &format!("{path}/{index}"), operations),
204                    });
205                (after.len()..before.len()).rev().for_each(|index| {
206                    operations.push(Operation(OperationRepr::Remove {
207                        path: format!("{path}/{index}"),
208                    }));
209                });
210                after.iter().skip(shared).for_each(|value| {
211                    operations.push(Operation(OperationRepr::Add {
212                        path: format!("{path}/-"),
213                        value: value.clone(),
214                    }));
215                });
216            }
217            | _ => operations.push(Operation(OperationRepr::Replace {
218                path: path.to_string(),
219                value: after.clone(),
220            })),
221        }
222    }
223}
224fn has_invalid_escape(pointer: &str) -> bool {
225    pointer
226        .as_bytes()
227        .iter()
228        .enumerate()
229        .any(|(index, character)| *character == b'~' && !matches!(pointer.as_bytes().get(index.saturating_add(1)), Some(b'0' | b'1')))
230}
231fn is_proper_prefix(from: &str, path: &str) -> bool {
232    path.len() > from.len() && path.starts_with(from) && path.as_bytes().get(from.len()).copied() == Some(b'/')
233}
234fn join(path: &str, token: &str) -> String {
235    fn escape(token: &str) -> String {
236        token.replace('~', "~0").replace('/', "~1")
237    }
238    format!("{path}/{}", escape(token))
239}
240fn validated(pointer: String) -> Result<String, PointerError> {
241    match (!pointer.is_empty() && !pointer.starts_with('/'), has_invalid_escape(&pointer)) {
242        | (true, _) => Err(PointerError::MissingLeadingSlash(pointer)),
243        | (_, true) => Err(PointerError::InvalidEscape(pointer)),
244        | _ => Ok(pointer),
245    }
246}
247
248#[cfg(test)]
249mod tests;