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
/*!
Module for Pattern matching. \

A Pattern matching API which provides a generic trait for using different pattern types when searching through a `&str`. \
For more details on implementation, see the trait [`Pattern`].

# Examples

[`Pattern`] is implemented for `char`, `&str`, slices of `char` and `&str`, [`Regex`](https://docs.rs/regex/latest/regex/struct.Regex.html)
and closures implementing `Fn(&str) -> bool`.

```
# use plexer::pattern::Pattern;
#
let hay = "Can you find a needle in a haystack";

// char pattern
assert!('n'.find_one_in(hay).is_some_and(|m| m.start == 2));
// &str pattern
assert!("you".find_one_in(hay).is_some_and(|m| m.start == 4));
// array of chars pattern
assert!(['a', 'e', 'i', 'o', 'u'].find_one_in(hay).is_some_and(|m| m.start == 1));
// array of &str pattern
assert!(["Can", "you"].find_one_in(hay).is_some_and(|m| m.start == 0));
// closure pattern
assert!((|s: &str| s.starts_with("f")).find_one_in(hay).is_some_and(|m| m.start == 8));
```
*/

use regex::Regex;

/// Returned by [`Pattern`] on match.
#[derive(Debug, Clone, PartialEq)]
pub struct Match<'a> {
    /// The string that was searched in
    pub haystack: &'a str,
    /// Start of the match
    pub start: usize,
    /// End of the match
    pub end: usize,
}

impl<'a> Match<'a> {
    /**
    Create a match from a haystack `&str` and `start..end` range.

    # Panics
    When ```start >= end``` or ```haystack.len() < end```.

    # Example
    ```should_panic
    # use plexer::pattern::Match;
    #
    let mat = Match::new("don't go to far...", 0, 100000);
    ```
    */
    pub fn new(haystack: &'a str, start: usize, end: usize) -> Self {
        assert!(start < end);
        assert!(haystack.len() >= end);
        Self {
            haystack,
            start,
            end,
        }
    }

    /**
    Returns the number of char in the match

    # Example
    ```
    # use plexer::pattern::Match;
    #
    assert_eq!(Match::new("three", 1, 4).len(), 3);
    ```
    */
    pub fn len(&self) -> usize {
        self.end - self.start
    }

    /**
    Convert to to `&str`.

    # Example
    ```
    # use plexer::pattern::Match;
    #
    let mat = Match::new("it's here not here", 5, 9);

    assert_eq!(mat.as_str(), "here");
    ```
    */
    pub fn as_str(&self) -> &'a str {
        &self.haystack[self.start..self.end]
    }
}

impl<'a> ToString for Match<'a> {
    fn to_string(&self) -> String {
        self.as_str().to_string()
    }
}

