-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathdiff.rs
98 lines (95 loc) · 3.19 KB
/
diff.rs
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
87
88
89
90
91
92
93
94
95
96
97
98
use serde_json::{json, Value};
pub fn calc_diff(old: &str, new: &str) -> Vec<Value> {
let res = diff::chars(old, new);
let mut diff = Vec::new();
let mut prev = "";
let mut count = 0i32;
let mut added_str = String::new();
for diff_res in res {
match diff_res {
diff::Result::Left(_) => {
if prev != "-" {
if prev == "+" {
diff.push(Value::Array(vec![json!(prev), json!(added_str)]));
added_str = String::new();
} else if count > 0 {
diff.push(Value::Array(vec![json!(prev), json!(count)]));
}
count = 0;
}
prev = "-";
count += 1;
}
diff::Result::Both(_, _) => {
if prev != "=" {
if prev == "+" {
diff.push(Value::Array(vec![json!(prev), json!(added_str)]));
added_str = String::new();
} else if count > 0 {
diff.push(Value::Array(vec![json!(prev), json!(count)]));
}
count = 0;
}
prev = "=";
count += 1;
}
diff::Result::Right(c) => {
if prev != "+" && count > 0 {
diff.push(Value::Array(vec![json!(prev), json!(count)]));
count = 0;
}
prev = "+";
count += 1;
added_str.push(c);
}
};
}
if prev == "+" {
diff.push(Value::Array(vec![json!(prev), json!(added_str)]));
} else {
diff.push(Value::Array(vec![json!(prev), json!(count)]));
}
diff
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_calc_diff() {
assert_eq!(
calc_diff("", "one, two, three"),
vec![Value::Array(vec![json!("+"), json!["one, two, three"]])],
);
assert_eq!(
calc_diff("one, two, three", "one, two, three, four, five"),
vec![
Value::Array(vec![json!("="), json![15]]),
Value::Array(vec![json!("+"), json![", four, five"]]),
]
);
assert_eq!(
calc_diff("one, two, three, six", "one, two, three, four, five, six"),
vec![
Value::Array(vec![json!("="), json![17]]),
Value::Array(vec![json!("+"), json!["four, five, "]]),
Value::Array(vec![json!("="), json![3]]),
]
);
assert_eq!(
calc_diff(
"one, two, three, hmm, six",
"one, two, three, four, five, six"
),
vec![
Value::Array(vec![json!("="), json![17]]),
Value::Array(vec![json!("-"), json![3]]),
Value::Array(vec![json!("+"), json!["four, five"]]),
Value::Array(vec![json!("="), json![5]]),
]
);
assert_eq!(
calc_diff("one, two, three", ""),
vec![Value::Array(vec![json!("-"), json![15]])]
);
}
}