minrx 0.1.0

High-level bindings to MinRX, by Michael J. Haertel.
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
use std::{
    error::Error,
    fmt::Display,
    mem::MaybeUninit,
    ops::{BitAnd, BitOr, Not},
    ptr::null_mut,
    range::Range,
};

use minrx_sys::{
    minrx_regcomp_flags_t, minrx_regcomp_flags_t_MINRX_REG_BRACE_COMPAT,
    minrx_regcomp_flags_t_MINRX_REG_BRACK_ESCAPE, minrx_regcomp_flags_t_MINRX_REG_EXTENDED,
    minrx_regcomp_flags_t_MINRX_REG_EXTENSIONS_BSD, minrx_regcomp_flags_t_MINRX_REG_EXTENSIONS_GNU,
    minrx_regcomp_flags_t_MINRX_REG_ICASE, minrx_regcomp_flags_t_MINRX_REG_MINDISABLE,
    minrx_regcomp_flags_t_MINRX_REG_MINIMAL, minrx_regcomp_flags_t_MINRX_REG_NATIVE1B,
    minrx_regcomp_flags_t_MINRX_REG_NEWLINE, minrx_regcomp_flags_t_MINRX_REG_NOSUB, minrx_regerror,
    minrx_regex_t, minrx_regexec_flags_t, minrx_regexec_flags_t_MINRX_REG_FIRSTSUB,
    minrx_regexec_flags_t_MINRX_REG_NOFIRSTBYTES, minrx_regexec_flags_t_MINRX_REG_NOSUBRESET,
    minrx_regexec_flags_t_MINRX_REG_NOTBOL, minrx_regexec_flags_t_MINRX_REG_NOTEOL,
    minrx_regexec_flags_t_MINRX_REG_RESUME, minrx_regfree, minrx_regmatch_t, minrx_regncomp,
    minrx_regnexec, minrx_result_t, minrx_result_t_MINRX_REG_BADBR,
    minrx_result_t_MINRX_REG_BADPAT, minrx_result_t_MINRX_REG_BADRPT,
    minrx_result_t_MINRX_REG_EBRACE, minrx_result_t_MINRX_REG_EBRACK,
    minrx_result_t_MINRX_REG_ECOLLATE, minrx_result_t_MINRX_REG_ECTYPE,
    minrx_result_t_MINRX_REG_EESCAPE, minrx_result_t_MINRX_REG_EPAREN,
    minrx_result_t_MINRX_REG_ERANGE, minrx_result_t_MINRX_REG_ESPACE,
    minrx_result_t_MINRX_REG_ESUBREG, minrx_result_t_MINRX_REG_NOMATCH,
    minrx_result_t_MINRX_REG_SUCCESS, minrx_result_t_MINRX_REG_UNKNOWN,
};

/// A MinRX regex matcher. [`Send`] but not [`Sync`].
#[repr(transparent)]
pub struct Regex(minrx_regex_t);

/// A match on some haystack. It is a wrapper of [`std::range::Range<usize>`]
/// with some convenience methods and derives.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Match {
    pub start: usize,
    pub end: usize,
}

/// An iterator over all matches on a haystack.
pub struct MatchIter<'r, 'h> {
    regex: &'r mut Regex,
    haystack: &'h [u8],
    rm: minrx_regmatch_t,
    options: MatchOptions,
    resuming: bool,
    is_done: bool,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct RegexBuilder(minrx_regcomp_flags_t);

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct MatchOptions(minrx_regexec_flags_t);

#[repr(u32)]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum BuildError {
    BadPattern(String) = minrx_result_t_MINRX_REG_BADPAT,
    BadBracket(String) = minrx_result_t_MINRX_REG_BADBR,
    BadRepetition(String) = minrx_result_t_MINRX_REG_BADRPT,
    UnbalancedBrace(String) = minrx_result_t_MINRX_REG_EBRACE,
    UnbalancedBracket(String) = minrx_result_t_MINRX_REG_EBRACK,
    InvalidCollate(String) = minrx_result_t_MINRX_REG_ECOLLATE,
    InvalidClass(String) = minrx_result_t_MINRX_REG_ECTYPE,
    InvalidEscape(String) = minrx_result_t_MINRX_REG_EESCAPE,
    UnbalancedParen(String) = minrx_result_t_MINRX_REG_EPAREN,
    InvalidEndpoint(String) = minrx_result_t_MINRX_REG_ERANGE,
    AllocError(String) = minrx_result_t_MINRX_REG_ESPACE,
    InvalidDigitEscape(String) = minrx_result_t_MINRX_REG_ESUBREG,
    Unknown(String) = minrx_result_t_MINRX_REG_UNKNOWN,
}

