ferroni 1.7.0

Oniguruma, continued in pure Rust, with a vscode-oniguruma-compatible TextMate scanner
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
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
// api.rs - Idiomatic Rust API for Ferroni.
//
// Wraps the C-ported internals (onig_new, onig_search, etc.) with
// Rust-native types: Regex, RegexBuilder, Match, Captures, FindIter.

use std::cell::RefCell;
use std::ops::Range;
use std::time::Duration;

use crate::encodings::utf8::ONIG_ENCODING_UTF8;
use crate::error::RegexError;
use crate::oniguruma::*;
use crate::regcomp::onig_new;
use crate::regexec::{
    MatchArg, OnigMatchParam, cache_msa, onig_name_to_backref_number, onig_new_match_param,
    onig_search, onig_search_bounds, onig_search_with_param, take_cached_msa,
};
use crate::regint::RegexType;
use crate::regsyntax::OnigSyntaxOniguruma;

thread_local! {
    /// One reusable capture region per thread. Taking the value out keeps
    /// nested and re-entrant searches independent; returning the larger region
    /// retains the most useful allocation when result values overlap.
    static CACHED_REGION: RefCell<Option<OnigRegion>> = const { RefCell::new(None) };
}

fn take_cached_region() -> OnigRegion {
    CACHED_REGION
        .try_with(|cached| cached.borrow_mut().take())
        .ok()
        .flatten()
        .unwrap_or_default()
}

fn cache_region(region: OnigRegion) {
    // Drop can run after this thread-local's destructor during thread
    // teardown. In that case, simply let the uncached region be freed.
    let _ = CACHED_REGION.try_with(|cached| {
        let mut cached = cached.borrow_mut();
        let region_capacity = region.beg.capacity() + region.end.capacity();
        let should_replace = match cached.as_ref() {
            Some(current) => region_capacity > current.beg.capacity() + current.end.capacity(),
            None => true,
        };
        if should_replace {
            *cached = Some(region);
        }
    });
}

fn timeout_to_millis(timeout: Duration) -> u64 {
    if timeout.is_zero() {
        return 0;
    }

    let millis = timeout.as_millis();
    let millis = millis + u128::from(!timeout.subsec_nanos().is_multiple_of(1_000_000));
    millis.clamp(1, u64::MAX as u128) as u64
}

/// Limits for a single search.
///
/// Every limit left unset keeps its process-wide setting (for example from
/// [`onig_set_time_limit`](crate::regexec::onig_set_time_limit)). A limit set
/// to zero turns that limit off for this search, as in Oniguruma.
///
/// Pass the options to the `*_with` search methods of [`Regex`], such as
/// [`Regex::find_with`]. Unlike the plain methods, they report a search that
/// stopped at a limit as an error instead of as "no match".
///
/// # Examples
///
/// ```
/// use std::time::Duration;
/// use ferroni::prelude::*;
///
/// let re = Regex::new(r"(a+)+b").unwrap();
/// let options = SearchOptions::new().timeout(Duration::from_millis(50));
///
/// assert_eq!(re.find_with("aab", options).unwrap().unwrap().as_str(), "aab");
///
/// let hostile = "a".repeat(40);
/// assert!(re.find_with(&hostile, options).is_err());
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SearchOptions {
    timeout: Option<Duration>,
    retry_limit_in_match: Option<u64>,
    retry_limit_in_search: Option<u64>,
    match_stack_limit: Option<u32>,
}

impl SearchOptions {
    /// Options that keep every process-wide limit.
    pub const fn new() -> Self {
        SearchOptions {
            timeout: None,
            retry_limit_in_match: None,
            retry_limit_in_search: None,
            match_stack_limit: None,
        }
    }

    /// Stop the search with [`RegexError::TimeLimitOver`] once `timeout` has
    /// passed. `Duration::ZERO` removes the time limit for this search.
    ///
    /// The engine reads the clock every 512 backtracks, so the search can run
    /// slightly past the deadline. Durations are rounded up to whole
    /// milliseconds.
    pub const fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Stop the search with [`RegexError::RetryLimitInMatchOver`] after `limit`
    /// backtracks at one start position. Zero removes the limit.
    pub const fn retry_limit_in_match(mut self, limit: u64) -> Self {
        self.retry_limit_in_match = Some(limit);
        self
    }

    /// Stop the search with [`RegexError::RetryLimitInSearchOver`] after `limit`
    /// backtracks in total. Zero removes the limit.
    pub const fn retry_limit_in_search(mut self, limit: u64) -> Self {
        self.retry_limit_in_search = Some(limit);
        self
    }

    /// Stop the search with [`RegexError::MatchStackLimitOver`] once the
    /// backtracking stack holds `limit` entries. Zero removes the limit.
    pub const fn match_stack_limit(mut self, limit: u32) -> Self {
        self.match_stack_limit = Some(limit);
        self
    }

    fn match_param(self) -> OnigMatchParam {
        let mut match_param = onig_new_match_param();
        if let Some(timeout) = self.timeout {
            match_param.time_limit = timeout_to_millis(timeout);
        }
        if let Some(limit) = self.retry_limit_in_match {
            match_param.retry_limit_in_match = limit;
        }
        if let Some(limit) = self.retry_limit_in_search {
            match_param.retry_limit_in_search = limit;
        }
        if let Some(limit) = self.match_stack_limit {
            match_param.match_stack_limit = limit;
        }
        match_param
    }
}

/// A compiled regular expression.
///
/// # Examples
///
/// ```
/// use ferroni::api::Regex;
///
/// let re = Regex::new(r"\d+").unwrap();
/// assert!(re.is_match("hello 42"));
///
/// let m = re.find("hello 42").unwrap();
/// assert_eq!(m.as_str(), "42");
/// assert_eq!(m.start(), 6);
/// assert_eq!(m.end(), 8);
/// ```
pub struct Regex {
    inner: RegexType,
}

