fastxfix 1.0.0

Extremely fast prefix/suffix finder for any 2D data type
Documentation
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
/*!

# FastXFix

**This crate is considered feature complete.**

A small utility crate for finding the longest common prefix/suffix of 2D collections at
absolutely insane speeds, made possible by [`rayon`] and SIMD optimizations.

"2D collections" refers to arrangements like `Vec<T>`, `HashSet<T>`, or `LinkedList<T>`.
When `T` implements `AsRef<str>`, you'll be able to use the methods of [`CommonStr`] on it.
When `T` implements `AsRef<&[U]>` (meaning that `T` is a slice of some kind) then you'll have
access to the methods of [`CommonRaw`]. These two conditions are not mutually exclusive, so
it's up to the user to ensure they're using the method that best coincides with what they're
trying to accomplish.

If you're trying to extract information about strings, **always** prefer using [`CommonStr`]
methods: they are specifically optimized for handling rust's UTF-8 encoded strings.

## Examples

```
use fastxfix::CommonStr;
use std::num::NonZeroUsize;

let s1 = "wowie_this_is_a_string".to_string();
let s2 = "wowie_this_is_another_string_".to_string();

let v = vec![s1, s2];
let common_prefix = v.common_prefix().expect("we know there is a common prefix");
let len: NonZeroUsize = v.common_prefix_len().expect("we know there is a common prefix");
assert!(common_prefix.len() == len.get());
// The strings have no common suffix.
assert!(v.common_suffix_len().is_none());
```
*/

#![deny(missing_docs)]

mod finder;

use finder::*;
use rayon::prelude::*;
use std::num::NonZeroUsize;

/// Trait for finding the longest common [`String`] prefix/suffix of any 2D collection.
pub trait CommonStr {
    /// Returns the longest common prefix of all referenced strings.
    ///
    /// Returns `None` when there is no common prefix.
    fn common_prefix(&self) -> Option<String> {
        self.common_prefix_ref().map(|s| s.to_string())
    }

    /// Returns the longest common suffix of all referenced strings.
    ///
    /// Returns `None` when there is no common suffix.
    fn common_suffix(&self) -> Option<String> {
        self.common_suffix_ref().map(|s| s.to_string())
    }

    /// Returns the length of the longest common prefix of all referenced strings.
    ///
    /// Returns `None` instead of 0 when there is no common prefix.
    fn common_prefix_len(&self) -> Option<NonZeroUsize> {
        self.common_prefix_ref()
            .map(|s| unsafe { NonZeroUsize::new_unchecked(s.len()) })
    }

    /// Returns the length of the longest common suffix of all referenced strings.
    ///
    /// Returns `None` instead of 0 when there is no common suffix.
    fn common_suffix_len(&self) -> Option<NonZeroUsize> {
        self.common_suffix_ref()
            .map(|s| unsafe { NonZeroUsize::new_unchecked(s.len()) })
    }

    /// Returns a reference to the string which has the longest common
    /// prefix of all strings in the collection.
    ///
    /// Returns `None` when there is no common prefix.
    fn common_prefix_ref(&self) -> Option<&str>;

    /// Returns a reference to the string which has the longest common
    /// suffix of all strings in the collection.
    ///
    /// Returns `None` when there is no common suffix.
    fn common_suffix_ref(&self) -> Option<&str>;
}

/// Trait for finding the longest common raw prefix/suffix of any 2D collection.
pub trait CommonRaw<T: Clone> {
    /// Returns the longest common prefix of all referenced data.
    ///
    /// Returns `None` when there is no common prefix.
    fn common_prefix_raw(&self) -> Option<Vec<T>> {
        self.common_prefix_raw_ref().map(|s| s.to_vec())
    }

    /// Returns the longest common suffix of all referenced data.
    ///
    /// Returns `None` when there is no common suffix.
    fn common_suffix_raw(&self) -> Option<Vec<T>> {
        self.common_suffix_raw_ref().map(|s| s.to_vec())
    }

    /// Returns the length of the longest common prefix of all referenced data.
    ///
    /// Returns `None` instead of 0 when there is no common prefix.
    fn common_prefix_raw_len(&self) -> Option<NonZeroUsize> {
        self.common_prefix_raw_ref()
            .map(|s| unsafe { NonZeroUsize::new_unchecked(s.len()) })
    }