#[repr(u32)]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum MatchError {
    AllocError(String) = minrx_result_t_MINRX_REG_ESPACE,
    Unknown(String) = minrx_result_t_MINRX_REG_UNKNOWN,
}

impl Regex {
    /// Constructs a new [`Regex`] with the default options. Look at
    /// [`RegexBuilder`] for information about configuration options.
    pub fn new(pattern: impl AsRef<[u8]>) -> Result<Self, BuildError> {
        RegexBuilder::new().build(pattern)
    }

    /// Returns the number of captures the pattern generated.
    pub fn capture_count(&self) -> usize {
        self.0.re_nsub as _
    }

    /// Returns matches for all captures, if any. Its behavior can be customized
    /// with [`Self::find_matches_with`].
    pub fn find_matches(
        &mut self,
        subject: impl AsRef<[u8]>,
    ) -> Result<Option<Box<[Option<Match>]>>, MatchError> {
        self.find_matches_with(subject, MatchOptions::new())
    }

    /// Returns if the pattern matches any substring. It is recommended you
    /// toggle [`RegexBuilder::no_substrings`] for better performance, if all
    /// you need is to check existance. Its behavior can be customized with
    /// [`Self::is_match_with`].
    pub fn is_match(&mut self, subject: impl AsRef<[u8]>) -> Result<bool, MatchError> {
        self.is_match_with(subject, MatchOptions::new())
    }

    /// Returns matches for all captures, if any. Allows for some execution
    /// options.
    pub fn find_matches_with(
        &mut self,
        haystack: impl AsRef<[u8]>,
        options: MatchOptions,
    ) -> Result<Option<Box<[Option<Match>]>>, MatchError> {
        let subject = haystack.as_ref();
        let mut buf = Vec::with_capacity(self.0.re_nsub + 1);
        let res = unsafe {
            minrx_regnexec(
                &raw mut self.0,
                subject.len(),
                subject.as_ptr(),
                buf.capacity(),
                buf.as_mut_ptr(),
                options.0 as _,
            )
        } as minrx_result_t;

        MatchError::from_raw(res, self).map(|found| {
            found.then(|| {
                unsafe { buf.set_len(buf.capacity()) };
                buf.into_iter()
                    .map(|m| {
                        Some(Match {
                            start: m.rm_so.try_into().ok()?,
                            end: m.rm_eo.try_into().ok()?,
                        })
                    })
                    .collect()
            })
        })
    }

    /// Returns if the pattern matches any substring. It is recommended you
    /// toggle [`RegexBuilder::no_substrings`] for better performance, if all
    /// you need is to check existance. Allows for some execution options.
    pub fn is_match_with(
        &mut self,
        haystack: impl AsRef<[u8]>,
        options: MatchOptions,
    ) -> Result<bool, MatchError> {
        let subject = haystack.as_ref();
        let res = unsafe {
            minrx_regnexec(
                &raw mut self.0,
                subject.len(),
                subject.as_ptr(),
                0,
                null_mut(),
                options.0 as _,
            )
        } as minrx_result_t;

        MatchError::from_raw(res, self)
    }

    /// Returns an iterator over all matches of the pattern. Its behavior can
    /// be customized with [`Self::find_matches_with`].
    pub fn find_iter<'r, 'h>(
        &'r mut self,
        haystack: &'h (impl AsRef<[u8]> + ?Sized),
    ) -> MatchIter<'r, 'h> {
        self.find_iter_with_flags(haystack, MatchOptions::new())
    }

