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
// TODO: this is not really a nice interface
pub struct StringAffix {
    pub prefix_len: usize,
	pub first_string_len: usize,
	pub second_string_len: usize,
}

impl StringAffix {
	pub fn find(first_string: &str, second_string: &str) -> StringAffix {
		// remove common prefix and suffix (linear vs square runtime for levensthein)
		let mut first_iter = first_string.chars();
		let mut second_iter = second_string.chars();
	
		let mut limit_start = 0;
	
		let mut first_iter_char = first_iter.next();
		let mut second_iter_char = second_iter.next();
		while first_iter_char != None && first_iter_char == second_iter_char  {
			first_iter_char = first_iter.next();
			second_iter_char = second_iter.next();
			limit_start += 1;
		}
	
		// save char since the iterator was already consumed
		let first_iter_cache = first_iter_char;
		let second_iter_cache = second_iter_char;
	
		if second_iter_char != None && first_iter_char != None {
			first_iter_char = first_iter.next_back();
			second_iter_char = second_iter.next_back();
			while first_iter_char != None && first_iter_char == second_iter_char  {
				first_iter_char = first_iter.next_back();
				second_iter_char = second_iter.next_back();
			}
		}
	
		match (first_iter_char, second_iter_char) {
			(None, None) => {
				// characters might not match even though they were consumed
				let remaining_char = (first_iter_cache != second_iter_cache) as usize;
				StringAffix {
					prefix_len: limit_start,
					first_string_len: remaining_char,
					second_string_len: remaining_char,
				}
			},
			(None, _) => {
				let remaining_char = (first_iter_cache != None && first_iter_cache != second_iter_char) as usize;
				StringAffix {
					prefix_len: limit_start,
					first_string_len: remaining_char,
					second_string_len: second_iter.count() + 1 + remaining_char,
				}
			},
			(_, None) => {
				let remaining_char = (second_iter_cache != None && second_iter_cache != first_iter_char) as usize;
				StringAffix {
					prefix_len: limit_start,
					first_string_len: first_iter.count() + 1 + remaining_char,
					second_string_len: remaining_char,
				}
			},
			_ => {
				StringAffix {
					prefix_len: limit_start,
					first_string_len: first_iter.count() + 2,
					second_string_len: second_iter.count() + 2,
				}
			}
		}
	}
}