norm 0.1.1

A collection of distance metrics on strings
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
469
470
use core::ops::{Index, IndexMut};

use super::Score;

/// Creating a new [`V2Slab`] allocates 5.25kb on a 64-bit system and 4.25kb on
/// a 32-bit system.
#[derive(Clone, Default)]
pub(super) struct V2Slab {
    /// TODO: docs
    pub(super) bonus: BonusSlab,

    /// TODO: docs
    pub(super) consecutive_matrix: MatrixSlab<usize>,

    /// TODO: docs
    pub(super) matched_indices: MatchedIndicesSlab,

    /// TODO: docs
    pub(super) scoring_matrix: MatrixSlab<Score>,
}

/// TODO: docs
#[derive(Clone, Default)]
pub(super) struct Bonus {
    value: u8,
    is_set: bool,
}

impl Bonus {
    #[inline(always)]
    pub fn is_set(&self) -> bool {
        self.is_set
    }

    #[inline(always)]
    pub fn set(&mut self, value: Score) {
        self.value = value as _;
        self.is_set = true;
    }

    #[inline(always)]
    pub fn value(&self) -> Score {
        self.value as _
    }
}

/// Creating a new [`BonusSlab`] allocates 256 bytes.
#[derive(Clone)]
pub(super) struct BonusSlab {
    vec: Vec<Bonus>,
}

impl Default for BonusSlab {
    #[inline(always)]
    fn default() -> Self {
        Self { vec: vec![Bonus::default(); 128] }
    }
}

impl BonusSlab {
    /// TODO: docs
    #[inline]
    pub fn alloc(&mut self, len: usize) -> &mut [Bonus] {
        if len > self.vec.len() {
            self.vec.resize(len, Bonus::default());
        }

        let slice = &mut self.vec[..len];

        for bonus in slice.iter_mut() {
            bonus.is_set = false;
        }

        slice
    }
}

/// Creating a new [`CandidateSlab`] allocates 512 bytes.
#[derive(Clone)]
pub(super) struct CandidateSlab {
    chars: Vec<char>,
}

impl Default for CandidateSlab {
    #[inline(always)]
    fn default() -> Self {
        Self { chars: vec![char::default(); 128] }
    }
}

impl CandidateSlab {
    #[inline(always)]
    pub fn alloc<'a>(&'a mut self, text: &str) -> &'a [char] {
        if text.len() > self.chars.len() {
            self.chars.resize(text.len(), char::default());
        }

        let mut char_len = 0;

        for ch in text.chars() {
            self.chars[char_len] = ch;
            char_len += 1;
        }

        &self.chars[..char_len]
    }
}

/// Creating a new [`MatchedIndicesSlab`] allocates 1kb on a 64-bit system.
#[derive(Clone)]
pub(super) struct MatchedIndicesSlab {
    vec: Vec<usize>,
}

impl Default for MatchedIndicesSlab {
    #[inline]
    fn default() -> Self {
        Self { vec: vec![0; 128] }
    }
}

impl MatchedIndicesSlab {
    #[inline]
    /// TODO: docs
    pub fn alloc(&mut self, len: usize) -> &mut [usize] {
        if len > self.vec.len() {
            self.vec.resize(len, 0);
        }

        &mut self.vec[..len]
    }
}

pub(super) trait MatrixItem: Copy + Ord + core::fmt::Display {
    /// TODO: docs
    fn fill() -> Self;

    /// TODO: docs
    fn printed_width(&self) -> usize;
}

impl MatrixItem for Score {
    #[inline]
    fn fill() -> Self {
        0
    }

    fn printed_width(&self) -> usize {
        if *self == 0 {
            1
        } else {
            (self.ilog10() + 1) as usize
        }
    }
}

impl MatrixItem for usize {
    #[inline]
    fn fill() -> Self {
        0
    }

    fn printed_width(&self) -> usize {
        if *self == 0 {
            1
        } else {
            (self.ilog10() + 1) as usize
        }
    }
}

/// Creating a new [`MatrixSlab`] allocates `256 * size_of::<T>()` bytes.
#[derive(Clone)]
pub(super) struct MatrixSlab<T: MatrixItem> {
    vec: Vec<T>,
}

impl<T: Default + MatrixItem> Default for MatrixSlab<T> {
    #[inline]
    fn default() -> MatrixSlab<T> {
        // We allocate a 256 cell matrix slab by default to minimize the
        // need to re-allocate for long `query * candidate` pairs.
        Self { vec: vec![T::default(); 256] }
    }
}

impl<T: MatrixItem> MatrixSlab<T> {
    /// TODO: docs
    #[inline]
    pub fn alloc(&mut self, width: usize, height: usize) -> Matrix<'_, T> {
        debug_assert!(height * width > 0);

        if height * width > self.vec.len() {
            self.vec.resize(height * width, T::fill());
        }

        let slice = &mut self.vec[..height * width];

        slice.fill(T::fill());

        Matrix { slice, height, width }
    }
}

/// TODO: docs
pub(super) struct Matrix<'a, T: MatrixItem> {
    /// TODO: docs
    ///
    /// <width><width>...<width>
    /// \---- height times ----/
    slice: &'a mut [T],
    height: usize,
    width: usize,
}

