grippo 0.1.3

Parse, match and scrub data at scale.
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
// Project:   grippo
// File:      src/ua/mod.rs
// Purpose:   User agents, operating systems and devices read with uap-core's rules
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! User agent strings read with a uap-core style rule table: the first rule
//! whose regex matches names the browser, the operating system or the
//! device, and its replacement fields shape the answer.
//!
//! The caller passes the table in, deserialised from `regexes.yaml` with
//! whatever reader it has. Each rule's required literals go into one
//! signature set per domain, so a string runs only the rules whose literals
//! it holds, in rule order, until one matches. Results are filled as
//! ua-parser 0.2.2 fills them, and borrow from the string and the parser
//! except where a `$N` template builds new text.

mod literals;
#[cfg(test)]
mod tests;

use std::borrow::Cow;
use std::fmt;

use serde::Deserialize;
use thiserror::Error;

use crate::MatcherTier;
use crate::strmatch::{
    BuildError, Captures, MAX_ALL_OF, ReplaceSyntax, Replacement, Signature, SignatureError,
    SignatureScratch, SignatureSet, StrMatcher,
};
use literals::Required;

/// A rule table in `regexes.yaml`'s shape. Keys the reader doesn't know are
/// ignored, and a missing list is empty.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct Rules {
    /// Browser rules, tried in order.
    #[serde(default)]
    pub user_agent_parsers: Vec<UserAgentRule>,
    /// Operating system rules, tried in order.
    #[serde(default)]
    pub os_parsers: Vec<OsRule>,
    /// Device rules, tried in order.
    #[serde(default)]
    pub device_parsers: Vec<DeviceRule>,
}

/// One browser rule.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct UserAgentRule {
    /// The pattern, in the regex crate's syntax.
    pub regex: String,
    /// The family. `$1` in it is replaced by group 1. Without it, group 1.
    pub family_replacement: Option<String>,
    /// The major version as written. Without it, group 2.
    pub v1_replacement: Option<String>,
    /// The minor version as written. Without it, group 3.
    pub v2_replacement: Option<String>,
    /// The patch as written. Without it, group 4.
    pub v3_replacement: Option<String>,
    /// The minor patch as written. Without it, group 5.
    pub v4_replacement: Option<String>,
}

/// One operating system rule. A replacement holding `$N` is a template,
/// expanded from the groups and trimmed.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct OsRule {
    /// The pattern, in the regex crate's syntax.
    pub regex: String,
    /// The family. Without it, group 1.
    pub os_replacement: Option<String>,
    /// The major version. Without it, group 2.
    pub os_v1_replacement: Option<String>,
    /// The minor version. Without it, group 3.
    pub os_v2_replacement: Option<String>,
    /// The patch. Without it, group 4.
    pub os_v3_replacement: Option<String>,
    /// The minor patch. Without it, group 5.
    pub os_v4_replacement: Option<String>,
}

/// One device rule. A replacement holding `$N` is a template, expanded from
/// the groups and trimmed.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct DeviceRule {
    /// The pattern, in the regex crate's syntax.
    pub regex: String,
    /// `i` folds ASCII case in the pattern.
    pub regex_flag: Option<RegexFlag>,
    /// The family. Without it, group 1.
    pub device_replacement: Option<String>,
    /// The brand. Without it, none.
    pub brand_replacement: Option<String>,
    /// The model. Without it, group 1.
    pub model_replacement: Option<String>,
}

/// A device rule's flag.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
pub enum RegexFlag {
    /// Written `i`: the rule folds ASCII case.
    #[serde(rename = "i")]
    IgnoreCase,
}

/// One of the three rule lists.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Domain {
    /// `user_agent_parsers`.
    UserAgent,
    /// `os_parsers`.
    Os,
    /// `device_parsers`.
    Device,
}

impl Domain {
    /// Every domain, in table order.
    pub const ALL: [Self; 3] = [Self::UserAgent, Self::Os, Self::Device];

    /// The shortest literal worth searching for, ua-parser's own lengths.
    const fn atom_len(self) -> usize {
        match self {
            Self::Device => 2,
            Self::UserAgent | Self::Os => 3,
        }
    }
}

impl fmt::Display for Domain {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::UserAgent => "user agent",
            Self::Os => "os",
            Self::Device => "device",
        })
    }
}

