ua-parser 0.2.2

Rust implementation of the User Agent String Parser project
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
#![deny(unsafe_code)]
#![warn(missing_docs)]
#![allow(clippy::empty_docs)]
#![doc = include_str!("../README.md")]

use regex::Captures;
use serde::Deserialize;

pub use regex_filtered::{BuildError, ParseError};

mod resolvers;

/// Error returned if the conversion of [`Regexes`] to [`Extractor`]
/// fails.
#[derive(Debug)]
pub enum Error {
    /// Compilation failed because one of the input regexes could not
    /// be parsed or processed.
    ParseError(ParseError),
    /// Compilation failed because one of the prefilters could not be
    /// built.
    BuildError(BuildError),
    /// A replacement template requires a group missing from the regex
    MissingGroup(usize),
}
impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Error::ParseError(p) => Some(p),
            Error::BuildError(b) => Some(b),
            Error::MissingGroup(_) => None,
        }
    }
}
impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{self:?}")
    }
}
impl From<ParseError> for Error {
    fn from(value: ParseError) -> Self {
        Self::ParseError(value)
    }
}
impl From<BuildError> for Error {
    fn from(value: BuildError) -> Self {
        Self::BuildError(value)
    }
}

/// Deserialization target for the parser descriptors, can be used
/// with the relevant serde implementation to load from `regexes.yaml`
/// or a conversion thereof.
///
/// Can then be compiled to a full [`Extractor`], or an individual
/// list of parsers can be converted to the corresponding extractor.
#[allow(missing_docs)]
#[derive(Deserialize)]
pub struct Regexes<'a> {
    pub user_agent_parsers: Vec<user_agent::Parser<'a>>,
    pub os_parsers: Vec<os::Parser<'a>>,
    pub device_parsers: Vec<device::Parser<'a>>,
}

impl<'a> TryFrom<Regexes<'a>> for Extractor<'a> {
    type Error = Error;
    /// Compile parsed regexes to the corresponding full extractor.
    ///
    /// Prefer using individual builder / extractors if you don't need
    /// all three domains extracted, as creating the individual
    /// extractors does have a cost.
    fn try_from(r: Regexes<'a>) -> Result<Self, Error> {
        let ua = r
            .user_agent_parsers
            .into_iter()
            .try_fold(user_agent::Builder::new(), |b, p| b.push(p))?
            .build()?;
        let os = r
            .os_parsers
            .into_iter()
            .try_fold(os::Builder::new(), |b, p| b.push(p))?
            .build()?;
        let dev = r
            .device_parsers
            .into_iter()
            .try_fold(device::Builder::new(), |b, p| b.push(p))?
            .build()?;
        Ok(Extractor { ua, os, dev })
    }
}

/// Full extractor, simply delegates to the underlying individual
/// extractors for the actual job.
#[allow(missing_docs)]
pub struct Extractor<'a> {
    pub ua: user_agent::Extractor<'a>,
    pub os: os::Extractor<'a>,
    pub dev: device::Extractor<'a>,
}
impl<'a> Extractor<'a> {
    /// Performs the extraction on every sub-extractor in sequence.
    pub fn extract(
        &'a self,
        ua: &'a str,
    ) -> (
        Option<user_agent::ValueRef<'a>>,
        Option<os::ValueRef<'a>>,
        Option<device::ValueRef<'a>>,
    ) {
        (
            self.ua.extract(ua),
            self.os.extract(ua),
            self.dev.extract(ua),
        )
    }
}

/// User agent module.
///
/// The user agent is the representation of the browser, in UAP lingo
/// the user agent is composed of a *family* (the browser project) and
/// a *version* of up to 4 segments.
pub mod user_agent {
    use serde::Deserialize;
    use std::borrow::Cow;

    use crate::resolvers::{FallbackResolver, FamilyResolver};
    use regex_filtered::BuildError;