/**
A string `Pattern` trait.

The type implementing it can be used as a pattern for `&str`,
by default it is implemented for the following types.

| Pattern type              | Match condition                         |
|---------------------------|-----------------------------------------|
| ```char```                | is contained in string                  |
| ```&str```                | is substring                            |
| ```String```              | is substring                            |
| ```&[char]```             | any `char` match                        |
| ```&[&str]```             | any `&str` match                        |
| ```F: Fn(&str) -> bool``` | `F` returns `true` for substring        |
| ```Regex```               | `Regex` match substring                 |
*/
pub trait Pattern<'a> {
    /**
    Find all occurences of the pattern in the given `&str`.

    # Examples
    ```
    # use plexer::pattern::{Match, Pattern};
    #
    assert!("ab".find_in("cd").is_empty());
    assert_eq!("ab".find_in("cabd"), vec![Match::new("cabd", 1, 3)]);
    ```
    */
    fn find_in(&self, haystack: &'a str) -> Vec<Match<'a>>;

    /**
    Find all occurences of the pattern in the given `&str` that are prefixes.

    # Examples
    ```
    # use plexer::pattern::{Match, Pattern};
    #
    assert!("ab".find_prefixes_in("cdab").is_empty());
    assert_eq!("ab".find_prefixes_in("abcd"), vec![Match::new("abcd", 0, 2)]);
    ```
    */
    fn find_prefixes_in(&self, haystack: &'a str) -> Vec<Match<'a>> {
        self.find_in(haystack)
            .into_iter()
            .filter(|mat| mat.start == 0)
            .collect()
    }

    /**
    Find all occurences of the pattern in the given `&str` that are suffixes.

    # Examples
    ```
    # use plexer::pattern::{Match, Pattern};
    #
    assert!("ab".find_suffixes_in("abcd").is_empty());
    assert_eq!("ab".find_suffixes_in("cdab"), vec![Match::new("cdab", 2, 4)]);
    ```
    */
    fn find_suffixes_in(&self, haystack: &'a str) -> Vec<Match<'a>> {
        let len = haystack.len();
        self.find_in(haystack)
            .into_iter()
            .filter(|mat| mat.end == len)
            .collect()
    }

    /**
    Find one occurrence of the pattern in the given `&str`.

    # Examples
    ```
    # use plexer::pattern::{Match, Pattern};
    #
    assert!("ab".find_one_in("cd").is_none());
    assert_eq!("ab".find_one_in("cdab"), Some(Match::new("cdab", 2, 4)));
    ```
    */
    fn find_one_in(&self, haystack: &'a str) -> Option<Match<'a>> {
        self.find_in(haystack).into_iter().next()
    }

    /**
    Find one occurrence of the pattern in the given `&str` that is prefix.

    # Examples
    ```
    # use plexer::pattern::{Match, Pattern};
    #
    assert!("ab".find_prefix_in("cdab").is_none());
    assert_eq!("ab".find_prefix_in("abcd"), Some(Match::new("abcd", 0, 2)));
    ```
    */
    fn find_prefix_in(&self, haystack: &'a str) -> Option<Match<'a>> {
        self.find_prefixes_in(haystack).into_iter().next()
    }

    /**
    Find one occurrence of the pattern in the given `&str` that is suffix.

    # Examples
    ```
    # use plexer::pattern::{Match, Pattern};
    #
    assert!("ab".find_suffix_in("abcd").is_none());
    assert_eq!("ab".find_suffix_in("cdab"), Some(Match::new("cdab", 2, 4)));
    ```
    */
    fn find_suffix_in(&self, haystack: &'a str) -> Option<Match<'a>> {
        self.find_suffixes_in(haystack).into_iter().next()
    }
}

impl<'a> Pattern<'a> for char {
    fn find_in(&self, haystack: &'a str) -> Vec<Match<'a>> {
        haystack
            .match_indices(&self.to_string())
            .map(|(i, mat)| Match::new(haystack, i, i + mat.len()))
            .collect()
    }
}

impl<'a> Pattern<'a> for [char] {
    fn find_in(&self, haystack: &'a str) -> Vec<Match<'a>> {
        self.iter().flat_map(|ch| ch.find_in(haystack)).collect()
    }
}

impl<'a, const N: usize> Pattern<'a> for [char; N] {
    fn find_in(&self, haystack: &'a str) -> Vec<Match<'a>> {
        self.as_slice().find_in(haystack)
    }
}

impl<'a, const N: usize> Pattern<'a> for &[char; N] {
    fn find_in(&self, haystack: &'a str) -> Vec<Match<'a>> {
        self.as_slice().find_in(haystack)
    }
}

impl<'a> Pattern<'a> for String {
    fn find_in(&self, haystack: &'a str) -> Vec<Match<'a>> {
        haystack
            .match_indices(self)
            .map(|(i, mat)| Match::new(haystack, i, i + mat.len()))
            .collect()
    }
}

impl<'a> Pattern<'a> for &str {
    fn find_in(&self, haystack: &'a str) -> Vec<Match<'a>> {
        self.to_string().find_in(haystack)
    }
}

impl<'a> Pattern<'a> for [&str] {
    fn find_in(&self, haystack: &'a str) -> Vec<Match<'a>> {
        self.iter().flat_map(|ch| ch.find_in(haystack)).collect()
    }
}

impl<'a, const N: usize> Pattern<'a> for [&str; N] {
    fn find_in(&self, haystack: &'a str) -> Vec<Match<'a>> {
        self.as_slice().find_in(haystack)
    }
}

impl<'a, const N: usize> Pattern<'a> for &[&str; N] {
    fn find_in(&self, haystack: &'a str) -> Vec<Match<'a>> {
        self.as_slice().find_in(haystack)
    }
}

impl<'a: 'b, 'b, F> Pattern<'a> for F
where
    F: Fn(&'b str) -> bool,
{
    fn find_in(&self, haystack: &'a str) -> Vec<Match<'a>> {
        let mut matches = Vec::new();
        let mut cur_1 = 0;
        // The goal is to check from left to right and to take the largest match
        while cur_1 < haystack.len() {
            let mut cur_2 = haystack.len();
            while cur_2 > cur_1 {
                let sub = &haystack[cur_1..cur_2];
                if (self)(sub) {
                    matches.push(Match::new(haystack, cur_1, cur_2));
                    cur_1 = cur_2;
                }
                cur_2 -= 1
            }
            cur_1 += 1;
        }
        matches
    }
}

impl<'a> Pattern<'a> for Regex {
    fn find_in(&self, haystack: &'a str) -> Vec<Match<'a>> {
        self.find_iter(haystack)
            .map(|mat| Match::new(haystack, mat.start(), mat.end()))
            .collect()
    }
}