1use 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
12pub trait DiffValue {
14 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}
21pub trait Rfc6902: Sized {
23 fn add(path: impl Into<String>, value: Value) -> Result<Self, PointerError>;
25 fn copy(from: impl Into<String>, path: impl Into<String>) -> Result<Self, PointerError>;
27 fn kind(&self) -> OperationKind;
29 fn move_(from: impl Into<String>, path: impl Into<String>) -> Result<Self, PointerError>;
31 fn remove(path: impl Into<String>) -> Result<Self, PointerError>;
33 fn replace(path: impl Into<String>, value: Value) -> Result<Self, PointerError>;
35 fn test(path: impl Into<String>, value: Value) -> Result<Self, PointerError>;
37}
38#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
40#[serde(rename_all = "lowercase")]
41pub enum OperationKind {
42 Add,
44 Copy,
46 Move,
48 Remove,
50 Replace,
52 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#[derive(Clone, Debug, Eq, PartialEq)]
67pub enum PointerError {
68 InvalidEscape(String),
70 MissingLeadingSlash(String),
72 MoveIntoChild {
74 from: String,
76 path: String,
78 },
79}
80#[derive(Clone, Debug, Default, PartialEq, Serialize)]
82#[serde(transparent)]
83pub struct JsonPatch(Vec<Operation>);
84#[derive(Clone, Debug, PartialEq)]
86pub struct Operation(OperationRepr);
87impl JsonPatch {
88 #[must_use]
90 pub fn is_empty(&self) -> bool {
91 self.0.is_empty()
92 }
93 #[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;