impl Regex {
    /// Compile a pattern using default options (Oniguruma syntax, UTF-8, no flags).
    pub fn new(pattern: &str) -> Result<Regex, RegexError> {
        Self::new_bytes(pattern.as_bytes())
    }

    /// Compile a pattern from raw bytes using default options.
    pub fn new_bytes(pattern: &[u8]) -> Result<Regex, RegexError> {
        let inner = onig_new(
            pattern,
            ONIG_OPTION_NONE,
            &ONIG_ENCODING_UTF8,
            &OnigSyntaxOniguruma,
        )?;
        Ok(Regex { inner })
    }

    /// Create a [`RegexBuilder`] for fine-grained control over compilation.
    pub fn builder(pattern: &str) -> RegexBuilder {
        RegexBuilder::new(pattern)
    }

    /// Return the first match in `text`, or `None` if no match.
    ///
    /// A search that stops at a process-wide limit (time, retry or stack) is
    /// reported as no match. Use [`Regex::find_with`] with [`SearchOptions`] to tell
    /// the two apart.
    pub fn find<'t>(&self, text: &'t str) -> Option<Match<'t>> {
        self.find_bytes(text.as_bytes())
    }

    /// Return the first match in `text` (as bytes), or `None` if no match.
    pub fn find_bytes<'t>(&self, text: &'t [u8]) -> Option<Match<'t>> {
        // Only the bounds are returned: where they follow from the attempt
        // position and the match length, no region is needed (see
        // `find_iter_bytes`).
        if !self.inner.keep_moves_match_start
            && !self.inner.options.contains(ONIG_OPTION_FIND_LONGEST)
        {
            let mut msa = take_cached_msa(&self.inner, ONIG_OPTION_NONE, None, 0);
            let found = onig_search_bounds(&self.inner, text, 0, &mut msa);
            cache_msa(msa);
            let (start, end) = found.ok()??;
            return (end <= text.len()).then_some(Match { text, start, end });
        }
        let (result, region) = onig_search(
            &self.inner,
            text,
            text.len(),
            0,
            text.len(),
            Some(take_cached_region()),
            ONIG_OPTION_NONE,
        );
        let region = region?;
        if result < 0 {
            cache_region(region);
            return None;
        }
        if region.num_regs < 1 {
            cache_region(region);
            return None;
        }
        let m = Match::from_region(text, region.beg[0], region.end[0]);
        cache_region(region);
        m
    }

    /// Return the first match in `text` under per-search `options`.
    ///
    /// # Errors
    ///
    /// Returns the [`RegexError`] of a limit the search reached, such as
    /// [`RegexError::TimeLimitOver`], instead of treating it as "no match".
    pub fn find_with<'t>(
        &self,
        text: &'t str,
        options: SearchOptions,
    ) -> Result<Option<Match<'t>>, RegexError> {
        self.find_bytes_with(text.as_bytes(), options)
    }

    /// Return the first match in `text` (as bytes) under per-search `options`.
    ///
    /// # Errors
    ///
    /// Returns the [`RegexError`] of a limit the search reached.
    pub fn find_bytes_with<'t>(
        &self,
        text: &'t [u8],
        options: SearchOptions,
    ) -> Result<Option<Match<'t>>, RegexError> {
        let (result, region) =
            self.search_with(text, 0, text.len(), Some(take_cached_region()), options)?;
        let Some(region) = region else {
            return Ok(None);
        };
        if result < 0 || region.num_regs < 1 {
            cache_region(region);
            return Ok(None);
        }
        let m = Match::from_region(text, region.beg[0], region.end[0]);
        cache_region(region);
        Ok(m)
    }

    /// Check whether `text` matches the pattern anywhere.
    ///
    /// A search that stops at a process-wide limit (time, retry or stack) is
    /// reported as no match. Use [`Regex::is_match_with`] with [`SearchOptions`] to tell
    /// the two apart.
    pub fn is_match(&self, text: &str) -> bool {
        self.is_match_bytes(text.as_bytes())
    }

    /// Check whether `text` (as bytes) matches the pattern anywhere.
    pub fn is_match_bytes(&self, text: &[u8]) -> bool {
        let (result, _) = onig_search(
            &self.inner,
            text,
            text.len(),
            0,
            text.len(),
            None,
            ONIG_OPTION_NONE,
        );
        result >= 0
    }

    /// Check whether `text` matches under per-search `options`.
    ///
    /// # Errors
    ///
    /// Returns the [`RegexError`] of a limit the search reached.
    pub fn is_match_with(&self, text: &str, options: SearchOptions) -> Result<bool, RegexError> {
        self.is_match_bytes_with(text.as_bytes(), options)
    }

    /// Check whether `text` (as bytes) matches under per-search `options`.
    ///
    /// # Errors
    ///
    /// Returns the [`RegexError`] of a limit the search reached.
    pub fn is_match_bytes_with(
        &self,
        text: &[u8],
        options: SearchOptions,
    ) -> Result<bool, RegexError> {
        let (result, _) = self.search_with(text, 0, text.len(), None, options)?;
        Ok(result >= 0)
    }

    /// Return the first match with all capture groups, or `None`.
    ///
    /// A search that stops at a process-wide limit (time, retry or stack) is
    /// reported as no match. Use [`Regex::captures_with`] with [`SearchOptions`] to tell
    /// the two apart.
    pub fn captures<'t>(&'t self, text: &'t str) -> Option<Captures<'t>> {
        self.captures_bytes(text.as_bytes())
    }

    /// Return the first match with all capture groups (bytes), or `None`.
    pub fn captures_bytes<'t>(&'t self, text: &'t [u8]) -> Option<Captures<'t>> {
        let (result, region) = onig_search(
            &self.inner,
            text,
            text.len(),
            0,
            text.len(),
            Some(take_cached_region()),
            ONIG_OPTION_NONE,
        );
        let region = region?;
        if result < 0 {
            cache_region(region);
            return None;
        }
        Some(Captures {
            text,
            region,
            regex: self,
        })
    }

    /// Return the first match with all capture groups under per-search
    /// `options`.
    ///
    /// # Errors
    ///
    /// Returns the [`RegexError`] of a limit the search reached.
    pub fn captures_with<'t>(
        &'t self,
        text: &'t str,
        options: SearchOptions,
    ) -> Result<Option<Captures<'t>>, RegexError> {
        self.captures_bytes_with(text.as_bytes(), options)
    }

    /// Return the first match with all capture groups (bytes) under
    /// per-search `options`.
    ///
    /// # Errors
    ///
    /// Returns the [`RegexError`] of a limit the search reached.
    pub fn captures_bytes_with<'t>(
        &'t self,
        text: &'t [u8],
        options: SearchOptions,
    ) -> Result<Option<Captures<'t>>, RegexError> {
        let (result, region) =
            self.search_with(text, 0, text.len(), Some(take_cached_region()), options)?;
        let Some(region) = region else {
            return Ok(None);
        };
        if result < 0 {
            cache_region(region);
            return Ok(None);
        }
        Ok(Some(Captures {
            text,
            region,
            regex: self,
        }))
    }

    /// Iterate over all non-overlapping matches in `text`.
    ///
    /// Iteration ends early when a search stops at a process-wide limit. Use
    /// [`Regex::find_iter_with`] with [`SearchOptions`] to see that error.
    pub fn find_iter<'r, 't>(&'r self, text: &'t str) -> FindIter<'r, 't> {
        self.find_iter_bytes(text.as_bytes())
    }

    /// Iterate over all non-overlapping matches in `text` (as bytes).
    pub fn find_iter_bytes<'r, 't>(&'r self, text: &'t [u8]) -> FindIter<'r, 't> {
        // An iterator yields match bounds only. Where they follow from the
        // attempt position and the match length, it searches without a
        // region, reusing one MatchArg for all its searches.
        let bounds_only = !self.inner.keep_moves_match_start
            && !self.inner.options.contains(ONIG_OPTION_FIND_LONGEST);
        FindIter {
            regex: self,
            text,
            last_end: 0,
            last_was_empty: false,
            region: if bounds_only {
                OnigRegion::new()
            } else {
                take_cached_region()
            },
            msa: bounds_only.then(|| take_cached_msa(&self.inner, ONIG_OPTION_NONE, None, 0)),
        }
    }

    /// Iterate over all non-overlapping matches in `text` under per-search
    /// `options`.
    ///
    /// The options apply to each search the iterator runs. A search that
    /// reaches a limit yields its error once and ends the iteration.
    pub fn find_iter_with<'r, 't>(
        &'r self,
        text: &'t str,
        options: SearchOptions,
    ) -> TryFindIter<'r, 't> {
        self.find_iter_bytes_with(text.as_bytes(), options)
    }

    /// Iterate over all non-overlapping matches in `text` (as bytes) under
    /// per-search `options`.
    pub fn find_iter_bytes_with<'r, 't>(
        &'r self,
        text: &'t [u8],
        options: SearchOptions,
    ) -> TryFindIter<'r, 't> {
        TryFindIter {
            regex: self,
            text,
            last_end: 0,
            last_was_empty: false,
            region: take_cached_region(),
            options,
            finished: false,
        }
    }

    fn search_with(
        &self,
        text: &[u8],
        start: usize,
        range: usize,
        region: Option<OnigRegion>,
        options: SearchOptions,
    ) -> Result<(i32, Option<OnigRegion>), RegexError> {
        let (result, region) = onig_search_with_param(
            &self.inner,
            text,
            text.len(),
            start,
            range,
            region,
            ONIG_OPTION_NONE,
            &options.match_param(),
        );
        if result < 0 && result != ONIG_MISMATCH {
            if let Some(region) = region {
                cache_region(region);
            }
            return Err(RegexError::from(result));
        }
        Ok((result, region))
    }

    /// Return the number of capture groups in the pattern (excluding group 0).
    pub fn captures_len(&self) -> usize {
        self.inner.num_mem as usize
    }

    /// Findings of the compile-time check for patterns that can backtrack
    /// catastrophically, such as `(a+)+` or `(a|aa)*`.
    ///
    /// The list is empty for patterns the check does not flag. It is a
    /// heuristic: it can miss risky patterns and flag harmless ones, and it
    /// never changes how the pattern matches. Use
    /// [`RegexBuilder::reject_backtracking_risks`] to turn findings into a
    /// compile error.
    ///
    /// ```
    /// use ferroni::api::Regex;
    ///
    /// assert!(Regex::new(r"(a+)+$").unwrap().backtracking_warnings().len() == 1);
    /// assert!(Regex::new(r"(a+b)+$").unwrap().backtracking_warnings().is_empty());
    /// ```
    pub fn backtracking_warnings(&self) -> &[crate::backtrack_lint::BacktrackWarning] {
        &self.inner.backtrack_warnings
    }

    /// Access the underlying `RegexType` for advanced / C-style usage.
    pub fn as_raw(&self) -> &RegexType {
        &self.inner
    }
}

