Skip to main content

unityrs_export/ngui/keys/
literal.rs

1//! Validation's checks of a template (`docs/BATCH_SPEC.md` 2.1): it
2//! parses for its kind, and what its literals fix passes 2.3's rules in
3//! every expansion. Each `/`-separated segment made only of literals passes
4//! the segment rules (`empty_segment`, `dot_segment`, `segment_too_long`,
5//! `reserved_name`); a template that starts with a literal passes
6//! `leading_slash` and `reserved_prefix` on it, the key `_unityrs` itself
7//! refused when that literal is the whole template; one that ends with a
8//! literal passes `trailing_slash`. Everything else is each expansion's.
9//!
10//! A member path (4.7) takes every rule but `reserved_prefix` and
11//! `reserved_name`, so its literals are not checked against them either.
12//!
13//! The check reads the text once through [`super::tokens`] and keeps a
14//! few bytes of the segment it is in, so a template of any length that
15//! parses costs no allocation. A refusal for an unknown or a disallowed
16//! placeholder allocates its name once ([`TemplateError::Unknown`],
17//! [`TemplateError::NotAllowed`], from [`super::tokens`]), on the error
18//! path only.
19
20use super::{
21    KeyRule, RESERVED_NAME, RESERVED_PREFIX, Rules, SEGMENT_MAX, TemplateError, TemplateKind,
22    Token, dot_segment, tokens,
23};
24
25/// Why validation refuses a template: rule `template` (section 10).
26#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
27pub enum TemplateRefusal {
28    /// It does not parse for its kind.
29    #[error(transparent)]
30    Parse(#[from] TemplateError),
31    /// A literal part breaks this rule of 2.3 in every expansion: the
32    /// first of those it breaks, in 2.3's order.
33    #[error("a literal part breaks {}", .0.name())]
34    Literal(KeyRule),
35}
36
37/// Checks a key template of `kind` (an output's key, 2.1): it parses, and
38/// its literals pass 2.3's rules as 2.1 says.
39pub fn check_template(text: &str, kind: TemplateKind) -> Result<(), TemplateRefusal> {
40    literal(text, kind, Rules::Key)
41}
42
43/// Checks an archive member's path template of `kind` (1.7, 4.7):
44/// [`check_template`] without `reserved_prefix` and `reserved_name`.
45pub fn check_member_template(text: &str, kind: TemplateKind) -> Result<(), TemplateRefusal> {
46    literal(text, kind, Rules::Member)
47}
48
49/// The most bytes of a segment's start the checks read: `.unityrs-tmp-`.
50const HEAD: usize = RESERVED_NAME.len();
51
52/// The segment being read.
53struct Segment {
54    /// Whether every piece of it so far is a literal.
55    literal: bool,
56    /// Its bytes so far, while it is literal.
57    len: usize,
58    /// Its first [`HEAD`] bytes.
59    head: [u8; HEAD],
60}
61
62impl Segment {
63    const fn new() -> Self {
64        Self {
65            literal: true,
66            len: 0,
67            head: [0; HEAD],
68        }
69    }
70
71    fn push(&mut self, b: u8) {
72        if let Some(slot) = self.head.get_mut(self.len) {
73            *slot = b;
74        }
75        self.len += 1;
76    }
77
78    fn head(&self) -> &[u8] {
79        self.head.get(..self.len.min(HEAD)).unwrap_or_default()
80    }
81
82    /// The rule a whole literal segment breaks, if any, `first` or `last`
83    /// in the template: an empty one is a leading or trailing `/` there
84    /// (the key's own rule), and `//` inside.
85    fn rule(&self, first: bool, last: bool, which: Rules) -> Option<KeyRule> {
86        if !self.literal {
87            return None;
88        }
89        if self.len == 0 {
90            return Some(if first {
91                KeyRule::LeadingSlash
92            } else if last {
93                KeyRule::TrailingSlash
94            } else {
95                KeyRule::EmptySegment
96            });
97        }
98        if std::str::from_utf8(self.head()).is_ok_and(|s| self.len <= 2 && dot_segment(s)) {
99            return Some(KeyRule::DotSegment);
100        }
101        if self.len > SEGMENT_MAX {
102            return Some(KeyRule::SegmentTooLong);
103        }
104        if which == Rules::Key && self.head() == RESERVED_NAME.as_bytes() {
105            return Some(KeyRule::ReservedName);
106        }
107        None
108    }
109}
110
111fn literal(text: &str, kind: TemplateKind, which: Rules) -> Result<(), TemplateRefusal> {
112    if text.is_empty() {
113        return Err(TemplateError::Empty.into());
114    }
115    let mut worst: Option<KeyRule> = None;
116    let mut broke = |rule: Option<KeyRule>| {
117        if let Some(r) = rule {
118            worst = Some(worst.map_or(r, |w| w.min(r)));
119        }
120    };
121    let mut segment = Segment::new();
122    let mut first = true;
123    // The literal the template starts with, while no variable has come.
124    let mut lead = Segment::new();
125    let mut leading = true;
126    for token in tokens(text, kind) {
127        match token? {
128            Token::Var(_) => {
129                segment.literal = false;
130                leading = false;
131            }
132            Token::Lit(s) => {
133                for &b in s.as_bytes() {
134                    if leading {
135                        lead.push(b);
136                    }
137                    if b == b'/' {
138                        broke(segment.rule(first, false, which));
139                        segment = Segment::new();
140                        first = false;
141                    } else if segment.literal {
142                        segment.push(b);
143                    }
144                }
145            }
146        }
147    }
148    broke(segment.rule(first, true, which));
149    let prefix = RESERVED_PREFIX.as_bytes();
150    if which == Rules::Key && lead.head().starts_with(prefix) {
151        // `_unityrs/...`, or `_unityrs` as the whole template.
152        let whole = leading && lead.len == prefix.len();
153        if whole || lead.head().get(prefix.len()) == Some(&b'/') {
154            broke(Some(KeyRule::ReservedPrefix));
155        }
156    }
157    match worst {
158        Some(rule) => Err(TemplateRefusal::Literal(rule)),
159        None => Ok(()),
160    }
161}