iri_string/template/
components.rs

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
//! Syntax components of URI templates.

use core::mem;

use crate::parser::str::find_split_hole;
use crate::template::error::Error;
use crate::template::parser::validate as validate_parser;

/// Expression body.
///
/// This does not contain the wrapping braces (`{` and `}`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct ExprBody<'a>(&'a str);

impl<'a> ExprBody<'a> {
    /// Creates a new expression body.
    ///
    /// # Precondition
    ///
    /// The given string should be a valid expression body.
    #[inline]
    #[must_use]
    pub(super) fn new(s: &'a str) -> Self {
        debug_assert!(
            !s.is_empty(),
            "[precondition] valid expression body is not empty"
        );

        Self(s)
    }

    /// Decomposes the expression into an `operator` and `variable-list`.
    ///
    /// # Panics
    ///
    /// May panic if the input is invalid.
    #[must_use]
    pub(super) fn decompose(&self) -> (Operator, VarListStr<'a>) {
        debug_assert!(
            !self.0.is_empty(),
            "[precondition] valid expression body is not empty"
        );
        let first = self.0.as_bytes()[0];
        if first.is_ascii_alphanumeric() || (first == b'_') || (first == b'%') {
            // The first byte is a part of the variable list.
            (Operator::String, VarListStr::new(self.0))
        } else {
            let op = Operator::from_byte(first).unwrap_or_else(|| {
                unreachable!(
                    "[precondition] valid expression has (optional) \
                     valid operator, but got a byte {first:#02x?}"
                )
            });
            (op, VarListStr::new(&self.0[1..]))
        }
    }

    /// Returns the raw expression in a string slice.
    #[inline]
    #[must_use]
    pub(super) fn as_str(&self) -> &'a str {
        self.0
    }
}

/// Variable name.
// QUESTION: Should hexdigits in percent-encoded triplets be compared case sensitively?
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct VarName<'a>(&'a str);

impl<'a> VarName<'a> {
    /// Creates a `VarName` from the trusted string.
    ///
    /// # Precondition
    ///
    /// The given string should be a valid variable name.
    #[inline]
    #[must_use]
    pub(super) fn from_trusted(s: &'a str) -> Self {
        Self(s)
    }

    /// Creates a `VarName` from the string.
    ///
    /// # Examples
    ///
    /// ```
    /// # use iri_string::template::Error;
    /// use iri_string::template::context::VarName;
    ///
    /// let name = VarName::new("hello")?;
    /// assert_eq!(name.as_str(), "hello");
    ///
    /// assert!(VarName::new("0+non-variable-name").is_err());
    ///
    /// # Ok::<_, Error>(())
    /// ```
    #[inline]
    pub fn new(s: &'a str) -> Result<Self, Error> {
        match validate_parser::validate_varname(s, 0) {
            Ok(_) => Ok(Self::from_trusted(s)),
            Err(e) => Err(e),
        }
    }

    /// Returns the varibale name.
    #[inline]
    #[must_use]
    pub fn as_str(&self) -> &'a str {
        self.0
    }
}

/// Variable specifier.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct VarSpec<'a> {
    /// Variable name.
    name: VarName<'a>,
    /// Variable modifier.
    modifier: Modifier,
}

impl<'a> VarSpec<'a> {
    /// Returns the varibale name.
    #[inline]
    #[must_use]
    pub(super) fn name(&self) -> VarName<'a> {
        self.name
    }

    /// Returns the modifier.
    #[inline]
    #[must_use]
    pub(super) fn modifier(&self) -> Modifier {
        self.modifier
    }

    /// Parses the trusted varspec string.
    ///
    /// # Panics
    ///
    /// May panic if the input is invalid.
    #[must_use]
    pub(super) fn parse_trusted(s: &'a str) -> Self {
        if let Some(varname) = s.strip_suffix('*') {
            // `varname "*"`.
            return Self {
                name: VarName::from_trusted(varname),
                modifier: Modifier::Explode,
            };
        }
        // `varname ":" max-length` or `varname`.
        match find_split_hole(s, b':') {
            Some((varname, max_len)) => {
                let max_len: u16 = max_len
                    .parse()
                    .expect("[precondition] the input should be valid `varspec`");
                Self {
                    name: VarName::from_trusted(varname),
                    modifier: Modifier::MaxLen(max_len),
                }
            }
            None => Self {
                name: VarName(s),
                modifier: Modifier::None,
            },
        }
    }
}

/// Variable list.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct VarListStr<'a>(&'a str);

