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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
//! A glob like pattern used throught Relay and its APIs.
//!
//! # Behaviour
//!
//! A pattern is similar to a glob but without support for brace expansions and without any support
//! for filesystem specific behaviour like platform dependent separators and file extension
//! matching.
//!
//! By default a [`Pattern`] does not support any separator characters.
//! For example `*` usually only matches up to the next path separator (often platform dependent),
//! in a [`Pattern`] `*` matches all characters. Optional support for a single separator character
//! is available.
//!
//! The empty glob `""` never matches.
//!
//! # Syntax
//!
//! Basic glob like syntax is supported with Unix style negations.
//!
//! * `?` matches any single character.
//! * `*` matches any number of any characters, including none.
//! * `[abc]` matches one character in the given bracket.
//! * `[!abc]` matches one character that is not in the given bracket.
//! * `[a-z]` matches one character in the given range.
//! * `[!a-z]` matches one character that is not in the given range.
//! * `{a,b}` matches any pattern within the alternation group.
//! * `\` escapes any of the above special characters and treats it as a literal.
//!
//! # Complexity
//!
//! Patterns can be limited to a maximum complexity using [`PatternBuilder::max_complexity`].
//! Complexity of a pattern is calculated by the amount of possible combinations created with
//! alternations.
//!
//! For example, the pattern `{foo,bar}` has a complexity of 2, the pattern `{foo,bar}/{*.html,*.js,*.css}`
//! has a complexity of `2 * 3`.
//!
//! For untrusted user input it is highly recommended to limit the maximum complexity.

use std::fmt;
use std::num::NonZeroUsize;

mod typed;
mod wildmatch;

pub use typed::*;

/// Pattern parsing error.
#[derive(Debug)]
pub struct Error {
    pattern: String,
    kind: ErrorKind,
}

#[derive(Debug)]
enum ErrorKind {
    /// The specified range is invalid. The `end` character is lexicographically
    /// after the `start` character.
    InvalidRange(char, char),
    /// Unbalanced character class. The pattern contains unbalanced `[`, `]` characters.
    UnbalancedCharacterClass,
    /// Character class is invalid and cannot be parsed.
    InvalidCharacterClass,
    /// Nested alternates are not valid.
    NestedAlternates,
    /// Unbalanced alternates. The pattern contains unbalanced `{`, `}` characters.
    UnbalancedAlternates,
    /// Dangling escape character.
    DanglingEscape,
    /// The pattern's complexity exceeds the maximum allowed complexity.
    Complexity {
        complexity: u64,
        max_complexity: u64,
    },
}

impl std::error::Error for Error {}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Error parsing pattern '{}': ", self.pattern)?;
        match &self.kind {
            ErrorKind::InvalidRange(start, end) => {
                write!(f, "Invalid character range `{start}-{end}`")
            }
            ErrorKind::UnbalancedCharacterClass => write!(f, "Unbalanced character class"),
            ErrorKind::InvalidCharacterClass => write!(f, "Invalid character class"),
            ErrorKind::NestedAlternates => write!(f, "Nested alternates"),
            ErrorKind::UnbalancedAlternates => write!(f, "Unbalanced alternates"),
            ErrorKind::DanglingEscape => write!(f, "Dangling escape"),
            ErrorKind::Complexity { complexity, max_complexity } =>
                write!(f, "Pattern complexity ({complexity}) exceeds maximum allowed complexity ({max_complexity})"),
        }
    }
}

/// `Pattern` represents a successfully parsed Relay pattern.
#[derive(Debug, Clone)]
pub struct Pattern {
    pattern: String,
    options: Options,
    strategy: MatchStrategy,
}

impl Pattern {
    /// Create a new [`Pattern`] from a string with the default settings.
    pub fn new(pattern: &str) -> Result<Self, Error> {
        Self::builder(pattern).build()
    }

    /// Create a new [`PatternBuilder`]. The builder can be used to adjust the
    /// pattern settings.
    pub fn builder(pattern: &str) -> PatternBuilder {
        PatternBuilder {
            pattern,
            options: Options::default(),
            max_complexity: u64::MAX,
        }
    }

    /// Returns `true` if the pattern matches the passed string.
    pub fn is_match(&self, haystack: &str) -> bool {
        self.strategy.is_match(haystack, self.options)
    }
}

impl fmt::Display for Pattern {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.pattern)
    }
}

/// A collection of [`Pattern`]s sharing the same configuration.
#[derive(Debug, Clone)]
pub struct Patterns {
    strategies: Vec<MatchStrategy>,
    options: Options,
}

impl Patterns {
    /// Creates an empty [`Patterns`] instance which never matches anything.
    ///
    /// ```
    /// # use relay_pattern::Patterns;
    /// let patterns = Patterns::empty();
    ///
    /// assert!(!patterns.is_match(""));
    /// assert!(!patterns.is_match("foobar"));
    /// ```
    pub fn empty() -> Self {
        Self {
            strategies: Vec::new(),
            options: Options::default(),
        }
    }

    /// Returns a [`PatternsBuilder`].
    pub fn builder() -> PatternsBuilder {
        PatternsBuilder {
            options: Options::default(),
        }
    }

    /// Returns `true` if any of the contained patterns matches the passed string.
    pub fn is_match(&self, haystack: &str) -> bool {
        self.strategies
            .iter()
            .any(|s| s.is_match(haystack, self.options))
    }

    /// Returns `true` if this instance contains no patterns.
    ///
    /// An empty [`Patterns`] never matches any input.
    pub fn is_empty(&self) -> bool {
        self.strategies.is_empty()
    }
}

/// A builder for a [`Pattern`].
#[derive(Debug)]
pub struct PatternBuilder<'a> {
    pattern: &'a str,
    max_complexity: u64,
    options: Options,
}

impl<'a> PatternBuilder<'a> {
    /// If enabled matches the pattern case insensitive.
    ///
    /// This is disabled by default.
    pub fn case_insensitive(&mut self, enabled: bool) -> &mut Self {
        self.options.case_insensitive = enabled;
        self
    }

    /// Sets the max complexity for this pattern.
    ///
    /// Attempting to build a pattern with a complexity higher
    /// than the maximum specified here will fail.
    ///
    /// Defaults to `u64::MAX`.
    pub fn max_complexity(&mut self, max_complexity: u64) -> &mut Self {
        self.max_complexity = max_complexity;
        self
    }

    /// Build a new [`Pattern`] from the passed pattern and configured options.
    pub fn build(&self) -> Result<Pattern, Error> {
        let mut parser = Parser::new(self.pattern, self.options);
        parser.parse().map_err(|kind| Error {
            pattern: self.pattern.to_owned(),
            kind,
        })?;

        if parser.complexity > self.max_complexity {
            return Err(Error {
                pattern: self.pattern.to_owned(),
                kind: ErrorKind::Complexity {
                    complexity: parser.complexity,
                    max_complexity: self.max_complexity,
                },
            });
        }

        let strategy =
            MatchStrategy::from_tokens(parser.tokens, self.options).map_err(|kind| Error {
                pattern: self.pattern.to_owned(),
                kind,
            })?;

        Ok(Pattern {
            pattern: self.pattern.to_owned(),
            options: self.options,
            strategy,
        })
    }
}

/// A builder for a collection of [`Patterns`].
#[derive(Debug)]
pub struct PatternsBuilder {
    options: Options,
}

impl PatternsBuilder {
    /// If enabled matches the pattern case insensitive.
    ///
    /// This is disabled by default.
    pub fn case_insensitive(&mut self, enabled: bool) -> &mut Self {
        self.options.case_insensitive = enabled;
        self
    }

    /// Returns a [`PatternsBuilderConfigured`] builder which allows adding patterns.
    pub fn patterns(&mut self) -> PatternsBuilderConfigured {
        PatternsBuilderConfigured {
            strategies: Vec::new(),
            options: self.options,
        }
    }

    /// Adds a pattern to the builder and returns the resulting [`PatternsBuilderConfigured`].
    pub fn add(&mut self, pattern: &str) -> Result<PatternsBuilderConfigured, Error> {
        let mut builder = PatternsBuilderConfigured {
            strategies: Vec::with_capacity(1),
            options: self.options,
        };
        builder.add(pattern)?;
        Ok(builder)
    }
}

/// A [`PatternsBuilder`] with all options configured.
///
/// The second step after [`PatternsBuilder`].
#[derive(Debug)]
pub struct PatternsBuilderConfigured {
    strategies: Vec<MatchStrategy>,
    options: Options,
}

impl PatternsBuilderConfigured {
    /// Adds a pattern to the builder.
    pub fn add(&mut self, pattern: &str) -> Result<&mut Self, Error> {
        let mut parser = Parser::new(pattern, self.options);
        parser.parse().map_err(|kind| Error {
            pattern: pattern.to_owned(),
            kind,
        })?;

        let strategy =
            MatchStrategy::from_tokens(parser.tokens, self.options).map_err(|kind| Error {
                pattern: pattern.to_owned(),
                kind,
            })?;

        self.strategies.push(strategy);

        Ok(self)
    }

