uri-template-system-core 0.1.5

URI Template System Core (prefer top-level URI Template System)
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
pub mod modifier;
pub mod operator;
pub mod variable;

use std::fmt::Write;

use crate::{
    string::{
        satisfy,
        Encode,
        Satisfy,
    },
    template::{
        component::expression::{
            modifier::Modifier,
            operator::Operator,
            variable::VariableList,
        },
        Expand,
        ExpandError,
        Parse,
        ParseError,
        TryParse,
    },
    value::{
        Value,
        Values,
    },
};

// =============================================================================
// Expression
// =============================================================================

// Types

#[derive(Debug, Eq, PartialEq)]
pub struct Expression<'t> {
    operator: Option<Operator>,
    variable_list: VariableList<'t>,
}

impl<'t> Expression<'t> {
    const fn new(operator: Option<Operator>, variable_list: VariableList<'t>) -> Self {
        Self {
            operator,
            variable_list,
        }
    }
}

// -----------------------------------------------------------------------------

// Parse

impl<'t> TryParse<'t> for Expression<'t> {
    fn try_parse(raw: &'t str, global: usize) -> Result<(usize, Self), ParseError> {
        let mut parsed_operator = None;
        let mut parsed_variable_list = Vec::new();
        let mut state = ExpressionState::default();

        loop {
            let rest = &raw[state.position..];

            match &state.next {
                ExpressionNext::OpeningBrace if rest.starts_with('{') => {
                    state.next = ExpressionNext::Operator;
                    state.position += 1;
                }
                ExpressionNext::OpeningBrace => {
                    return Err(ParseError::UnexpectedInput {
                        position: global + state.position,
                        message: "unexpected input when parsing expression component".into(),
                        expected: "opening brace ('{')".into(),
                    });
                }
                ExpressionNext::Operator => {
                    let (position, operator) =
                        Option::<Operator>::parse(rest, global + state.position);

                    parsed_operator = operator;
                    state.next = ExpressionNext::VariableList;
                    state.position += position;
                }
                ExpressionNext::VariableList => {
                    match VariableList::try_parse(rest, global + state.position) {
                        Ok((position, variable_list)) => {
                            parsed_variable_list.extend(variable_list);
                            state.next = ExpressionNext::ClosingBrace;
                            state.position += position;
                        }
                        Err(err) => return Err(err),
                    }
                }
                ExpressionNext::ClosingBrace if rest.starts_with('}') => {
                    state.position += 1;

                    return Ok((
                        state.position,
                        Self::new(parsed_operator, parsed_variable_list),
                    ));
                }
                ExpressionNext::ClosingBrace => {
                    return Err(ParseError::UnexpectedInput {
                        position: global + state.position,
                        message: "unexpected input when parsing expression component".into(),
                        expected: "closing brace ('}')".into(),
                    });
                }
            }
        }
    }
}

#[derive(Default)]
struct ExpressionState {
    next: ExpressionNext,
    position: usize,
}

#[derive(Default)]
enum ExpressionNext {
    #[default]
    OpeningBrace,
    Operator,
    VariableList,
    ClosingBrace,
}

// -----------------------------------------------------------------------------

// Expand