/// Why a rule table did not build.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum UaError {
    /// A rule's regex doesn't build.
    #[error("ua: {domain} rule {index}: {source}")]
    Pattern {
        /// The rule's list.
        domain: Domain,
        /// The rule's position in it.
        index: usize,
        /// The matcher's error.
        #[source]
        source: Box<BuildError>,
    },
    /// A browser rule's `family_replacement` names `$1` and its regex has no
    /// group, which ua-parser refuses too.
    #[error("ua: user agent rule {index}: family_replacement names $1 and the regex has no group")]
    MissingGroup {
        /// The rule's position in `user_agent_parsers`.
        index: usize,
    },
    /// A domain's literals don't build into a signature set.
    #[error("ua: {domain} rules: {source}")]
    Signatures {
        /// The list.
        domain: Domain,
        /// The set's error.
        #[source]
        source: SignatureError,
    },
}

/// The browser a rule named.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UserAgent<'a> {
    /// The browser family, empty when the rule gives none.
    pub family: Cow<'a, str>,
    /// The major version.
    pub major: Option<&'a str>,
    /// The minor version.
    pub minor: Option<&'a str>,
    /// The patch.
    pub patch: Option<&'a str>,
    /// The minor patch.
    pub patch_minor: Option<&'a str>,
}

/// The operating system a rule named.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Os<'a> {
    /// The family, empty when the rule gives none.
    pub family: Cow<'a, str>,
    /// The major version.
    pub major: Option<Cow<'a, str>>,
    /// The minor version.
    pub minor: Option<Cow<'a, str>>,
    /// The patch.
    pub patch: Option<Cow<'a, str>>,
    /// The minor patch.
    pub patch_minor: Option<Cow<'a, str>>,
}

/// The device a rule named.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Device<'a> {
    /// The family, empty when the rule gives none.
    pub family: Cow<'a, str>,
    /// The brand.
    pub brand: Option<Cow<'a, str>>,
    /// The model.
    pub model: Option<Cow<'a, str>>,
}

/// All three answers for one string. `None` where no rule matched, which
/// uap-core reports as the family `Other`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Client<'a> {
    /// The browser.
    pub user_agent: Option<UserAgent<'a>>,
    /// The operating system.
    pub os: Option<Os<'a>>,
    /// The device.
    pub device: Option<Device<'a>>,
}

/// How one output field is filled.
#[derive(Debug, Clone)]
enum Field {
    /// No value.
    None,
    /// Text from the rule, as written.
    Text(Box<str>),
    /// A group, none when it took no part or matched nothing.
    Group(usize),
    /// Every `$1` replaced by group 1, the browser family's reading.
    Family(Box<str>),
    /// `$N` expanded, trimmed, none when empty.
    Template(Replacement),
}

/// `$` then a digit, ua-parser's test for a template.
fn has_group_ref(s: &str) -> bool {
    s.as_bytes()
        .windows(2)
        .any(|w| w[0] == b'$' && w[1].is_ascii_digit())
}

/// A field that takes a `$N` template: OS fields and device fields.
fn templated(m: &StrMatcher, repl: Option<&str>, groups: usize, index: usize) -> Field {
    match repl.filter(|s| !s.trim().is_empty()) {
        Some(s) if has_group_ref(s) => Field::Template(m.replacement(s, ReplaceSyntax::Rust)),
        Some(s) => Field::Text(s.into()),
        None if groups >= index => Field::Group(index),
        None => Field::None,
    }
}

/// A browser version: the replacement as written, else the group.
fn version(repl: Option<&str>, groups: usize, index: usize) -> Field {
    match repl.filter(|s| !s.is_empty()) {
        Some(s) => Field::Text(s.into()),
        None if groups >= index => Field::Group(index),
        None => Field::None,
    }
}

/// One rule, built.
#[derive(Debug)]
struct Rule {
    matcher: StrMatcher,
    fields: [Field; 5],
}

/// One domain's rules and the signature set over their literals.
#[derive(Debug)]
struct Table {
    rules: Vec<Rule>,
    set: SignatureSet,
    /// The rule each signature came from, in signature order.
    owner: Vec<u32>,
    /// Rules with no required literal, tried on every string.
    always: Vec<u32>,
}

/// A rule's pattern text, case flag and five replacements, from any domain.
struct Source<'r> {
    regex: &'r str,
    folded: bool,
    repl: [Option<&'r str>; 5],
}

fn index_u32(i: usize, domain: Domain) -> Result<u32, UaError> {
    u32::try_from(i).map_err(|_| UaError::Signatures {
        domain,
        source: SignatureError::TooMany {
            max: u32::MAX as usize,
        },
    })
}

