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
//! stringedits contains the [Edit] trait, which provides access to a number of iterators for small edits to strings.
//! Based off the article [How to Write A Spelling Corrector](https://norvig.com/spell-correct.html) by Peter Norvig.
//! Available under the MIT license.
//!
//! Usage:
//! ```
//! use stringedits::Edit;
//! "foo".dist1edits();
//! ```
//!
#[cfg(test)]
mod tests;
use std::collections::HashSet;

/// The Edit trait provides access to a number of iterators for single-and-double character edits of a string.
/// It is implemented for any type that implements `AsRef<str>`.
pub trait Edit: AsRef<str> {
    /// create an iterator over all the splits at a single position of a word.
    /// ```
    /// # use stringedits::Edit;
    /// # use std::collections::HashSet;
    /// let want: HashSet<(String, String)> = vec![("", "foo"), ("f", "oo"), ("fo", "o"), ("foo", "")]
    ///     .into_iter()
    ///     .map(|(a, b)| (a.to_string(), b.to_string()))
    ///     .collect();
    /// let got: HashSet<(String, String)> = "foo".splits().collect();
    /// assert_eq!(want, got);
    /// ```
    fn splits(&self) -> Splits {
        Splits {
            word: self.as_ref().to_string(),
            i: 0,
        }
    }

    /// create an iterator over all distance-1 transpositions of a word
    /// ```
    /// # use stringedits::Edit;
    /// # use std::collections::HashSet;
    /// let got: HashSet<String> = "bar".replaces().collect();
    /// assert!(got.contains("bzr"));
    /// assert!(got.contains("xar"));
    /// ```
    fn transposes(&self) -> Transposes {
        Transposes(self.splits())
    }

    /// create an iterator over all distance-1 replacements with a lowercase ASCII letter (`'b'a..=b'z'`)
    /// ```
    /// # use stringedits::Edit;
    /// # use std::collections::HashSet;
    /// let got: HashSet<String> = "bar".replaces().collect();
    /// assert!(got.contains("bzr"));
    /// assert!(got.contains("xar"));
    /// ```
    fn replaces(&self) -> Replaces {
        Replaces {
            splits: self.splits(),
            current: None,
            i: 0,
        }
    }

    /// create an iterator over all distance-1 insertions of a lowercase ASCII letter (`'b'a..=b'z'`)
    /// ```
    /// # use stringedits::Edit;
    /// # use std::collections::HashSet;
    /// let got: HashSet<String> = "bar".inserts().collect();
    /// assert!(got.contains("abar"));
    /// assert!(got.contains("bbar"));
    /// assert!(got.contains("bacr"));
    /// assert!(got.contains("bard"));
    /// ```
    fn inserts(&self) -> Inserts {
        Inserts {
            splits: self.splits(),
            i: 0,
            current: None,
        }
    }

    /// create an iterator over all single-character deletions of a word
    /// ```
    /// # use stringedits::Edit;
    /// # use std::collections::HashSet;
    /// let got: HashSet<String> = "bar".deletions().collect();
    /// let mut want: HashSet<String> = vec!["ar", "ba", "br"].into_iter().map(|s| s.to_string()).collect();
    /// assert_eq!(want, got);
    /// ```
    fn deletions(&self) -> Deletions {
        Deletions(self.splits())
    }

    /// create an iterator over all distance-1 edits of the string; that is, the transposes, replacements, insertions, and deletions
    /// ```
    /// # use stringedits::Edit;
    /// # use std::collections::HashSet;
    /// let got: HashSet<String> = "bar".dist1edits().collect();
    /// assert!(got.contains("br")); // deletion
    /// assert!(got.contains("bbar")); // addition
    /// assert!(got.contains("bra")); // transposition
    /// assert!(got.contains("baz")); // substitution
    /// ```
    fn dist1edits(&self) -> Dist1Edits {
        Dist1Edits {
            deletes: self.deletions(),
            transposes: self.transposes(),
            replaces: self.replaces(),
            inserts: self.inserts(),
        }
    }

    /// create an iterator over all distance-2 edits of the string; that is, choose two (with replacement) from transposition, replacement with `b'a..=b'z'`, insertion of `b'a'..=b'z'`, and deletion
    /// ```
    /// # use stringedits::Edit;
    /// # use std::collections::HashSet;
    /// let got: HashSet<String> = "bar".dist2edits().collect();
    /// assert!(got.contains("b")); // deletion 2
    /// assert!(got.contains("bbra")); // addition and substitution
    /// assert!(got.contains("rba")); // transposition 2
    /// assert!(got.contains("bz")); // substitution and deletion
    /// ```
    fn dist2edits(&self) -> Dist2Edits {
        Dist2Edits {
            current: self.dist1edits(),
            dist1: self
                .dist1edits()
                .collect::<HashSet<_>>()
                .into_iter()
                .collect::<Vec<_>>(),
            i: 0,
        }
    }
}

