k8_diff/
lib.rs

1mod json;
2
3use std::fmt;
4
5pub trait Changes {
6    type Replace;
7    type Patch;
8
9    fn diff(&self, new: &Self) -> Result<Diff<Self::Replace, Self::Patch>, DiffError>;
10}
11
12#[derive(Debug)]
13pub enum DiffError {
14    DiffValue, // json values are different
15}
16
17impl std::fmt::Display for DiffError {
18    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
19        write!(f, "JSON value types are different")
20    }
21}
22
23impl std::error::Error for DiffError {}
24
25// use Option as inspiration
26#[derive(Debug)]
27pub enum Diff<R, P> {
28    None,
29    Delete,
30    Patch(P),   // for non primitive type
31    Replace(R), // can be used for map and list (with our without tag), works on ordered list
32    Merge(R),   // need tag, works on unorderd list
33}
34
35impl<R, P> Diff<R, P> {
36    pub fn is_none(&self) -> bool {
37        matches!(self, Diff::None)
38    }
39
40    pub fn is_delete(&self) -> bool {
41        matches!(self, Diff::Delete)
42    }
43
44    pub fn is_replace(&self) -> bool {
45        matches!(self, Diff::Replace(_))
46    }
47
48    pub fn is_patch(&self) -> bool {
49        matches!(self, Diff::Patch(_))
50    }
51
52    pub fn is_merge(&self) -> bool {
53        matches!(self, Diff::Merge(_))
54    }
55
56    pub fn as_replace_ref(&self) -> &R {
57        match self {
58            Diff::Replace(ref val) => val,
59            _ => panic!("no change value"),
60        }
61    }
62
63    pub fn as_patch_ref(&self) -> &P {
64        match self {
65            Diff::Patch(ref val) => val,
66            _ => panic!("no change value"),
67        }
68    }
69}