Skip to main content

demo/
demo.rs

1use tiny_diff::{
2    Diff,
3    DiffNode,
4};
5
6struct Node {
7    key: &'static str,
8    text: &'static str,
9    path: Vec<u32>,
10    children: Vec<Node>,
11}
12
13impl DiffNode for Node {
14    type Key = &'static str;
15    type Modifications = &'static str;
16
17    fn key(&self) -> &Self::Key {
18        &self.key
19    }
20
21    fn path(&self) -> &[u32] {
22        &self.path
23    }
24
25    fn children(&self) -> &[Self] {
26        &self.children
27    }
28
29    fn compatible(&self, _: &Self) -> bool {
30        true
31    }
32
33    fn modifications(&self, previous: &Self) -> Option<Self::Modifications> {
34        (self.text != previous.text).then_some(self.text)
35    }
36}
37
38fn list(items: &[(&'static str, &'static str)]) -> Node {
39    Node {
40        key: "list",
41        text: "",
42        path: Vec::new(),
43        children: items
44            .iter()
45            .enumerate()
46            .map(|(index, &(key, text))| Node {
47                key,
48                text,
49                path: vec![index as u32],
50                children: Vec::new(),
51            })
52            .collect(),
53    }
54}
55
56fn main() {
57    let previous = list(&[
58        ("apple", "Apple"),
59        ("banana", "Banana"),
60        ("cherry", "Cherry"),
61    ]);
62    let current = list(&[
63        ("banana", "Ripe banana"),
64        ("orange", "Orange"),
65        ("apple", "Apple"),
66    ]);
67
68    let mut changes = Diff::default();
69    current.diff(Some(&previous), &mut changes);
70
71    println!("Added at new paths: {:?}", changes.added);
72    println!("Removed at old paths: {:?}", changes.removed);
73    println!("New text at new paths: {:?}", changes.modified);
74    println!(
75        "Old/new child indices by new parent path: {:?}",
76        changes.moved
77    );
78}