grippo 0.2.1

Parse, match and scrub data faster and more efficiently.
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
// Project:   grippo
// File:      src/strmatch/glob.rs
// Purpose:   Glob patterns, lowered to byte operations where the glob allows
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! A glob matches the whole haystack. `X`, `*X`, `X*`, `*X*`, `X*Y` and `*`
//! lower to byte operations. Every other glob is translated to a regex and
//! run through [`StrMatcher`], so it gets the same fall-through warning and
//! counter as any regex.

use memchr::memmem::Finder;

use super::{BuildError, StrMatcher};
use crate::tier::MatcherTier;

#[derive(Debug)]
enum Kind {
    Any,
    Exact(Box<[u8]>),
    Prefix(Box<[u8]>),
    Suffix(Box<[u8]>),
    Contains(Box<Finder<'static>>),
    Affix {
        prefix: Box<[u8]>,
        suffix: Box<[u8]>,
    },
    Engine(Box<StrMatcher>),
}

/// A compiled glob.
#[derive(Debug)]
pub struct GlobMatcher {
    kind: Kind,
    tier: MatcherTier,
    pattern: String,
    reason: &'static str,
}

/// Builds a [`GlobMatcher`].
#[derive(Debug, Clone, Copy, Default)]
#[allow(
    clippy::struct_excessive_bools,
    reason = "independent switches, as glob 0.3's MatchOptions holds them"
)]
pub struct GlobBuilder {
    literal_separator: bool,
    case_insensitive: bool,
    literal_leading_dot: bool,
    backslash_literal: bool,
    either_separator: bool,
}

impl GlobBuilder {
    /// `*` and `?` don't match `/` when set. Default off.
    #[must_use]
    pub const fn literal_separator(mut self, on: bool) -> Self {
        self.literal_separator = on;
        self
    }

    /// Match ASCII letters regardless of case, and other characters as
    /// given. Default off. A case-folded glob runs on the regex translation.
    #[must_use]
    pub const fn case_insensitive(mut self, on: bool) -> Self {
        self.case_insensitive = on;
        self
    }

    /// `*`, `?` and `[...]` don't match a `.` that starts a path component,
    /// so `*` doesn't match `.git`, as glob 0.3's `require_literal_leading_dot`
    /// reads. Needs [`literal_separator`](Self::literal_separator). Default off.
    #[must_use]
    pub const fn literal_leading_dot(mut self, on: bool) -> Self {
        self.literal_leading_dot = on;
        self
    }

    /// Read `\` as a character, not an escape, as glob 0.3 does. Default off.
    #[must_use]
    pub const fn backslash_literal(mut self, on: bool) -> Self {
        self.backslash_literal = on;
        self
    }

    /// `/` and `\` are both separators and match each other, as glob 0.3
    /// reads a path on Windows. `\` is then never an escape. Default off.
    #[must_use]
    pub const fn either_separator(mut self, on: bool) -> Self {
        self.either_separator = on;
        self
    }