impl<'t> Expand for Expression<'t> {
    #[allow(clippy::cognitive_complexity)] // TODO: Reduce?
    #[allow(clippy::equatable_if_let)]
    #[allow(clippy::too_many_lines)]
    fn expand(&self, values: &Values, write: &mut impl Write) -> Result<(), ExpandError> {
        let behaviour = self
            .operator
            .as_ref()
            .map_or(&operator::DEFAULT_BEHAVIOUR, Operator::behaviour);

        let satisfier = behaviour.allow.satisfier();
        let mut first = true;

        for (var_name, modifier) in &self.variable_list {
            // Lookup the value for the scanned variable name, and then
            //
            // * If the varname is unknown or corresponds to a variable with an undefined
            //   value (Section 2.3), then skip to the next varspec.

            let value = match values.get(var_name.name()) {
                Some(value) if value.defined() => value,
                _ => continue,
            };

            // * If this is the first defined variable for this expression, append the first
            //   string for this expression type to the result string and remember that it
            //   has been done.  Otherwise, append the sep string to the result string.

            if first {
                if let Some(c) = behaviour.first {
                    write.write_char(c)?;
                }

                first = false;
            } else {
                write.write_char(behaviour.sep)?;
            }

            if let Value::Item(value) = value {
                // If this variable's value is a string, then

                if behaviour.named {
                    // * if named is true, append the varname to the result string using the same
                    //   encoding process as for literals, and

                    write.encode(var_name.name(), &satisfy::unreserved_or_reserved())?;

                    if value.is_empty() {
                        // + if the value is empty, append the ifemp string to the result string and
                        //   skip to the next varspec;

                        if let Some(c) = behaviour.ifemp {
                            write.write_char(c)?;
                        }
                    } else {
                        // + otherwise, append "=" to the result string.

                        write.write_char('=')?;
                    }
                }

                match modifier {
                    Some(Modifier::Prefix(length)) => {
                        // * if a prefix modifier is present and the prefix length is less than the
                        //   value string length in number of Unicode characters, append that number
                        //   of characters from the beginning of the value string to the result
                        //   string, after pct-encoding any characters that are not in the allow
                        //   set, while taking care not to split multi-octet or pct-encoded triplet
                        //   characters that represent a single Unicode code point;

                        let pos: usize = value.chars().take(*length).map(char::len_utf8).sum();

                        write.encode(&value[..pos], &satisfier)?;
                    }
                    _ => {
                        // * otherwise, append the value to the result string after pct-encoding any
                        //   characters that are not in the allow set.

                        write.encode(value, &satisfier)?;
                    }
                };
            } else if let Some(Modifier::Explode) = modifier {
                // else if an explode modifier is given, then

                if behaviour.named {
                    // * if named is true, then for each defined list member or array (name, value)
                    //   pair with a defined value, do:

                    if let Value::AssociativeArray(value) = value {
                        let mut first = true;

                        for (name, value) in value {
                            // + if this is not the first defined member/value, append the sep
                            //   string to the result string;

                            if first {
                                first = false;
                            } else {
                                write.write_char(behaviour.sep)?;
                            }

                            // + if this is a pair, append the name to the result string using the
                            //   same encoding process as for literals;

                            write.encode(name, &satisfy::unreserved_or_reserved())?;

                            // + if the member/value is empty, append the ifemp string to the result
                            //   string; otherwise, append "=" and the member/value to the result
                            //   string, after pct-encoding any member/value characters that are not
                            //   in the allow set.

                            if value.is_empty() {
                                if let Some(c) = behaviour.ifemp {
                                    write.write_char(c)?;
                                }
                            } else {
                                write.write_char('=')?;
                                write.encode(value, &satisfier)?;
                            }
                        }
                    } else if let Value::List(value) = value {
                        let mut first = true;

                        for value in value {
                            // + if this is not the first defined member/value, append the sep
                            //   string to the result string;

                            if first {
                                first = false;
                            } else {
                                write.write_char(behaviour.sep)?;
                            }

                            // + if this is a list, append the varname to the result string using
                            //   the same encoding process as for literals;

                            write.encode(var_name.name(), &satisfy::unreserved_or_reserved())?;

                            // + if the member/value is empty, append the ifemp string to the result
                            //   string; otherwise, append "=" and the member/value to the result
                            //   string, after pct-encoding any member/value characters that are not
                            //   in the allow set.

                            if value.is_empty() {
                                if let Some(c) = behaviour.ifemp {
                                    write.write_char(c)?;
                                }
                            } else {
                                write.write_char('=')?;
                                write.encode(value, &satisfier)?;
                            }
                        }
                    }
                } else {
                    // * else if named is false, then

                    if let Value::AssociativeArray(value) = value {
                        // + if this is an array of (name, value) pairs, append each pair with a
                        //   defined value to the result string as "name=value", after pct-encoding
                        //   any characters that are not in the allow set, with the sep string
                        //   appended to the result between each defined pair.

                        let mut first = true;

                        for (name, value) in value {
                            if !value.is_empty() {
                                if first {
                                    first = false;
                                } else {
                                    write.write_char(behaviour.sep)?;
                                }
                            }

                            write.encode(name, &satisfier)?;
                            write.write_char('=')?;
                            write.encode(value, &satisfier)?;
                        }
                    } else if let Value::List(value) = value {
                        // + if this is a list, append each defined list member to the result
                        //   string, after pct-encoding any characters that are not in the allow
                        //   set, with the sep string appended to the result between each defined
                        //   list member.

                        let mut first = true;

                        for value in value {
                            if !value.is_empty() {
                                if first {
                                    first = false;
                                } else {
                                    write.write_char(behaviour.sep)?;
                                }
                            }

                            write.encode(value, &satisfier)?;
                        }
                    }
                }
            } else {
                // else if no explode modifier is given, then

                if behaviour.named {
                    // * if named is true, append the varname to the result string using the same
                    //   encoding process as for literals, and

                    write.encode(var_name.name(), &satisfy::unreserved_or_reserved())?;

                    // + if the value is empty, append the ifemp string to the result string and
                    //   skip to the next varspec;
                    // + otherwise, append "=" to the result string; and

                    // NOTE: Empty values are not meaningful currently, so this logic is skipped for
                    // now

                    write.write_char('=')?;
                }

                if let Value::AssociativeArray(value) = value {
                    // * if this variable's value is an associative array or any other form of
                    //   paired (name, value) structure, append each pair with defined value to the
                    //   result string as "name,value", after pct-encoding any characters that are
                    //   not in the allow set, with a comma (",") appended to the result between
                    //   each defined pair.

                    let mut first = true;

                    for (name, value) in value {
                        if !value.is_empty() {
                            if first {
                                first = false;
                            } else {
                                write.write_char(',')?;
                            }

                            write.encode(name, &satisfier)?;
                            write.write_char(',')?;
                            write.encode(value, &satisfier)?;
                        }
                    }
                } else if let Value::List(value) = value {
                    // * if this variable's value is a list, append each defined list member to the
                    //   result string, after pct-encoding any characters that are not in the allow
                    //   set, with a comma (",") appended to the result between each defined list
                    //   member;

                    let mut first = true;

                    for value in value {
                        if !value.is_empty() {
                            if first {
                                first = false;
                            } else {
                                write.write_char(',')?;
                            }

                            write.encode(value, &satisfier)?;
                        }
                    }
                }
            }
        }

        Ok(())
    }
}

#[derive(Debug)]
pub struct Behaviour {
    pub first: Option<char>,
    pub sep: char,
    pub named: bool,
    pub ifemp: Option<char>,
    pub allow: Allow,
}

#[derive(Debug)]
pub enum Allow {
    U,
    UR,
}

impl Allow {
    pub fn satisfier(&self) -> Box<dyn Satisfy> {
        match self {
            Self::U => Box::new(satisfy::unreserved()),
            Self::UR => Box::new(satisfy::unreserved_or_reserved()),
        }
    }
}