    /// Individual user agent parser description. Plain data which can
    /// be deserialized from serde-compatible storage, or created
    /// literally (e.g. using a conversion or build script).
    #[derive(Deserialize, Default)]
    pub struct Parser<'a> {
        /// Regex to check the UA against, if the regex matches the
        /// parser applies.
        pub regex: Cow<'a, str>,
        /// If set, used for the [`ValueRef::family`] field. If it
        /// contains a `$1` placeholder, that is replaced by the value
        /// of the first match group.
        ///
        /// If unset, the first match group is used directly.
        pub family_replacement: Option<Cow<'a, str>>,
        /// If set, provides the value of the major version number,
        /// otherwise the second match group is used.
        pub v1_replacement: Option<Cow<'a, str>>,
        /// If set, provides the value of the minor version number,
        /// otherwise the third match group is used.
        pub v2_replacement: Option<Cow<'a, str>>,
        /// If set, provides the value of the patch version number,
        /// otherwise the fourth match group is used.
        pub v3_replacement: Option<Cow<'a, str>>,
        /// If set, provides the value of the minor patch version
        /// number, otherwise the fifth match group is used.
        pub v4_replacement: Option<Cow<'a, str>>,
    }

    type Repl<'a> = (
        FamilyResolver<'a>,
        // Per spec, should actually be restrict-templated (same as
        // family but for indexes 2-5 instead of 1).
        FallbackResolver<'a>,
        FallbackResolver<'a>,
        FallbackResolver<'a>,
        FallbackResolver<'a>,
    );

    /// Extractor builder, used to `push` parsers into before building
    /// the extractor.
    #[derive(Default)]
    pub struct Builder<'a> {
        builder: regex_filtered::Builder,
        repl: Vec<Repl<'a>>,
    }
    impl<'a> Builder<'a> {
        /// Initialise an empty builder.
        pub fn new() -> Self {
            Self {
                builder: regex_filtered::Builder::new_atom_len(3),
                repl: Vec::new(),
            }
        }

        /// Build the extractor, may be called without pushing any
        /// parser in though that is not very useful.
        pub fn build(self) -> Result<Extractor<'a>, BuildError> {
            let Self { builder, repl } = self;

            Ok(Extractor {
                matcher: builder.build()?,
                repl,
            })
        }

        /// Pushes a parser into the builder, may fail if the
        /// [`Parser::regex`] is invalid.
        pub fn push(mut self, ua: Parser<'a>) -> Result<Self, super::Error> {
            self.builder = self.builder.push(&super::rewrite_regex(&ua.regex))?;
            let r = &self.builder.regexes()[self.builder.regexes().len() - 1];
            // number of groups in regex, excluding implicit entire match group
            let groups = r.captures_len() - 1;
            self.repl.push((
                FamilyResolver::new(ua.family_replacement, groups)?,
                FallbackResolver::new(ua.v1_replacement, groups, 2),
                FallbackResolver::new(ua.v2_replacement, groups, 3),
                FallbackResolver::new(ua.v3_replacement, groups, 4),
                FallbackResolver::new(ua.v4_replacement, groups, 5),
            ));
            Ok(self)
        }

        /// Bulk loading of parsers into the builder.
        pub fn push_all<I>(self, ua: I) -> Result<Self, super::Error>
        where
            I: IntoIterator<Item = Parser<'a>>,
        {
            ua.into_iter().try_fold(self, |s, p| s.push(p))
        }
    }

    /// User Agent extractor.
    pub struct Extractor<'a> {
        matcher: regex_filtered::Regexes,
        repl: Vec<Repl<'a>>,
    }
    impl<'a> Extractor<'a> {
        /// Tries the loaded [`Parser`], upon finding the first
        /// matching [`Parser`] performs data extraction following its
        /// replacement directives and returns the result.
        ///
        /// Returns [`None`] if:
        ///
        /// - no matching parser was found
        /// - the match does not have any matching groups *and*
        ///   [`Parser::family_replacement`] is unset
        /// - [`Parser::family_replacement`] has a substitution
        ///   but there is no group in the regex
        pub fn extract(&'a self, ua: &'a str) -> Option<ValueRef<'a>> {
            let (idx, re) = self.matcher.matching(ua).next()?;
            let c = re.captures(ua)?;

            let (f, v1, v2, v3, v4) = &self.repl[idx];

            Some(ValueRef {
                family: f.resolve(&c),
                major: v1.resolve(&c),
                minor: v2.resolve(&c),
                patch: v3.resolve(&c),
                patch_minor: v4.resolve(&c),
            })
        }
    }
    /// Borrowed extracted value, borrows the content of the original
    /// parser or the content of the user agent string, unless a
    /// replacement is performed. (which is only possible for the )
    #[derive(PartialEq, Eq, Default, Debug, Clone)]
    pub struct ValueRef<'a> {
        ///
        pub family: Cow<'a, str>,
        ///
        pub major: Option<&'a str>,
        ///
        pub minor: Option<&'a str>,
        ///
        pub patch: Option<&'a str>,
        ///
        pub patch_minor: Option<&'a str>,
    }

    impl ValueRef<'_> {
        /// Converts the borrowed result into an owned one,
        /// independent from both the extractor and the user agent
        /// string.
        pub fn into_owned(self) -> Value {
            Value {
                family: self.family.into_owned(),
                major: self.major.map(|c| c.to_string()),
                minor: self.minor.map(|c| c.to_string()),
                patch: self.patch.map(|c| c.to_string()),
                patch_minor: self.patch_minor.map(|c| c.to_string()),
            }
        }
    }

    /// Owned extracted value, identical to [`ValueRef`] but not
    /// linked to either the UA string or the extractor.
    #[derive(PartialEq, Eq, Default, Debug, Clone)]
    pub struct Value {
        ///
        pub family: String,
        ///
        pub major: Option<String>,
        ///
        pub minor: Option<String>,
        ///
        pub patch: Option<String>,
        ///
        pub patch_minor: Option<String>,
    }
}