    /// Returns an iterator over all matches of the pattern. Allows for some
    /// execution options.
    pub fn find_iter_with_flags<'r, 'h>(
        &'r mut self,
        haystack: &'h (impl AsRef<[u8]> + ?Sized),
        options: MatchOptions,
    ) -> MatchIter<'r, 'h> {
        MatchIter {
            regex: self,
            haystack: haystack.as_ref(),
            rm: minrx_regmatch_t { rm_so: 0, rm_eo: 0 },
            options,
            resuming: false,
            is_done: false,
        }
    }
}

impl RegexBuilder {
    /// Creates a new [`RegexBuilder`] that can be freely reused. This struct
    /// configures [`Regex`], and constructs it with [`RegexBuilder::build`].
    pub fn new() -> Self {
        Self(minrx_regcomp_flags_t_MINRX_REG_EXTENDED)
    }

    /// Attempts to build a new [`Regex`] with the given pattern and options.
    pub fn build(&self, pattern: impl AsRef<[u8]>) -> Result<Regex, BuildError> {
        let pattern = pattern.as_ref();
        let mut regex = MaybeUninit::uninit();
        let res = unsafe {
            minrx_regncomp(
                regex.as_mut_ptr(),
                pattern.len(),
                pattern.as_ptr(),
                self.0 as _,
            )
        } as minrx_result_t;
        BuildError::from_raw(res, &mut regex)?;

        let regex = unsafe { regex.assume_init() };
        Ok(Regex(regex))
    }

    /// Uses extended POSIX syntax. This is enabled by default, and in the
    /// current version of MinRX, disabling it is a no-op. In the meantime,
    /// this function is a placeholder.
    pub fn extended(&mut self, _enable: bool) -> &mut Self {
        self
    }

    /// Ignore case in both pattern and search.
    pub fn case_insensitive(&mut self, enable: bool) -> &mut Self {
        self.0 = mask(self.0, minrx_regcomp_flags_t_MINRX_REG_ICASE, enable);
        self
    }

    /// Swap meaning of operators `?` and `??`, `*` and `*?`, and `+` and `+?`.
    pub fn swap_greed(&mut self, enable: bool) -> &mut Self {
        self.0 = mask(self.0, minrx_regcomp_flags_t_MINRX_REG_MINIMAL, enable);
        self
    }

    /// Excludes `\n` from `.` and `[^...]`; treat as boundary for `^` and `$`.
    pub fn multi_line(&mut self, enable: bool) -> &mut Self {
        self.0 = mask(self.0, minrx_regcomp_flags_t_MINRX_REG_NEWLINE, enable);
        self
    }

    /// Output true/false results only; no [`Match`] substring results.
    pub fn no_substrings(&mut self, enable: bool) -> &mut Self {
        self.0 = mask(self.0, minrx_regcomp_flags_t_MINRX_REG_NOSUB, enable);
        self
    }

    /// `{` begins interval expression only when followed by digit.
    pub fn brace_compat(&mut self, enable: bool) -> &mut Self {
        self.0 = mask(self.0, minrx_regcomp_flags_t_MINRX_REG_BRACE_COMPAT, enable);
        self
    }

    /// Bracket expressions `[...]` allow backslash escapes.
    pub fn escapes_in_brackets(&mut self, enable: bool) -> &mut Self {
        self.0 = mask(self.0, minrx_regcomp_flags_t_MINRX_REG_BRACK_ESCAPE, enable);
        self
    }

    /// Enable BSD extensions: `\<` and `\>`.
    pub fn bsd_extensions(&mut self, enable: bool) -> &mut Self {
        self.0 = mask(
            self.0,
            minrx_regcomp_flags_t_MINRX_REG_EXTENSIONS_BSD,
            enable,
        );
        self
    }

    /// Enable GNU extensions: `\b`, `\B`, `\s`, `\S`, `\w`, `\W`.
    pub fn gnu_extensions(&mut self, enable: bool) -> &mut Self {
        self.0 = mask(
            self.0,
            minrx_regcomp_flags_t_MINRX_REG_EXTENSIONS_GNU,
            enable,
        );
        self
    }

    /// Use native encoding for 8-bit character sets.
    pub fn native_encoding(&mut self, enable: bool) -> &mut Self {
        self.0 = mask(self.0, minrx_regcomp_flags_t_MINRX_REG_NATIVE1B, enable);
        self
    }

