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
use std::{cmp::Ordering, slice::Iter};

use crate::Scoring;

/// A (possible partial) match of query within the target string. Matched chars
/// are stored as indices into the target string.
///
/// The score is not clamped to any range and can be negative.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct Match {
    /// Accumulative score
    score: isize,
    /// Count of current consecutive matched chars
    consecutive: usize,
    /// Matched char indices
    matched: Vec<usize>,
}

impl Match {
    /// Creates a new match with the given scoring and matched indices.
    pub(crate) fn with_matched(score: isize, consecutive: usize, matched: Vec<usize>) -> Self {
        Match {
            score,
            consecutive,
            matched,
        }
    }

    /// Returns the accumulative score for this match.
    pub fn score(&self) -> isize {
        self.score
    }

    /// Returns an iterator over the matched char indices.
    pub fn matched_indices(&self) -> Iter<usize> {
        self.matched.iter()
    }

    /// Returns an iterator that groups the individual char matches into groups.
    pub fn continuous_matches(&self) -> ContinuousMatches {
        ContinuousMatches {
            matched: &self.matched,
            current: 0,
        }
    }

    /// Extends this match with `other`.
    pub fn extend_with(&mut self, other: &Match, scoring: &Scoring) {
        self.score += other.score;
        self.consecutive += other.consecutive;

        if let (Some(last), Some(first)) = (self.matched.last(), other.matched.first()) {
            let distance = first - last;

            match distance {
                0 => {}
                1 => {
                    self.consecutive += 1;
                    self.score += self.consecutive as isize * scoring.bonus_consecutive;
                }
                _ => {
                    self.consecutive = 0;
                    let penalty = (distance as isize - 1) * scoring.penalty_distance;
                    self.score -= penalty;
                }
            }
        }

        self.matched.extend(&other.matched);
    }
}

impl Ord for Match {
    fn cmp(&self, other: &Match) -> Ordering {
        self.score.cmp(&other.score)
    }
}

impl PartialOrd for Match {
    fn partial_cmp(&self, other: &Match) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Eq for Match {}

impl PartialEq for Match {
    fn eq(&self, other: &Match) -> bool {
        self.score == other.score
    }
}

/// Describes a continuous group of char indices
#[derive(Debug)]
pub struct ContinuousMatch {
    start: usize,
    len: usize,
}

impl ContinuousMatch {
    pub(crate) fn new(start: usize, len: usize) -> Self {
        ContinuousMatch { start, len }
    }

    /// Returns the start index of this group.
    pub fn start(&self) -> usize {
        self.start
    }

    /// Returns the length of this group.
    pub fn len(&self) -> usize {
        self.len
    }
}

impl Eq for ContinuousMatch {}

impl PartialEq for ContinuousMatch {
    fn eq(&self, other: &ContinuousMatch) -> bool {
        self.start == other.start && self.len == other.len
    }
}

/// Iterator returning [`ContinuousMatch`]es from the matched char indices in a [`Match`]
pub struct ContinuousMatches<'a> {
    matched: &'a Vec<usize>,
    current: usize,
}

impl<'a> Iterator for ContinuousMatches<'_> {
    type Item = ContinuousMatch;

    fn next(&mut self) -> Option<ContinuousMatch> {
        let mut start = None;
        let mut len = 0;

        let mut last_idx = None;

        for idx in self.matched.iter().cloned().skip(self.current) {
            start = start.or(Some(idx));

            if last_idx.is_some() && (idx - last_idx.unwrap() != 1) {
                return Some(ContinuousMatch::new(start.unwrap(), len));
            }

            self.current += 1;
            len += 1;
            last_idx = Some(idx);
        }

        if last_idx.is_some() {
            return Some(ContinuousMatch::new(start.unwrap(), len));
        }

        None
    }
}

#[cfg(test)]
mod tests {
    use crate::Scoring;

    use super::{ContinuousMatch, Match};

    #[test]
    fn continuous() {
        let m = Match::with_matched(0, 0, vec![0, 1, 2, 5, 6, 10]);

        assert_eq!(
            m.continuous_matches().collect::<Vec<ContinuousMatch>>(),
            vec![
                ContinuousMatch { start: 0, len: 3 },
                ContinuousMatch { start: 5, len: 2 },
                ContinuousMatch { start: 10, len: 1 },
            ]
        )
    }

    #[test]
    fn extend_match() {
        let mut a = Match::with_matched(16, 3, vec![1, 2, 3]);
        let b = Match::with_matched(8, 3, vec![5, 6, 7]);

        let s = Scoring::default();

        a.extend_with(&b, &s);

        assert_eq!(a.score(), 24 - s.penalty_distance);
        assert_eq!(a.consecutive, 0);
        assert_eq!(a.matched_indices().len(), 6);
    }

    #[test]
    fn extend_match_cont() {
        let mut a = Match::with_matched(16, 3, vec![1, 2, 3]);
        let b = Match::with_matched(8, 3, vec![4, 5, 6]);

        let s = Scoring::default();

        a.extend_with(&b, &s);

        assert_eq!(a.score(), 16 + 8 + (3 + 3 + 1) * s.bonus_consecutive);
        assert_eq!(a.consecutive, 3 + 3 + 1);
        assert_eq!(a.matched_indices().len(), 6);
    }
}