-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvisitor.rs
More file actions
86 lines (74 loc) · 2.13 KB
/
visitor.rs
File metadata and controls
86 lines (74 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
use difficient::{AcceptVisitor, Diffable, Enter};
// Define our visitor
#[derive(Default)]
struct ChangeEmitter {
location: Vec<Enter>,
changes: Vec<(String, serde_json::Value)>,
}
// impl Visitor
impl difficient::Visitor for ChangeEmitter {
fn enter(&mut self, val: Enter) {
self.location.push(val);
}
fn exit(&mut self) {
self.location.pop().unwrap();
}
fn replaced<T: serde::Serialize>(&mut self, val: T) {
let mut path = String::new();
for (ix, loc) in self.location.iter().enumerate() {
match loc {
Enter::NamedField { name, .. } | Enter::Variant { name, .. } => path.push_str(name),
Enter::PositionalField(p) => path.push_str(&p.to_string()),
Enter::MapKey(key) => path.push_str(key),
Enter::Index(key) => path.push_str(&key.to_string()),
}
if ix != self.location.len() - 1 {
path.push('.');
}
}
self.changes
.push((path, serde_json::to_value(val).unwrap()));
}
fn splice<T: serde::Serialize>(&mut self, _from_index: usize, _replace: usize, _values: &[T]) {
todo!()
}
}
#[derive(Diffable, PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize)]
struct Struct1 {
a: Struct2,
b: Struct2,
}
#[derive(Diffable, PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize)]
struct Struct2 {
c: Struct3,
}
#[derive(Diffable, PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize)]
struct Struct3 {
d: i32,
e: i32,
}
fn main() {
let mut emitter = ChangeEmitter::default();
let v1 = Struct1 {
a: Struct2 {
c: Struct3 { d: 1, e: 2 },
},
b: Struct2 {
c: Struct3 { d: 3, e: 4 },
},
};
let v2 = Struct1 {
a: Struct2 {
c: Struct3 { d: 1, e: 22 },
},
b: Struct2 {
c: Struct3 { d: 33, e: 4 },
},
};
let diff = v1.diff(&v2);
diff.accept(&mut emitter);
println!("Changed paths:");
for (path, val) in emitter.changes {
println!("{path}: {val}");
}
}