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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
use std::fs::File;
use std::io::Read;
use crate::*;
use crate::token::*;

/// Using the LCS algorithm to compare text files (like linux diff).
/// #Examples
///
/// How to compare two files with locations fpath_a and fpath_b:
/// ```
/// let mut text_parser = diff::text::parser(fpath_a, fpath_b).unwrap();
/// text_parser.run(beediff::Sensivity::CaseSensitive);
/// text_parser.print_same();
/// text_parser.print_others();
/// ```
///

pub struct TextParser {
    chars_a: Vec<char>,
    chars_b: Vec<char>,
    same: Option<Vec<Token>>,
    others: Option<Vec<Token>>,
    nlines_a: usize,
    nlines_b: usize,
}

/// Create a new parser that is used to find
/// text differences for the given two files.
pub fn parser(fpath_a: &str, fpath_b: &str) -> Option<TextParser> {
    if let Some(text_a) = read_file_as_string(fpath_a) {
        if let Some(text_b) = read_file_as_string(fpath_b) {
            let chars_a: Vec<char> = text_a.chars().collect();
            let chars_b: Vec<char> = text_b.chars().collect();
            return Some(TextParser { chars_a,
                chars_b,
                same: None,
                others: None,
                nlines_a: 0,
                nlines_b: 0,
            })
        }
    }
    None
}

impl TextParser {
    /// Starts LCS parsing for two files contents.<br>
    /// Returns tuple of two vectors.
    /// The first vector contains information (Tokens) about the same lines.<br>
    /// The second one contains information about the remaining lines,
    /// not the same lines (Added, Changed, Deleted).
    pub fn run(&mut self, sensitivity: Sensivity) {
        let data_a: Vec<&[char]> = split(&self.chars_a);
        let data_b: Vec<&[char]> = split(&self.chars_b);

        self.nlines_a = data_a.len();
        self.nlines_b = data_b.len();

        let same = diff_text(&data_a, &data_b, sensitivity);
        let others = diff_text_reverted(&same);

        self.same = Some(same);
        self.others = Some(others);
    }

    /// Returns copy of vector with 'Tokens' described the same lines.
    pub fn same(&self) -> Option<Vec<Token>> {
        if let Some(data) = &self.same {
            return Some(data.clone())
        }
        None
    }

    /// Returns copy of vector with 'Tokens' described not the same lines.
    pub fn others(&self) -> Option<Vec<Token>> {
        if let Some(data) = &self.others {
            return Some(data.clone())
        }
        None
    }

    /// Prints information about the same lines.
    pub fn print_same(&self) {
        if let Some(same) = &self.same {
            println!();
            println!("The same lines.");
            println!("---------------------------------------");
            for item in same {
                println!("{}", item);
            }
            println!("---------------------------------------");
            println!("The first file: {} lines", self.nlines_a);
            println!("The second file: {} lines", self.nlines_b);
            println!("Total number of all the same lines: {}", same.len());
        }
    }

    /// Prints information about the same lines.
    pub fn print_others(&self) {
        if let Some(others) = &self.others {
            println!();
            println!("The other lines.");
            println!("---------------------------------------");
            let mut changed = 0_usize;
            let mut deleted = 0_usize;
            let mut added = 0_usize;
            for item in others {
                if item.action == Action::Changed {
                    changed += 1;
                } else if item.action == Action::Deleted {
                    deleted += 1;
                } else if item.action == Action::Added {
                    added += 1;
                }
                println!("{}", item);
            }
            println!("---------------------------------------");
            println!("Changed: {} lines", changed);
            println!("Removed from the first file: {} lines", deleted);
            println!("Added to the second file: {} lines", added);
            println!("Total number of all not same lines: {}", others.len());
        }
    }

    pub fn print_unix_diff(&self) {

    }
}

fn diff_text(lines_a: &[&[char]], lines_b: &[&[char]], sensivity: Sensivity) -> Vec<token::Token> {
    let mut tokens: Vec<token::Token> = Vec::new();

    let m = lines_a.len();
    let n = lines_b.len();

    let mut lens = create_2dim_vector(m, n);
    for i in 0..m {
        for j in 0..n {
            if equal(&lines_a[i], &lines_b[j], sensivity) {
                lens[i + 1][j + 1] = 1 + lens[i][j];
            }
            else {
                lens[i+1][j+1] = max(lens[i+1][j], lens[i][j+1]);
            }
        }
    }

    let vlen = |i: isize, j: isize| {
        unsafe {
            lens.get_unchecked(i as usize)
                .get_unchecked(j as usize)
        }
    };

    let mut i = m as isize -1;
    let mut j = n as isize -1;
    while i >= 0 && j >= 0 {
        let item_a = unsafe { lines_a.get_unchecked(i as usize) };
        let item_b = unsafe { lines_b.get_unchecked(j as usize) };

        if equal(item_a, item_b, sensivity) {
            if let Some(last) = tokens.last_mut() {
                if last.range_a.below(i) && last.range_b.below(j) {
                    last.range_a.start_pos(i);
                    last.range_b.start_pos(j);
                }
                else {
                    push_new_token(&mut tokens, i, j);
                }
            }
            else {
                push_new_token(&mut tokens, i, j);
            }
            i -= 1;
            j -= 1;
        } else if  vlen(i+1, j) > vlen(i, j+1) {
            j -= 1;
        } else {
            i -= 1;
        }
    }

    if !tokens.is_empty() {
        tokens.reverse();
    }
    tokens.shrink_to_fit();
    tokens
}