    /// Returns the length of the longest common suffix of all referenced data.
    ///
    /// Returns `None` instead of 0 when there is no common suffix.
    fn common_suffix_raw_len(&self) -> Option<NonZeroUsize> {
        self.common_suffix_raw_ref()
            .map(|s| unsafe { NonZeroUsize::new_unchecked(s.len()) })
    }

    /// Returns a reference to the element which has the longest common
    /// prefix of all data in the collection.
    ///
    /// Returns `None` when there is no common prefix.
    fn common_prefix_raw_ref(&self) -> Option<&[T]>;

    /// Returns a reference to the element which has the longest common
    /// suffix of all data in the collection.
    ///
    /// Returns `None` when there is no common suffix.
    fn common_suffix_raw_ref(&self) -> Option<&[T]>;
}

impl<C: ?Sized, T> CommonStr for C
where
    for<'a> &'a C: IntoParallelIterator<Item = &'a T>,
    T: AsRef<str> + Sync,
{
    fn common_prefix_ref(&self) -> Option<&str> {
        find_common::<_, StringPrefix, _, _>(self)
    }

    fn common_suffix_ref(&self) -> Option<&str> {
        find_common::<_, StringSuffix, _, _>(self)
    }
}

impl<C: ?Sized, T, U> CommonRaw<U> for C
where
    for<'a> &'a C: IntoParallelIterator<Item = &'a T>,
    T: AsRef<[U]> + Sync,
    U: Clone + Eq + Sync,
{
    fn common_prefix_raw_ref(&self) -> Option<&[U]> {
        find_common::<_, GenericPrefix, _, _>(self)
    }

    fn common_suffix_raw_ref(&self) -> Option<&[U]> {
        find_common::<_, GenericSuffix, _, _>(self)
    }
}

/// Core function for finding LCP or LCS. It looks a bit involved,
/// but most of what goes on in here is just to ensure we satisfy the
/// type constraints laid out by rayon.
///
/// The core idea is to, for each pair of referenced values, compute the
/// result of [`Finder::common`] and pass it along to be one of
/// the values in the next pair. At any point, that result might be `None`,
/// (there was no common prefix/suffix), causing the routine to terminate
/// as soon as rayon is able to halt execution.
fn find_common<C: ?Sized, F, T, U>(collection: &C) -> Option<&U>
where
    for<'a> &'a C: IntoParallelIterator<Item = &'a T>,
    F: Finder<U>,
    T: AsRef<U> + Sync,
    U: ?Sized + Sync,
{
    // We need to use the `try_*` variants of fold/reduce so we can fail
    // early when any two items don't have a common prefix/suffix.
    collection
        .into_par_iter()
        .try_fold(
            || None,
            |previous, current| {
                let cur_ref = current.as_ref();
                match previous {
                    Some(prev) => F::common(prev, cur_ref).map(Some),
                    None => Some(Some(cur_ref)),
                }
            },
        )
        .try_reduce(
            || None,
            |a, b| match (a, b) {
                (Some(a), Some(b)) => F::common(a, b).map(Some),
                (Some(common), None) | (None, Some(common)) => Some(Some(common)),
                (None, None) => None,
            },
        )
        .flatten()
}

#[cfg(test)]
mod tests {
    use super::{CommonRaw, CommonStr};
    use std::hint::black_box;
    use std::iter;
    use ya_rand::*;

    const BASE_LEN: usize = 19;
    const COMMON: &str = "this is just a simple sentence";
    const EXT_LEN: usize = 13;
    const TOTAL_LEN: usize = BASE_LEN + EXT_LEN;
    const VEC_LEN: usize = 1 << 15;

    #[test]
    fn str_prefix_sanity() {
        let v = black_box(vec![COMMON.to_string(); BASE_LEN]);
        let common = v.common_prefix_ref().unwrap();
        assert_eq!(common, COMMON);
        assert_eq!(common.len(), COMMON.len());
    }

    #[test]
    fn str_suffix_sanity() {
        let v = black_box(vec![COMMON.to_string(); BASE_LEN]);
        let common = v.common_suffix_ref().unwrap();
        assert_eq!(common, COMMON);
        assert_eq!(common.len(), COMMON.len());
    }