impl Table {
    fn build<'r>(
        domain: Domain,
        sources: impl Iterator<Item = Source<'r>>,
    ) -> Result<Self, UaError> {
        let mut rules = Vec::new();
        let mut sigs = Vec::new();
        let mut owner = Vec::new();
        let mut always = Vec::new();
        for (index, src) in sources.enumerate() {
            let rule = index_u32(index, domain)?;
            let pattern = literals::rewrite(src.regex);
            let matcher = StrMatcher::builder()
                .ascii_case_insensitive(src.folded)
                .build(&pattern)
                .map_err(|e| UaError::Pattern {
                    domain,
                    index,
                    source: Box::new(e),
                })?;
            let groups = matcher.group_len() - 1;
            let fields = Self::fields(domain, &matcher, &src.repl, groups)
                .ok_or(UaError::MissingGroup { index })?;
            // A pattern regex-syntax can't read has no literals to require.
            let required = regex_syntax::parse(&pattern).map_or(Required::Nothing, |hir| {
                literals::required(&hir, domain.atom_len())
            });
            let mut push = |all_of: &[Vec<u8>], any_of: &[Vec<u8>]| -> Result<(), UaError> {
                let mut all_of: Vec<&Vec<u8>> = all_of.iter().collect();
                all_of.sort_by_key(|l| std::cmp::Reverse(l.len()));
                all_of.truncate(MAX_ALL_OF);
                let sig = Signature::builder()
                    .all_of(all_of)
                    .any_of(any_of)
                    .ascii_case_insensitive(src.folded)
                    .build()
                    .map_err(|source| UaError::Signatures { domain, source })?;
                sigs.push(sig);
                owner.push(rule);
                Ok(())
            };
            match required {
                Required::Nothing => always.push(rule),
                Required::Clauses(clauses) => {
                    for c in &clauses {
                        push(c, &[])?;
                    }
                }
                Required::Flat { all_of, any_of } => push(&all_of, &any_of)?,
            }
            rules.push(Rule { matcher, fields });
        }
        let set =
            SignatureSet::new(&sigs).map_err(|source| UaError::Signatures { domain, source })?;
        Ok(Self {
            rules,
            set,
            owner,
            always,
        })
    }

    /// The five fields as ua-parser 0.2.2's resolvers read them. `None` for a
    /// browser family that names `$1` with no group to take it from.
    fn fields(
        domain: Domain,
        m: &StrMatcher,
        repl: &[Option<&str>; 5],
        groups: usize,
    ) -> Option<[Field; 5]> {
        Some(match domain {
            Domain::UserAgent => {
                let family = match repl[0] {
                    Some(s) if s.contains("$1") => {
                        if groups < 1 {
                            return None;
                        }
                        Field::Family(s.into())
                    }
                    Some(s) if !s.is_empty() => Field::Text(s.into()),
                    _ if groups >= 1 => Field::Group(1),
                    _ => Field::None,
                };
                [
                    family,
                    version(repl[1], groups, 2),
                    version(repl[2], groups, 3),
                    version(repl[3], groups, 4),
                    version(repl[4], groups, 5),
                ]
            }
            Domain::Os => [
                templated(m, repl[0], groups, 1),
                templated(m, repl[1], groups, 2),
                templated(m, repl[2], groups, 3),
                templated(m, repl[3], groups, 4),
                templated(m, repl[4], groups, 5),
            ],
            Domain::Device => [
                templated(m, repl[0], groups, 1),
                templated(m, repl[1], 0, 1),
                templated(m, repl[2], groups, 1),
                Field::None,
                Field::None,
            ],
        })
    }

    fn scratch(&self) -> TableScratch {
        TableScratch {
            sigs: self.set.scratch(),
            candidates: Vec::with_capacity(self.rules.len().min(64)),
            caps: self
                .rules
                .iter()
                .map(|r| r.matcher.create_captures())
                .collect(),
        }
    }

    /// The candidate rules for `hay`, in rule order, into `s.candidates`.
    fn candidates(&self, hay: &[u8], s: &mut TableScratch) {
        let out = &mut s.candidates;
        out.clear();
        // The set reports in signature order and a rule's signatures sit
        // together, so a repeat is always the one just pushed.
        self.set.for_each_match(hay, &mut s.sigs, |m| {
            let rule = self.owner[m.index];
            if out.last() != Some(&rule) {
                out.push(rule);
            }
        });
        if !self.always.is_empty() {
            out.extend_from_slice(&self.always);
            out.sort_unstable();
        }
    }

    /// The first rule that matches `hay`, its groups left in `s.caps`.
    fn first(&self, hay: &[u8], s: &mut TableScratch) -> Option<usize> {
        if s.caps.len() != self.rules.len() {
            *s = self.scratch();
        }
        self.candidates(hay, s);
        s.candidates
            .iter()
            .map(|&r| r as usize)
            .find(|&r| self.rules[r].matcher.captures_into(hay, &mut s.caps[r]))
    }
}