impl std::fmt::Debug for Regex {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Regex").finish_non_exhaustive()
    }
}

// === RegexBuilder ===

/// Builder for compiling a [`Regex`] with custom options.
///
/// # Examples
///
/// ```
/// use ferroni::api::Regex;
///
/// let re = Regex::builder(r"hello world")
///     .case_insensitive(true)
///     .build()
///     .unwrap();
/// assert!(re.is_match("Hello World"));
/// ```
pub struct RegexBuilder {
    pattern: Vec<u8>,
    options: OnigOptionType,
    syntax: &'static OnigSyntaxType,
    reject_backtracking_risks: bool,
}

impl RegexBuilder {
    /// Create a new builder for the given pattern.
    pub fn new(pattern: &str) -> Self {
        RegexBuilder {
            pattern: pattern.as_bytes().to_vec(),
            options: ONIG_OPTION_NONE,
            syntax: &OnigSyntaxOniguruma,
            reject_backtracking_risks: false,
        }
    }

    /// Enable or disable case-insensitive matching.
    pub fn case_insensitive(mut self, yes: bool) -> Self {
        if yes {
            self.options |= ONIG_OPTION_IGNORECASE;
        } else {
            self.options &= !ONIG_OPTION_IGNORECASE;
        }
        self
    }

    /// Enable or disable multiline mode (`.` matches `\n`).
    pub fn dot_matches_newline(mut self, yes: bool) -> Self {
        if yes {
            self.options |= ONIG_OPTION_MULTILINE;
        } else {
            self.options &= !ONIG_OPTION_MULTILINE;
        }
        self
    }