    /// Builds a [`Patterns`] from the contained patterns.
    pub fn build(self) -> Patterns {
        Patterns {
            strategies: self.strategies,
            options: self.options,
        }
    }

    /// Returns [`Patterns`] containing all added patterns and removes them from the builder.
    ///
    /// The builder can still be used afterwards, it keeps the configuration.
    pub fn take(&mut self) -> Patterns {
        Patterns {
            strategies: std::mem::take(&mut self.strategies),
            options: self.options,
        }
    }
}

/// Options to influence [`Pattern`] matching behaviour.
#[derive(Debug, Clone, Copy, Default)]
struct Options {
    case_insensitive: bool,
}

/// Matching strategy for a [`Pattern`].
///
/// Certain patterns can be matched more efficiently while the complex
/// patterns fallback to [`wildmatch::is_match`].
#[derive(Debug, Clone)]
enum MatchStrategy {
    /// The pattern is a single literal string.
    ///
    /// The stored string is converted to lowercase for case insensitive patterns.
    ///
    /// Example pattern: `foobar`.
    Literal(Literal),
    /// The pattern only has a single wildcard in the end and can be
    /// matched with a simple prefix check.
    ///
    /// The stored string is converted to lowercase for case insensitive patterns.
    ///
    /// Example pattern: `foobar*`.
    Prefix(Literal),
    /// The pattern only has a single wildcard at the start and can be
    /// matched with a simple suffix check.
    ///
    /// The stored string is converted to lowercase for case insensitive patterns.
    ///
    /// Example pattern: `*foobar`.
    Suffix(Literal),
    /// The pattern is surrounded with wildcards and contains a literal in the middle
    /// and can be matched with a simple contains check.
    ///
    /// The stored string is converted to lowercase for case insensitive patterns.
    ///
    /// Example pattern: `*foobar*`.
    Contains(Literal),
    /// The pattern always evaluates to a static boolean.
    ///
    /// Example: `*`
    Static(bool),
    /// The pattern is complex and needs to be evaluated using [`wildmatch`].
    Wildmatch(Tokens),
    // Possible future optimizations for `Any` variations:
    // Examples: `??`. `??suffix`, `prefix??` and `?contains?`.
}

impl MatchStrategy {
    /// Create a [`MatchStrategy`] from [`Tokens`].
    fn from_tokens(mut tokens: Tokens, _options: Options) -> Result<Self, ErrorKind> {
        let s = match tokens.as_mut_slice() {
            [] => Self::Static(false),
            [Token::Wildcard] => Self::Static(true),
            [Token::Literal(literal)] => Self::Literal(std::mem::take(literal)),
            [Token::Literal(literal), Token::Wildcard] => Self::Prefix(std::mem::take(literal)),
            [Token::Wildcard, Token::Literal(literal)] => Self::Suffix(std::mem::take(literal)),
            [Token::Wildcard, Token::Literal(literal), Token::Wildcard] => {
                Self::Contains(std::mem::take(literal))
            }
            _ => Self::Wildmatch(tokens),
        };

        Ok(s)
    }

    /// Returns `true` if the pattern matches the passed string.
    pub fn is_match(&self, haystack: &str, options: Options) -> bool {
        match &self {
            MatchStrategy::Literal(literal) => match_literal(literal, haystack, options),
            MatchStrategy::Prefix(prefix) => match_prefix(prefix, haystack, options),
            MatchStrategy::Suffix(suffix) => match_suffix(suffix, haystack, options),
            MatchStrategy::Contains(contains) => match_contains(contains, haystack, options),
            MatchStrategy::Static(matches) => *matches,
            MatchStrategy::Wildmatch(tokens) => wildmatch::is_match(haystack, tokens, options),
        }
    }
}

#[inline(always)]
fn match_literal(literal: &Literal, haystack: &str, options: Options) -> bool {
    if options.case_insensitive {
        // Can't do an explicit len compare first here `literal.len() == haystack.len()`,
        // the amount of characters can change when converting case.
        let mut literal = literal.as_case_converted_str().chars();
        let mut haystack = haystack.chars().flat_map(|c| c.to_lowercase());

        loop {
            match (literal.next(), haystack.next()) {
                // Both iterators exhausted -> literal matches.
                (None, None) => break true,
                // Either iterator exhausted while the other one is not -> no match.
                (None, _) | (_, None) => break false,
                (Some(p), Some(h)) if p != h => break false,
                _ => {}
            }
        }
    } else {
        literal.as_case_converted_str() == haystack
    }
}

#[inline(always)]
fn match_prefix(prefix: &Literal, haystack: &str, options: Options) -> bool {
    if options.case_insensitive {
        let mut prefix = prefix.as_case_converted_str().chars();
        let mut haystack = haystack.chars().flat_map(|c| c.to_lowercase());

        loop {
            match (prefix.next(), haystack.next()) {
                // If the prefix is exhausted it matched.
                (None, _) => break true,
                // If the haystack is exhausted, but the pattern is not -> no match.
                (Some(_), None) => break false,
                (Some(p), Some(h)) if p != h => break false,
                _ => {}
            }
        }
    } else {
        haystack.starts_with(prefix.as_case_converted_str())
    }
}

#[inline(always)]
fn match_suffix(suffix: &Literal, haystack: &str, options: Options) -> bool {
    if options.case_insensitive {
        let mut suffix = suffix.as_case_converted_str().chars().rev();
        let mut haystack = haystack.chars().flat_map(|c| c.to_lowercase()).rev();

        loop {
            match (suffix.next(), haystack.next()) {
                // If the prefix is exhausted it matched.
                (None, _) => break true,
                // If the haystack is exhausted, but the pattern is not -> no match.
                (Some(_), None) => break false,
                (Some(s), Some(h)) if s != h => break false,
                _ => {}
            }
        }
    } else {
        haystack.ends_with(suffix.as_case_converted_str())
    }
}

#[inline(always)]
fn match_contains(contains: &Literal, haystack: &str, options: Options) -> bool {
    if options.case_insensitive {
        let haystack = haystack.to_lowercase();
        memchr::memmem::find(haystack.as_bytes(), contains.as_case_converted_bytes()).is_some()
    } else {
        memchr::memmem::find(haystack.as_bytes(), contains.as_case_converted_bytes()).is_some()
    }
}

struct Parser<'a> {
    chars: std::iter::Peekable<std::str::Chars<'a>>,
    tokens: Tokens,
    alternates: Option<Vec<Tokens>>,
    current_literal: Option<String>,
    options: Options,
    complexity: u64,
}

impl<'a> Parser<'a> {
    fn new(pattern: &'a str, options: Options) -> Self {
        Self {
            chars: pattern.chars().peekable(),
            tokens: Default::default(),
            alternates: None,
            current_literal: None,
            options,
            complexity: 0,
        }
    }

    fn parse(&mut self) -> Result<(), ErrorKind> {
        while let Some(c) = self.advance() {
            match c {
                '?' => self.push_token(Token::Any(NonZeroUsize::MIN)),
                '*' => self.push_token(Token::Wildcard),
                '[' => self.parse_class()?,
                ']' => return Err(ErrorKind::UnbalancedCharacterClass),
                '{' => self.start_alternates()?,
                '}' => self.end_alternates()?,
                '\\' => match self.advance() {
                    Some(c) => self.push_literal(c),
                    None => return Err(ErrorKind::DanglingEscape),
                },
                ',' if self.alternates.is_some() => {
                    self.finish_literal();
                    // safe to unwrap, we just checked for `some`.
                    let alternates = self.alternates.as_mut().unwrap();
                    alternates.push(Tokens::default());
                }
                c => self.push_literal(c),
            }
        }

        // Finish off the parsing with creating a token for any remaining literal buffered.
        self.finish_literal();

        Ok(())
    }

    fn start_alternates(&mut self) -> Result<(), ErrorKind> {
        if self.alternates.is_some() {
            return Err(ErrorKind::NestedAlternates);
        }
        self.finish_literal();
        self.alternates = Some(Vec::new());
        Ok(())
    }

    fn end_alternates(&mut self) -> Result<(), ErrorKind> {
        self.finish_literal();
        match self.alternates.take() {
            None => return Err(ErrorKind::UnbalancedAlternates),
            Some(alternates) => {
                if !alternates.is_empty() {
                    self.complexity = self
                        .complexity
                        .max(1)
                        .saturating_mul(alternates.len() as u64);
                    self.push_token(Token::Alternates(alternates));
                }
            }
        }

        Ok(())
    }