    /// Compile `glob`.
    ///
    /// # Errors
    ///
    /// [`BuildError::Empty`] for an empty glob, [`BuildError::Glob`] for one
    /// that doesn't parse, and any [`StrMatcher`] error for its regex.
    pub fn build(self, glob: &str) -> Result<GlobMatcher, BuildError> {
        if glob.is_empty() {
            return Err(BuildError::Empty);
        }
        let own = self.literal_leading_dot || self.backslash_literal || self.either_separator;
        let simple = !self.case_insensitive
            && !own
            && !glob.contains(['?', '[', ']', '{', '}', '\\'])
            && !glob.contains("**")
            && (!self.literal_separator || !glob.contains('*'));
        if simple && let Some((kind, reason)) = lower(glob) {
            let tier = shape_tier(&kind);
            return Ok(GlobMatcher {
                kind,
                tier,
                pattern: glob.to_owned(),
                reason,
            });
        }
        let regex = if own {
            Translate::new(glob, self)
                .run()
                .map_err(|(at, hint)| BuildError::GlobSyntax {
                    pattern: glob.to_owned(),
                    at,
                    hint,
                })?
        } else {
            globset::GlobBuilder::new(glob)
                .literal_separator(self.literal_separator)
                .build()
                .map_err(|e| BuildError::Glob {
                    pattern: glob.to_owned(),
                    source: Box::new(e),
                    hint: "check the glob syntax: `*`, `?`, `[...]`, `{a,b}`",
                })?
                .regex()
                .to_owned()
        };
        // globset compiles its regex with `.` matching a newline, a builder flag its string omits.
        let m = StrMatcher::builder()
            .ascii_case_insensitive(self.case_insensitive)
            .build(&format!("(?s){regex}"))?;
        Ok(GlobMatcher {
            tier: m.tier(),
            reason: m.reason(),
            kind: Kind::Engine(Box::new(m)),
            pattern: glob.to_owned(),
        })
    }
}

/// A glob translated to a regex with glob 0.3's readings.
struct Translate {
    chars: Vec<(usize, char)>,
    i: usize,
    out: String,
    b: GlobBuilder,
    /// The separators, written as they go inside a regex class.
    sep: &'static str,
}