    /// Enable or disable `^`/`$` matching at every line boundary.
    ///
    /// With the default Oniguruma syntax, this behavior is enabled by default.
    /// When disabled, anchors match only at input boundaries. Calling this
    /// method overrides the selected syntax's default anchor behavior.
    pub fn multi_line_anchors(mut self, yes: bool) -> Self {
        if yes {
            self.options |= ONIG_OPTION_NEGATE_SINGLELINE;
            self.options &= !ONIG_OPTION_SINGLELINE;
        } else {
            self.options &= !ONIG_OPTION_NEGATE_SINGLELINE;
            self.options |= ONIG_OPTION_SINGLELINE;
        }
        self
    }

    /// Enable or disable extended mode (whitespace and `#` comments ignored).
    pub fn extended(mut self, yes: bool) -> Self {
        if yes {
            self.options |= ONIG_OPTION_EXTEND;
        } else {
            self.options &= !ONIG_OPTION_EXTEND;
        }
        self
    }

    /// Set a raw option flag. See `ONIG_OPTION_*` constants.
    pub fn option(mut self, flag: OnigOptionType) -> Self {
        self.options |= flag;
        self
    }

    /// Select the syntax definition to use (default: Oniguruma).
    ///
    /// Pass one of the `OnigSyntax*` statics from [`crate::regsyntax`].
    pub fn syntax(mut self, syntax: &'static OnigSyntaxType) -> Self {
        self.syntax = syntax;
        self
    }

    /// Fail to compile a pattern that the backtracking check flags.
    ///
    /// By default such a pattern compiles and the findings are available
    /// from [`Regex::backtracking_warnings`]. With this set, `build` returns
    /// `ONIGERR_VERY_INEFFICIENT_PATTERN` instead. The check is a heuristic
    /// and may flag harmless patterns; leave this off to keep them.
    ///
    /// ```
    /// use ferroni::api::Regex;
    ///
    /// assert!(Regex::builder(r"(a+)+$").reject_backtracking_risks(true).build().is_err());
    /// assert!(Regex::builder(r"(a+)+$").build().is_ok());
    /// ```
    pub fn reject_backtracking_risks(mut self, yes: bool) -> Self {
        self.reject_backtracking_risks = yes;
        self
    }

    /// Compile the pattern into a [`Regex`].
    pub fn build(self) -> Result<Regex, RegexError> {
        let inner = onig_new(
            &self.pattern,
            self.options,
            &ONIG_ENCODING_UTF8,
            self.syntax,
        )?;
        if self.reject_backtracking_risks && !inner.backtrack_warnings.is_empty() {
            return Err(ONIGERR_VERY_INEFFICIENT_PATTERN.into());
        }
        Ok(Regex { inner })
    }
}

// === Match ===

/// A single match result referencing the original text.
#[derive(Debug, Clone, Copy)]
pub struct Match<'t> {
    text: &'t [u8],
    start: usize,
    end: usize,
}

impl<'t> Match<'t> {
    /// Build a match from one region entry, or `None` if the entry is not a
    /// range of `text`: unset (negative), past the end, or with start > end.
    /// Oniguruma can report start > end for a capture whose group started
    /// again but failed before closing; every `Match` upholds
    /// `start <= end <= text.len()`, so its accessors never panic on slicing.
    fn from_region(text: &'t [u8], beg: i32, end: i32) -> Option<Self> {
        let start = usize::try_from(beg).ok()?;
        let end = usize::try_from(end).ok()?;
        (start <= end && end <= text.len()).then_some(Match { text, start, end })
    }

    /// Byte offset of the start of the match.
    pub fn start(&self) -> usize {
        self.start
    }

    /// Byte offset of the end of the match (exclusive).
    pub fn end(&self) -> usize {
        self.end
    }

    /// Byte range of the match.
    pub fn range(&self) -> Range<usize> {
        self.start..self.end
    }

    /// The matched text as a byte slice.
    pub fn as_bytes(&self) -> &'t [u8] {
        &self.text[self.start..self.end]
    }

    /// The matched text as a `&str`.
    ///
    /// # Panics
    ///
    /// Panics if the matched bytes are not valid UTF-8.
    pub fn as_str(&self) -> &'t str {
        std::str::from_utf8(self.as_bytes()).expect("match is not valid UTF-8")
    }

    /// Returns the length of the match in bytes.
    pub fn len(&self) -> usize {
        self.end - self.start
    }

    /// Returns `true` if the match is empty (zero-length).
    pub fn is_empty(&self) -> bool {
        self.start == self.end
    }
}

// === Captures ===