/// Prints the matrix like this:
///
/// ```text
///   ┌                         ┐
///   │0  16 16 13 12 11 10 9  8│
///   │0  0  0  0  0  0  0  0  0│
///   │0  0  0  0  0  0  0  0  0│
///   └                         ┘
/// ```
impl<T: MatrixItem> core::fmt::Debug for Matrix<'_, T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        use core::fmt::Write;

        // The matrix should never be empty, but just in case.
        if self.slice.is_empty() {
            return f.write_str("[ ]");
        }

        // The character width of the biggest score in the whole matrix.
        let max_score_width = {
            let max_score = self.slice.iter().copied().max().unwrap();
            max_score.printed_width()
        };

        // The character width of the biggest score in the last column.
        let last_col_max_score_width = {
            // The cell in the last column of the first row.
            let first_row_last_col =
                self.cols(self.top_left()).last().unwrap();

            let last_col_max_score = self
                .rows(first_row_last_col)
                .map(|cell| self[cell])
                .max()
                .unwrap();

            last_col_max_score.printed_width()
        };

        let printed_matrix_inner_width = (self.width - 1)
            * (max_score_width + 1)
            + last_col_max_score_width;

        let opening_char: char;

        let closing_char: char;

        if self.height == 1 {
            opening_char = '[';
            closing_char = ']';
        } else {
            f.write_char('')?;
            f.write_str(&" ".repeat(printed_matrix_inner_width))?;
            f.write_char('')?;
            f.write_char('\n')?;
            opening_char = '';
            closing_char = '';
        }

        for cell in self.rows(self.top_left()) {
            f.write_char(opening_char)?;

            for cell in self.cols(cell) {
                let item = self[cell];

                write!(f, "{item}")?;

                let num_spaces = if self.col_of(cell) + 1 == self.width {
                    last_col_max_score_width - item.printed_width()
                } else {
                    max_score_width - item.printed_width() + 1
                };

                f.write_str(&" ".repeat(num_spaces))?;
            }

            f.write_char(closing_char)?;

            f.write_char('\n')?;
        }

        if self.height > 1 {
            f.write_char('')?;
            f.write_str(&" ".repeat(printed_matrix_inner_width))?;
            f.write_char('')?;
        }

        Ok(())
    }
}

impl<'a, T: MatrixItem + Copy> Matrix<'a, T> {
    /// TODO: docs
    #[inline(always)]
    pub fn get_value(&self, cell: MatrixCell) -> Option<T> {
        self.slice.get(cell.0).copied()
    }
}

impl<'a, T: MatrixItem> Matrix<'a, T> {
    /// TODO: docs
    #[inline]
    pub fn col_of(&self, cell: MatrixCell) -> usize {
        cell.0 % self.width
    }

    /// TODO: docs
    #[inline]
    pub fn cols(&self, starting_from: MatrixCell) -> Cols {
        Cols {
            next: starting_from,
            remaining: self.width - self.col_of(starting_from),
        }
    }

    /// TODO: docs
    #[inline]
    pub fn down_right(&self, cell: MatrixCell) -> MatrixCell {
        MatrixCell(cell.0 + self.width + 1)
    }

    /// TODO: docs
    #[inline(always)]
    pub fn height(&self) -> usize {
        self.height
    }

    /// TODO: docs
    #[inline]
    pub fn left(&self, cell: MatrixCell) -> MatrixCell {
        MatrixCell(cell.0 - 1)
    }

    /// TODO: docs
    #[inline]
    pub fn row_of(&self, cell: MatrixCell) -> usize {
        cell.0 / self.width
    }

    /// TODO: docs
    #[inline]
    pub fn row_mut(&mut self, row: usize) -> &mut [T] {
        let start = row * self.width;
        let end = start + self.width;
        &mut self.slice[start..end]
    }

    #[inline]
    pub fn rows(&self, starting_from: MatrixCell) -> Rows {
        Rows {
            next: starting_from,
            matrix_width: self.width,
            remaining: self.height - self.row_of(starting_from),
        }
    }

    /// TODO: docs
    #[inline]
    pub fn top_left(&self) -> MatrixCell {
        MatrixCell(0)
    }

    /// TODO: docs
    #[inline]
    pub fn two_rows_mut(
        &mut self,
        row_idx_a: usize,
        row_idx_b: usize,
    ) -> (&mut Row<T>, &mut Row<T>) {
        debug_assert!(row_idx_a < row_idx_b);

        let start_b = row_idx_b * self.width;

        let (part_a, part_b) = self.slice.split_at_mut(start_b);

        let start_a = row_idx_a * self.width;

        (&mut part_a[start_a..start_a + self.width], &mut part_b[..self.width])
    }

    #[inline]
    pub fn up_left(&self, cell: MatrixCell) -> MatrixCell {
        MatrixCell(cell.0 - self.width - 1)
    }

    /// TODO: docs
    #[inline(always)]
    pub fn width(&self) -> usize {
        self.width
    }
}

pub(super) type Row<T> = [T];

#[derive(Debug, Clone, Copy)]
pub(super) struct MatrixCell(pub(super) usize);

impl<T: MatrixItem> Index<MatrixCell> for Matrix<'_, T> {
    type Output = T;

    #[inline]
    fn index(&self, index: MatrixCell) -> &Self::Output {
        &self.slice[index.0]
    }
}

impl<T: MatrixItem> IndexMut<MatrixCell> for Matrix<'_, T> {
    #[inline]
    fn index_mut(&mut self, index: MatrixCell) -> &mut Self::Output {
        &mut self.slice[index.0]
    }
}

/// TODO: docs
pub(super) struct Cols {
    next: MatrixCell,
    remaining: usize,
}

impl Iterator for Cols {
    type Item = MatrixCell;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.remaining == 0 {
            return None;
        }
        let this = self.next;
        self.next.0 += 1;
        self.remaining -= 1;
        Some(this)
    }
}

/// TODO: docs
pub(super) struct Rows {
    next: MatrixCell,
    matrix_width: usize,
    remaining: usize,
}

impl Iterator for Rows {
    type Item = MatrixCell;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.remaining == 0 {
            return None;
        }
        let this = self.next;
        self.next.0 += self.matrix_width;
        self.remaining -= 1;
        Some(this)
    }
}