ferroni 1.3.3

Pure-Rust Oniguruma regex engine with SIMD-accelerated search
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
// 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 crate::encodings::utf8::ONIG_ENCODING_UTF8;
use crate::error::RegexError;
use crate::oniguruma::*;
use crate::regcomp::onig_new;
use crate::regexec::{onig_name_to_backref_number, onig_search};
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);
        }
    });
}

/// 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.
    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>> {
        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 start = region.beg[0] as usize;
        let end = region.end[0] as usize;
        cache_region(region);
        Some(Match { text, start, end })
    }

    /// Check whether `text` matches the pattern anywhere.
    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
    }

    /// Return the first match with all capture groups, or `None`.
    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,
        })
    }

    /// Iterate over all non-overlapping matches in `text`.
    pub fn find_iter<'r, 't>(&'r self, text: &'t str) -> FindIter<'r, 't> {
        FindIter {
            regex: self,
            text: text.as_bytes(),
            last_end: 0,
            last_was_empty: false,
            region: take_cached_region(),
        }
    }

    /// 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> {
        FindIter {
            regex: self,
            text,
            last_end: 0,
            last_was_empty: false,
            region: take_cached_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
    }

    /// 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,
}

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,
        }
    }

    /// 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
    }

    /// 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,
        )?;
        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> {
    /// 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.
    pub fn get(&self, i: usize) -> Option<Match<'t>> {
        if i >= self.region.num_regs as usize {
            return None;
        }
        let beg = self.region.beg[i];
        let end = self.region.end[i];
        if beg == ONIG_REGION_NOTPOS {
            return None;
        }
        Some(Match {
            text: self.text,
            start: beg as usize,
            end: end as usize,
        })
    }

    /// 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,
}

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 (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;
        }

        let start = self.region.beg[0] as usize;
        let end = self.region.end[0] as usize;

        // 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(Match {
            text: self.text,
            start,
            end,
        })
    }
}

impl Drop for FindIter<'_, '_> {
    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();
        let re = Regex::new(r"(a)(b)(c)").unwrap();

        assert_eq!(re.find("abc").unwrap().as_str(), "abc");
        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(), "abc");
        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();
        let re = Regex::new(r"(\w+)").unwrap();
        let mut matches = re.find_iter("one two");

        assert_eq!(matches.next().unwrap().as_str(), "one");
        let first = matches.region.beg.as_ptr();
        assert_eq!(matches.next().unwrap().as_str(), "two");
        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 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 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);
    }
}