impl<T: AsRef<str>> Edit for T {}

///Iterator over all the splits at a single position of a word. See [Edit::splits]
pub struct Splits {
    word: String,
    i: usize,
}
/// Iterator over all transpositions of a single position of a word. See [Edit::transposes]
pub struct Transposes(Splits);
///Iterator over all the words formed from the delition of a single character from a word.
/// See [Edit::deletions]
pub struct Deletions(Splits);

///Iterator over all the words formed from the replacement of a character in a word with a letter in a...z
/// see [Edit::replaces]
pub struct Replaces {
    splits: Splits,
    current: Option<(String, String)>,
    i: u8,
}

/// Iterator over all the words formed from the insertion of a letter in a...z in any position in a word, including before the first character and after the last
/// see [Edit::inserts]
pub struct Inserts {
    splits: Splits,
    current: Option<(String, String)>,
    i: u8,
}

///Iterator over all the distance-1 edits of a word; deletion, insertion, or replacement of one character,
///or transposition of two characters. See [Edit::dist1edits]
pub struct Dist1Edits {
    deletes: Deletions,
    transposes: Transposes,
    replaces: Replaces,
    inserts: Inserts,
}

///Iterator over all the distance-2 edits of a word; deletion, insertion, or replacement of one character,
/// or transposition of two characters. See [Edit::dist2edits]
pub struct Dist2Edits {
    current: Dist1Edits,
    dist1: Vec<String>,
    i: usize,
}

#[inline]
fn nth_letter(n: u8) -> char {
    (b'a' + n) as char
}

//  -------- ITERATORS  ------
impl Iterator for Inserts {
    type Item = String;
    fn next(&mut self) -> Option<Self::Item> {
        if let (Some((ref a, ref b)), n @ 0...25) = (&self.current, self.i) {
            self.i += 1;
            let mut insert = a.to_string();
            insert.push(nth_letter(n));
            return Some(insert + b);
        };
        match self.splits.next() {
            None => None,
            Some((a, b)) => {
                self.i = 0;
                self.current = Some((a, b));
                self.next()
            }
        }
    }
}

impl Iterator for Dist2Edits {
    type Item = String;
    fn next(&mut self) -> Option<Self::Item> {
        match self.current.next() {
            Some(edit) => Some(edit),
            None if self.i < self.dist1.len() => {
                self.current = self.dist1[self.i].dist1edits();
                self.i += 1;
                self.next()
            }
            None => None,
        }
    }
}

impl Iterator for Dist1Edits {
    type Item = String;
    fn next(&mut self) -> Option<Self::Item> {
        (self.deletes.next())
            .or_else(|| self.transposes.next())
            .or_else(|| self.replaces.next())
            .or_else(|| self.inserts.next())
    }
}
impl Iterator for Replaces {
    type Item = String;
    fn next(&mut self) -> Option<Self::Item> {
        match (&self.current, self.i) {
            (Some((ref a, ref b)), n @ 0...25) if !a.is_empty() => {
                self.i += 1;
                let mut replace = a.to_string();
                replace.pop();
                replace.push(nth_letter(n));
                return Some(replace + b);
            }
            _ => {}
        };

        match self.splits.next() {
            None => None,
            Some((a, b)) => {
                self.i = 0;
                self.current = Some((a, b));
                self.next()
            }
        }
    }
}

impl Iterator for Deletions {
    type Item = String;
    fn next(&mut self) -> Option<Self::Item> {
        match self.0.next() {
            None => None,
            Some((_, ref b)) if b.is_empty() => self.next(),
            Some((a, b)) => Some(a + &b[1..]),
        }
    }
}

impl Iterator for Transposes {
    type Item = String;
    fn next(&mut self) -> Option<Self::Item> {
        match self.0.next() {
            None => None,
            Some((_, ref b)) if b.len() < 2 => self.next(), //we can only transpose the rightmost two characters if there are two or more
            Some((a, b)) => {
                let mut transpose = a.to_string();
                let chars: Vec<char> = b.chars().collect();
                transpose.push(chars[1]);
                transpose.push(chars[0]);
                transpose.extend(&chars[2..]);
                Some(transpose)
            }
        }
    }
}

impl Iterator for Splits {
    type Item = (String, String);
    fn next(&mut self) -> Option<Self::Item> {
        if self.i > self.word.len() {
            return None;
        }
        let n = self.i;
        self.i += 1;
        Some((String::from(&self.word[..n]), String::from(&self.word[n..])))
    }
}