/// All capture groups from a single match.
///
/// Group 0 is the entire match. Groups 1..N correspond to `(...)` in the pattern.
pub struct Captures<'t> {
    text: &'t [u8],
    region: OnigRegion,
    regex: &'t Regex,
}

impl<'t> Captures<'t> {
    /// Get capture group `i`, or `None` if the group did not participate.
    ///
    /// Group 0 is the entire match.
    ///
    /// Like Oniguruma, the engine can leave a capture with its start after
    /// its end: a group that matched once, then started again and failed
    /// before closing, keeps the new start and the old end (for example
    /// group 1 of `((?=(a|ab))a?){2}` against `"a"` is `1..0`). Such a
    /// capture is not a range of the text and is reported as not
    /// participating (`None`), here and in [`Captures::iter`] and
    /// [`Captures::name`]. The raw values stay available through the
    /// low-level [`OnigRegion`].
    pub fn get(&self, i: usize) -> Option<Match<'t>> {
        if i >= self.region.num_regs as usize {
            return None;
        }
        Match::from_region(self.text, self.region.beg[i], self.region.end[i])
    }

    /// Get the last capture group with the given name that participated, or `None`.
    pub fn name(&self, name: &str) -> Option<Match<'t>> {
        let num =
            onig_name_to_backref_number(&self.regex.inner, name.as_bytes(), Some(&self.region))
                .ok()?;
        self.get(num as usize)
    }

    /// Number of capture groups (including group 0).
    pub fn len(&self) -> usize {
        self.region.num_regs as usize
    }

    /// Returns `true` if there are no capture groups (should never happen for a valid match).
    pub fn is_empty(&self) -> bool {
        self.region.num_regs == 0
    }

    /// Iterate over all capture groups.
    pub fn iter(&self) -> CapturesIter<'_, 't> {
        CapturesIter {
            captures: self,
            index: 0,
        }
    }
}

impl std::fmt::Debug for Captures<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut list = f.debug_list();
        for i in 0..self.len() {
            list.entry(&self.get(i));
        }
        list.finish()
    }
}

impl Drop for Captures<'_> {
    fn drop(&mut self) {
        cache_region(std::mem::take(&mut self.region));
    }
}

// === CapturesIter ===

/// Iterator over capture groups in a [`Captures`].
pub struct CapturesIter<'c, 't> {
    captures: &'c Captures<'t>,
    index: usize,
}

impl<'c, 't> Iterator for CapturesIter<'c, 't> {
    type Item = Option<Match<'t>>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.index >= self.captures.len() {
            return None;
        }
        let m = self.captures.get(self.index);
        self.index += 1;
        Some(m)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.captures.len() - self.index;
        (remaining, Some(remaining))
    }
}

impl ExactSizeIterator for CapturesIter<'_, '_> {}

// === FindIter ===

/// Iterator over all non-overlapping matches in a text.
pub struct FindIter<'r, 't> {
    regex: &'r Regex,
    text: &'t [u8],
    last_end: usize,
    last_was_empty: bool,
    region: OnigRegion,
    /// Set when the searches need no region (`onig_search_bounds`).
    msa: Option<Box<MatchArg>>,
}

impl<'r, 't> Iterator for FindIter<'r, 't> {
    type Item = Match<'t>;

    fn next(&mut self) -> Option<Match<'t>> {
        if self.last_end > self.text.len() {
            return None;
        }

        let m = if let Some(msa) = self.msa.as_deref_mut() {
            let (start, end) =
                onig_search_bounds(&self.regex.inner, self.text, self.last_end, msa).ok()??;
            (end <= self.text.len()).then_some(Match {
                text: self.text,
                start,
                end,
            })?
        } else {
            let (result, region) = onig_search(
                &self.regex.inner,
                self.text,
                self.text.len(),
                self.last_end,
                self.text.len(),
                Some(std::mem::take(&mut self.region)),
                ONIG_OPTION_NONE,
            );
            self.region = region?;

            if result < 0 {
                return None;
            }
            if self.region.num_regs < 1 {
                return None;
            }

            Match::from_region(self.text, self.region.beg[0], self.region.end[0])?
        };
        let (start, end) = (m.start, m.end);

        // Handle empty matches: advance by one byte to avoid infinite loop.
        if start == end {
            if self.last_was_empty {
                if self.last_end >= self.text.len() {
                    return None;
                }
                // Skip one character to avoid infinite loop on empty match
                self.last_end += self
                    .regex
                    .inner
                    .enc
                    .mbc_enc_len(&self.text[self.last_end..]);
                self.last_was_empty = false;
                return self.next();
            }
            self.last_was_empty = true;
        } else {
            self.last_was_empty = false;
        }

        self.last_end = end;

        Some(m)
    }
}

impl Drop for FindIter<'_, '_> {
    fn drop(&mut self) {
        match self.msa.take() {
            Some(msa) => cache_msa(msa),
            None => cache_region(std::mem::take(&mut self.region)),
        }
    }
}

/// Iterator over matches that applies [`SearchOptions`] to each search.
///
/// Created by [`Regex::find_iter_with`]. A search that reaches a limit is
/// yielded once as `Err` and ends the iterator.
pub struct TryFindIter<'r, 't> {
    regex: &'r Regex,
    text: &'t [u8],
    last_end: usize,
    last_was_empty: bool,
    region: OnigRegion,
    options: SearchOptions,
    finished: bool,
}