    #[test]
    fn raw_prefix_sanity() {
        let v = black_box(vec![COMMON.as_bytes().to_vec(); BASE_LEN]);
        let common = v.common_prefix_raw_ref().unwrap();
        assert_eq!(common, COMMON.as_bytes());
        assert_eq!(common.len(), COMMON.len());
    }

    #[test]
    fn raw_suffix_sanity() {
        let v = black_box(vec![COMMON.as_bytes().to_vec(); BASE_LEN]);
        let common = v.common_suffix_raw_ref().unwrap();
        assert_eq!(common, COMMON.as_bytes());
        assert_eq!(common.len(), COMMON.len());
    }

    #[test]
    fn misc() {
        let input: [String; 0] = [];
        let prefix = input.common_prefix();
        assert_eq!(prefix, None);
        let suffix = input.common_suffix();
        assert_eq!(suffix, None);

        let input = ["just a single entry"];
        let prefix = input.common_prefix().unwrap();
        assert_eq!(prefix, input[0]);
        let suffix = input.common_suffix().unwrap();
        assert_eq!(suffix, input[0]);

        let input = ["foobar", "fooqux", "foodle", "fookys"];
        let prefix = input.common_prefix().unwrap();
        assert_eq!(prefix, "foo");
        let suffix = input.common_suffix();
        assert_eq!(suffix, None);

        let input = ["café", "caféine"];
        let prefix = input.common_prefix().unwrap();
        assert_eq!(prefix, "café");
        let suffix = input.common_suffix();
        assert_eq!(suffix, None);

        let input = ["äbc", "âbc"];
        let prefix = input.common_prefix();
        assert_eq!(prefix, None);
        let suffix = input.common_suffix().unwrap();
        assert_eq!(suffix, "bc");

        let input = ["abc€", "xyz€"];
        let prefix = input.common_prefix();
        assert_eq!(prefix, None);
        let suffix = input.common_suffix().unwrap();
        assert_eq!(suffix, "");

        let input = ["abcä", "defâ"];
        let prefix = input.common_prefix();
        assert_eq!(prefix, None);
        let suffix = input.common_suffix();
        assert_eq!(suffix, None);

        let input = ["some thingy", "nothing"];
        let prefix = input.common_prefix();
        assert_eq!(prefix, None);
        let suffix = input.common_suffix();
        assert_eq!(suffix, None);

        let input = ["-lol-", "_lol_"];
        let prefix = input.common_prefix();
        assert_eq!(prefix, None);
        let suffix = input.common_suffix();
        assert_eq!(suffix, None);

        let input = ["a🤖b", "a🤡b"];
        let prefix = input.common_prefix().unwrap();
        assert_eq!(prefix, "a");
        let suffix = input.common_suffix().unwrap();
        assert_eq!(suffix, "b");

        let input = ["résumé", "résister"];
        let prefix = input.common_prefix().unwrap();
        assert_eq!(prefix, "rés");
        let suffix = input.common_suffix();
        assert_eq!(suffix, None);

        let input = ["abcédef", "xyzèdef"];
        let prefix = input.common_prefix();
        assert_eq!(prefix, None);
        let suffix = input.common_suffix().unwrap();
        assert_eq!(suffix, "def");

        let input = ["Goodbye 👋", "Farewell 👋"];
        let prefix = input.common_prefix();
        assert_eq!(prefix, None);
        let suffix = input.common_suffix().unwrap();
        assert_eq!(suffix, " 👋");

        let input = ["Family: 👨‍👩‍👧", "Group: 👨‍👩‍👧"];
        let prefix = input.common_prefix();
        assert_eq!(prefix, None);
        let suffix = input.common_suffix().unwrap();
        assert_eq!(suffix, ": 👨‍👩‍👧");

        let input = ["just some words 世界", "世界"];
        let prefix = input.common_prefix();
        assert_eq!(prefix, None);
        let suffix = input.common_suffix().unwrap();
        assert_eq!(suffix, "世界");

        let input = ["tests😀", "best😀"];
        let prefix = input.common_prefix();
        assert_eq!(prefix, None);
        let suffix = input.common_suffix().unwrap();
        assert_eq!(suffix, "😀");

        let input = ["wowie_bruhther_clap", "wowie-lol-clap", "wowie_xd_clap"];
        let prefix = input.common_prefix().unwrap();
        assert_eq!(prefix, "wowie");
        let suffix = input.common_suffix().unwrap();
        assert_eq!(suffix, "clap");
    }

