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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
#![crate_name = "text_diff"]
#![doc(html_root_url = "https://johannhof.github.io/text-diff.rs/")]
#![deny(missing_docs)]
mod lcs;
mod merge;
use lcs::lcs;
use merge::merge;
#[derive(PartialEq, Debug)]
pub enum Difference {
Same(String),
Add(String),
Rem(String)
}
pub fn diff(orig: &str, edit: &str, split: &str) -> (i32, Vec<Difference>) {
let (dist, common) = lcs(orig, edit, split);
(dist, merge(orig, edit, &common, split))
}
pub fn assert_diff(orig: &str, edit: &str, split: &str, expected: i32) {
let (d, _) = diff(orig, edit, split);
if d != expected {
print_diff(orig, edit, split);
panic!("assertion failed: edit distance between {:?} and {:?} is {} and not {}, see diffset above"
, orig, edit, d, expected)
}
}
pub fn print_diff(orig: &str, edit: &str, split: &str) {
let (_, changeset) = diff(orig, edit, split);
let mut ret = String::new();
for seq in changeset {
match seq {
Difference::Same(ref x) => {
ret.push_str(x);
ret.push_str(split);
},
Difference::Add(ref x) => {
ret.push_str("\x1B[92m");
ret.push_str(x);
ret.push_str("\x1B[0m");
ret.push_str(split);
},
Difference::Rem(ref x) => {
ret.push_str("\x1B[91m");
ret.push_str(x);
ret.push_str("\x1B[0m");
ret.push_str(split);
}
}
}
println!("{}", ret);
}
#[test]
fn test_diff() {
let text1 = "Roses are red, violets are blue,\n\
I wrote this library,\n\
just for you.\n\
(It's true).";
let text2 = "Roses are red, violets are blue,\n\
I wrote this documentation,\n\
just for you.\n\
(It's quite true).";
let (dist, changeset) = diff(text1, text2, "\n");
assert_eq!(dist, 4);
assert_eq!(changeset, vec![
Difference::Same("Roses are red, violets are blue,".to_string()),
Difference::Rem("I wrote this library,".to_string()),
Difference::Add("I wrote this documentation,".to_string()),
Difference::Same("just for you.".to_string()),
Difference::Rem("(It's true).".to_string()),
Difference::Add("(It's quite true).".to_string())
]);
}
#[test]
#[should_panic]
fn test_assert_diff_panic() {
let text1 = "Roses are red, violets are blue,\n\
I wrote this library,\n\
just for you.\n\
(It's true).";
let text2 = "Roses are red, violets are blue,\n\
I wrote this documentation,\n\
just for you.\n\
(It's quite true).";
assert_diff(text1, text2, "\n'", 0);
}
#[test]
fn test_assert_diff() {
let text1 = "Roses are red, violets are blue";
let text2 = "Roses are green, violets are blue";
assert_diff(text1, text2, " ", 2);
}