/// Where reading stopped, and what to change.
type Stop = (usize, &'static str);

impl Translate {
    fn new(glob: &str, b: GlobBuilder) -> Self {
        Self {
            chars: glob.char_indices().collect(),
            i: 0,
            out: String::from("^"),
            b,
            sep: if b.either_separator { r"/\\" } else { "/" },
        }
    }

    fn run(mut self) -> Result<String, Stop> {
        if self.b.literal_leading_dot && !self.b.literal_separator {
            return Err((0, "literal_leading_dot needs literal_separator"));
        }
        self.seq(0, true)?;
        self.out.push('$');
        Ok(self.out)
    }

    fn peek(&self) -> Option<char> {
        self.chars.get(self.i).map(|&(_, c)| c)
    }

    fn at(&self) -> usize {
        match self.chars.get(self.i) {
            Some(&(at, _)) => at,
            None => self.chars.last().map_or(0, |&(at, c)| at + c.len_utf8()),
        }
    }

    const fn is_sep(&self, c: char) -> bool {
        c == '/' || (self.b.either_separator && c == '\\')
    }

    /// What a wildcard may not match: a separator under `literal_separator`,
    /// and a `.` where `start` says a component begins.
    fn excluded(&self, start: bool) -> String {
        let mut excluded = String::new();
        if self.b.literal_separator {
            excluded.push_str(self.sep);
        }
        if self.b.literal_leading_dot && start {
            excluded.push_str(r"\.");
        }
        excluded
    }

    fn one(&self, start: bool) -> String {
        let excluded = self.excluded(start);
        if excluded.is_empty() {
            ".".to_owned()
        } else {
            format!("[^{excluded}]")
        }
    }

    /// Any run of characters inside one component.
    fn run_in(&self, start: bool) -> String {
        let any = self.one(false);
        if start && self.b.literal_leading_dot {
            format!("(?:{}{any}*)?", self.one(true))
        } else {
            format!("{any}*")
        }
    }

    fn literal(&mut self, c: char) {
        self.out
            .push_str(&regex_syntax::escape(c.encode_utf8(&mut [0; 4])));
    }

    /// Reads to the end, or to the `,` or `}` that ends an alternative when
    /// `depth` is past 0. `start` is set where a path component begins.
    fn seq(&mut self, depth: usize, mut start: bool) -> Result<(), Stop> {
        while let Some(c) = self.peek() {
            match c {
                ',' | '}' if depth > 0 => return Ok(()),
                '{' => self.alternatives(depth, start)?,
                '?' => {
                    self.i += 1;
                    let one = self.one(start);
                    self.out.push_str(&one);
                }
                '*' => {
                    if self.stars(start)? {
                        continue;
                    }
                }
                '[' => self.class(start)?,
                c if self.is_sep(c) => {
                    self.i += 1;
                    let sep = format!("[{}]", self.sep);
                    self.out.push_str(&sep);
                    start = true;
                    continue;
                }
                '\\' if !self.b.backslash_literal => {
                    self.i += 1;
                    let Some(escaped) = self.peek() else {
                        return Err((self.at(), "a character after `\\`"));
                    };
                    self.i += 1;
                    self.literal(escaped);
                }
                c => {
                    self.i += 1;
                    self.literal(c);
                }
            }
            start = false;
        }
        if depth > 0 {
            return Err((self.at(), "a `}` to close `{`"));
        }
        Ok(())
    }

    fn alternatives(&mut self, depth: usize, start: bool) -> Result<(), Stop> {
        let open = self.at();
        self.i += 1;
        self.out.push_str("(?:");
        loop {
            self.seq(depth + 1, start)?;
            match self.peek() {
                Some(',') => self.out.push('|'),
                Some('}') => break,
                _ => return Err((open, "a `}` to close `{`")),
            }
            self.i += 1;
        }
        self.i += 1;
        self.out.push(')');
        Ok(())
    }

    /// A run of `*`. `**` that is a whole component spans components, and
    /// takes the separator after it. `true` when the next component starts
    /// where the run ends.
    fn stars(&mut self, start: bool) -> Result<bool, Stop> {
        let count = self.chars[self.i..]
            .iter()
            .take_while(|&&(_, c)| c == '*')
            .count();
        self.i += count;
        let next = self.peek();
        let whole = count > 1 && start && next.is_none_or(|n| self.is_sep(n));
        if !whole {
            // A `*` that matches nothing leaves the component start to the `?` or class after it.
            if start && self.b.literal_leading_dot && matches!(next, Some('?' | '[')) {
                let (any, first) = if next == Some('?') {
                    self.i += 1;
                    (self.one(false), self.one(true))
                } else {
                    let set = self.read_class()?;
                    (self.class_at(&set, false), self.class_at(&set, true))
                };
                let lead = self.one(true);
                let inner = self.one(false);
                self.out
                    .extend(["(?:", &lead, &inner, "*", &any, "|", &first, ")"]);
                return Ok(false);
            }
            let run = self.run_in(start);
            self.out.push_str(&run);
            return Ok(false);
        }
        let part = self.run_in(true);
        let sep = format!("[{}]", self.sep);
        // A `**/` that ends the glob reads as a final `**`, as glob 0.3 reads it.
        let middle = next.is_some() && self.chars.get(self.i + 1).is_some();
        self.i += usize::from(next.is_some());
        let pieces: &[&str] = if middle {
            &["(?:", &part, &sep, ")*"]
        } else {
            &["(?:", &part, "(?:", &sep, &part, ")*)?"]
        };
        self.out.extend(pieces.iter().copied());
        Ok(middle)
    }

    /// `[...]` or `[!...]`, with ranges, never matching what
    /// [`Self::excluded`] leaves out.
    fn class(&mut self, start: bool) -> Result<(), Stop> {
        let set = self.read_class()?;
        let class = self.class_at(&set, start);
        self.out.push_str(&class);
        Ok(())
    }

    /// The regex class for `set`, less what [`Self::excluded`] leaves out.
    fn class_at(&self, set: &str, start: bool) -> String {
        let excluded = self.excluded(start);
        if excluded.is_empty() {
            set.to_owned()
        } else {
            ["[", set, "&&[^", excluded.as_str(), "]]"].concat()
        }
    }

    /// Reads `[...]` or `[!...]` with its ranges, as a regex class.
    fn read_class(&mut self) -> Result<String, Stop> {
        let open = self.at();
        self.i += 1;
        let negated = self.peek() == Some('!');
        self.i += usize::from(negated);
        let mut items = String::new();
        let mut first = true;
        loop {
            let Some(c) = self.peek() else {
                return Err((open, "a `]` to close `[`"));
            };
            self.i += 1;
            if c == ']' && !first {
                break;
            }
            first = false;
            class_char(&mut items, c);
            let range_end = self.chars.get(self.i + 1).map(|&(_, n)| n);
            if self.peek() == Some('-')
                && let Some(end) = range_end.filter(|&n| n != ']')
            {
                self.i += 2;
                items.push('-');
                class_char(&mut items, end);
            }
        }
        Ok(if negated {
            format!("[^{items}]")
        } else {
            format!("[{items}]")
        })
    }
}

/// `c` as it goes inside a regex class.
fn class_char(items: &mut String, c: char) {
    if c.is_ascii_punctuation() {
        items.push('\\');
    }
    items.push(c);
}

/// The byte operation and reason for a glob made of literals and at most two
/// `*`.
fn lower(glob: &str) -> Option<(Kind, &'static str)> {
    let pieces: Vec<&[u8]> = glob.as_bytes().split(|&b| b == b'*').collect();
    let boxed = |b: &[u8]| -> Box<[u8]> { b.into() };
    Some(match pieces.as_slice() {
        [exact] => (Kind::Exact(boxed(exact)), "glob:exact"),
        [[], []] => (Kind::Any, "glob:any"),
        [[], suffix] => (Kind::Suffix(boxed(suffix)), "glob:suffix"),
        [prefix, []] => (Kind::Prefix(boxed(prefix)), "glob:prefix"),
        [prefix, suffix] => (
            Kind::Affix {
                prefix: boxed(prefix),
                suffix: boxed(suffix),
            },
            "glob:affix",
        ),
        [[], middle, []] if !middle.is_empty() => (
            Kind::Contains(Box::new(Finder::new(middle).into_owned())),
            "glob:contains",
        ),
        _ => return None,
    })
}

fn shape_tier(kind: &Kind) -> MatcherTier {
    match kind {
        Kind::Any => MatcherTier::Fixed,
        Kind::Exact(b) | Kind::Prefix(b) | Kind::Suffix(b) if b.len() == 1 => MatcherTier::Byte,
        Kind::Contains(f) if f.needle().len() == 1 => MatcherTier::Byte,
        Kind::Engine(m) => m.tier(),
        Kind::Exact(_)
        | Kind::Prefix(_)
        | Kind::Suffix(_)
        | Kind::Contains(_)
        | Kind::Affix { .. } => MatcherTier::Literal,
    }
}

impl GlobMatcher {
    /// Compile `glob` with the defaults.
    ///
    /// # Errors
    ///
    /// As [`GlobBuilder::build`].
    pub fn new(glob: &str) -> Result<Self, BuildError> {
        GlobBuilder::default().build(glob)
    }

    /// Start a builder.
    #[must_use]
    pub fn builder() -> GlobBuilder {
        GlobBuilder::default()
    }

    /// `true` when the whole haystack matches the glob.
    #[must_use]
    pub fn is_match(&self, hay: &[u8]) -> bool {
        match &self.kind {
            Kind::Any => true,
            Kind::Exact(b) => hay == &**b,
            Kind::Prefix(b) => hay.starts_with(b),
            Kind::Suffix(b) => hay.ends_with(b),
            Kind::Contains(f) => f.find(hay).is_some(),
            Kind::Affix { prefix, suffix } => {
                hay.len() >= prefix.len() + suffix.len()
                    && hay.starts_with(prefix)
                    && hay.ends_with(suffix)
            }
            Kind::Engine(m) => m.is_match(hay),
        }
    }

    /// The tier this glob runs on.
    #[must_use]
    pub const fn tier(&self) -> MatcherTier {
        self.tier
    }

    /// The glob as given.
    #[must_use]
    pub fn pattern(&self) -> &str {
        &self.pattern
    }

    /// Why the glob landed on its tier: `glob:suffix`, or the regex
    /// classifier's reason for one that runs on its translation.
    #[must_use]
    pub const fn reason(&self) -> &'static str {
        self.reason
    }

    /// What to change to reach a faster tier, empty when there is nothing to
    /// change.
    #[must_use]
    pub fn hint(&self) -> &'static str {
        match &self.kind {
            Kind::Engine(m) => m.hint(),
            _ => "",
        }
    }
}

