regexr 0.3.0

A high-performance regex engine built from scratch with JIT compilation and SIMD acceleration
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
//! Public API integration tests.
//!
//! Tests for the core `Regex` type and its methods: `new`, `is_match`, `find`,
//! `find_iter`, `captures`, `captures_iter`, `replace`, `replace_all`.
//!
//! When the `jit` feature is enabled, these tests use JIT compilation.

use regexr::Regex;
#[cfg(feature = "jit")]
use regexr::RegexBuilder;

/// Creates a Regex with JIT enabled when the `jit` feature is available.
#[allow(dead_code)]
fn regex(pattern: &str) -> Regex {
    #[cfg(feature = "jit")]
    {
        RegexBuilder::new(pattern)
            .jit(true)
            .build()
            .expect("failed to compile pattern")
    }
    #[cfg(not(feature = "jit"))]
    {
        Regex::new(pattern).expect("failed to compile pattern")
    }
}

// =============================================================================
// Regex::new and as_str
// =============================================================================

#[test]
fn test_regex_new() {
    let re = Regex::new("hello").unwrap();
    assert_eq!(re.as_str(), "hello");
}

// =============================================================================
// is_match
// =============================================================================

#[test]
fn test_is_match() {
    let re = regex("hello");
    assert!(re.is_match("hello world"));
    assert!(re.is_match("say hello"));
    assert!(!re.is_match("goodbye"));
}

// =============================================================================
// find
// =============================================================================

#[test]
fn test_find() {
    let re = regex("world");
    let m = re.find("hello world").unwrap();
    assert_eq!(m.start(), 6);
    assert_eq!(m.end(), 11);
    assert_eq!(m.as_str(), "world");
    assert_eq!(m.len(), 5);
    assert!(!m.is_empty());
}

#[test]
fn test_find_none() {
    let re = regex("xyz");
    assert!(re.find("hello world").is_none());
}

#[test]
fn test_match_range() {
    let re = regex("test");
    let m = re.find("this is a test").unwrap();
    assert_eq!(m.range(), 10..14);
}

#[test]
fn test_empty_match() {
    let re = regex("a*");
    let m = re.find("bbb").unwrap();
    assert!(m.is_empty());
    assert_eq!(m.len(), 0);
}

// =============================================================================
// find_iter
// =============================================================================

#[test]
fn test_find_iter() {
    let re = regex("a");
    let matches: Vec<_> = re.find_iter("abracadabra").collect();
    assert_eq!(matches.len(), 5);
    assert_eq!(matches[0].start(), 0);
    assert_eq!(matches[1].start(), 3);
    assert_eq!(matches[2].start(), 5);
    assert_eq!(matches[3].start(), 7);
    assert_eq!(matches[4].start(), 10);
}

#[test]
fn test_find_iter_empty() {
    let re = regex("xyz");
    let matches: Vec<_> = re.find_iter("hello world").collect();
    assert!(matches.is_empty());
}

// =============================================================================
// find_iter over multi-byte UTF-8
// =============================================================================
//
// `.` and character classes match one whole codepoint (this is the engine's
// canonical semantics, see `regexr::reference`), so their spans cover complete
// characters. The iterator also always resumes at the next codepoint boundary,
// so no match ever starts inside a codepoint and no `&str` is ever sliced at a
// non-boundary.

/// Collects `(start, end)` for every match, driving the iterator to completion.
fn ranges(re: &Regex, text: &str) -> Vec<(usize, usize)> {
    re.find_iter(text).map(|m| (m.start(), m.end())).collect()
}

#[test]
fn test_find_iter_dot_over_multibyte_text() {
    // `.` over text containing 3-byte codepoints: one match per character.
    // "Hello " is bytes 0..6, '世' is 6..9, '界' is 9..12, '!' is 12..13.
    let re = regex(".");
    let text = "Hello 世界!";

    assert_eq!(
        ranges(&re, text),
        vec![
            (0, 1),
            (1, 2),
            (2, 3),
            (3, 4),
            (4, 5),
            (5, 6),
            (6, 9),
            (9, 12),
            (12, 13),
        ]
    );

    // Every span is a whole character, so every one has a `&str` form.
    let strs: Vec<_> = re.find_iter(text).map(|m| m.as_str()).collect();
    assert_eq!(strs, vec!["H", "e", "l", "l", "o", " ", "", "", "!"]);

    // The bytes agree: the full UTF-8 encoding, not just the lead byte.
    let bytes: Vec<_> = re.find_iter(text).map(|m| m.as_bytes().to_vec()).collect();
    assert_eq!(bytes[6], "".as_bytes().to_vec());
    assert_eq!(bytes[7], "".as_bytes().to_vec());
}