    fn parse_class(&mut self) -> Result<(), ErrorKind> {
        let negated = self.advance_if(|c| c == '!');

        let mut ranges = Ranges::default();

        let mut first = true;
        let mut in_range = false;
        loop {
            let Some(c) = self.advance() else {
                return Err(ErrorKind::UnbalancedCharacterClass);
            };

            match c {
                // Another opening bracket is invalid, literal `[` need to be escaped.
                '[' => return Err(ErrorKind::InvalidCharacterClass),
                ']' => break,
                '-' => {
                    if first {
                        ranges.push(Range::single('-'));
                    } else if in_range {
                        // safe to unwrap, `in_range` is only true if there is already
                        // a range pushed.
                        ranges.last_mut().unwrap().set_end('-')?;
                        in_range = false;
                    } else {
                        assert!(!ranges.is_empty());
                        in_range = true;
                    }
                }
                c => {
                    let c = match c {
                        '\\' => self.advance().ok_or(ErrorKind::DanglingEscape)?,
                        c => c,
                    };

                    if in_range {
                        // safe to unwrap, `in_range` is only true if there is already
                        // a range pushed.
                        ranges.last_mut().unwrap().set_end(c)?;
                        in_range = false;
                    } else {
                        ranges.push(Range::single(c))
                    }
                }
            }

            first = false;
        }

        if in_range {
            // A pattern which ends with a `-`.
            ranges.push(Range::single('-'));
        }

        self.push_token(Token::Class { negated, ranges });

        Ok(())
    }

    /// Pushes a new character into the currently active literal token.
    ///
    /// Starts a new literal token if there is none already.
    fn push_literal(&mut self, c: char) {
        self.current_literal.get_or_insert_with(String::new).push(c);
    }

    /// Finishes and pushes the currently in progress literal token.
    fn finish_literal(&mut self) {
        if let Some(literal) = self.current_literal.take() {
            self.push_token(Token::Literal(Literal::new(literal, self.options)));
        }
    }

    /// Pushes the passed `token` and finishes the currently in progress literal token.
    fn push_token(&mut self, token: Token) {
        self.finish_literal();
        match self.alternates.as_mut() {
            Some(alternates) => match alternates.last_mut() {
                Some(tokens) => tokens.push(token),
                None => {
                    let mut tokens = Tokens::default();
                    tokens.push(token);
                    alternates.push(tokens);
                }
            },
            None => self.tokens.push(token),
        }
    }

    fn advance(&mut self) -> Option<char> {
        self.chars.next()
    }

    fn advance_if(&mut self, matcher: impl FnOnce(char) -> bool) -> bool {
        if self.peek().is_some_and(matcher) {
            let _ = self.advance();
            true
        } else {
            false
        }
    }

    fn peek(&mut self) -> Option<char> {
        self.chars.peek().copied()
    }
}

/// A container of tokens.
///
/// Automatically folds redundant tokens.
///
/// The contained tokens are guaranteed to uphold the following invariants:
/// - A [`Token::Wildcard`] is never followed by [`Token::Wildcard`].
/// - A [`Token::Any`] is never followed by [`Token::Any`].
/// - A [`Token::Literal`] is never followed by [`Token::Literal`].
/// - A [`Token::Class`] is never empty.
#[derive(Clone, Debug, Default)]
struct Tokens(Vec<Token>);

impl Tokens {
    fn push(&mut self, mut token: Token) {
        // Normalize / clean the token.
        if let Token::Alternates(alternates) = &mut token {
            let mut contains_wildcard = false;
            alternates.retain_mut(|alternate| {
                // Empty groups can just be ignored and skipped.
                if alternate.0.is_empty() {
                    return false;
                }

                if matches!(alternate.0.as_slice(), [Token::Wildcard]) {
                    contains_wildcard = true;
                }

                true
            });

            // If any of the alternations contains a wildcard, we can fold the entire
            // alternation into a single wildcard.
            if contains_wildcard {
                token = Token::Wildcard;
            }
        }

        match (self.0.last_mut(), token) {
            // Collapse Any's.
            (Some(Token::Any(n)), Token::Any(n2)) => *n = n.saturating_add(n2.get()),
            // We can collapse multiple wildcards into a single one.
            // TODO: separator special handling (?)
            (Some(Token::Wildcard), Token::Wildcard) => {}
            // Collapse multiple literals into one.
            (Some(Token::Literal(ref mut last)), Token::Literal(s)) => last.push(&s),
            // Ignore empty class tokens.
            (_, Token::Class { negated: _, ranges }) if ranges.is_empty() => {}
            // Everything else is just another token.
            (_, token) => self.0.push(token),
        }
    }

    fn as_mut_slice(&mut self) -> &mut [Token] {
        self.0.as_mut_slice()
    }

    fn as_slice(&self) -> &[Token] {
        self.0.as_slice()
    }
}

/// Represents a token in a Relay pattern.
#[derive(Clone, Debug)]
enum Token {
    /// A literal token.
    Literal(Literal),
    /// The any token `?` and how many `?` are seen in a row.
    Any(NonZeroUsize),
    /// The wildcard token `*`.
    Wildcard,
    /// A class token `[abc]` or its negated variant `[!abc]`.
    Class { negated: bool, ranges: Ranges },
    /// A list of nested alternate tokens `{a,b}`.
    Alternates(Vec<Tokens>),
}

/// A string literal.
///
/// The contained literal is only available as a case converted string.
/// Depending on whether the pattern is case sensitive or case insensitive the literal is either
/// the original string or converted to lowercase.
#[derive(Clone, Debug, Default)]
struct Literal(String);

impl Literal {
    /// Creates a new literal from `s` and `options`.
    fn new(s: String, options: Options) -> Self {
        match options.case_insensitive {
            false => Self(s),
            true => Self(s.to_lowercase()),
        }
    }

    /// Adds a literal to this literal.
    ///
    /// This function does not validate case conversion, both literals must be for the same caseing.
    fn push(&mut self, Literal(other): &Literal) {
        self.0.push_str(other);
    }

    /// Returns a reference to the case converted string.
    fn as_case_converted_str(&self) -> &str {
        &self.0
    }

    /// Returns a reference to the case converted string as bytes.
    fn as_case_converted_bytes(&self) -> &[u8] {
        self.as_case_converted_str().as_bytes()
    }
}

/// A [`Range`] contains whatever is contained between `[` and `]` of
/// a glob pattern, except the negation.
///
/// For example the pattern `[a-z]` contains the range from `a` to `z`,
/// the pattern `[ax-zbf-h]` contains the ranges `x-z`, `f-h`, `a-a` and `b-b`.
#[derive(Clone, Debug, Default)]
enum Ranges {
    /// An empty, default range not containing any characters.
    ///
    /// The empty range matches nothing.
    #[default]
    Empty,
    /// The pattern only contains a single range.
    ///
    /// For example: `[a]` or `[a-z]`.
    Single(Range),
    /// The pattern contains more than one range.
    ///
    /// The `Empty` and `Single` states are just explicit and optimized
    /// cases for `Multiple` with a vector containing zero or just one range.
    Multiple(Vec<Range>),
}

impl Ranges {
    /// Pushes another range into the current [`Range`].
    ///
    /// Returns [`Error`] if the range starts with a lexicographically larger character than it
    /// ends with.
    fn push(&mut self, range: Range) {
        match self {
            Self::Empty => *self = Self::Single(range),
            Self::Single(single) => *self = Self::Multiple(vec![*single, range]),
            Self::Multiple(ref mut v) => v.push(range),
        }
    }

    /// Returns a mutable reference to the last range contained.
    fn last_mut(&mut self) -> Option<&mut Range> {
        match self {
            Ranges::Empty => None,
            Ranges::Single(range) => Some(range),
            Ranges::Multiple(ranges) => ranges.last_mut(),
        }
    }

    /// Returns `true` if there is no contained range.
    fn is_empty(&self) -> bool {
        match self {
            Ranges::Empty => true,
            Ranges::Single(_) => false,
            Ranges::Multiple(ranges) => {
                // While not technically wrong, the invariant should uphold.
                debug_assert!(!ranges.is_empty());
                ranges.is_empty()
            }
        }
    }

    /// Returns `true` if the character `c` is contained matches any contained range.
    #[inline(always)]
    fn contains(&self, c: char) -> bool {
        // TODO: optimize this into a `starts_with` which gets a `&str`, this can be optimized to
        // byte matches
        match self {
            Self::Empty => false,
            Self::Single(range) => range.contains(c),
            Self::Multiple(ranges) => ranges.iter().any(|range| range.contains(c)),
        }
    }
}

/// Represents a character range in a [`Token::Class`].
#[derive(Clone, Copy, Debug)]
struct Range {
    start: char,
    end: char,
}

impl Range {
    /// Create a new range which matches a single character.
    fn single(c: char) -> Self {
        Self { start: c, end: c }
    }

    /// Changes the end of the range to a new character.
    ///
    /// Returns an error if the new end character is lexicographically before
    /// the start character.
    fn set_end(&mut self, end: char) -> Result<(), ErrorKind> {
        if self.start > end {
            return Err(ErrorKind::InvalidRange(self.start, end));
        }
        self.end = end;
        Ok(())
    }