#[cfg(test)]
mod tests {
    use proptest::prelude::*;

    use super::*;

    fn oracle(glob: &str, literal_separator: bool) -> globset::GlobMatcher {
        globset::GlobBuilder::new(glob)
            .literal_separator(literal_separator)
            .build()
            .unwrap()
            .compile_matcher()
    }

    #[test]
    fn simple_globs_lower_to_byte_shapes() {
        let rows: &[(&str, MatcherTier, &str)] = &[
            ("*", MatcherTier::Fixed, "glob:any"),
            ("a.log", MatcherTier::Literal, "glob:exact"),
            ("*.log", MatcherTier::Literal, "glob:suffix"),
            ("/var/*", MatcherTier::Literal, "glob:prefix"),
            ("*error*", MatcherTier::Literal, "glob:contains"),
            ("*x*", MatcherTier::Byte, "glob:contains"),
            ("app-*.log", MatcherTier::Literal, "glob:affix"),
        ];
        for (glob, tier, reason) in rows {
            let m = GlobMatcher::new(glob).unwrap();
            assert_eq!((m.tier(), m.reason()), (*tier, *reason), "{glob}");
        }
    }

    #[test]
    fn other_globs_run_on_their_regex_translation() {
        for glob in ["a?c", "[ab]*", "{x,y}.log", "a*b*c", "**/x"] {
            let m = GlobMatcher::new(glob).unwrap();
            assert!(
                !m.reason().starts_with("glob:"),
                "{glob} lowered: {}",
                m.reason()
            );
        }
        let sep = GlobMatcher::builder()
            .literal_separator(true)
            .build("*.log")
            .unwrap();
        assert!(!sep.reason().starts_with("glob:"));
        assert!(!sep.is_match(b"a/b.log"));
        assert!(sep.is_match(b"b.log"));
        let ci = GlobMatcher::builder()
            .case_insensitive(true)
            .build("*.LOG")
            .unwrap();
        assert!(ci.is_match(b"a.log"));
    }