#[test]
fn test_find_iter_dot_over_two_byte_codepoint() {
    // 'a' is 0..1, 'é' is 1..3, 'b' is 3..4.
    let re = regex(".");
    assert_eq!(ranges(&re, "aéb"), vec![(0, 1), (1, 3), (3, 4)]);
}

#[test]
fn test_find_iter_dot_over_three_byte_codepoint() {
    // '世' is 0..3, '界' is 3..6.
    let re = regex(".");
    assert_eq!(ranges(&re, "世界"), vec![(0, 3), (3, 6)]);
}

#[test]
fn test_find_iter_dot_over_four_byte_codepoint() {
    // 'x' is 0..1, '🎉' is 1..5, 'y' is 5..6.
    let re = regex(".");
    assert_eq!(ranges(&re, "x🎉y"), vec![(0, 1), (1, 5), (5, 6)]);
}

#[test]
fn test_dot_matches_one_whole_codepoint() {
    let re = regex(".");
    for text in ["é", "", "🎉"] {
        let m = re.find(text).expect("`.` must match a non-ASCII character");
        assert_eq!((m.start(), m.end()), (0, text.len()), "text {text:?}");
        assert_eq!(m.as_str(), text);
    }
}

#[test]
fn test_dot_anchored_against_single_codepoint() {
    // `^.$` only holds if `.` consumes the whole character.
    let re = regex("^.$");
    for text in ["é", "", "🎉"] {
        let m = re.find(text).expect("`^.$` must match a lone character");
        assert_eq!((m.start(), m.end()), (0, text.len()), "text {text:?}");
    }
    // Two characters must not match a single `.` between the anchors.
    assert!(regex("^.$").find("éé").is_none());
}

#[test]
fn test_dot_between_ascii_literals() {
    let re = regex("X.Y");
    let m = re.find("XéY").expect("`X.Y` must span the whole codepoint");
    assert_eq!((m.start(), m.end()), (0, "XéY".len()));
    assert_eq!(m.as_str(), "XéY");

    let m = regex("X.Y").find("X🎉Y").expect("4-byte codepoint");
    assert_eq!(m.as_str(), "X🎉Y");
}

#[test]
fn test_dot_and_newline() {
    // Without dot-all, `.` still excludes '\n'.
    assert!(regex(".").find("\n").is_none());
    assert!(regex("a.b").find("a\nb").is_none());

    // With `(?s)` it matches it.
    let m = regex("(?s)a.b")
        .find("a\nb")
        .expect("dot-all matches newline");
    assert_eq!(m.as_str(), "a\nb");

    // Dot-all still matches whole codepoints.
    let m = regex("(?s).").find("").expect("dot-all over a character");
    assert_eq!(m.as_str(), "");
}

#[test]
fn test_dot_inside_class_is_a_literal() {
    let re = regex("[.]");
    assert_eq!(re.find("a.b").map(|m| (m.start(), m.end())), Some((1, 2)));
    assert!(re.find("aéb").is_none());
}

#[test]
fn test_find_iter_never_starts_inside_a_codepoint() {
    // The invariant the resume rule maintains, over mixed 1/2/3/4-byte text.
    let re = regex(".");
    let text = "a é 世 🎉 z";
    for m in re.find_iter(text) {
        assert!(
            text.is_char_boundary(m.start()),
            "match at {} starts inside a codepoint",
            m.start()
        );
    }
}

#[test]
fn test_find_iter_empty_matches_over_multibyte_text() {
    // The pre-existing empty-match guard: one empty match per codepoint plus
    // one at the end, and the iterator terminates.
    // 'é' is 0..2, '世' is 2..5.
    let re = regex("x*");
    assert_eq!(ranges(&re, "é世"), vec![(0, 0), (2, 2), (5, 5)]);
}