/// OS extraction module
pub mod os {
    use serde::Deserialize;
    use std::borrow::Cow;

    use regex_filtered::{BuildError, ParseError};

    use crate::resolvers::{OptResolver, Resolver};

    /// OS parser configuration
    #[derive(Deserialize, Default)]
    pub struct Parser<'a> {
        ///
        pub regex: Cow<'a, str>,
        /// Replacement for the [`ValueRef::os`], must be set if there
        /// is no capture in the [`Self::regex`], if there are
        /// captures may be fully templated (with `$n` placeholders
        /// for any group of the [`Self::regex`]).
        pub os_replacement: Option<Cow<'a, str>>,
        /// Replacement for the [`ValueRef::major`], may be fully templated.
        pub os_v1_replacement: Option<Cow<'a, str>>,
        /// Replacement for the [`ValueRef::minor`], may be fully templated.
        pub os_v2_replacement: Option<Cow<'a, str>>,
        /// Replacement for the [`ValueRef::patch`], may be fully templated.
        pub os_v3_replacement: Option<Cow<'a, str>>,
        /// Replacement for the [`ValueRef::patch_minor`], may be fully templated.
        pub os_v4_replacement: Option<Cow<'a, str>>,
    }
    /// Builder for [`Extractor`].
    #[derive(Default)]
    pub struct Builder<'a> {
        builder: regex_filtered::Builder,
        repl: Vec<(
            Resolver<'a>,
            OptResolver<'a>,
            OptResolver<'a>,
            OptResolver<'a>,
            OptResolver<'a>,
        )>,
    }
    impl<'a> Builder<'a> {
        ///
        pub fn new() -> Self {
            Self {
                builder: regex_filtered::Builder::new_atom_len(3),
                repl: Vec::new(),
            }
        }

        /// Builds the [`Extractor`], may fail if building the
        /// prefilter fails.
        pub fn build(self) -> Result<Extractor<'a>, BuildError> {
            let Self { builder, repl } = self;

            Ok(Extractor {
                matcher: builder.build()?,
                repl,
            })
        }

        /// Add a [`Parser`] configuration, fails if the regex can not
        /// be parsed, or if [`Parser::os_replacement`] is missing and
        /// the regex has no groups.
        pub fn push(mut self, os: Parser<'a>) -> Result<Self, ParseError> {
            self.builder = self.builder.push(&super::rewrite_regex(&os.regex))?;
            let r = &self.builder.regexes()[self.builder.regexes().len() - 1];
            // number of groups in regex, excluding implicit entire match group
            let groups = r.captures_len() - 1;
            self.repl.push((
                Resolver::new(os.os_replacement, groups, 1),
                OptResolver::new(os.os_v1_replacement, groups, 2),
                OptResolver::new(os.os_v2_replacement, groups, 3),
                OptResolver::new(os.os_v3_replacement, groups, 4),
                OptResolver::new(os.os_v4_replacement, groups, 5),
            ));
            Ok(self)
        }

        /// Bulk loading of parsers into the builder.
        pub fn push_all<I>(self, ua: I) -> Result<Self, ParseError>
        where
            I: IntoIterator<Item = Parser<'a>>,
        {
            ua.into_iter().try_fold(self, |s, p| s.push(p))
        }
    }

    /// OS extractor structure
    pub struct Extractor<'a> {
        matcher: regex_filtered::Regexes,
        repl: Vec<(
            Resolver<'a>,
            OptResolver<'a>,
            OptResolver<'a>,
            OptResolver<'a>,
            OptResolver<'a>,
        )>,
    }
    impl<'a> Extractor<'a> {
        /// Matches & extracts the OS data for this user agent,
        /// returns `None` if the UA string could not be matched.
        pub fn extract(&'a self, ua: &'a str) -> Option<ValueRef<'a>> {
            let (idx, re) = self.matcher.matching(ua).next()?;
            let c = re.captures(ua)?;

            let (o, v1, v2, v3, v4) = &self.repl[idx];

            Some(ValueRef {
                os: o.resolve(&c),
                major: v1.resolve(&c),
                minor: v2.resolve(&c),
                patch: v3.resolve(&c),
                patch_minor: v4.resolve(&c),
            })
        }
    }

    /// An OS extraction result.
    #[derive(PartialEq, Eq, Default, Debug, Clone)]
    pub struct ValueRef<'a> {
        ///
        pub os: Cow<'a, str>,
        ///
        pub major: Option<Cow<'a, str>>,
        ///
        pub minor: Option<Cow<'a, str>>,
        ///
        pub patch: Option<Cow<'a, str>>,
        ///
        pub patch_minor: Option<Cow<'a, str>>,
    }

    impl ValueRef<'_> {
        /// Converts a [`ValueRef`] into a [`Value`] to avoid lifetime
        /// concerns, may need to allocate and copy any data currently
        /// borrowed from a [`Parser`] or user agent string.
        pub fn into_owned(self) -> Value {
            Value {
                os: self.os.into_owned(),
                major: self.major.map(|c| c.into_owned()),
                minor: self.minor.map(|c| c.into_owned()),
                patch: self.patch.map(|c| c.into_owned()),
                patch_minor: self.patch_minor.map(|c| c.into_owned()),
            }
        }
    }

    /// Owned version of [`ValueRef`].
    #[derive(PartialEq, Eq, Default, Debug, Clone)]
    pub struct Value {
        ///
        pub os: String,
        ///
        pub major: Option<String>,
        ///
        pub minor: Option<String>,
        ///
        pub patch: Option<String>,
        ///
        pub patch_minor: Option<String>,
    }
}