/// Group `index` of the match, none when it took no part, matched nothing
/// or falls off a character boundary.
fn group<'a>(ua: &'a str, caps: &Captures, index: usize) -> Option<&'a str> {
    caps.get(index)
        .and_then(|m| ua.get(m.start..m.end))
        .filter(|s| !s.is_empty())
}

/// Fill `field` from the match.
fn resolve<'a>(
    field: &'a Field,
    ua: &'a str,
    caps: &Captures,
    buf: &mut Vec<u8>,
) -> Option<Cow<'a, str>> {
    match field {
        Field::None => None,
        Field::Text(s) => Some(Cow::Borrowed(s)),
        Field::Group(i) => group(ua, caps, *i).map(Cow::Borrowed),
        Field::Family(t) => Some(Cow::Owned(
            t.replace("$1", group(ua, caps, 1).unwrap_or("")),
        )),
        Field::Template(rep) => {
            buf.clear();
            caps.expand(ua.as_bytes(), rep, buf);
            let text = String::from_utf8_lossy(buf);
            let trimmed = text.trim();
            (!trimmed.is_empty()).then(|| Cow::Owned(trimmed.to_owned()))
        }
    }
}

/// A browser version, never owned: only text and groups fill one.
fn borrowed<'a>(field: &'a Field, ua: &'a str, caps: &Captures) -> Option<&'a str> {
    match field {
        Field::Text(s) => Some(s),
        Field::Group(i) => group(ua, caps, *i),
        Field::None | Field::Family(_) | Field::Template(_) => None,
    }
}

/// Per-domain buffers.
#[derive(Debug, Clone)]
struct TableScratch {
    sigs: SignatureScratch,
    candidates: Vec<u32>,
    caps: Vec<Captures>,
}

/// Per-thread buffers, reused across strings so a lookup allocates only for
/// a template's text. One from another parser is rebuilt on first use.
#[derive(Debug, Clone)]
pub struct UaScratch {
    tables: [TableScratch; 3],
    buf: Vec<u8>,
}

/// A rule table built once and shared across threads. Each thread brings
/// its own [`UaScratch`].
///
/// ```
/// use grippo::ua::{Rules, UaParser, UserAgentRule};
///
/// let rules = Rules {
///     user_agent_parsers: vec![UserAgentRule {
///         regex: r"(Firefox)/(\d+)\.(\d+)".into(),
///         ..UserAgentRule::default()
///     }],
///     ..Rules::default()
/// };
/// let parser = UaParser::new(&rules)?;
/// let mut scratch = parser.scratch();
/// let ua = parser.user_agent("Mozilla/5.0 Firefox/133.0", &mut scratch).unwrap();
/// assert_eq!((&*ua.family, ua.major, ua.minor), ("Firefox", Some("133"), Some("0")));
/// assert!(parser.os("Mozilla/5.0 Firefox/133.0", &mut scratch).is_none());
/// # Ok::<(), grippo::ua::UaError>(())
/// ```
#[derive(Debug)]
pub struct UaParser {
    tables: [Table; 3],
}

impl UaParser {
    /// Build every rule in `rules`, each read as ua-parser 0.2.2 reads it:
    /// `\d` and `\w` as ASCII, and a `{0,N}` or `{1,N}` with N of 100 or
    /// more as `*` or `+`.
    ///
    /// # Errors
    ///
    /// [`UaError::Pattern`] for a regex that doesn't build,
    /// [`UaError::MissingGroup`] for a browser family template with no group
    /// to fill it, and [`UaError::Signatures`] when a domain's literals don't
    /// build into a set.
    pub fn new(rules: &Rules) -> Result<Self, UaError> {
        let user_agent = Table::build(
            Domain::UserAgent,
            rules.user_agent_parsers.iter().map(|r| Source {
                regex: &r.regex,
                folded: false,
                repl: [
                    r.family_replacement.as_deref(),
                    r.v1_replacement.as_deref(),
                    r.v2_replacement.as_deref(),
                    r.v3_replacement.as_deref(),
                    r.v4_replacement.as_deref(),
                ],
            }),
        )?;
        let os = Table::build(
            Domain::Os,
            rules.os_parsers.iter().map(|r| Source {
                regex: &r.regex,
                folded: false,
                repl: [
                    r.os_replacement.as_deref(),
                    r.os_v1_replacement.as_deref(),
                    r.os_v2_replacement.as_deref(),
                    r.os_v3_replacement.as_deref(),
                    r.os_v4_replacement.as_deref(),
                ],
            }),
        )?;
        let device = Table::build(
            Domain::Device,
            rules.device_parsers.iter().map(|r| Source {
                regex: &r.regex,
                folded: r.regex_flag == Some(RegexFlag::IgnoreCase),
                repl: [
                    r.device_replacement.as_deref(),
                    r.brand_replacement.as_deref(),
                    r.model_replacement.as_deref(),
                    None,
                    None,
                ],
            }),
        )?;
        Ok(Self {
            tables: [user_agent, os, device],
        })
    }