#[test]
fn test_find_iter_ascii_behaviour_unchanged() {
    // Every ASCII index is a codepoint boundary, so the resume rule is a no-op.
    let re = regex(".");
    assert_eq!(ranges(&re, "abc"), vec![(0, 1), (1, 2), (2, 3)]);
    let strs: Vec<_> = re.find_iter("abc").map(|m| m.as_str()).collect();
    assert_eq!(strs, vec!["a", "b", "c"]);

    let re = regex("x*");
    assert_eq!(ranges(&re, "abc"), vec![(0, 0), (1, 1), (2, 2), (3, 3)]);
}

#[test]
fn test_captures_iter_over_multibyte_text() {
    // `CapturesIter` resumes the same way as `find_iter`.
    let re = regex("(.)");
    let spans: Vec<_> = re
        .captures_iter("世界")
        .map(|c| {
            let m = c.get(0).unwrap();
            (m.start(), m.end())
        })
        .collect();
    assert_eq!(spans, vec![(0, 3), (3, 6)]);
}

#[test]
fn test_replace_over_multibyte_text() {
    // `.` consumes whole codepoints, so a replace over multi-byte text
    // round-trips cleanly: no orphaned continuation bytes, no U+FFFD.
    let re = regex(".");
    let replaced = re.replace_all("", "-");
    assert_eq!(replaced, "-");
    assert!(!replaced.contains('\u{FFFD}'));

    let replaced = re.replace_all("a世🎉b", "-");
    assert_eq!(replaced, "----");
    assert!(!replaced.contains('\u{FFFD}'));

    // Replacing only the first match leaves the rest of the text intact.
    assert_eq!(re.replace("é世", "-"), "-世");

    // Codepoint-aligned matches are unaffected.
    let re = regex("");
    assert_eq!(re.replace_all("a世b", "-"), "a-b");
    assert_eq!(re.replace("a世b世", "-"), "a-b世");
}

// =============================================================================
// captures
// =============================================================================

#[test]
fn test_captures() {
    let re = regex("(\\d+)-(\\d+)");
    let caps = re.captures("phone: 123-456").unwrap();
    assert!(caps.len() >= 3);
    assert_eq!(&caps[0], "123-456");
    assert_eq!(&caps[1], "123");
    assert_eq!(&caps[2], "456");
}

// =============================================================================
// captures_iter
// =============================================================================

#[test]
fn test_captures_iter_basic() {
    let re = regex(r"(\w+)");
    let text = "hello world foo";
    let caps: Vec<_> = re.captures_iter(text).collect();
    assert_eq!(caps.len(), 3);
    assert_eq!(&caps[0][0], "hello");
    assert_eq!(&caps[1][0], "world");
    assert_eq!(&caps[2][0], "foo");
}

#[test]
fn test_captures_iter_with_groups() {
    let re = regex(r"(\w+)=(\d+)");
    let text = "a=1 b=2 c=3";
    let caps: Vec<_> = re.captures_iter(text).collect();
    assert_eq!(caps.len(), 3);
    assert_eq!(&caps[0][1], "a");
    assert_eq!(&caps[0][2], "1");
    assert_eq!(&caps[1][1], "b");
    assert_eq!(&caps[1][2], "2");
    assert_eq!(&caps[2][1], "c");
    assert_eq!(&caps[2][2], "3");
}

#[test]
fn test_captures_iter_named() {
    let re = regex(r"(?<key>\w+)=(?<value>\d+)");
    let text = "x=10 y=20";
    let caps: Vec<_> = re.captures_iter(text).collect();
    assert_eq!(caps.len(), 2);
    assert_eq!(&caps[0]["key"], "x");
    assert_eq!(&caps[0]["value"], "10");
    assert_eq!(&caps[1]["key"], "y");
    assert_eq!(&caps[1]["value"], "20");
}

#[test]
fn test_captures_iter_positions() {
    let re = regex(r"(\d+)");
    let text = "a1b22c333";
    let caps: Vec<_> = re.captures_iter(text).collect();
    assert_eq!(caps.len(), 3);
    assert_eq!(caps[0].get(0).unwrap().start(), 1);
    assert_eq!(caps[0].get(0).unwrap().end(), 2);
    assert_eq!(caps[1].get(0).unwrap().start(), 3);
    assert_eq!(caps[1].get(0).unwrap().end(), 5);
    assert_eq!(caps[2].get(0).unwrap().start(), 6);
    assert_eq!(caps[2].get(0).unwrap().end(), 9);
}

// =============================================================================
// replace
// =============================================================================

#[test]
fn test_replace() {
    let re = regex("world");
    let result = re.replace("hello world", "rust");
    assert_eq!(result, "hello rust");
}

