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
#[cfg(test)]
mod tests;
use std::cmp::min;
use std::cell::RefCell;
use crate::utils::{Rewrite, common_prefix_size};
const DEFAULT_CAPATITY: usize = 25;
pub struct Jaro {
pub state: RefCell<State>,
}
pub struct State {
pub buffer1: Vec<BufferItem>,
pub buffer2: Vec<BufferItem>,
}
#[derive(PartialEq)]
pub struct BufferItem {
pub val: char,
pub matched: bool,
}
impl BufferItem {
pub fn new(val: char) -> Self {
Self { val, matched: false }
}
}
impl Jaro {
pub fn new() -> Self {
Jaro {
state: RefCell::new(State {
buffer1: Vec::with_capacity(DEFAULT_CAPATITY),
buffer2: Vec::with_capacity(DEFAULT_CAPATITY),
})
}
}
pub fn similarity(&self, str1: &str, str2: &str) -> f64 {
match (str1.len(), str2.len()) {
(0, 0) => { return 1.0; }
(_, 0) => { return 0.0; }
(0, _) => { return 0.0; }
(_, _) => { }
}
let State { buffer1, buffer2 } = &mut *self.state.borrow_mut();
buffer1.rewrite_with(str1.chars().map(BufferItem::new));
buffer2.rewrite_with(str2.chars().map(BufferItem::new));
let prefix = common_prefix_size(buffer1, buffer2);
let buffer1 = &mut buffer1[prefix..];
let buffer2 = &mut buffer2[prefix..];
let mut matches = 0;
let len1 = buffer1.len();
let len2 = buffer2.len();
let i2_range = max!(1, (len1 + prefix) / 2, (len2 + prefix) / 2) - 1;
let mut i1 = 0;
for item1 in buffer1.iter_mut() {
let i2_lo = i1 - min(i2_range, i1);
let i2_up = min(i1 + i2_range + 1, len2);
i1 += 1;
if i2_lo >= i2_up { continue; }
for item2 in buffer2[i2_lo..i2_up].iter_mut() {
if !item2.matched && item1.val == item2.val {
item1.matched = true;
item2.matched = true;
matches += 1;
break;
}
}
}
if prefix + matches == 0 { return 0.0; }
let mut trans = 0;
if matches != 0 {
let mut matches2 = buffer2.iter().filter(|x| x.matched);
for item1 in buffer1.iter().filter(|x| x.matched) {
if let Some(item2) = matches2.next() {
if item1.val != item2.val { trans += 1; }
}
}
}
let matches = (prefix + matches) as f64;
let trans = trans as f64;
let len1 = (prefix + len1) as f64;
let len2 = (prefix + len2) as f64;
(matches/len1 + matches/len2 + ((matches - trans/2.) / matches)) / 3.
}
pub fn rel_dist(&self, str1: &str, str2: &str) -> f64 {
1.0 - self.similarity(str1, str2)
}
}