    #[test]
    fn bad_globs_are_errors() {
        assert!(matches!(GlobMatcher::new(""), Err(BuildError::Empty)));
        assert!(matches!(
            GlobMatcher::new("[a"),
            Err(BuildError::Glob { .. })
        ));
    }

    #[test]
    fn glob_03_options_read_as_glob_03_does() {
        let sep = GlobMatcher::builder().literal_separator(true);
        let dot = sep.literal_leading_dot(true);
        let either = sep.either_separator(true);
        let literal = GlobMatcher::builder().backslash_literal(true);
        let rows: &[(GlobBuilder, &str, &str, bool)] = &[
            (dot, "*", ".git", false),
            (dot, "*", "git", true),
            (dot, ".*", ".git", true),
            (dot, "?git", ".git", false),
            (dot, "[.g]git", ".git", false),
            (dot, "a/*", "a/.b", false),
            (dot, "a/x*", "a/x.b", true),
            (dot, "**/b", ".a/b", false),
            (dot, "**/b", "a/c/b", true),
            (dot, "**", "a/.c", false),
            (sep, "**/b", "b", true),
            (sep, "a/**", "a/b/c", true),
            (sep, "*.log", "a/b.log", false),
            (sep, "**.log", "b.log", true),
            (sep, "[!a]", "/", false),
            (either, "a/b", r"a\b", true),
            (either, r"a\b", "a/b", true),
            (either, "*", r"a\b", false),
            (either.backslash_literal(true), "*", r"a\", false),
            (either.backslash_literal(true), r"a\b", "a/b", true),
            (literal, r"a\*", r"a\bc", true),
            (literal, r"a\*", "a*", false),
            (literal, "{x,y}.log", "y.log", true),
            (literal.case_insensitive(true), "[A-C]B", "bb", true),
            (literal.case_insensitive(true), "\u{c9}", "\u{e9}", false),
        ];
        for &(b, glob, hay, want) in rows {
            let m = b.build(glob).unwrap();
            assert_eq!(m.is_match(hay.as_bytes()), want, "{glob} on {hay}");
        }
        let bad: &[(GlobBuilder, &str)] = &[
            (literal, "[a"),
            (literal, "{a,b"),
            (GlobMatcher::builder().literal_leading_dot(true), "*"),
            (GlobMatcher::builder().either_separator(true), "a{"),
        ];
        for &(b, glob) in bad {
            assert!(
                matches!(b.build(glob), Err(BuildError::GlobSyntax { .. })),
                "{glob}"
            );
        }
    }

    fn glob_03_strategy() -> impl Strategy<Value = String> {
        prop::collection::vec(
            prop::sample::select(vec![
                "a", "B", ".", "/", "*", "?", "**/", "/**", "[a-b]", "[!a]", "[.]", "\\",
            ]),
            1..6,
        )
        .prop_map(|p| p.concat())
    }

    fn glob_03_hay_strategy() -> impl Strategy<Value = String> {
        prop::collection::vec(
            prop::sample::select(vec!["a", "b", "B", ".", "/", ".a", "\\", "\n"]),
            0..7,
        )
        .prop_map(|p| p.concat())
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(4096))]
        #[test]
        fn glob_03_options_agree_with_glob_03(
            glob in glob_03_strategy(),
            hay in glob_03_hay_strategy(),
            sep in any::<bool>(),
            dot in any::<bool>(),
            fold in any::<bool>(),
        ) {
            let Ok(theirs) = glob03::Pattern::new(&glob) else {
                return Ok(());
            };
            let options = glob03::MatchOptions {
                case_sensitive: !fold,
                require_literal_separator: sep,
                require_literal_leading_dot: sep && dot,
            };
            // glob 0.3 reads `\` as a separator too on Windows.
            let ours = GlobMatcher::builder()
                .backslash_literal(true)
                .either_separator(cfg!(windows))
                .literal_separator(sep)
                .literal_leading_dot(sep && dot)
                .case_insensitive(fold)
                .build(&glob)
                .unwrap();
            prop_assert_eq!(
                ours.is_match(hay.as_bytes()),
                theirs.matches_with(&hay, options),
                "glob {:?} on {:?}, separator {} dot {} fold {}", glob, hay, sep, dot, fold
            );
        }
    }

    fn glob_strategy() -> impl Strategy<Value = String> {
        prop::collection::vec(
            prop::sample::select(vec!["a", "b", "/", ".", "*", "ab"]),
            1..6,
        )
        .prop_map(|p| p.concat())
        .prop_filter("non-empty", |g| !g.is_empty())
    }

    fn hay_strategy() -> impl Strategy<Value = String> {
        prop::collection::vec(
            prop::sample::select(vec!["a", "b", "/", ".", "ab", "\n"]),
            0..8,
        )
        .prop_map(|p| p.concat())
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(2048))]
        #[test]
        fn every_glob_agrees_with_globset(glob in glob_strategy(), hay in hay_strategy(), sep in any::<bool>()) {
            let ours = GlobMatcher::builder().literal_separator(sep).build(&glob).unwrap();
            prop_assert_eq!(
                ours.is_match(hay.as_bytes()),
                oracle(&glob, sep).is_match(&hay),
                "glob {:?} reason {}", glob, ours.reason()
            );
        }
    }
}