/// Extraction module for the device data of the user agent string.
pub mod device {
    use serde::Deserialize;
    use std::borrow::Cow;

    use regex_filtered::{BuildError, ParseError};

    use crate::resolvers::{OptResolver, Resolver};

    /// regex flags
    #[derive(Deserialize, PartialEq, Eq)]
    pub enum Flag {
        /// Enables case-insensitive regex matching, deserializes from
        /// the string `"i"`
        #[serde(rename = "i")]
        IgnoreCase,
    }
    /// Device parser description.
    #[derive(Deserialize, Default)]
    pub struct Parser<'a> {
        /// Regex pattern to use for matching and data extraction.
        pub regex: Cow<'a, str>,
        /// Configuration flags for the regex, if any.
        pub regex_flag: Option<Flag>,
        /// Device replacement data, fully templated, must be present
        /// *or* the regex must have at least one group, which will be
        /// used instead.
        pub device_replacement: Option<Cow<'a, str>>,
        /// Brand replacement data, fully templated, optional, if
        /// missing there is no fallback.
        pub brand_replacement: Option<Cow<'a, str>>,
        /// Model replacement data, fully templated, optional, if
        /// missing will be replaced by the first group if the regex
        /// has one.
        pub model_replacement: Option<Cow<'a, str>>,
    }

    /// Extractor builder.
    #[derive(Default)]
    pub struct Builder<'a> {
        builder: regex_filtered::Builder,
        repl: Vec<(Resolver<'a>, OptResolver<'a>, OptResolver<'a>)>,
    }
    impl<'a> Builder<'a> {
        /// Creates a builder in the default configurtion, which is
        /// the only configuration.
        pub fn new() -> Self {
            Self {
                builder: regex_filtered::Builder::new_atom_len(2),
                repl: Vec::new(),
            }
        }

        /// Builds an Extractor, may fail if compiling the prefilter fails.
        pub fn build(self) -> Result<Extractor<'a>, BuildError> {
            let Self { builder, repl } = self;

            Ok(Extractor {
                matcher: builder.build()?,
                repl,
            })
        }

        /// Add a parser to the set, may fail if parsing the regex
        /// fails *or* if [`Parser::device_replacement`] is unset and
        /// [`Parser::regex`] does not have at least one group, or a
        /// templated [`Parser::device_replacement`] requests groups
        /// which [`Parser::regex`] is missing.
        pub fn push(mut self, device: Parser<'a>) -> Result<Self, ParseError> {
            self.builder = self.builder.push_opt(
                &super::rewrite_regex(&device.regex),
                regex_filtered::Options::new()
                    .case_insensitive(device.regex_flag == Some(Flag::IgnoreCase)),
            )?;
            let r = &self.builder.regexes()[self.builder.regexes().len() - 1];
            // number of groups in regex, excluding implicit entire match group
            let groups = r.captures_len() - 1;
            self.repl.push((
                Resolver::new(device.device_replacement, groups, 1),
                OptResolver::new(device.brand_replacement, 0, 999),
                OptResolver::new(device.model_replacement, groups, 1),
            ));
            Ok(self)
        }

        /// Bulk loading of parsers into the builder.
        pub fn push_all<I>(self, ua: I) -> Result<Self, ParseError>
        where
            I: IntoIterator<Item = Parser<'a>>,
        {
            ua.into_iter().try_fold(self, |s, p| s.push(p))
        }
    }

    /// Device extractor object.
    pub struct Extractor<'a> {
        matcher: regex_filtered::Regexes,
        repl: Vec<(Resolver<'a>, OptResolver<'a>, OptResolver<'a>)>,
    }
    impl<'a> Extractor<'a> {
        /// Perform data extraction from the user agent string,
        /// returns `None` if no regex in the [`Extractor`] matches
        /// the input.
        pub fn extract(&'a self, ua: &'a str) -> Option<ValueRef<'a>> {
            let (idx, re) = self.matcher.matching(ua).next()?;
            let c = re.captures(ua)?;

            let (d, v1, v2) = &self.repl[idx];

            Some(ValueRef {
                device: d.resolve(&c),
                brand: v1.resolve(&c),
                model: v2.resolve(&c),
            })
        }
    }

    /// Extracted device content, may borrow from one of the
    /// [`Parser`] or from the user agent string.
    #[derive(PartialEq, Eq, Default, Debug, Clone)]
    pub struct ValueRef<'a> {
        ///
        pub device: Cow<'a, str>,
        ///
        pub brand: Option<Cow<'a, str>>,
        ///
        pub model: Option<Cow<'a, str>>,
    }

    impl ValueRef<'_> {
        /// Converts [`Self`] to an owned [`Value`] getting rid of
        /// borrowing concerns, may need to allocate and copy if any
        /// of the attributes actually borrows from a [`Parser`] or
        /// the user agent string.
        pub fn into_owned(self) -> Value {
            Value {
                device: self.device.into_owned(),
                brand: self.brand.map(|c| c.into_owned()),
                model: self.model.map(|c| c.into_owned()),
            }
        }
    }

    /// Owned version of [`ValueRef`].
    #[derive(PartialEq, Eq, Default, Debug, Clone)]
    pub struct Value {
        ///
        pub device: String,
        ///
        pub brand: Option<String>,
        ///
        pub model: Option<String>,
    }
}