    #[test]
    fn prefix_ascii() {
        let mut rng = new_rng();
        let base = new_string_with::<BASE_LEN, _>(|| random_ascii(&mut rng));
        let mut strings = vec![String::with_capacity(TOTAL_LEN); VEC_LEN];
        strings.iter_mut().for_each(|s| {
            let ext = new_string_with::<EXT_LEN, _>(|| random_ascii(&mut rng));
            s.push_str(&base);
            s.push_str(&ext);
        });
        let prefix = strings.common_prefix().unwrap();
        assert_eq!(base, prefix);
    }

    #[test]
    fn suffix_ascii() {
        let mut rng = new_rng();
        let base = new_string_with::<BASE_LEN, _>(|| random_ascii(&mut rng));
        let mut strings = vec![String::with_capacity(TOTAL_LEN); VEC_LEN];
        strings.iter_mut().for_each(|s| {
            let ext = new_string_with::<EXT_LEN, _>(|| random_ascii(&mut rng));
            s.push_str(&ext);
            s.push_str(&base);
        });
        let suffix = strings.common_suffix().unwrap();
        assert_eq!(base, suffix);
    }

    fn random_ascii(rng: &mut ShiroRng) -> char {
        rng.bits(7) as u8 as char
    }

    #[test]
    fn prefix_char() {
        let mut rng = new_rng();
        let base = new_string_with::<BASE_LEN, _>(|| random_char(&mut rng));
        let mut strings = vec![String::with_capacity(TOTAL_LEN * 4); VEC_LEN];
        strings.iter_mut().for_each(|s| {
            let ext = new_string_with::<EXT_LEN, _>(|| random_char(&mut rng));
            s.push_str(&base);
            s.push_str(&ext);
        });
        let prefix = strings.common_prefix().unwrap();
        assert_eq!(base, prefix);
    }

    #[test]
    fn suffix_char() {
        let mut rng = new_rng();
        let base = new_string_with::<BASE_LEN, _>(|| random_char(&mut rng));
        let mut strings = vec![String::with_capacity(TOTAL_LEN * 4); VEC_LEN];
        strings.iter_mut().for_each(|s| {
            let ext = new_string_with::<EXT_LEN, _>(|| random_char(&mut rng));
            s.push_str(&ext);
            s.push_str(&base);
        });
        let suffix = strings.common_suffix().unwrap();
        assert_eq!(base, suffix);
    }

    fn random_char(rng: &mut ShiroRng) -> char {
        loop {
            // 2^21 is the smallest power-of-two value outside of
            // the maximum valid UTF-8 character range.
            let val = rng.bits(21) as u32;
            match char::from_u32(val) {
                Some(c) => return c,
                None => continue,
            }
        }
    }

    fn new_string_with<const SIZE: usize, F>(f: F) -> String
    where
        F: FnMut() -> char,
    {
        iter::repeat_with(f).take(SIZE).collect()
    }

    #[test]
    fn prefix_generic() {
        let mut rng = new_rng();
        let base = new_vec_with::<BASE_LEN, _>(|| rng.u64());
        let mut nested = vec![Vec::new(); VEC_LEN];
        nested.iter_mut().for_each(|cur| {
            let ext = new_vec_with::<EXT_LEN, _>(|| rng.u64());
            cur.extend_from_slice(&base);
            cur.extend_from_slice(&ext);
        });
        let prefix = nested.common_prefix_raw().unwrap();
        assert_eq!(base, prefix);
    }

    #[test]
    fn suffix_generic() {
        let mut rng = new_rng();
        let base = new_vec_with::<BASE_LEN, _>(|| rng.u64());
        let mut nested = vec![Vec::new(); VEC_LEN];
        nested.iter_mut().for_each(|cur| {
            let ext = new_vec_with::<EXT_LEN, _>(|| rng.u64());
            cur.extend_from_slice(&ext);
            cur.extend_from_slice(&base);
        });
        let prefix = nested.common_suffix_raw().unwrap();
        assert_eq!(base, prefix);
    }

    fn new_vec_with<const SIZE: usize, F>(f: F) -> Vec<u64>
    where
        F: FnMut() -> u64,
    {
        iter::repeat_with(f).take(SIZE).collect()
    }
}