    /// Disable POSIX 2024 minimal repetitions.
    pub fn disable_min_reps(&mut self, enable: bool) -> &mut Self {
        self.0 = mask(self.0, minrx_regcomp_flags_t_MINRX_REG_MINDISABLE, enable);
        self
    }
}

impl MatchOptions {
    /// Creates a new [`MatchOptions`] that can be freely reused. This struct
    /// configures [`Regex`] matching, and can be used with
    /// [`Regex::find_matches_with`] and [`Regex::is_match_with`]. Their
    /// non-`_with` counterparts use the default value of this.
    pub fn new() -> Self {
        Self(0)
    }

    /// Disables matching `^` at the beginning of the string.
    pub fn not_bol(&mut self, enable: bool) -> &mut Self {
        self.0 = mask(self.0, minrx_regexec_flags_t_MINRX_REG_NOTBOL, enable);
        self
    }

    /// Disables matching `$` at the end of the string.
    pub fn not_eol(&mut self, enable: bool) -> &mut Self {
        self.0 = mask(self.0, minrx_regexec_flags_t_MINRX_REG_NOTEOL, enable);
        self
    }

    /// repeated subexpressions capture their first occurrence (rather than last).
    pub fn first_subexpr(&mut self, enable: bool) -> &mut Self {
        self.0 = mask(self.0, minrx_regexec_flags_t_MINRX_REG_FIRSTSUB, enable);
        self
    }

    /// Repeated subexpressions don't clear their contained subexpressions.
    pub fn no_subexpr_reset(&mut self, enable: bool) -> &mut Self {
        self.0 = mask(self.0, minrx_regexec_flags_t_MINRX_REG_NOSUBRESET, enable);
        self
    }

    /// Resumes matching at the end of the last match. Private on purpose;
    /// cannot be safely used without extra care.
    fn resume(&mut self, enable: bool) -> &mut Self {
        self.0 = mask(self.0, minrx_regexec_flags_t_MINRX_REG_RESUME, enable);
        self
    }

    /// Disables rapid skip-ahead over impossible first bytes.
    pub fn no_first_bytes(&mut self, enable: bool) -> &mut Self {
        self.0 = mask(self.0, minrx_regexec_flags_t_MINRX_REG_NOFIRSTBYTES, enable);
        self
    }
}

impl Default for RegexBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl Default for MatchOptions {
    fn default() -> Self {
        Self::new()
    }
}

impl BuildError {
    fn from_raw(res: minrx_result_t, regex: &mut MaybeUninit<minrx_regex_t>) -> Result<(), Self> {
        let err = || regerror(res, regex.as_ptr());
        let err = match res {
            res if res == minrx_result_t_MINRX_REG_SUCCESS => return Ok(()),
            res if res == minrx_result_t_MINRX_REG_BADPAT => Err(Self::BadPattern(err())),
            res if res == minrx_result_t_MINRX_REG_BADBR => Err(Self::BadBracket(err())),
            res if res == minrx_result_t_MINRX_REG_BADRPT => Err(Self::BadRepetition(err())),
            res if res == minrx_result_t_MINRX_REG_EBRACE => Err(Self::UnbalancedBrace(err())),
            res if res == minrx_result_t_MINRX_REG_EBRACK => Err(Self::UnbalancedBracket(err())),
            res if res == minrx_result_t_MINRX_REG_ECOLLATE => Err(Self::InvalidCollate(err())),
            res if res == minrx_result_t_MINRX_REG_ECTYPE => Err(Self::InvalidClass(err())),
            res if res == minrx_result_t_MINRX_REG_EESCAPE => Err(Self::InvalidEscape(err())),
            res if res == minrx_result_t_MINRX_REG_EPAREN => Err(Self::UnbalancedParen(err())),
            res if res == minrx_result_t_MINRX_REG_ERANGE => Err(Self::InvalidEndpoint(err())),
            res if res == minrx_result_t_MINRX_REG_ESPACE => Err(Self::AllocError(err())),
            res if res == minrx_result_t_MINRX_REG_ESUBREG => Err(Self::InvalidDigitEscape(err())),
            _ => Err(Self::Unknown(err())),
        };
        drop(Regex(unsafe { regex.assume_init() }));
        err
    }
}