impl<'a> VarListStr<'a> {
    /// Creates a new variable list.
    ///
    /// # Precondition
    ///
    /// The given string should be a valid variable list.
    #[inline]
    #[must_use]
    pub(super) fn new(s: &'a str) -> Self {
        Self(s)
    }
}

impl<'a> IntoIterator for VarListStr<'a> {
    type IntoIter = VarListIter<'a>;
    type Item = (usize, VarSpec<'a>);

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        VarListIter { rest: self.0 }
    }
}

/// Iterator of variable specs.
#[derive(Debug, Clone)]
pub(super) struct VarListIter<'a> {
    /// Remaining input.
    rest: &'a str,
}

impl<'a> Iterator for VarListIter<'a> {
    /// A pair of the length of the varspec and the varspec itself.
    type Item = (usize, VarSpec<'a>);

    fn next(&mut self) -> Option<Self::Item> {
        match find_split_hole(self.rest, b',') {
            Some((prefix, new_rest)) => {
                self.rest = new_rest;
                Some((prefix.len(), VarSpec::parse_trusted(prefix)))
            }
            None => {
                if self.rest.is_empty() {
                    None
                } else {
                    Some((
                        self.rest.len(),
                        VarSpec::parse_trusted(mem::take(&mut self.rest)),
                    ))
                }
            }
        }
    }
}

/// Variable modifier.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(super) enum Modifier {
    /// No modifiers.
    None,
    /// Max length, greater than 0 and less than 10000.
    MaxLen(u16),
    /// Explode the variable, e.g. the var spec has `*`.
    Explode,
}

/// Operator that is possibly reserved for future extension.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(super) enum MaybeOperator {
    /// Working operator.
    Operator(Operator),
    /// Reserved for future extensions.
    Reserved(OperatorReservedForFuture),
}

impl MaybeOperator {
    /// Returns the operator for the given character.
    pub(super) fn from_byte(b: u8) -> Option<Self> {
        match b {
            b'+' => Some(Self::Operator(Operator::Reserved)),
            b'#' => Some(Self::Operator(Operator::Fragment)),
            b'.' => Some(Self::Operator(Operator::Label)),
            b'/' => Some(Self::Operator(Operator::PathSegments)),
            b';' => Some(Self::Operator(Operator::PathParams)),
            b'?' => Some(Self::Operator(Operator::FormQuery)),
            b'&' => Some(Self::Operator(Operator::FormQueryCont)),
            b'=' => Some(Self::Reserved(OperatorReservedForFuture::Equals)),
            b',' => Some(Self::Reserved(OperatorReservedForFuture::Comma)),
            b'!' => Some(Self::Reserved(OperatorReservedForFuture::Exclamation)),
            b'@' => Some(Self::Reserved(OperatorReservedForFuture::AtSign)),
            b'|' => Some(Self::Reserved(OperatorReservedForFuture::Pipe)),
            _ => None,
        }
    }
}

/// Working operator.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(super) enum Operator {
    /// No operator. String expansion.
    String,
    /// Reserved expansion by `+`.
    Reserved,
    /// Fragment expansion by `#`.
    Fragment,
    /// Label expansion by `.`.
    Label,
    /// Path segments by `/`.
    PathSegments,
    /// Path-style parameters by `;`.
    PathParams,
    /// Form-style query by `?`.
    FormQuery,
    /// Form-style query continuation by `&`.
    FormQueryCont,
}

impl Operator {
    /// Returns the operator for the given character.
    #[must_use]
    pub(super) fn from_byte(b: u8) -> Option<Self> {
        match b {
            b'+' => Some(Self::Reserved),
            b'#' => Some(Self::Fragment),
            b'.' => Some(Self::Label),
            b'/' => Some(Self::PathSegments),
            b';' => Some(Self::PathParams),
            b'?' => Some(Self::FormQuery),
            b'&' => Some(Self::FormQueryCont),
            _ => None,
        }
    }

    /// Returns the string length of the operator.
    #[inline]
    #[must_use]
    pub(super) const fn len(self) -> usize {
        if matches!(self, Self::String) {
            0
        } else {
            1
        }
    }
}

/// Operator reserved for future extension.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(super) enum OperatorReservedForFuture {
    /// Reserved `=` operator.
    Equals,
    /// Reserved `,` operator.
    Comma,
    /// Reserved `!` operator.
    Exclamation,
    /// Reserved `@` operator.
    AtSign,
    /// Reserved `|` operator.
    Pipe,
}