impl<'r, 't> Iterator for TryFindIter<'r, 't> {
    type Item = Result<Match<'t>, RegexError>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.finished || self.last_end > self.text.len() {
            self.finished = true;
            return None;
        }

        let search = self.regex.search_with(
            self.text,
            self.last_end,
            self.text.len(),
            Some(std::mem::take(&mut self.region)),
            self.options,
        );
        let (result, region) = match search {
            Ok(result) => result,
            Err(error) => {
                self.finished = true;
                return Some(Err(error));
            }
        };
        let Some(region) = region else {
            self.finished = true;
            return None;
        };
        self.region = region;

        if result < 0 {
            self.finished = true;
            return None;
        }
        if self.region.num_regs < 1 {
            self.finished = true;
            return None;
        }

        let Some(m) = Match::from_region(self.text, self.region.beg[0], self.region.end[0]) else {
            self.finished = true;
            return None;
        };
        let (start, end) = (m.start, m.end);

        if start == end {
            if self.last_was_empty {
                if self.last_end >= self.text.len() {
                    self.finished = true;
                    return None;
                }
                self.last_end += self
                    .regex
                    .inner
                    .enc
                    .mbc_enc_len(&self.text[self.last_end..]);
                self.last_was_empty = false;
                return self.next();
            }
            self.last_was_empty = true;
        } else {
            self.last_was_empty = false;
        }

        self.last_end = end;
        Some(Ok(m))
    }
}

impl std::iter::FusedIterator for TryFindIter<'_, '_> {}