impl MatchError {
    fn from_raw(res: minrx_result_t, regex: &Regex) -> Result<bool, Self> {
        let err = || regerror(res, &raw const regex.0);
        match res {
            res if res == minrx_result_t_MINRX_REG_SUCCESS => Ok(true),
            res if res == minrx_result_t_MINRX_REG_NOMATCH => Ok(false),
            res if res == minrx_result_t_MINRX_REG_ESPACE => Err(Self::AllocError(err())),
            _ => Err(Self::Unknown(err())),
        }
    }
}

impl<'r, 'h> Iterator for MatchIter<'r, 'h> {
    type Item = Result<Match, MatchError>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.is_done {
            return None;
        }

        self.options.resume(self.resuming);

        let res = unsafe {
            minrx_regnexec(
                &raw mut self.regex.0,
                self.haystack.len(),
                self.haystack.as_ptr(),
                1,
                &raw mut self.rm,
                self.options.0 as _,
            )
        };

        match MatchError::from_raw(res as _, self.regex) {
            Ok(true) => {
                let so = self.rm.rm_so as usize;
                let eo = self.rm.rm_eo as usize;

                if so == eo {
                    if eo >= self.haystack.len() {
                        self.is_done = true;
                    } else {
                        // MINRX_REG_RESUME only repositions when `rm_eo > 0`,
                        // so an empty match would otherwise be found again
                        // forever. This bumps it forward one character.
                        self.rm.rm_eo = (eo + 1) as _;
                    }
                }

                self.resuming = true;
                Some(Ok(Match { start: so, end: eo }))
            }
            Ok(false) => {
                self.is_done = true;
                None
            }
            Err(e) => {
                self.is_done = true;
                Some(Err(e))
            }
        }
    }
}

#[inline]
fn mask<T>(set: T, bit: T, enable: bool) -> T
where
    T: BitOr<Output = T> + BitAnd<Output = T> + Not<Output = T>,
{
    if enable { set | bit } else { set & !bit }
}

fn regerror(res: minrx_result_t, regex: *const minrx_regex_t) -> String {
    let mut buf = Vec::with_capacity(53);
    let new_len = unsafe { minrx_regerror(res as _, regex, buf.as_mut_ptr(), buf.capacity()) };

    if new_len > buf.capacity() {
        buf.reserve_exact(new_len);
        unsafe { minrx_regerror(res as _, regex, buf.as_mut_ptr(), buf.capacity()) };
    }

    unsafe { buf.set_len(new_len.saturating_sub(1)) }; // Set len; remove null-terminator.
    String::from_utf8_lossy(&buf).to_string()
}

impl Drop for Regex {
    fn drop(&mut self) {
        unsafe { minrx_regfree(&raw mut self.0) };
    }
}

unsafe impl Send for Regex {}

impl From<Match> for std::ops::Range<usize> {
    fn from(value: Match) -> Self {
        value.start..value.end
    }
}

impl Match {
    pub fn range(&self) -> Range<usize> {
        (self.start..self.end).into()
    }
}

impl From<Match> for Range<usize> {
    fn from(value: Match) -> Self {
        value.range()
    }
}

impl Display for BuildError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BuildError::BadPattern(s)
            | BuildError::BadBracket(s)
            | BuildError::BadRepetition(s)
            | BuildError::UnbalancedBrace(s)
            | BuildError::UnbalancedBracket(s)
            | BuildError::InvalidCollate(s)
            | BuildError::InvalidClass(s)
            | BuildError::InvalidEscape(s)
            | BuildError::UnbalancedParen(s)
            | BuildError::InvalidEndpoint(s)
            | BuildError::AllocError(s)
            | BuildError::InvalidDigitEscape(s)
            | BuildError::Unknown(s) => f.write_str(s),
        }
    }
}

impl Display for MatchError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            MatchError::AllocError(s) | MatchError::Unknown(s) => f.write_str(s),
        }
    }
}

impl Error for BuildError {}
impl Error for MatchError {}