/// Rewrites a regex's character classes to ascii and bounded
/// repetitions to unbounded, the second to reduce regex memory
/// requirements, and the first for both that and to better match the
/// (inferred) semantics intended for ua-parser.
fn rewrite_regex(re: &str) -> std::borrow::Cow<'_, str> {
    let mut from = 0;
    let mut out = String::new();

    let mut it = re.char_indices();
    let mut escape = false;
    let mut inclass = 0;
    'main: while let Some((idx, c)) = it.next() {
        match c {
            '\\' if !escape => {
                escape = true;
                continue;
            }
            '{' if !escape && inclass == 0 => {
                if idx == 0 {
                    // we're repeating nothing, this regex is broken, bail
                    return re.into();
                }
                // we don't need to loop, we only want to replace {0, ...} and {1, ...}
                let Some((_, start)) = it.next() else {
                    continue;
                };
                if start != '0' && start != '1' {
                    continue;
                }

                if !matches!(it.next(), Some((_, ','))) {
                    continue;
                }

                let mut digits = 0;
                for (ri, rc) in it.by_ref() {
                    match rc {
                        '}' if digits > 2 => {
                            // here idx is the index of the start of
                            // the range and ri is the end of range
                            out.push_str(&re[from..idx]);
                            from = ri + 1;
                            out.push_str(if start == '0' { "*" } else { "+" });
                            break;
                        }
                        c if c.is_ascii_digit() => {
                            digits += 1;
                        }
                        _ => continue 'main,
                    }
                }
            }
            '[' if !escape => {
                inclass += 1;
            }
            ']' if !escape => {
                inclass -= 1;
            }
            // no need for special cases because regex allows nesting
            // character classes, whereas js or python don't \o/
            'd' if escape => {
                // idx is d so idx-1 is \\, and we want to exclude it
                out.push_str(&re[from..idx - 1]);
                from = idx + 1;
                out.push_str("[0-9]");
            }
            'D' if escape => {
                out.push_str(&re[from..idx - 1]);
                from = idx + 1;
                out.push_str("[^0-9]");
            }
            'w' if escape => {
                out.push_str(&re[from..idx - 1]);
                from = idx + 1;
                out.push_str("[A-Za-z0-9_]");
            }
            'W' if escape => {
                out.push_str(&re[from..idx - 1]);
                from = idx + 1;
                out.push_str("[^A-Za-z0-9_]");
            }
            _ => (),
        }
        escape = false;
    }

    if from == 0 {
        re.into()
    } else {
        out.push_str(&re[from..]);
        out.into()
    }
}