    /// Buffers for one thread.
    #[must_use]
    pub fn scratch(&self) -> UaScratch {
        UaScratch {
            tables: self.tables.each_ref().map(Table::scratch),
            buf: Vec::new(),
        }
    }

    /// How many of `domain`'s rules run on each tier, indexed by
    /// [`MatcherTier::index`].
    #[must_use]
    pub fn tier_counts(&self, domain: Domain) -> [usize; MatcherTier::ALL.len()] {
        let mut counts = [0_usize; MatcherTier::ALL.len()];
        for r in &self.table(domain).rules {
            counts[r.matcher.tier().index()] += 1;
        }
        counts
    }

    const fn table(&self, domain: Domain) -> &Table {
        match domain {
            Domain::UserAgent => &self.tables[0],
            Domain::Os => &self.tables[1],
            Domain::Device => &self.tables[2],
        }
    }

    /// The first matching rule of `domain` and its fields, its groups in
    /// the scratch.
    fn lookup<'s>(
        &self,
        domain: Domain,
        ua: &str,
        scratch: &'s mut UaScratch,
    ) -> Option<(&[Field; 5], &'s Captures, &'s mut Vec<u8>)> {
        let table = self.table(domain);
        let s = &mut scratch.tables[domain as usize];
        let rule = table.first(ua.as_bytes(), s)?;
        Some((&table.rules[rule].fields, &s.caps[rule], &mut scratch.buf))
    }

    /// The browser `ua` names, `None` when no rule matches.
    #[must_use]
    pub fn user_agent<'a>(&'a self, ua: &'a str, scratch: &mut UaScratch) -> Option<UserAgent<'a>> {
        let (f, caps, buf) = self.lookup(Domain::UserAgent, ua, scratch)?;
        Some(UserAgent {
            family: resolve(&f[0], ua, caps, buf).unwrap_or(Cow::Borrowed("")),
            major: borrowed(&f[1], ua, caps),
            minor: borrowed(&f[2], ua, caps),
            patch: borrowed(&f[3], ua, caps),
            patch_minor: borrowed(&f[4], ua, caps),
        })
    }

    /// The operating system `ua` names, `None` when no rule matches.
    #[must_use]
    pub fn os<'a>(&'a self, ua: &'a str, scratch: &mut UaScratch) -> Option<Os<'a>> {
        let (f, caps, buf) = self.lookup(Domain::Os, ua, scratch)?;
        Some(Os {
            family: resolve(&f[0], ua, caps, buf).unwrap_or(Cow::Borrowed("")),
            major: resolve(&f[1], ua, caps, buf),
            minor: resolve(&f[2], ua, caps, buf),
            patch: resolve(&f[3], ua, caps, buf),
            patch_minor: resolve(&f[4], ua, caps, buf),
        })
    }

    /// The device `ua` names, `None` when no rule matches.
    #[must_use]
    pub fn device<'a>(&'a self, ua: &'a str, scratch: &mut UaScratch) -> Option<Device<'a>> {
        let (f, caps, buf) = self.lookup(Domain::Device, ua, scratch)?;
        Some(Device {
            family: resolve(&f[0], ua, caps, buf).unwrap_or(Cow::Borrowed("")),
            brand: resolve(&f[1], ua, caps, buf),
            model: resolve(&f[2], ua, caps, buf),
        })
    }

    /// The browser, operating system and device `ua` names.
    #[must_use]
    pub fn parse<'a>(&'a self, ua: &'a str, scratch: &mut UaScratch) -> Client<'a> {
        Client {
            user_agent: self.user_agent(ua, scratch),
            os: self.os(ua, scratch),
            device: self.device(ua, scratch),
        }
    }
}