impl Drop for TryFindIter<'_, '_> {
    fn drop(&mut self) {
        cache_region(std::mem::take(&mut self.region));
    }
}

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

    fn assert_send_sync<T: Send + Sync>() {}

    fn clear_cached_region() {
        CACHED_REGION.with(|cached| *cached.borrow_mut() = None);
    }

    fn cached_region_buffer() -> Option<(*const i32, usize)> {
        CACHED_REGION.with(|cached| {
            cached
                .borrow()
                .as_ref()
                .map(|region| (region.beg.as_ptr(), region.beg.capacity()))
        })
    }

    #[test]
    fn compiled_regex_types_are_send_and_sync() {
        assert_send_sync::<Regex>();
        assert_send_sync::<crate::regset::OnigRegSet>();
        assert_send_sync::<crate::scanner::Scanner>();
    }

    #[test]
    fn find_reuses_the_thread_local_region_buffer() {
        clear_cached_region();
        // `\K` keeps `find` on the region path.
        let re = Regex::new(r"(a)(b)\K(c)").unwrap();

        assert_eq!(re.find("abc").unwrap().as_str(), "c");
        let first = cached_region_buffer().expect("find should return its region to the cache");
        assert!(first.1 >= 4);

        assert_eq!(re.find("abc").unwrap().as_str(), "c");
        let second = cached_region_buffer().expect("find should preserve the cached region");
        assert_eq!(second, first);
    }

    #[test]
    fn captures_returns_its_region_buffer_when_dropped() {
        clear_cached_region();
        let re = Regex::new(r"(a)(b)(c)").unwrap();
        let captures = re.captures("abc").unwrap();
        let buffer = captures.region.beg.as_ptr();

        assert!(cached_region_buffer().is_none());
        drop(captures);

        let cached = cached_region_buffer().expect("drop should return the captures region");
        assert_eq!(cached.0, buffer);
        assert!(cached.1 >= 4);
    }

    #[test]
    fn result_drop_during_thread_local_teardown_does_not_panic() {
        thread_local! {
            static LATE_RESULT: RefCell<Option<Captures<'static>>> = const { RefCell::new(None) };
        }

        std::thread::spawn(|| {
            // Initialize the result holder before CACHED_REGION so it is
            // destroyed afterwards and drops Captures with the cache gone.
            LATE_RESULT.with(|result| assert!(result.borrow().is_none()));
            let regex = Box::leak(Box::new(Regex::new(r"(a)").unwrap()));
            let captures = regex.captures("a").unwrap();
            LATE_RESULT.with(|result| *result.borrow_mut() = Some(captures));
        })
        .join()
        .expect("result drop during thread teardown must not panic");
    }

    #[test]
    fn find_iter_reuses_one_region_for_every_step() {
        clear_cached_region();
        // `\K` moves the match start away from the attempt, so only the
        // region carries the match.
        let re = Regex::new(r"(\w)\K\w+").unwrap();
        let mut matches = re.find_iter("one two");
        assert!(matches.msa.is_none());

        assert_eq!(matches.next().unwrap().as_str(), "ne");
        let first = matches.region.beg.as_ptr();
        assert_eq!(matches.next().unwrap().as_str(), "wo");
        assert_eq!(matches.region.beg.as_ptr(), first);
        drop(matches);

        let cached = cached_region_buffer().expect("iterator drop should return its region");
        assert_eq!(cached.0, first);
    }

    #[test]
    fn find_iter_reuses_one_match_arg_without_a_region() {
        let re = Regex::new(r"(\w+)").unwrap();
        let mut matches = re.find_iter("one two");
        let msa: *const MatchArg = &**matches.msa.as_ref().expect("bounds-only iterator");
        assert_eq!(matches.next().unwrap().as_str(), "one");
        assert_eq!(matches.next().unwrap().as_str(), "two");
        assert!(matches.next().is_none());
        assert!(std::ptr::eq(&**matches.msa.as_ref().unwrap(), msa));
        assert!(matches.region.beg.is_empty(), "no region was requested");
    }

    /// The bounds-only iterator yields what the region-based one yields.
    #[test]
    fn find_iter_bounds_match_the_region_path() {
        let patterns = [
            r"\d+",
            r"(\w+)",
            r"(a)|b",
            r"\b(\w+)\s+\1\b",
            r"(?<=@)\w+",
            r"\w+(?=\()",
            r"x*",
            r"",
            r"^",
            r"$",
            r"(?m)^\s*$",
            r"alpha|beta|gamma|delta",
            r"(alpha|beta|gamma|delta)",
            r"(?i)(?:error|warn|fatal|panic)",
            r"\b(?:if|else|for|while)\b",
            r"(?>a+)b|a",
            r"(a|ab)(c|bcd)(d*)",
            r"[\w.+-]+@\w+\.\w+",
            r"\p{L}+",
            r"é|e",
            r".*",
            r"(?<n>\d)(?<m>\d)?",
        ];
        let texts = [
            "",
            "a",
            "one two two three",
            "x@y.z foo(1) bar( a@b.cd",
            "alpha beta gammadelta ERROR warn Panic",
            "if else\nfor  \n\nwhile",
            "aab abcd abcbcdd",
            "Grüße café éte 12 345",
            "xxaxxb",
        ];
        for pattern in patterns {
            let re = Regex::new(pattern).unwrap();
            for text in texts {
                let bounds = re.find_iter(text);
                assert!(bounds.msa.is_some(), "{pattern}");
                let region_path = FindIter {
                    regex: &re,
                    text: text.as_bytes(),
                    last_end: 0,
                    last_was_empty: false,
                    region: OnigRegion::new(),
                    msa: None,
                };
                let got: Vec<_> = bounds.map(|m| m.range()).collect();
                let expected: Vec<_> = region_path.map(|m| m.range()).collect();
                assert_eq!(got, expected, "{pattern:?} {text:?}");
                assert_eq!(
                    re.find(text).map(|m| m.range()),
                    expected.first().cloned(),
                    "{pattern:?} {text:?}"
                );
            }
        }
        // With `\K` the region carries the match start.
        let keep = Regex::new(r"(\w)\K\w+").unwrap();
        assert_eq!(keep.find("one two").map(|m| m.range()), Some(1..3));
    }

    #[test]
    fn regex_new_and_find() {
        let re = Regex::new(r"\d+").unwrap();
        let m = re.find("hello 42 world").unwrap();
        assert_eq!(m.as_str(), "42");
        assert_eq!(m.start(), 6);
        assert_eq!(m.end(), 8);
        assert_eq!(m.range(), 6..8);
        assert_eq!(m.len(), 2);
        assert!(!m.is_empty());
    }

    #[test]
    fn regex_no_match() {
        let re = Regex::new(r"\d+").unwrap();
        assert!(re.find("no digits here").is_none());
    }

    #[test]
    fn regex_is_match() {
        let re = Regex::new(r"hello").unwrap();
        assert!(re.is_match("say hello"));
        assert!(!re.is_match("say goodbye"));
    }

    #[test]
    fn search_options_methods_return_matches_and_captures() {
        let _lock = crate::regexec::LIMIT_TEST_LOCK.lock().unwrap();
        let re = Regex::new(r"(\w+)").unwrap();
        let options = SearchOptions::new().timeout(Duration::from_secs(1));

        assert_eq!(
            re.find_with("hello 42", options).unwrap().unwrap().as_str(),
            "hello"
        );
        assert_eq!(
            re.find_bytes_with(b"hello 42", options)
                .unwrap()
                .unwrap()
                .as_str(),
            "hello"
        );
        assert!(re.is_match_with("hello", options).unwrap());
        assert!(!re.is_match_bytes_with(b"!!!", options).unwrap());
        assert_eq!(
            re.captures_with("hello 42", options)
                .unwrap()
                .unwrap()
                .get(1)
                .unwrap()
                .as_str(),
            "hello"
        );
        assert!(re.captures_bytes_with(b"!!!", options).unwrap().is_none());
    }

    #[test]
    fn search_options_surface_time_limit_errors() {
        let _lock = crate::regexec::LIMIT_TEST_LOCK.lock().unwrap();
        let re = Regex::new(r"(a+)+b").unwrap();
        let text = "a".repeat(40);
        let options = SearchOptions::new()
            .timeout(Duration::from_millis(1))
            .retry_limit_in_match(0)
            .retry_limit_in_search(0);

        assert!(matches!(
            re.find_with(&text, options),
            Err(RegexError::TimeLimitOver)
        ));
        assert!(matches!(
            re.is_match_with(&text, options),
            Err(RegexError::TimeLimitOver)
        ));
        assert!(matches!(
            re.captures_with(&text, options),
            Err(RegexError::TimeLimitOver)
        ));
    }

    #[test]
    fn search_options_timeout_spans_every_start_position() {
        let _lock = crate::regexec::LIMIT_TEST_LOCK.lock().unwrap();
        // Each start position backtracks only ~400 times; the limit must still
        // fire for the search as a whole.
        let re = Regex::new(r"a{1,400}?(?=b)").unwrap();
        let text = "a".repeat(500_000);
        let options = SearchOptions::new().timeout(Duration::from_millis(10));

        let started = std::time::Instant::now();
        assert!(matches!(
            re.find_with(&text, options),
            Err(RegexError::TimeLimitOver)
        ));
        assert!(started.elapsed() < Duration::from_secs(1));
    }

    #[test]
    fn search_options_surface_retry_limit_errors() {
        let _lock = crate::regexec::LIMIT_TEST_LOCK.lock().unwrap();
        let re = Regex::new(r"(a+)+b").unwrap();
        let text = "a".repeat(30);

        assert!(matches!(
            re.find_with(&text, SearchOptions::new().retry_limit_in_match(1_000)),
            Err(RegexError::RetryLimitInMatchOver)
        ));
        assert!(matches!(
            re.find_with(
                &text,
                SearchOptions::new()
                    .retry_limit_in_match(0)
                    .retry_limit_in_search(1_000)
            ),
            Err(RegexError::RetryLimitInSearchOver)
        ));
    }

    #[test]
    fn search_options_leave_unset_limits_process_wide() {
        let _lock = crate::regexec::LIMIT_TEST_LOCK.lock().unwrap();
        let old_retry = crate::regexec::onig_get_retry_limit_in_match();
        crate::regexec::onig_set_retry_limit_in_match(1_000);
        let re = Regex::new(r"(a+)+b").unwrap();
        let text = "a".repeat(30);

        let unset = re.find_with(&text, SearchOptions::new());
        let disabled = re.find_with(
            &text,
            SearchOptions::new()
                .retry_limit_in_match(0)
                .retry_limit_in_search(0)
                .timeout(Duration::from_millis(50)),
        );
        crate::regexec::onig_set_retry_limit_in_match(old_retry);

        assert!(matches!(unset, Err(RegexError::RetryLimitInMatchOver)));
        assert!(matches!(disabled, Err(RegexError::TimeLimitOver)));
    }

    #[test]
    fn search_options_iterator_yields_matches_and_then_finishes() {
        let _lock = crate::regexec::LIMIT_TEST_LOCK.lock().unwrap();
        let re = Regex::new(r"\w+").unwrap();
        let options = SearchOptions::new().timeout(Duration::from_secs(1));
        let mut matches = re.find_iter_with("one two", options);

        assert_eq!(matches.next().unwrap().unwrap().as_str(), "one");
        assert_eq!(matches.next().unwrap().unwrap().as_str(), "two");
        assert!(matches.next().is_none());
        assert!(matches.next().is_none());
        let bytes: Vec<_> = re
            .find_iter_bytes_with(b"a b", options)
            .map(|m| m.unwrap().as_bytes().to_vec())
            .collect();
        assert_eq!(bytes, vec![b"a".to_vec(), b"b".to_vec()]);
    }

    #[test]
    fn search_options_iterator_surfaces_an_error_once() {
        let _lock = crate::regexec::LIMIT_TEST_LOCK.lock().unwrap();
        let re = Regex::new(r"(a+)+b").unwrap();
        let text = "a".repeat(40);
        let options = SearchOptions::new()
            .timeout(Duration::from_millis(1))
            .retry_limit_in_match(0)
            .retry_limit_in_search(0);
        let mut matches = re.find_iter_with(&text, options);

        assert!(matches!(
            matches.next().unwrap(),
            Err(RegexError::TimeLimitOver)
        ));
        assert!(matches.next().is_none());
    }

    #[test]
    fn search_options_default_keeps_every_limit_unset() {
        assert_eq!(SearchOptions::default(), SearchOptions::new());
        assert_send_sync::<SearchOptions>();
        assert_send_sync::<TryFindIter<'static, 'static>>();
    }

    #[test]
    fn timeout_is_rounded_up_to_milliseconds() {
        assert_eq!(timeout_to_millis(Duration::ZERO), 0);
        assert_eq!(timeout_to_millis(Duration::from_nanos(1)), 1);
        assert_eq!(timeout_to_millis(Duration::from_millis(1)), 1);
        assert_eq!(timeout_to_millis(Duration::from_nanos(1_000_001)), 2);
        assert_eq!(timeout_to_millis(Duration::MAX), u64::MAX);
    }

    #[test]
    fn regex_captures() {
        let re = Regex::new(r"(\d{4})-(\d{2})-(\d{2})").unwrap();
        let caps = re.captures("date: 2026-02-14").unwrap();
        assert_eq!(caps.get(0).unwrap().as_str(), "2026-02-14");
        assert_eq!(caps.get(1).unwrap().as_str(), "2026");
        assert_eq!(caps.get(2).unwrap().as_str(), "02");
        assert_eq!(caps.get(3).unwrap().as_str(), "14");
        assert!(caps.get(4).is_none());
        assert_eq!(caps.len(), 4);
    }

    #[test]
    fn regex_captures_len() {
        let re = Regex::new(r"(a)(b)(c)").unwrap();
        assert_eq!(re.captures_len(), 3);
    }

    #[test]
    fn regex_find_iter() {
        let re = Regex::new(r"\d+").unwrap();
        let matches: Vec<&str> = re.find_iter("1 + 22 = 333").map(|m| m.as_str()).collect();
        assert_eq!(matches, vec!["1", "22", "333"]);
    }

    #[test]
    fn regex_builder_case_insensitive() {
        let re = Regex::builder(r"hello")
            .case_insensitive(true)
            .build()
            .unwrap();
        assert!(re.is_match("HELLO"));
        assert!(re.is_match("Hello"));
    }

    #[test]
    fn regex_invalid_pattern() {
        let err = Regex::new(r"(unclosed").unwrap_err();
        assert!(matches!(err, RegexError::Syntax { .. }));
    }

    #[test]
    fn match_as_bytes() {
        let re = Regex::new(r"world").unwrap();
        let m = re.find("hello world").unwrap();
        assert_eq!(m.as_bytes(), b"world");
    }

    #[test]
    fn captures_iter() {
        let re = Regex::new(r"(a)(b)?").unwrap();
        let caps = re.captures("a").unwrap();
        let items: Vec<_> = caps.iter().collect();
        // group 0 = "a", group 1 = "a", group 2 = None (didn't participate)
        assert_eq!(items.len(), 3);
        assert!(items[0].is_some());
        assert!(items[1].is_some());
        assert!(items[2].is_none());
    }

    #[test]
    fn named_captures() {
        let re = Regex::new(r"(?<year>\d{4})-(?<month>\d{2})").unwrap();
        let caps = re.captures("2026-02").unwrap();
        assert_eq!(caps.name("year").unwrap().as_str(), "2026");
        assert_eq!(caps.name("month").unwrap().as_str(), "02");
        assert!(caps.name("day").is_none());
    }

    #[test]
    fn empty_match_find_iter() {
        let re = Regex::new(r"").unwrap();
        let matches: Vec<_> = re.find_iter("ab").collect();
        // Should yield empty matches at positions 0, 1, 2
        assert_eq!(matches.len(), 3);
        assert_eq!(matches[0].start(), 0);
        assert_eq!(matches[1].start(), 1);
        assert_eq!(matches[2].start(), 2);
    }
}