fn diff_text_reverted(tokens: &[token::Token]) -> Vec<token::Token> {
    let mut data: Vec<token::Token> = Vec::new();
    let mut previous_token = token::new();

    for (i, token) in tokens.iter().enumerate() {
        // dziura w A?
        let pos_start_a = previous_token.range_a.end() + 1;
        let pos_end_a = token.range_a.start() - 1;
        let na = if pos_end_a >= pos_start_a {
            pos_end_a - pos_start_a + 1
        } else {
            0
        };

        // dziura w B?
        let pos_start_b = previous_token.range_b.end() + 1;
        let pos_end_b = token.range_b.start() - 1;
        let nb = if pos_end_b >= pos_start_b {
            pos_end_b - pos_start_b + 1
        } else {
            0
        };

        if na > 0 || nb > 0 {
            if na == 0 && nb > 0 {
                let range_a = if i > 0 {
                    range::with_start(tokens[i-1].range_a.end())
                } else {
                    range::new()
                };
                let range_b = range::with_start_end(pos_start_b, pos_end_b);
                data.push(token::with_ranges_action(range_a, range_b, Action::Added));
            }
            else if na > 0 && nb == 0 {
                let range_a = range::with_start_end(pos_start_a, pos_end_a);
                let range_b = if i > 0 {
                    range::with_start(tokens[i-1].range_b.end())
                } else {
                    range::new()
                };
                data.push(token::with_ranges_action(range_a, range_b, Action::Deleted));
            }
            else {
                let range_a = range::with_start_end(pos_start_a, pos_end_a);
                let range_b = range::with_start_end(pos_start_b, pos_end_b);
                data.push(token::with_ranges_action(range_a, range_b, Action::Changed));
            }
            previous_token = token.dup();
        }
    }
    data
}

#[inline]
fn push_new_token(tokens: &mut Vec<token::Token>, i: isize, j: isize) {
    let range_a = range::with_start(i);
    let range_b = range::with_start(j);
    let token = token::with_ranges(range_a, range_b);
    tokens.push(token);
}

/// Compare two character slices.
#[inline]
fn equal(a: &[char], b: &[char], sensivity: Sensivity) -> bool {
    if sensivity == Sensivity::CaseInsensitive {
        return equal_case_insensitive(a, b);
    }
    equal_case_sensitive(a, b)
}

fn equal_case_sensitive(a: &[char], b: &[char]) -> bool {
    let m = a.len();
    let n = b.len();
    if n != m { return false }

    let mut i = 0_usize;
    let mut j = 0_usize;
    while i < m && j < n {
        if a[i] != b[j] {
            return false;
        }
        i += 1;
        j += 1;
    }
    true

    /* unefficent version
    a.iter()
        .zip(b.iter())
        .map(|(x, y)| x.cmp(y))     // !!! unefficent
        .find(|&ord| ord != Ordering::Equal)
        .unwrap_or(a.len().cmp(&b.len()))
     */
}

fn equal_case_insensitive(a: &[char], b: &[char]) -> bool {
    let m = a.len();
    let n = b.len();
    if n != m { return false }

    let mut i = 0_usize;
    let mut j = 0_usize;
    while i < m && j < n {
        let c1: Vec<char> = a[i].to_lowercase().collect();
        let c2: Vec<char> = b[j].to_lowercase().collect();
        if !equal_case_sensitive(&c1, &c2) {
            return false;
        }
        i += 1;
        j += 1;
    }
    true
}

fn read_file_as_string(fpath: &str) -> Option<String> {
    match File::open(fpath) {
        Ok(mut f) => {
            let mut content = String::new();
            match f.read_to_string(&mut content) {
                Ok(_) => Some(content),
                Err(e) => {
                    eprintln!("{} [{}]", e, fpath);
                    None
                }
            }
        },
        Err(e) => {
            eprintln!("{} [{}]", e, fpath);
            None
        }
    }
}

fn split(data: &[char]) -> Vec<&[char]> {
    let n = data.len();
    let mut store: Vec<&[char]> = Vec::new();

    let mut idx = 0_usize;
    let mut i = 0_usize;
    while i < n {
        if data[i] == '\n' {
            store.push(&data[idx..i]);
            idx = i+1;
            i = idx;
            continue;
        }
        i += 1;
    }
    let item = &data[idx..];
    if !item.is_empty() {
        store.push(item);
    }

    store
}