#[test]
fn test_replace_no_match() {
    let re = regex("xyz");
    let result = re.replace("hello world", "rust");
    assert_eq!(result, "hello world");
}

// =============================================================================
// replace_all
// =============================================================================

#[test]
fn test_replace_all() {
    let re = regex("o");
    let result = re.replace_all("hello world", "0");
    assert_eq!(result, "hell0 w0rld");
}

#[test]
fn test_replace_all_no_match() {
    let re = regex("xyz");
    let result = re.replace_all("hello world", "!");
    assert_eq!(result, "hello world");
}

// =============================================================================
// Prefix Optimization
// =============================================================================

#[cfg(feature = "jit")]
mod prefix_opt {
    use regexr::RegexBuilder;

    #[test]
    fn test_prefix_optimized_basic() {
        // Pattern with many tokens sharing common prefixes
        let re = RegexBuilder::new(r"the|that|them|they|this")
            .optimize_prefixes(true)
            .build()
            .unwrap();

        assert!(re.is_match("the"));
        assert!(re.is_match("that"));
        assert!(re.is_match("them"));
        assert!(re.is_match("they"));
        assert!(re.is_match("this"));
        assert!(!re.is_match("those"));
    }

    #[test]
    fn test_prefix_optimized_find() {
        let re = RegexBuilder::new(r"apple|application|apply|apt")
            .optimize_prefixes(true)
            .build()
            .unwrap();

        let m = re.find("the application was running").unwrap();
        assert_eq!(m.as_str(), "application");
    }

    #[test]
    fn test_prefix_optimized_multiple_branches() {
        // Words that share some prefixes but not all
        let re = RegexBuilder::new(r"test|testing|tested|tester|apple|application")
            .optimize_prefixes(true)
            .build()
            .unwrap();

        assert!(re.is_match("test"));
        assert!(re.is_match("testing"));
        assert!(re.is_match("tested"));
        assert!(re.is_match("tester"));
        assert!(re.is_match("apple"));
        assert!(re.is_match("application"));
        // "tests" matches because it contains "test"
        assert!(re.is_match("tests"));
        // But "xyz" doesn't match
        assert!(!re.is_match("xyz"));
    }

    #[test]
    fn test_prefix_optimized_with_jit() {
        // Combine prefix optimization with JIT
        let re = RegexBuilder::new(r"the|that|them|they|this")
            .optimize_prefixes(true)
            .jit(true)
            .build()
            .unwrap();

        assert!(re.is_match("the"));
        assert!(re.is_match("that"));
        assert!(re.is_match("them"));
        assert!(re.is_match("they"));
        assert!(re.is_match("this"));
        assert!(!re.is_match("those"));
    }

    #[test]
    fn test_prefix_optimized_find_iter() {
        let re = RegexBuilder::new(r"the|that|them|they")
            .optimize_prefixes(true)
            .build()
            .unwrap();

        let text = "the cat that sat on them made they jump";
        let matches: Vec<_> = re.find_iter(text).map(|m| m.as_str()).collect();
        // Leftmost-first/PCRE semantics: the first alternative `the` wins wherever
        // it matches, so "them" and "they" both match as their prefix "the".
        // (Python: re.findall(r"the|that|them|they", text) == ['the','that','the','the'].)
        assert_eq!(matches, vec!["the", "that", "the", "the"]);
    }
}

// =============================================================================
// JIT Alternation Tests
// =============================================================================

#[cfg(feature = "jit")]
mod jit_alternation {
    use regexr::RegexBuilder;

    #[test]
    fn test_jit_simple_alternation() {
        let re = RegexBuilder::new(r"foo|bar").jit(true).build().unwrap();

        assert!(re.is_match("foo"));
        assert!(re.is_match("bar"));
        assert!(!re.is_match("baz"));
    }

    #[test]
    fn test_jit_alternation_find() {
        let re = RegexBuilder::new(r"foo|bar").jit(true).build().unwrap();

        let m = re.find("xyzfoo123").unwrap();
        assert_eq!(m.start(), 3);
        assert_eq!(m.end(), 6);
        assert_eq!(m.as_str(), "foo");

        let m = re.find("xyzbar123").unwrap();
        assert_eq!(m.start(), 3);
        assert_eq!(m.end(), 6);
        assert_eq!(m.as_str(), "bar");
    }