    /// Returns `true` if the character `c` is contained in the range.
    #[inline(always)]
    fn contains(&self, c: char) -> bool {
        self.start <= c && c <= self.end
    }
}

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

    macro_rules! assert_pattern {
        ($pattern:expr, $s:expr $(,$options:tt)?) => {{
            let mut pattern = Pattern::builder($pattern);
            for opt in stringify!($($options)?).chars() {
                match opt {
                    'i' => { pattern.case_insensitive(true); }
                    _ => {}
                }
            }
            let pattern = pattern.build().unwrap();
            assert!(
                pattern.is_match($s),
                "expected pattern '{}' to match '{}' - {pattern:?}",
                $pattern,
                $s
            );
        }};
        ($pattern:expr, NOT $s:expr $(,$options:tt)?) => {{
            let mut pattern = Pattern::builder($pattern);
            for opt in stringify!($($options)?).chars() {
                match opt {
                    'i' => { pattern.case_insensitive(true); }
                    _ => {}
                }
            }
            let pattern = pattern.build().unwrap();
            assert!(
                !pattern.is_match($s),
                "expected pattern '{}' to not match '{}' - {pattern:?}",
                $pattern,
                $s
            );
        }};
    }

    macro_rules! assert_strategy {
        ($pattern:expr, $expected:pat) => {{
            let pattern = Pattern::new($pattern).unwrap();
            let kind = match &pattern.strategy {
                MatchStrategy::Literal(_) => "Literal",
                MatchStrategy::Prefix(_) => "Prefix",
                MatchStrategy::Suffix(_) => "Suffix",
                MatchStrategy::Contains(_) => "Contains",
                MatchStrategy::Static(_) => "Static",
                MatchStrategy::Wildmatch(_) => "Wildmatch",
            };
            assert_eq!(
                kind,
                stringify!($expected),
                "expected pattern '{}' to have strategy '{}' - {pattern:?}",
                $pattern,
                stringify!($expected)
            );
        }};
    }

    macro_rules! assert_invalid {
        ($pattern:expr) => {{
            if let Ok(pattern) = Pattern::new($pattern) {
                assert!(
                    false,
                    "expected pattern '{}' to not compile - {pattern:?}",
                    $pattern
                );
            }
        }};
    }

    #[test]
    fn test_empty() {
        assert_pattern!("", NOT "");
        assert_pattern!("", NOT "foo");
    }

    #[test]
    fn test_literal() {
        assert_pattern!("foo", "foo");
        assert_pattern!("foo", NOT "fOo");
        assert_pattern!("foo", NOT "FOO");
        assert_pattern!(r"f\{\}o", "f{}o");
        assert_pattern!(r"f\}o", "f}o");
        assert_pattern!(r"f\{o", "f{o");
        assert_pattern!(r"f\{b,a,r\}o", "f{b,a,r}o");
        assert_pattern!(r"f\\o", r"f\o");
        assert_pattern!("fඞo", "fඞo");
    }

    #[test]
    fn test_literal_case_insensitive() {
        assert_pattern!("foo", "foo", i);
        assert_pattern!("foo", "fOo", i);
        assert_pattern!("fOo", "Foo", i);
        assert_pattern!("İ", "i\u{307}", i);
        assert_pattern!("İ", "i̇", i);
    }

    #[test]
    fn test_literal_strategy() {
        assert_strategy!("foo", Literal);
        assert_strategy!(r"f\{b,a,r\}o", Literal);
        assert_strategy!(r"f\\o", Literal);
        assert_strategy!("fඞo", Literal);
    }

    #[test]
    fn test_prefix() {
        assert_pattern!("foo*", "foo___");
        assert_pattern!("foo*", "foo");
        assert_pattern!("foo**", "foo");
        assert_pattern!("foo*?*", NOT "foo");
        assert_pattern!("foo*?*", "foo_");
        assert_pattern!("foo*?*?", "foo_____");
        assert_pattern!("foo*?*?", NOT "foo");
        assert_pattern!("foo*?*?", "foo__");
        assert_pattern!("foo*?*?", "foo_____");
        assert_pattern!("foo**", "foo___");
        assert_pattern!("foo*?*", "foo___");
        assert_pattern!("foo*?*?", "foo___");
        assert_pattern!("foo*", "fooඞ");
        assert_pattern!("ඞ*", "ඞfoo");
        assert_pattern!("foo*", NOT "___");
        assert_pattern!("foo*", NOT "fo");
        assert_pattern!("foo*", NOT "fob");
        assert_pattern!("foo*", NOT "boo");
        assert_pattern!("foo*", NOT "Foo");
        assert_pattern!("foo*", NOT "FOO___");

        // No special slash handling
        assert_pattern!("foo/bar*", "foo/bar___");
        assert_pattern!("foo*", "foo/bar___");
        assert_pattern!("foo*", NOT "/foo");
    }

    #[test]
    fn test_prefix_case_insensitive() {
        assert_pattern!("foo*", "foo___", i);
        assert_pattern!("foo*", "fOo___", i);
        assert_pattern!("foo*", "FOO___", i);
        assert_pattern!("fOo*", "FOO___", i);
        assert_pattern!("fOo*", "Foo___", i);

        assert_pattern!("İ*", "İ___", i);
        assert_pattern!("İ*", "İ", i);
        assert_pattern!("İ*", "i̇", i);
        assert_pattern!("İ*", "i\u{307}___", i);
        assert_pattern!("İ*", NOT "i____", i);
    }

    #[test]
    fn test_prefix_strategy() {
        assert_strategy!("foo*", Prefix);
        assert_strategy!("foo**", Prefix);
        assert_strategy!("foo?*", Wildmatch);
    }

    #[test]
    fn test_suffix() {
        assert_pattern!("*foo", "___foo");
        assert_pattern!("*foo", "foo");
        assert_pattern!("**foo", "foo");
        assert_pattern!("*?*foo", NOT "foo");
        assert_pattern!("*?*foo", "_foo");
        assert_pattern!("*?*foo", "_____foo");
        assert_pattern!("?*?*foo", NOT "foo");
        assert_pattern!("?*?*foo", NOT "_foo");
        assert_pattern!("?*?*foo", "__foo");
        assert_pattern!("?*?*foo", "_____foo");
        assert_pattern!("**foo", "___foo");
        assert_pattern!("*?*foo", "___foo");
        assert_pattern!("*?*?foo", "__foo");
        assert_pattern!("*foo", "ඞfoo");
        assert_pattern!("*ඞ", "fooඞ");
        assert_pattern!("*foo", NOT "bar");
        assert_pattern!("*foo", NOT "fo");
        assert_pattern!("*foo", NOT "fob");
        assert_pattern!("*foo", NOT "boo");
        assert_pattern!("*foo", NOT "Foo");
        assert_pattern!("*foo", NOT "___FOO");

        // No special slash handling
        assert_pattern!("*foo/bar", "___foo/bar");
        assert_pattern!("*bar", "___foo/bar");
        assert_pattern!("*foo", NOT "foo/");
    }

    #[test]
    fn test_suffix_case_insensitive() {
        assert_pattern!("foo*", "foo___", i);
        assert_pattern!("foo*", "fOo___", i);
        assert_pattern!("foo*", "FOO___", i);
        assert_pattern!("fOo*", "FOO___", i);
        assert_pattern!("fOo*", "Foo___", i);

        assert_pattern!("*İ", "___İ", i);
        assert_pattern!("*İ", "İ", i);
        assert_pattern!("*İ", "i̇", i);
        assert_pattern!("*İ", "___i\u{307}", i);
        assert_pattern!("*İ", NOT "___i", i);
    }

    #[test]
    fn test_suffix_strategy() {
        assert_strategy!("*foo", Suffix);
        assert_strategy!("**foo", Suffix);
        assert_strategy!("*?foo", Wildmatch);
    }

    #[test]
    fn test_contains() {
        assert_pattern!("*foo*", "foo");
        assert_pattern!("*foo*", "foo___");
        assert_pattern!("*foo*", "___foo");
        assert_pattern!("*foo*", "___foo___");
        assert_pattern!("*foo*", NOT "___fo");
        assert_pattern!("*foo*", NOT "oo___");
        assert_pattern!("*foo*", NOT "___fo___");
        assert_pattern!("*foo*", NOT "fඞo");
        assert_pattern!("*foo*", NOT "___fOo___");
        assert_pattern!("*foo*", NOT "___FOO___");

        // No special slash handling
        assert_pattern!("*foo*", "foo");
        assert_pattern!("*foo*", "foo_/_");
        assert_pattern!("*foo*", "_/_foo");
        assert_pattern!("*foo*", "_/_foo_/_");
        assert_pattern!("*f/o*", "_/_f/o_/_");
    }

    #[test]
    fn test_contains_case_insensitive() {
        assert_pattern!("*foo*", "foo", i);
        assert_pattern!("*foo*", "fOo", i);
        assert_pattern!("*fOo*", "Foo", i);
        assert_pattern!("*foo*", "___foo___", i);
        assert_pattern!("*foo*", "___fOo___", i);
        assert_pattern!("*foo*", "___FOO___", i);
        assert_pattern!("*fOo*", "___FOO___", i);
        assert_pattern!("*fOo*", "___Foo___", i);

        assert_pattern!("*İ*", "___İ___", i);
        assert_pattern!("*İ*", "İ", i);
        assert_pattern!("*İ*", "___İ", i);
        assert_pattern!("*İ*", "İ___", i);
        assert_pattern!("*İ*", "___İ___", i);
        assert_pattern!("*İ*", "i̇", i);
        assert_pattern!("*İ*", "___i̇", i);
        assert_pattern!("*İ*", "i̇___", i);
        assert_pattern!("*İ*", "___i̇___", i);
        assert_pattern!("*İ*", "___i\u{307}", i);
        assert_pattern!("*İ*", "i\u{307}___", i);
        assert_pattern!("*İ*", "___i\u{307}___", i);
        assert_pattern!("*İ*", NOT "i", i);
        assert_pattern!("*İ*", NOT "i___", i);
        assert_pattern!("*İ*", NOT "___i", i);
        assert_pattern!("*İ*", NOT "___i___", i);
    }

    #[test]
    fn test_contains_strategy() {
        assert_strategy!("*foo*", Contains);
        assert_strategy!("**foo**", Contains);
        assert_strategy!("*?foo*", Wildmatch);
        assert_strategy!("*foo?*", Wildmatch);
        assert_strategy!("*foo*?", Wildmatch);
        assert_strategy!("?*foo*", Wildmatch);
    }

    #[test]
    fn test_wildcard() {
        assert_pattern!("*", "");
        assert_pattern!("*", "a");
        assert_pattern!("*", "\n");
        assert_pattern!("*", "\n\n");
        assert_pattern!("*", "\na\n");
        assert_pattern!("*", "\na\nb\nc");
        assert_pattern!("*", "ඞfooඞfooඞ");

        // No special slash handling
        assert_pattern!("*", "/");
        assert_pattern!("*", "_/");
        assert_pattern!("*", "/_");
        assert_pattern!("*", "_/_");
        assert_pattern!("*", "/?/?/");
    }

    #[test]
    fn test_wildcard_strategy() {
        assert_strategy!("*", Static);
        assert_strategy!("{*}", Static);
        assert_strategy!("{*,}", Static);
        assert_strategy!("{foo,*}", Static);
        assert_strategy!("{foo,*}?{*,bar}", Wildmatch);
        assert_strategy!("{*,}?{*,}", Wildmatch);
    }

    #[test]
    fn test_any() {
        assert_pattern!("?", NOT "");
        assert_pattern!("?", "ඞ");
        assert_pattern!("?", "?");
        assert_pattern!("?", "\n");
        assert_pattern!("?", "_");
        assert_pattern!("?", NOT "aa");
        assert_pattern!("?", NOT "aaaaaaaaaaaaaaaaaa");
        assert_pattern!("??", "aa");
        assert_pattern!("??", NOT "aaa");
        assert_pattern!("a?a?a", "aaaaa");
        assert_pattern!("a?a?a", "abaca");
        assert_pattern!("a?a?a", NOT "ab_ca");
        assert_pattern!("a?a?a", NOT "aaAaa");
        assert_pattern!("???????????x???????????", "???????????x???????????");
        assert_pattern!("???????????x???????????", "??______???x?????_?????");
        assert_pattern!("???????????x???????????", NOT "?______???x?????_?????");
        assert_pattern!("???????????x???????????", NOT "??______???_?????_?????");
        assert_pattern!(
            "??????????????????????????????????????????????????",
            "?????????????????????????????????????????????????!"
        );
        assert_pattern!("foo?bar", "foo?bar");
        assert_pattern!("foo?bar", "foo!bar");
        assert_pattern!("a??a", "aඞඞa");

        // No special slash handling
        assert_pattern!("?", "/");
    }

    #[test]
    fn test_any_wildcard() {
        assert_pattern!("??*", NOT "");
        assert_pattern!("??*", NOT "a");
        assert_pattern!("??*", "ab");
        assert_pattern!("??*", "abc");
        assert_pattern!("??*", "abcde");

        assert_pattern!("*??", NOT "");
        assert_pattern!("*??", NOT "a");
        assert_pattern!("*??", "ab");
        assert_pattern!("*??", "abc");
        assert_pattern!("*??", "abcde");

        assert_pattern!("*??*", NOT "");
        assert_pattern!("*??*", NOT "a");
        assert_pattern!("*??*", "ab");
        assert_pattern!("*??*", "abc");
        assert_pattern!("*??*", "abcde");

        assert_pattern!("*?*?*", NOT "");
        assert_pattern!("*?*?*", NOT "a");
        assert_pattern!("*?*?*", "ab");
        assert_pattern!("*?*?*", "abc");
        assert_pattern!("*?*?*", "abcde");
    }

    #[test]
    fn test_escapes() {
        assert_pattern!(r"f\\o", r"f\o");
        assert_pattern!(r"f\*o", r"f*o");
        assert_pattern!(r"f\*o", NOT r"f\*o");
        assert_pattern!(r"f\\*o", r"f\*o");
        assert_pattern!(r"f\\*o", r"f\o");
        assert_pattern!(r"f\\*o", r"f\___o");
        assert_pattern!(r"f\\\*o", r"f\*o");
        assert_pattern!(r"f\[\]o", r"f[]o");
        assert_pattern!(r"f\[?\]o", r"f[?]o");
        assert_pattern!(r"f\[a-z\]o", r"f[a-z]o");
        assert_pattern!(r"f\[o", r"f[o");
        assert_pattern!(r"f\]o", r"f]o");
        assert_pattern!(r"\[", r"[");
    }

    #[test]
    fn test_invalid() {
        assert_invalid!(r"\");
        assert_invalid!(r"f\");
        assert_invalid!(r"*\");
        assert_invalid!("[");
        assert_invalid!("[a-z");
        assert_invalid!(r"[a-z\");
        assert_invalid!("[[]");
        assert_invalid!("[]]");
        assert_invalid!("]");
        assert_invalid!("[a-z");
        assert_invalid!("[b-a]");
        assert_invalid!("[a-A]");
    }

    #[test]
    fn test_classes() {
        assert_pattern!("[]", NOT "");
        assert_pattern!("[]", NOT "_");
        assert_pattern!("[a]", "a");
        assert_pattern!("[a]", NOT "[a]");
        assert_pattern!("[a]", NOT "b");
        assert_pattern!("[a]", NOT "A");
        assert_pattern!("[ඞ]", "ඞ");
        assert_pattern!("[ඞ]", NOT "a");
        assert_pattern!("[ඞa]", "a");
        assert_pattern!("[aඞ]", "ඞ");
        assert_pattern!("[ඞa]", NOT "b");
        assert_pattern!("[ab]", "a");
        assert_pattern!("[ab]", "b");
        assert_pattern!("[ab]", NOT "c");
        assert_pattern!("x[ab]x", "xax");
        assert_pattern!("x[ab]x", "xbx");
        assert_pattern!("x[ab]x", NOT "xBx");
        assert_pattern!("x[ab]x", NOT "xcx");
        assert_pattern!("x[ab]x", NOT "aax");
        assert_pattern!("x[ab]x", NOT "xaa");
        assert_pattern!("x[ab]x", NOT "xaax");
        assert_pattern!("x[ab]x", NOT "xxax");
        assert_pattern!("x[ab]x", NOT "xaxx");
        assert_pattern!("[a-b]", "a");
        assert_pattern!("[a-b]", "b");
        assert_pattern!("[a-b]", NOT "c");
        assert_pattern!("[a-c]", "a");
        assert_pattern!("[a-c]", "b");
        assert_pattern!("[a-c]", "c");
        assert_pattern!("[a-c]", NOT "d");
        assert_pattern!("[a-c]", NOT "1");
        assert_pattern!("[a-c]", NOT "ඞ");
        assert_pattern!("[A-z]", "a");
        assert_pattern!("[A-z]", "z");
        assert_pattern!("[A-z]", "["); // `[` is actually inbetween here in the ascii table
        assert_pattern!("[A-z]", "A");
        assert_pattern!("[A-z]", "Z");
        assert_pattern!("[A-z]", NOT "0");
        assert_pattern!("[0-9]", "0");
        assert_pattern!("[0-9]", "1");
        assert_pattern!("[0-9]", "2");
        assert_pattern!("[0-9]", "3");
        assert_pattern!("[0-9]", "4");
        assert_pattern!("[0-9]", "5");
        assert_pattern!("[0-9]", "6");
        assert_pattern!("[0-9]", "7");
        assert_pattern!("[0-9]", "8");
        assert_pattern!("[0-9]", "9");
        assert_pattern!(
            "[0-9a-bX-ZfF][0-9a-bX-ZfF][0-9a-bX-ZfF][0-9a-bX-ZfF]",
            "3bYf"
        );
        assert_pattern!(
            "[0-9a-bX-ZfF][0-9a-bX-ZfF][0-9a-bX-ZfF][0-9a-bX-ZfF]",
            NOT "3cYf"
        );
        assert_pattern!(
            "[0-9a-bX-ZfF][0-9a-bX-ZfF][0-9a-bX-ZfF][0-9a-bX-ZfF]",
            NOT "3ඞYf"
        );
        assert_pattern!("[0-9]", NOT "a9");
        assert_pattern!("[0-9]", NOT "9a");
        assert_pattern!("[0-9]", NOT "a9a");
        assert_pattern!("[0-9]", NOT "");
        assert_pattern!("[0-9!]", "!");
        assert_pattern!("[0-9][a-b]", NOT "");
        assert_pattern!("[0-9][a-b]", NOT "a");
        assert_pattern!("[0-9][a-b]", NOT "a0");
        assert_pattern!("[0-9][a-b]", "0a");
        assert_pattern!(r"a[\]a\-]b", "aab");

        // TODO: lenient: assert_pattern!("a[]-]b", NOT "aab");
        // TODO: lenient: assert_pattern!("]", "]");
        // TODO: lenient: assert_pattern!("a[]-]b", "a-]b");
        // TODO: lenient: assert_pattern!("a[]-]b", "a]b");
        // TODO: lenient: assert_pattern!("a[]]b", "a]b");

        // Escapes in character classes
        assert_pattern!(r"[\\]", r"\");
        assert_pattern!(r"[\\]", NOT "a");
        assert_pattern!(r"[\]]", "]");
        assert_pattern!(r"[\]]", NOT "a");
        assert_pattern!(r"[\[]", "[");
        assert_pattern!(r"[\[]", NOT "a");
        assert_pattern!(r"[\]]", NOT r"\");

        assert_pattern!("a[X-]b", "a-b");
        assert_pattern!("a[X-]b", "aXb");
    }

    #[test]
    fn test_classes_case_insensitive() {
        assert_pattern!("[a]", "a", i);
        assert_pattern!("[a]", "A", i);
        assert_pattern!("x[ab]x", "xAX", i);
        assert_pattern!("x[ab]x", "XBx", i);
        assert_pattern!("x[ab]x", NOT "Xcx", i);
        assert_pattern!("x[ab]x", NOT "aAx", i);
        assert_pattern!("x[ab]x", NOT "xAa", i);
        assert_pattern!("[ǧ]", "Ǧ", i);
        assert_pattern!("[Ǧ]", "ǧ", i);
    }

    #[test]
    fn test_classes_negated() {
        assert_pattern!("[!]", NOT "");
        assert_pattern!("[!a]", "b");
        assert_pattern!("[!a]", "A");
        assert_pattern!("[!a]", "B");
        assert_pattern!("[!b]", NOT "b");
        assert_pattern!("[!ab]", NOT "a");
        assert_pattern!("[!ab]", NOT "b");
        assert_pattern!("[!ab]", "c");
        assert_pattern!("x[!ab]x", "xcx");
        assert_pattern!("x[!ab]x", NOT "xax");
        assert_pattern!("x[!ab]x", NOT "xbx");
        assert_pattern!("x[!ab]x", NOT "xxcx");
        assert_pattern!("x[!ab]x", NOT "xcxx");
        assert_pattern!("x[!ab]x", NOT "xc");
        assert_pattern!("x[!ab]x", NOT "cx");
        assert_pattern!("x[!ab]x", NOT "x");
        assert_pattern!("[!a-c]", NOT "a");
        assert_pattern!("[!a-c]", NOT "b");
        assert_pattern!("[!a-c]", NOT "c");
        assert_pattern!("[!a-c]", "d");
        assert_pattern!("[!a-c]", "A");
        assert_pattern!("[!a-c]", "ඞ");
        assert_pattern!(r"[!a-c\\]", "d");
        assert_pattern!(r"[!a-c\\]", NOT r"\");
        assert_pattern!(r"[!\]]", "a");
        assert_pattern!(r"[!\]]", NOT "]");
        assert_pattern!(r"[!!]", "a");
        assert_pattern!(r"[!!]", NOT "!");
    }

    #[test]
    fn test_classes_negated_case_insensitive() {
        assert_pattern!("[!a]", "b", i);
        assert_pattern!("[!a]", "B", i);
        assert_pattern!("[!b]", NOT "b", i);
        assert_pattern!("[!b]", NOT "B", i);
        assert_pattern!("[!ab]", NOT "a", i);
        assert_pattern!("[!ab]", NOT "A", i);
        assert_pattern!("[!ab]", NOT "b", i);
        assert_pattern!("[!ab]", NOT "B", i);
        assert_pattern!("[!ab]", "c", i);
        assert_pattern!("[!ab]", "C", i);
    }

    #[test]
    fn test_alternates() {
        assert_pattern!("{}foo{}", "foo");
        assert_pattern!("foo{}bar", "foobar");
        assert_pattern!("foo{}{}bar", "foobar");
        assert_pattern!("{foo}", "foo");
        assert_pattern!("{foo}", NOT "fOo");
        assert_pattern!("{foo}", NOT "bar");
        assert_pattern!("{foo,bar}", "foo");
        assert_pattern!("{foo,bar}", "bar");
        assert_pattern!("{foo,bar}", NOT "Foo");
        assert_pattern!("{foo,bar}", NOT "fOo");
        assert_pattern!("{foo,bar}", NOT "BAR");
        assert_pattern!("{foo,bar}", NOT "fooo");
        assert_pattern!("{foo,bar}", NOT "baar");
        assert_pattern!("{[fb][oa][or]}", "foo");
        assert_pattern!("{[fb][oa][or]}", "bar");
        assert_pattern!("{[fb][oa][or],baz}", "foo");
        assert_pattern!("{[fb][oa][or],baz}", "bar");
        assert_pattern!("{[fb][oa][or],baz}", "baz");
        assert_pattern!("{baz,[fb][oa][or]}", "baz");
        assert_pattern!("{baz,[fb][oa][or]}", "foo");
        assert_pattern!("{baz,[fb][oa][or]}", "bar");
        assert_pattern!("{baz,[fb][oa][or]}", "bor");
        assert_pattern!("{baz,[fb][oa][or]}", NOT "barr");
        assert_pattern!("{baz,[fb][oa][or]}", NOT "boz");
        assert_pattern!("{baz,[fb][oa][or]}", NOT "fbar");
        assert_pattern!("{baz,[fb][oa][or]}", NOT "bAr");
        assert_pattern!("{baz,[fb][oa][or]}", NOT "Foo");
        assert_pattern!("{baz,[fb][oa][or]}", NOT "Bar");
        assert_pattern!("{baz,b[aA]r}", NOT "bAz");
        assert_pattern!("{baz,b[!aA]r}", NOT "bar");
        assert_pattern!("{baz,b[!aA]r}", "bXr");
        assert_pattern!("{[a-z],[0-9]}", "a");
        assert_pattern!("{[a-z],[0-9]}", "3");
        assert_pattern!("a{[a-z],[0-9]}a", "a3a");
        assert_pattern!("a{[a-z],[0-9]}a", "aba");
        assert_pattern!("a{[a-z],[0-9]}a", NOT "aAa");
        assert_pattern!("a{[a-z],?}a", "aXa");
        assert_pattern!(r"a{[a-z],\?}a", "a?a");
        assert_pattern!(r"a{[a-z],\?}a", NOT "aXa");
        assert_pattern!(r"a{[a-z],\?}a", NOT r"a\a");
        assert_pattern!(r"a{\[\],\{\}}a", "a[]a");
        assert_pattern!(r"a{\[\],\{\}}a", "a{}a");
        assert_pattern!(r"a{\[\],\{\}}a", NOT "a[}a");
        assert_pattern!(r"a{\[\],\{\}}a", NOT "a{]a");
        assert_pattern!(r"a{\[\],\{\}}a", NOT "a[a");
        assert_pattern!(r"a{\[\],\{\}}a", NOT "a]a");
        assert_pattern!(r"a{\[\],\{\}}a", NOT "a{a");
        assert_pattern!(r"a{\[\],\{\}}a", NOT "a}a");
        assert_pattern!("foo/{*.js,*.html}", "foo/.js");
        assert_pattern!("foo/{*.js,*.html}", "foo/.html");
        assert_pattern!("foo/{*.js,*.html}", "foo/bar.js");
        assert_pattern!("foo/{*.js,*.html}", "foo/bar.html");
        assert_pattern!("foo/{*.js,*.html}", NOT "foo/bar.png");
        assert_pattern!("foo/{*.js,*.html}", NOT "bar/bar.js");
        assert_pattern!("{foo,abc}{def,bar}", "foodef");
        assert_pattern!("{foo,abc}{def,bar}", "foobar");
        assert_pattern!("{foo,abc}{def,bar}", "abcdef");
        assert_pattern!("{foo,abc}{def,bar}", "abcbar");
        assert_pattern!("{foo,abc}{def,bar}", NOT "foofoo");
        assert_pattern!("{foo,abc}{def,bar}", NOT "fooabc");
        assert_pattern!("{foo,abc}{def,bar}", NOT "defdef");
        assert_pattern!("{foo,abc}{def,bar}", NOT "defabc");
    }

    #[test]
    fn test_alternate_strategy() {
        // Empty alternates can be simplified.
        assert_strategy!("{}foo{}", Literal);
        assert_strategy!("foo{}bar", Literal);
        assert_strategy!("foo{}{}{}bar", Literal);
    }

    #[test]
    fn test_alternates_case_insensitive() {
        assert_pattern!("{foo}", "foo", i);
        assert_pattern!("{foo}", "fOo", i);
        assert_pattern!("{foo}", NOT "bar", i);
        assert_pattern!("{foo,bar}", "foo", i);
        assert_pattern!("{foo,bar}", "bar", i);
        assert_pattern!("{foo,bar}", "Foo", i);
        assert_pattern!("{foo,bar}", "fOo", i);
        assert_pattern!("{foo,bar}", "BAR", i);
        assert_pattern!("{foo,bar}", NOT "bao", i);
        assert_pattern!("{f[o0-9]o,b[a]r}", "foo", i);
        assert_pattern!("{f[o0-9]o,b[a]r}", "fOo", i);
        assert_pattern!("{f[o0-9]o,b[a]r}", "f1o", i);
        assert_pattern!("{f[o0-9]o,b[a]r}", "foO", i);
        assert_pattern!("{f[o0-9]o,b[a]r}", "FOO", i);
        assert_pattern!("{f[o0-9]o,b[a]r}", "bar", i);
        assert_pattern!("{f[o0-9]o,b[a]r}", "bAr", i);
        assert_pattern!("{f[o0-9]o,b[a]r}", "baR", i);
        assert_pattern!("{f[o0-9]o,b[a]r}", "BAR", i);
        assert_pattern!("{f[o0-9]o,b[!a]r}", "foo", i);
        assert_pattern!("{f[o0-9]o,b[!a]r}", "bXr", i);
        assert_pattern!("{f[o0-9]o,b[!a]r}", NOT "bar", i);
        assert_pattern!("{f[o0-9]o,b[!a]r}", NOT "bAr", i);
    }

    #[test]
    fn test_complex() {
        assert_pattern!("*?", "\n");
        assert_pattern!("?*", "\n");
        assert_pattern!("*?*", "\n");
        assert_pattern!("1.18.[!0-4].*", "1.18.5.");
        assert_pattern!("1.18.[!0-4].*", "1.18.5.aBc");
        assert_pattern!("1.18.[!0-4].*", NOT "1.18.3.abc");
        assert_pattern!("!*!*.md", "!foo!.md"); // no `!` outside of character classes
        assert_pattern!("foo*foofoo*foobar", "foofoofooxfoofoobar");
        assert_pattern!("foo*fooFOO*fOobar", "fooFoofooXfoofooBAR", i);
        assert_pattern!("[0-9]*a", "0aaaaaaaaa", i);
        assert_pattern!("[0-9]*Bar[x]", "0foobarx", i);

        assert_pattern!(
            r"/api/0/organizations/\{organization_slug\}/event*",
            "/api/0/organizations/{organization_slug}/event/foobar"
        );
        assert_pattern!(
            r"/api/0/organizations/\{organization_slug\}/event*",
            NOT r"/api/0/organizations/\{organization_slug\}/event/foobar"
        );

        assert_pattern!(
            "*b??{foo,bar,baz,with}*cr{x,y,z,?}zyl[a-z]ng{suffix,pr?*ix}*it?**?uallymatches",
            "foobarwithacrazylongprefixandanditactuallymatches"
        );
        assert_pattern!(
            "*b??{foo,bar,baz,with}*cr{x,y,z,?}zyl[a-z]ng{suffix,pr?*ix}*it?**?uallymatches",
            "FOOBARWITHACRAZYLONGPREFIXANDANDITACTUALLYMATCHES",
            i
        );
    }

    /// Tests collected by [Kirk J Krauss].
    ///
    /// Kirk J Krauss: http://developforperformance.com/MatchingWildcards_AnImprovedAlgorithmForBigData.html.
    #[test]
    fn test_kirk_j_krauss() {
        // Case with first wildcard after total match.
        assert_pattern!("Hi*", "Hi");

        // Case with mismatch after '*'
        assert_pattern!("ab*d", NOT "abc");

        // Cases with repeating character sequences.
        assert_pattern!("*ccd", "abcccd");
        assert_pattern!("*issip*ss*", "mississipissippi");
        assert_pattern!("xxxx*zzy*fffff", NOT "xxxx*zzzzzzzzy*f");
        assert_pattern!("xxx*zzy*f", "xxxx*zzzzzzzzy*f");
        assert_pattern!("xxxx*zzy*fffff", NOT "xxxxzzzzzzzzyf");
        assert_pattern!("xxxx*zzy*f", "xxxxzzzzzzzzyf");
        assert_pattern!("xy*z*xyz", "xyxyxyzyxyz");
        assert_pattern!("*sip*", "mississippi");
        assert_pattern!("xy*xyz", "xyxyxyxyz");
        assert_pattern!("mi*sip*", "mississippi");
        assert_pattern!("*abac*", "ababac");
        assert_pattern!("*abac*", "ababac");
        assert_pattern!("a*zz*", "aaazz");
        assert_pattern!("*12*23", NOT "a12b12");
        assert_pattern!("a12b", NOT "a12b12");
        assert_pattern!("*12*12*", "a12b12");

        // From DDJ reader Andy Belf
        assert_pattern!("*a?b", "caaab");

        // Additional cases where the '*' char appears in the tame string.
        assert_pattern!("*", "*");
        assert_pattern!("a*b", "a*abab");
        assert_pattern!("a*", "a*r");
        assert_pattern!("a*aar", NOT "a*ar");

        // More double wildcard scenarios.
        assert_pattern!("XY*Z*XYz", "XYXYXYZYXYz");
        assert_pattern!("*SIP*", "missisSIPpi");
        assert_pattern!("*issip*PI", "mississipPI");
        assert_pattern!("xy*xyz", "xyxyxyxyz");
        assert_pattern!("mi*sip*", "miSsissippi");
        assert_pattern!("mi*Sip*", NOT "miSsissippi");
        assert_pattern!("*Abac*", "abAbac");
        assert_pattern!("*Abac*", "abAbac");
        assert_pattern!("a*zz*", "aAazz");
        assert_pattern!("*12*23", NOT "A12b12");
        assert_pattern!("*12*12*", "a12B12");
        assert_pattern!("*oWn*", "oWn");

        // Completely tame (no wildcards) cases.
        assert_pattern!("bLah", "bLah");
        assert_pattern!("bLaH", NOT "bLah");

        // Simple mixed wildcard tests suggested by Marlin Deckert.
        assert_pattern!("*?", "a");
        assert_pattern!("*?", "ab");
        assert_pattern!("*?", "abc");

        // More mixed wildcard tests including coverage for false positives.
        assert_pattern!("??", NOT "a");
        assert_pattern!("?*?", "ab");
        assert_pattern!("*?*?*", "ab");
        assert_pattern!("?**?*?", "abc");
        assert_pattern!("?**?*&?", NOT "abc");
        assert_pattern!("?b*??", "abcd");
        assert_pattern!("?a*??", NOT "abcd");
        assert_pattern!("?**?c?", "abcd");
        assert_pattern!("?**?d?", NOT "abcd");
        assert_pattern!("?*b*?*d*?", "abcde");

        // Single-character-match cases.
        assert_pattern!("bL?h", "bLah");
        assert_pattern!("bLa?", NOT "bLaaa");
        assert_pattern!("bLa?", "bLah");
        assert_pattern!("?Lah", NOT "bLaH");
        assert_pattern!("?LaH", "bLaH");

        // Many-wildcard scenarios.
        assert_pattern!(
            "a*a*a*a*a*a*aa*aaa*a*a*b",
            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab"
        );
        assert_pattern!(
            "*a*b*ba*ca*a*aa*aaa*fa*ga*b*",
            "abababababababababababababababababababaacacacacacacacadaeafagahaiajakalaaaaaaaaaaaaaaaaaffafagaagggagaaaaaaaab"
        );
        assert_pattern!(
            "*a*b*ba*ca*a*x*aaa*fa*ga*b*",
            NOT "abababababababababababababababababababaacacacacacacacadaeafagahaiajakalaaaaaaaaaaaaaaaaaffafagaagggagaaaaaaaab"
        );
        assert_pattern!(
            "*a*b*ba*ca*aaaa*fa*ga*gggg*b*",
            NOT "abababababababababababababababababababaacacacacacacacadaeafagahaiajakalaaaaaaaaaaaaaaaaaffafagaagggagaaaaaaaab"
        );
        assert_pattern!(
            "*a*b*ba*ca*aaaa*fa*ga*ggg*b*",
            "abababababababababababababababababababaacacacacacacacadaeafagahaiajakalaaaaaaaaaaaaaaaaaffafagaagggagaaaaaaaab"
        );
        assert_pattern!("*aabbaa*a*", "aaabbaabbaab");
        assert_pattern!(
            "a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*",
            "a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*"
        );
        assert_pattern!("*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*", "aaaaaaaaaaaaaaaaa");
        assert_pattern!(
            "*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*",
            NOT "aaaaaaaaaaaaaaaa"
        );
        assert_pattern!(
            "abc*abc*abc*abc*abc*abc*abc*abc*abc*abc*abc*abc*abc*abc*abc*abc*abc*",
            NOT "abc*abcd*abcde*abcdef*abcdefg*abcdefgh*abcdefghi*abcdefghij*abcdefghijk*abcdefghijkl*abcdefghijklm*abcdefghijklmn"
        );
        assert_pattern!(
            "abc*abc*abc*abc*abc*abc*abc*abc*abc*abc*abc*abc*",
            "abc*abcd*abcde*abcdef*abcdefg*abcdefgh*abcdefghi*abcdefghij*abcdefghijk*abcdefghijkl*abcdefghijklm*abcdefghijklmn"
        );
        assert_pattern!("abc*abc*abc*abc*abc", NOT "abc*abcd*abcd*abc*abcd");
        assert_pattern!(
            "abc*abc*abc*abc*abc*abc*abc*abc*abc*abc*abcd",
            "abc*abcd*abcd*abc*abcd*abcd*abc*abcd*abc*abc*abcd"
        );
        assert_pattern!("********a********b********c********", "abc");
        assert_pattern!("abc", NOT "********a********b********c********");
        assert_pattern!("********a********b********b********", NOT "abc");
        assert_pattern!("***a*b*c***", "*abc*");

        // A case-insensitive algorithm test.
        assert_pattern!("*issip*PI", "mississippi", i);

        // Tests suggested by other DDJ readers
        assert_pattern!("?", NOT "");
        assert_pattern!("*?", NOT "");
        // assert_pattern!("", ""); - Removed, relay-pattern behaves differently for empty strings.
        assert_pattern!("", NOT "a");

        // Tame tests:
        assert_pattern!("abd", NOT "abc");

        // Cases with repeating character sequences.
        assert_pattern!("abcccd", "abcccd");
        assert_pattern!("mississipissippi", "mississipissippi");
        assert_pattern!("xxxxzzzzzzzzyfffff", NOT "xxxxzzzzzzzzyf");
        assert_pattern!("xxxxzzzzzzzzyf", "xxxxzzzzzzzzyf");
        assert_pattern!("xxxxzzy.fffff", NOT "xxxxzzzzzzzzyf");
        assert_pattern!("xxxxzzzzzzzzyf", "xxxxzzzzzzzzyf");
        assert_pattern!("xyxyxyzyxyz", "xyxyxyzyxyz");
        assert_pattern!("mississippi", "mississippi");
        assert_pattern!("xyxyxyxyz", "xyxyxyxyz");
        assert_pattern!("m ississippi", "m ississippi");
        assert_pattern!("ababac?", NOT "ababac");
        assert_pattern!("ababac", NOT "dababac");
        assert_pattern!("aaazz", "aaazz");
        assert_pattern!("1212", NOT "a12b12");
        assert_pattern!("a12b", NOT "a12b12");
        assert_pattern!("a12b12", "a12b12");

        // A mix of cases
        assert_pattern!("n", "n");
        assert_pattern!("aabab", "aabab");
        assert_pattern!("ar", "ar");
        assert_pattern!("aaar", NOT "aar");
        assert_pattern!("XYXYXYZYXYz", "XYXYXYZYXYz");
        assert_pattern!("missisSIPpi", "missisSIPpi");
        assert_pattern!("mississipPI", "mississipPI");
        assert_pattern!("xyxyxyxyz", "xyxyxyxyz");
        assert_pattern!("miSsissippi", "miSsissippi");
        assert_pattern!("miSsisSippi", NOT "miSsissippi");
        assert_pattern!("abAbac", "abAbac");
        assert_pattern!("abAbac", "abAbac");
        assert_pattern!("aAazz", "aAazz");
        assert_pattern!("A12b123", NOT "A12b12");
        assert_pattern!("a12B12", "a12B12");
        assert_pattern!("oWn", "oWn");
        assert_pattern!("bLah", "bLah");
        assert_pattern!("bLaH", NOT "bLah");

        // Single '?' cases.
        assert_pattern!("a", "a");
        assert_pattern!("a?", "ab");
        assert_pattern!("ab?", "abc");

        // Mixed '?' cases.
        assert_pattern!("??", NOT "a");
        assert_pattern!("??", "ab");
        assert_pattern!("???", "abc");
        assert_pattern!("????", "abcd");
        assert_pattern!("????", NOT "abc");
        assert_pattern!("?b??", "abcd");
        assert_pattern!("?a??", NOT "abcd");
        assert_pattern!("??c?", "abcd");
        assert_pattern!("??d?", NOT "abcd");
        assert_pattern!("?b?d*?", "abcde");

        // Longer string scenarios.
        assert_pattern!(
            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab"
        );
        assert_pattern!(
            "abababababababababababababababababababaacacacacacacacadaeafagahaiajakalaaaaaaaaaaaaaaaaaffafagaagggagaaaaaaaab",
            "abababababababababababababababababababaacacacacacacacadaeafagahaiajakalaaaaaaaaaaaaaaaaaffafagaagggagaaaaaaaab"
        );
        assert_pattern!(
            "abababababababababababababababababababaacacacacacacacadaeafagahaiajaxalaaaaaaaaaaaaaaaaaffafagaagggagaaaaaaaab",
            NOT "abababababababababababababababababababaacacacacacacacadaeafagahaiajakalaaaaaaaaaaaaaaaaaffafagaagggagaaaaaaaab"
        );
        assert_pattern!(
            "abababababababababababababababababababaacacacacacacacadaeafagahaiajakalaaaaaaaaaaaaaaaaaffafagaggggagaaaaaaaab",
            NOT "abababababababababababababababababababaacacacacacacacadaeafagahaiajakalaaaaaaaaaaaaaaaaaffafagaagggagaaaaaaaab"
        );
        assert_pattern!(
            "abababababababababababababababababababaacacacacacacacadaeafagahaiajakalaaaaaaaaaaaaaaaaaffafagaagggagaaaaaaaab",
            "abababababababababababababababababababaacacacacacacacadaeafagahaiajakalaaaaaaaaaaaaaaaaaffafagaagggagaaaaaaaab"
        );
        assert_pattern!("aaabbaabbaab", "aaabbaabbaab");
        assert_pattern!(
            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
        );
        assert_pattern!("aaaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaaa");
        assert_pattern!("aaaaaaaaaaaaaaaaa", NOT "aaaaaaaaaaaaaaaa");
        assert_pattern!(
            "abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc",
            NOT "abcabcdabcdeabcdefabcdefgabcdefghabcdefghiabcdefghijabcdefghijkabcdefghijklabcdefghijklmabcdefghijklmn"
        );
        assert_pattern!(
            "abcabcdabcdeabcdefabcdefgabcdefghabcdefghiabcdefghijabcdefghijkabcdefghijklabcdefghijklmabcdefghijklmn",
            "abcabcdabcdeabcdefabcdefgabcdefghabcdefghiabcdefghijabcdefghijkabcdefghijklabcdefghijklmabcdefghijklmn"
        );
        assert_pattern!("abcabc?abcabcabc", NOT "abcabcdabcdabcabcd");
        assert_pattern!(
            "abcabc?abc?abcabc?abc?abc?bc?abc?bc?bcd",
            "abcabcdabcdabcabcdabcdabcabcdabcabcabcd"
        );
        assert_pattern!("?abc?", "?abc?");
    }

    #[test]
    fn test_builder_complexity() {
        assert!(Pattern::builder("{foo,bar}")
            .max_complexity(1)
            .build()
            .is_err());
        assert!(Pattern::builder("{foo,bar}")
            .max_complexity(2)
            .build()
            .is_ok());
        assert!(Pattern::builder("{foo,bar}/{*.html,*.js,*.css}")
            .max_complexity(5)
            .build()
            .is_err());
        assert!(Pattern::builder("{foo,bar}/{*.html,*.js,*.css}")
            .max_complexity(6)
            .build()
            .is_ok());
    }

    #[test]
    fn test_patterns() {
        let patterns = Patterns::builder()
            .add("foobaR")
            .unwrap()
            .add("a*")
            .unwrap()
            .add("*a")
            .unwrap()
            .add("[0-9]*baz")
            .unwrap()
            .take();

        assert!(patterns.is_match("foobaR"));
        assert!(patterns.is_match("abc"));
        assert!(patterns.is_match("cba"));
        assert!(patterns.is_match("3baz"));
        assert!(patterns.is_match("123456789baz"));
        assert!(!patterns.is_match("foobar"));
        assert!(!patterns.is_match("FOOBAR"));
    }

    #[test]
    fn test_patterns_case_insensitive() {
        let patterns = Patterns::builder()
            .case_insensitive(true)
            .add("fOObar")
            .unwrap()
            .add("a*")
            .unwrap()
            .add("*a")
            .unwrap()
            .add("[0-9]*baz")
            .unwrap()
            .take();

        assert!(patterns.is_match("FooBar"));
        assert!(patterns.is_match("abC"));
        assert!(patterns.is_match("cbA"));
        assert!(patterns.is_match("3BAZ"));
        assert!(patterns.is_match("123456789baz"));
        assert!(!patterns.is_match("b"));
    }

    #[test]
    fn test_patterns_take_clears_builder() {
        let mut builder = Patterns::builder().add("foo").unwrap();

        let patterns = builder.take();
        assert!(patterns.is_match("foo"));
        assert!(!patterns.is_match("bar"));

        builder.add("bar").unwrap();
        let patterns = builder.build();
        assert!(!patterns.is_match("foo"));
        assert!(patterns.is_match("bar"));
    }
}