#[cfg(test)]
mod test_rewrite_regex {
    use super::rewrite_regex as rewrite;

    #[test]
    fn ignore_small_repetition() {
        assert_eq!(rewrite(".{0,2}x"), ".{0,2}x");
        assert_eq!(rewrite(".{0,}"), ".{0,}");
        assert_eq!(rewrite(".{1,}"), ".{1,}");
    }

    #[test]
    fn rewrite_large_repetitions() {
        assert_eq!(rewrite(".{0,20}x"), ".{0,20}x");
        assert_eq!(rewrite("(.{0,100})"), "(.*)");
        assert_eq!(rewrite("(.{1,50})"), "(.{1,50})");
        assert_eq!(rewrite(".{1,300}x"), ".+x");
    }

    #[test]
    fn rewrite_all_repetitions() {
        assert_eq!(
            rewrite("; {0,2}(T-(?:07|[^0][0-9])[^;/]{1,100}?)(?: Build|\\) AppleWebKit)"),
            "; {0,2}(T-(?:07|[^0][0-9])[^;/]+?)(?: Build|\\) AppleWebKit)",
        );
        assert_eq!(
            rewrite(
                "; {0,2}(SH\\-?[0-9][0-9][^;/]{1,100}|SBM[0-9][^;/]{1,100}?)(?: Build|\\) AppleWebKit)"
            ),
            "; {0,2}(SH\\-?[0-9][0-9][^;/]+|SBM[0-9][^;/]+?)(?: Build|\\) AppleWebKit)",
        )
    }

    #[test]
    fn ignore_non_repetitions() {
        assert_eq!(
            rewrite(r"\{1,2}"),
            r"\{1,2}",
            "if the opening brace is escaped it's not a repetition"
        );
        assert_eq!(
            rewrite("[.{1,100}]"),
            "[.{1,100}]",
            "inside a set it's not a repetition"
        );
    }

    #[test]
    fn rewrite_classes() {
        assert_eq!(rewrite(r"\dx"), "[0-9]x");
        assert_eq!(rewrite(r"\wx"), "[A-Za-z0-9_]x");
        assert_eq!(rewrite(r"[\d]x"), r"[[0-9]]x");
    }
}