    #[test]
    fn test_jit_alternation_multi() {
        let re = RegexBuilder::new(r"hello|world|test")
            .jit(true)
            .build()
            .unwrap();

        assert!(re.is_match("hello"));
        assert!(re.is_match("world"));
        assert!(re.is_match("test"));
        assert!(!re.is_match("other"));

        let m = re.find("say hello there").unwrap();
        assert_eq!(m.as_str(), "hello");
    }

    #[test]
    fn test_jit_alternation_with_char_class() {
        let re = RegexBuilder::new(r"[a-z]+|[0-9]+")
            .jit(true)
            .build()
            .unwrap();

        assert!(re.is_match("abc"));
        assert!(re.is_match("123"));

        let m = re.find("...abc...").unwrap();
        assert_eq!(m.as_str(), "abc");

        let m = re.find("...123...").unwrap();
        assert_eq!(m.as_str(), "123");
    }

    #[test]
    fn test_jit_alternation_find_iter() {
        let re = RegexBuilder::new(r"foo|bar").jit(true).build().unwrap();

        let text = "foo bar foo bar baz";
        let matches: Vec<_> = re.find_iter(text).map(|m| m.as_str()).collect();
        assert_eq!(matches, vec!["foo", "bar", "foo", "bar"]);
    }

    #[test]
    fn test_jit_alternation_different_lengths() {
        let re = RegexBuilder::new(r"a|bb|ccc").jit(true).build().unwrap();

        assert!(re.is_match("a"));
        assert!(re.is_match("bb"));
        assert!(re.is_match("ccc"));

        let m = re.find("xxaxx").unwrap();
        assert_eq!(m.as_str(), "a");

        let m = re.find("xxbbxx").unwrap();
        assert_eq!(m.as_str(), "bb");

        let m = re.find("xxcccxx").unwrap();
        assert_eq!(m.as_str(), "ccc");
    }

    #[test]
    fn test_jit_captures_basic() {
        // Test that JIT captures work correctly
        let re = RegexBuilder::new(r"([a-z]+)=([0-9]+)")
            .jit(true)
            .build()
            .unwrap();

        let caps = re.captures("key=123").unwrap();
        assert_eq!(&caps[0], "key=123");
        assert_eq!(&caps[1], "key");
        assert_eq!(&caps[2], "123");
    }

    #[test]
    fn test_jit_captures_find_in_text() {
        let re = RegexBuilder::new(r"([a-z]+):([0-9]+)")
            .jit(true)
            .build()
            .unwrap();

        let caps = re.captures("data is foo:42 and bar:99").unwrap();
        assert_eq!(&caps[0], "foo:42");
        assert_eq!(&caps[1], "foo");
        assert_eq!(&caps[2], "42");
    }

    #[test]
    fn test_jit_captures_iter() {
        let re = RegexBuilder::new(r"([a-z]+)=([0-9]+)")
            .jit(true)
            .build()
            .unwrap();

        let text = "a=1 b=2 c=3";
        let caps: Vec<_> = re.captures_iter(text).collect();
        assert_eq!(caps.len(), 3);
        assert_eq!(&caps[0][1], "a");
        assert_eq!(&caps[0][2], "1");
        assert_eq!(&caps[1][1], "b");
        assert_eq!(&caps[1][2], "2");
        assert_eq!(&caps[2][1], "c");
        assert_eq!(&caps[2][2], "3");
    }
}

// =============================================================================
// escape()
// =============================================================================

mod escape_fn {
    use regexr::{escape, Regex};

    /// Builds a real `Regex` from `escape(s)` and asserts it matches `s`
    /// literally at that position: the escaped pattern must match the whole
    /// string, and anchoring it with `^...$` must match nothing else.
    fn assert_round_trips(s: &str) {
        let pattern = escape(s);
        let re = Regex::new(&pattern)
            .unwrap_or_else(|e| panic!("escape({s:?}) = {pattern:?} failed to compile: {e}"));
        let m = re
            .find(s)
            .unwrap_or_else(|| panic!("escape({s:?}) = {pattern:?} did not match {s:?} literally"));
        assert_eq!(m.as_str(), s, "escape({s:?}) matched the wrong substring");

        // Anchored, it must match `s` exactly and nothing longer or shorter.
        let anchored = format!("^(?:{pattern})$");
        let anchored_re = Regex::new(&anchored)
            .unwrap_or_else(|e| panic!("anchored pattern {anchored:?} failed to compile: {e}"));
        assert!(
            anchored_re.is_match(s),
            "anchored escape({s:?}) = {anchored:?} did not fully match {s:?}"
        );
    }

