Skip to content

Commit

Permalink
oh RFC 6902, why, why
Browse files Browse the repository at this point in the history
  • Loading branch information
asmello committed Mar 19, 2024
1 parent b9ee0f0 commit bab30d8
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions src/diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,30 @@ use serde_json::Value;
struct PatchDiffer {
path: Pointer,
patch: super::Patch,
shift: usize,
}

impl PatchDiffer {
fn new() -> Self {
Self {
path: Pointer::root(),
patch: super::Patch(Vec::new()),
shift: 0,
}
}
}

impl<'a> treediff::Delegate<'a, treediff::value::Key, Value> for PatchDiffer {
fn push(&mut self, key: &treediff::value::Key) {
match key {
treediff::value::Key::Index(idx) => self.path.push_back(idx.into()),
treediff::value::Key::Index(idx) => self.path.push_back((idx - self.shift).into()),
treediff::value::Key::String(key) => self.path.push_back(key.into()),
}
}

fn pop(&mut self) {
self.path.pop_back();
self.shift = 0;
}

fn removed<'b>(&mut self, k: &'b treediff::value::Key, _v: &'a Value) {
Expand All @@ -34,7 +37,11 @@ impl<'a> treediff::Delegate<'a, treediff::value::Key, Value> for PatchDiffer {
.push(super::PatchOperation::Remove(super::RemoveOperation {
path: self.path.clone(),
}));
self.pop();
// Shift indices, we are deleting array elements
if let treediff::value::Key::Index(_) = k {
self.shift += 1;
}
self.path.pop_back();
}

fn added(&mut self, k: &treediff::value::Key, v: &Value) {
Expand All @@ -45,7 +52,7 @@ impl<'a> treediff::Delegate<'a, treediff::value::Key, Value> for PatchDiffer {
path: self.path.clone(),
value: v.clone(),
}));
self.pop();
self.path.pop_back();
}

fn modified(&mut self, _old: &'a Value, new: &'a Value) {
Expand Down Expand Up @@ -167,7 +174,7 @@ mod tests {
p,
serde_json::from_value(json!([
{ "op": "remove", "path": "/0" },
{ "op": "remove", "path": "/1" },
{ "op": "remove", "path": "/0" },
]))
.unwrap()
);
Expand All @@ -182,7 +189,7 @@ mod tests {
p,
serde_json::from_value(json!([
{ "op": "remove", "path": "/1" },
{ "op": "remove", "path": "/2" },
{ "op": "remove", "path": "/1" },
]))
.unwrap()
);
Expand All @@ -197,7 +204,7 @@ mod tests {
serde_json::from_value(json!([
{ "op": "add", "path": "/hello", "value": "bye" },
{ "op": "remove", "path": "/0" },
{ "op": "remove", "path": "/1" },
{ "op": "remove", "path": "/0" },
]))
.unwrap()
);
Expand Down

0 comments on commit bab30d8

Please sign in to comment.