    #[test]
    fn test_round_trip_empty_string() {
        assert_round_trips("");
    }

    #[test]
    fn test_round_trip_all_metacharacters() {
        // Every character regexr's parser treats specially at the top level.
        assert_round_trips(r"\.*+?|^$(){}[]");
    }

    #[test]
    fn test_round_trip_no_metacharacters() {
        assert_round_trips("hello world 123");
    }

    #[test]
    fn test_round_trip_mixed_literal_and_meta() {
        assert_round_trips("a.b*c(d)[e]{f}g|h^i$j\\k");
    }

    #[test]
    fn test_round_trip_embedded_whitespace_and_newlines() {
        assert_round_trips("line one\nline two\ttabbed  double-spaced\r\n");
    }

    #[test]
    fn test_round_trip_non_ascii() {
        // Multi-byte UTF-8: accented Latin, CJK, and a 4-byte emoji. None of
        // these should be split or corrupted by byte-wise escaping.
        assert_round_trips("héllo wörld");
        assert_round_trips("こんにちは世界");
        assert_round_trips("emoji: 😀🎉👍");
    }

    #[test]
    fn test_round_trip_context_dependent_characters() {
        // These are only special *inside* other constructs in regexr's own
        // parser (`-` inside `[...]`, `:` `<` `>` `=` `!` `,` inside `(?...)`
        // and `{n,m}`, digits inside backreferences) but parse as plain
        // literals at the top level, which is the only context `escape`'s
        // output is used in. They must still round-trip correctly.
        assert_round_trips("a-b:c<d>e=f!g,h123");
        assert_round_trips("range: 1-100, ratio: 3:2");
    }

    #[test]
    fn test_round_trip_unmatched_brackets_and_parens() {
        // Individually these would be parse errors (or change meaning) if
        // left unescaped: unmatched `)`, `]`, `}`, or an unescaped `(`.
        assert_round_trips(")");
        assert_round_trips("]");
        assert_round_trips("}");
        assert_round_trips("(");
        assert_round_trips("[");
        assert_round_trips("{");
    }

    #[test]
    fn test_round_trip_backslash_sequences() {
        // Text that looks like escape sequences (\d, \n, \\) must be matched
        // as those literal characters, not interpreted as regexr escapes.
        assert_round_trips(r"\d\w\s\n\t\\");
    }

    #[test]
    fn test_round_trip_repetition_like_text() {
        // Looks like a quantified atom (`a{2,4}`) but must match only the
        // literal text `a{2,4}`, not "a repeated 2-4 times".
        assert_round_trips("a{2,4}");
        assert!(!Regex::new(&escape("a{2,4}")).unwrap().is_match("aa"));
    }

    #[test]
    fn test_escape_used_as_literal_delimiter() {
        // The motivating use case: splitting/matching on a literal delimiter
        // that happens to be a regex metacharacter.
        let re = Regex::new(&escape(".")).unwrap();
        assert!(re.is_match("a.b"));
        assert!(!re.is_match("axb"));

        let re = Regex::new(&escape("|")).unwrap();
        assert!(re.is_match("a|b"));
        assert!(!re.is_match("ab"));
    }

    #[test]
    fn test_escape_does_not_over_escape_safe_characters() {
        // Characters that are already safe unescaped should pass through
        // byte-for-byte, so escape() output stays minimal and readable.
        for s in ["-", ":", "<", ">", "=", "!", ",", "&", "~", "/", "0"] {
            assert_eq!(escape(s), s);
        }
    }

    #[test]
    fn test_escape_output_survives_extended_mode() {
        // Extended mode strips unescaped whitespace and `#` comments, so
        // escaped text spliced into an `(?x)` pattern must keep them.
        for s in ["a b", "a#b", "a # not a comment\nb", "a\tb"] {
            let re = Regex::new(&format!("(?x){}", escape(s)))
                .unwrap_or_else(|e| panic!("escape({s:?}) failed to compile under (?x): {e}"));
            let m = re
                .find(s)
                .unwrap_or_else(|| panic!("escape({s:?}) did not match under (?x)"));
            assert_eq!(m.as_str(), s);
        }
    }
}