sfv 0.14.0

Structured Field Values for HTTP parser. Implementation of RFC 8941 and RFC 9651.
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
use std::{borrow::Cow, string::String as StdString};

use crate::{
    error, utils,
    visitor::{
        DictionaryVisitor, EntryVisitor, InnerListVisitor, ItemVisitor, ListVisitor,
        ParameterVisitor,
    },
    BareItemFromInput, Date, Decimal, Integer, KeyRef, Num, SFVResult, String, StringRef, TokenRef,
    Version,
};

fn parse_item<'de>(
    parser: &mut Parser<'de>,
    visitor: impl ItemVisitor<'de>,
) -> Result<(), error::Repr> {
    // https://httpwg.org/specs/rfc9651.html#parse-item
    let param_visitor = visitor.bare_item(parser.parse_bare_item()?)?;
    parser.parse_parameters(param_visitor)
}

fn parse_comma_separated<'de>(
    parser: &mut Parser<'de>,
    mut parse_member: impl FnMut(&mut Parser<'de>) -> Result<(), error::Repr>,
) -> Result<(), error::Repr> {
    while parser.peek().is_some() {
        parse_member(parser)?;

        parser.consume_ows_chars();

        if parser.peek().is_none() {
            return Ok(());
        }

        let comma_index = parser.index;

        if let Some(c) = parser.peek() {
            if c != b',' {
                return Err(error::Repr::TrailingCharactersAfterMember(parser.index));
            }
            parser.next();
        }

        parser.consume_ows_chars();

        if parser.peek().is_none() {
            // Report the error at the position of the comma itself, rather
            // than at the end of input.
            return Err(error::Repr::TrailingComma(comma_index));
        }
    }

    Ok(())
}

/// Exposes methods for parsing input into a structured field value.
#[must_use]
pub struct Parser<'de> {
    input: &'de [u8],
    index: usize,
    version: Version,
}

impl<'de> Parser<'de> {
    /// Creates a parser from the given input with [`Version::Rfc9651`].
    pub fn new(input: &'de (impl ?Sized + AsRef<[u8]>)) -> Self {
        Self {
            input: input.as_ref(),
            index: 0,
            version: Version::Rfc9651,
        }
    }

    /// Sets the parser's version and returns it.
    pub fn with_version(mut self, version: Version) -> Self {
        self.version = version;
        self
    }

    /// Parses a structured field value.
    ///
    /// # Errors
    /// When the parsing process is unsuccessful.
    #[cfg(feature = "parsed-types")]
    pub fn parse<T: crate::FieldType>(self) -> SFVResult<T> {
        T::parse(self)
    }

    /// Parses input into a structured field value of `Dictionary` type, using
    /// the given visitor.
    #[cfg_attr(
        feature = "parsed-types",
        doc = r#"

This can also be used to parse a dictionary that is split into multiple lines by merging
them into an existing structure:

```
# use sfv::{Dictionary, FieldType, Parser};
# fn main() -> Result<(), sfv::Error> {
let mut dict: Dictionary = Parser::new("a=1").parse()?;

Parser::new("b=2").parse_dictionary_with_visitor(&mut dict)?;

assert_eq!(
    dict.serialize().as_deref(),
    Some("a=1, b=2"),
);
# Ok(())
# }
```
"#
    )]
    ///
    /// # Errors
    /// When the parsing process is unsuccessful, including any error raised by a visitor.
    pub fn parse_dictionary_with_visitor(
        self,
        visitor: &mut (impl ?Sized + DictionaryVisitor<'de>),
    ) -> SFVResult<()> {
        // https://httpwg.org/specs/rfc9651.html#parse-dictionary
        self.parse_internal(move |parser| {
            parse_comma_separated(parser, |parser| {
                // Note: It is up to the visitor to properly handle duplicate keys.
                let entry_visitor = visitor.entry(parser.parse_key()?)?;

                if let Some(b'=') = parser.peek() {
                    parser.next();
                    parser.parse_list_entry(entry_visitor)
                } else {
                    let param_visitor = entry_visitor.bare_item(BareItemFromInput::from(true))?;
                    parser.parse_parameters(param_visitor)
                }
            })
        })
    }

    /// Parses input into a structured field value of `List` type, using the
    /// given visitor.
    #[allow(clippy::needless_raw_string_hashes)] // false positive: https://github.com/rust-lang/rust-clippy/issues/11737
    #[cfg_attr(
        feature = "parsed-types",
        doc = r##"

This can also be used to parse a list that is split into multiple lines by merging them
into an existing structure:
```
# use sfv::{FieldType, List, Parser};
# fn main() -> Result<(), sfv::Error> {
let mut list: List = Parser::new("11, (12 13)").parse()?;

Parser::new(r#""foo",        "bar""#).parse_list_with_visitor(&mut list)?;

assert_eq!(
    list.serialize().as_deref(),
    Some(r#"11, (12 13), "foo", "bar""#),
);
# Ok(())
# }
```
"##
    )]
    ///
    /// # Errors
    /// When the parsing process is unsuccessful, including any error raised by a visitor.
    pub fn parse_list_with_visitor(
        self,
        visitor: &mut (impl ?Sized + ListVisitor<'de>),
    ) -> SFVResult<()> {
        // https://httpwg.org/specs/rfc9651.html#parse-list
        self.parse_internal(|parser| {
            parse_comma_separated(parser, |parser| parser.parse_list_entry(visitor.entry()?))
        })
    }

    /// Parses input into a structured field value of `Item` type, using the
    /// given visitor.
    ///
    /// # Errors
    /// When the parsing process is unsuccessful, including any error raised by a visitor.
    pub fn parse_item_with_visitor(self, visitor: impl ItemVisitor<'de>) -> SFVResult<()> {
        self.parse_internal(|parser| parse_item(parser, visitor))
    }

    fn peek(&self) -> Option<u8> {
        self.input.get(self.index).copied()
    }

    fn next(&mut self) -> Option<u8> {
        self.peek().inspect(|_| self.index += 1)
    }

    // Generic parse method for checking input before parsing
    // and handling trailing text error
    fn parse_internal(
        mut self,
        f: impl FnOnce(&mut Self) -> Result<(), error::Repr>,
    ) -> SFVResult<()> {
        // https://httpwg.org/specs/rfc9651.html#text-parse

        self.consume_sp_chars();

        f(&mut self)?;

        self.consume_sp_chars();

        if self.peek().is_some() {
            return Err(error::Repr::TrailingCharactersAfterParsedValue(self.index).into());
        }

        Ok(())
    }

    fn parse_list_entry(&mut self, visitor: impl EntryVisitor<'de>) -> Result<(), error::Repr> {
        // https://httpwg.org/specs/rfc9651.html#parse-item-or-list
        // ListEntry represents a tuple (item_or_inner_list, parameters)

        match self.peek() {
            Some(b'(') => self.parse_inner_list(visitor.inner_list()?),
            _ => parse_item(self, visitor),
        }
    }

    pub(crate) fn parse_inner_list(
        &mut self,
        mut visitor: impl InnerListVisitor<'de>,
    ) -> Result<(), error::Repr> {
        // https://httpwg.org/specs/rfc9651.html#parse-innerlist

        if Some(b'(') != self.peek() {
            return Err(error::Repr::ExpectedStartOfInnerList(self.index));
        }

        self.next();

        while self.peek().is_some() {
            self.consume_sp_chars();

            if Some(b')') == self.peek() {
                self.next();
                let param_visitor = visitor.finish()?;
                return self.parse_parameters(param_visitor);
            }

            parse_item(self, visitor.item()?)?;

            if let Some(c) = self.peek() {
                if c != b' ' && c != b')' {
                    return Err(error::Repr::ExpectedInnerListDelimiter(self.index));
                }
            }
        }

        Err(error::Repr::UnterminatedInnerList(self.index))
    }

    pub(crate) fn parse_bare_item(&mut self) -> Result<BareItemFromInput<'de>, error::Repr> {
        // https://httpwg.org/specs/rfc9651.html#parse-bare-item

        Ok(match self.peek() {
            Some(b'?') => BareItemFromInput::Boolean(self.parse_bool()?),
            Some(b'"') => BareItemFromInput::String(self.parse_string()?),
            Some(b':') => BareItemFromInput::ByteSequence(self.parse_byte_sequence()?),
            Some(b'@') => BareItemFromInput::Date(self.parse_date()?),
            Some(b'%') => BareItemFromInput::DisplayString(self.parse_display_string()?),
            Some(c) if utils::is_allowed_start_token_char(c) => {
                BareItemFromInput::Token(self.parse_token()?)
            }
            Some(c) if c == b'-' || c.is_ascii_digit() => match self.parse_number()? {
                Num::Decimal(val) => BareItemFromInput::Decimal(val),
                Num::Integer(val) => BareItemFromInput::Integer(val),
            },
            _ => return Err(error::Repr::ExpectedStartOfBareItem(self.index)),
        })
    }

    pub(crate) fn parse_bool(&mut self) -> Result<bool, error::Repr> {
        // https://httpwg.org/specs/rfc9651.html#parse-boolean

        if self.peek() != Some(b'?') {
            return Err(error::Repr::ExpectedStartOfBoolean(self.index));
        }

        self.next();

        match self.peek() {
            Some(b'0') => {
                self.next();
                Ok(false)
            }
            Some(b'1') => {
                self.next();
                Ok(true)
            }
            _ => Err(error::Repr::ExpectedBoolean(self.index)),
        }
    }

    pub(crate) fn parse_string(&mut self) -> Result<Cow<'de, StringRef>, error::Repr> {
        // https://httpwg.org/specs/rfc9651.html#parse-string

        if self.peek() != Some(b'"') {
            return Err(error::Repr::ExpectedStartOfString(self.index));
        }

        self.next();

        let start = self.index;
        let mut output = Cow::Borrowed(&[] as &[u8]);

        while let Some(curr_char) = self.peek() {
            match curr_char {
                b'"' => {
                    self.next();
                    // TODO: The UTF-8 validation is redundant with the preceding character checks, but
                    // its removal is only possible with unsafe code.
                    return Ok(match output {
                        Cow::Borrowed(output) => {
                            let output = std::str::from_utf8(output).unwrap();
                            Cow::Borrowed(StringRef::from_str(output).unwrap())
                        }
                        Cow::Owned(output) => {
                            let output = StdString::from_utf8(output).unwrap();
                            Cow::Owned(String::from_string(output).unwrap())
                        }
                    });
                }
                0x00..=0x1f | 0x7f..=0xff => {
                    return Err(error::Repr::InvalidStringCharacter(self.index));
                }
                b'\\' => {
                    self.next();
                    match self.peek() {
                        Some(c @ (b'\\' | b'"')) => {
                            self.next();
                            output.to_mut().push(c);
                        }
                        None => return Err(error::Repr::UnterminatedEscapeSequence(self.index)),
                        Some(_) => return Err(error::Repr::InvalidEscapeSequence(self.index)),
                    }
                }
                _ => {
                    self.next();
                    match output {
                        Cow::Borrowed(ref mut output) => *output = &self.input[start..self.index],
                        Cow::Owned(ref mut output) => output.push(curr_char),
                    }
                }
            }
        }
        Err(error::Repr::UnterminatedString(self.index))
    }

    fn parse_non_empty_str(
        &mut self,
        is_allowed_start_char: impl FnOnce(u8) -> bool,
        is_allowed_inner_char: impl Fn(u8) -> bool,
    ) -> Option<&'de str> {
        let start = self.index;

        match self.peek() {
            Some(c) if is_allowed_start_char(c) => {
                self.next();
            }
            _ => return None,
        }

        loop {
            match self.peek() {
                Some(c) if is_allowed_inner_char(c) => {
                    self.next();
                }
                // TODO: The UTF-8 validation is redundant with the preceding character checks, but
                // its removal is only possible with unsafe code.
                _ => return Some(std::str::from_utf8(&self.input[start..self.index]).unwrap()),
            }
        }
    }

    pub(crate) fn parse_token(&mut self) -> Result<&'de TokenRef, error::Repr> {
        // https://httpwg.org/specs/9651.html#parse-token

        match self.parse_non_empty_str(
            utils::is_allowed_start_token_char,
            utils::is_allowed_inner_token_char,
        ) {
            None => Err(error::Repr::ExpectedStartOfToken(self.index)),
            Some(str) => Ok(TokenRef::from_validated_str(str)),
        }
    }

    pub(crate) fn parse_byte_sequence(&mut self) -> Result<Vec<u8>, error::Repr> {
        // https://httpwg.org/specs/rfc9651.html#parse-binary

        if self.peek() != Some(b':') {
            return Err(error::Repr::ExpectedStartOfByteSequence(self.index));
        }

        self.next();
        let start = self.index;

        loop {
            match self.next() {
                Some(b':') => break,
                Some(_) => {}
                None => return Err(error::Repr::UnterminatedByteSequence(self.index)),
            }
        }

        let colon_index = self.index - 1;

        match base64::Engine::decode(&utils::BASE64, &self.input[start..colon_index]) {
            Ok(content) => Ok(content),
            Err(err) => {
                let index = match err {
                    base64::DecodeError::InvalidByte(offset, _)
                    | base64::DecodeError::InvalidLastSymbol(offset, _) => start + offset,
                    // Report these two at the position of the last base64
                    // character, since they correspond to errors in the input
                    // as a whole.
                    base64::DecodeError::InvalidLength(_) | base64::DecodeError::InvalidPadding => {
                        colon_index - 1
                    }
                };

                Err(error::Repr::InvalidByteSequence(index))
            }
        }
    }

    pub(crate) fn parse_number(&mut self) -> Result<Num, error::Repr> {
        // https://httpwg.org/specs/rfc9651.html#parse-number

        fn char_to_i64(c: u8) -> i64 {
            i64::from(c - b'0')
        }

        let sign = if let Some(b'-') = self.peek() {
            self.next();
            -1
        } else {
            1
        };

        let mut magnitude = match self.peek() {
            Some(c @ b'0'..=b'9') => {
                self.next();
                char_to_i64(c)
            }
            _ => return Err(error::Repr::ExpectedDigit(self.index)),
        };

        let mut digits = 1;

        loop {
            match self.peek() {
                Some(b'.') => {
                    if digits > 12 {
                        return Err(error::Repr::TooManyDigitsBeforeDecimalPoint(self.index));
                    }
                    self.next();
                    break;
                }
                Some(c @ b'0'..=b'9') => {
                    digits += 1;
                    if digits > 15 {
                        return Err(error::Repr::TooManyDigits(self.index));
                    }
                    self.next();
                    magnitude = magnitude * 10 + char_to_i64(c);
                }
                _ => return Ok(Num::Integer(Integer::try_from(sign * magnitude).unwrap())),
            }
        }

        magnitude *= 1000;
        let mut scale = 100;

        while let Some(c @ b'0'..=b'9') = self.peek() {
            if scale == 0 {
                return Err(error::Repr::TooManyDigitsAfterDecimalPoint(self.index));
            }

            self.next();
            magnitude += char_to_i64(c) * scale;
            scale /= 10;
        }

        if scale == 100 {
            // Report the error at the position of the decimal itself, rather
            // than the next position.
            Err(error::Repr::TrailingDecimalPoint(self.index - 1))
        } else {
            Ok(Num::Decimal(Decimal::from_integer_scaled_1000(
                Integer::try_from(sign * magnitude).unwrap(),
            )))
        }
    }

    pub(crate) fn parse_date(&mut self) -> Result<Date, error::Repr> {
        // https://httpwg.org/specs/rfc9651.html#parse-date

        if self.peek() != Some(b'@') {
            return Err(error::Repr::ExpectedStartOfDate(self.index));
        }

        match self.version {
            Version::Rfc8941 => return Err(error::Repr::Rfc8941Date(self.index)),
            Version::Rfc9651 => {}
        }

        let start = self.index;
        self.next();

        match self.parse_number()? {
            Num::Integer(seconds) => Ok(Date::from_unix_seconds(seconds)),
            Num::Decimal(_) => Err(error::Repr::NonIntegerDate(start)),
        }
    }

    pub(crate) fn parse_display_string(&mut self) -> Result<Cow<'de, str>, error::Repr> {
        // https://httpwg.org/specs/rfc9651.html#parse-display

        if self.peek() != Some(b'%') {
            return Err(error::Repr::ExpectedStartOfDisplayString(self.index));
        }

        match self.version {
            Version::Rfc8941 => return Err(error::Repr::Rfc8941DisplayString(self.index)),
            Version::Rfc9651 => {}
        }

        self.next();

        if self.peek() != Some(b'"') {
            return Err(error::Repr::ExpectedQuote(self.index));
        }

        self.next();

        let start = self.index;
        let mut output = Cow::Borrowed(&[] as &[u8]);

        while let Some(curr_char) = self.peek() {
            match curr_char {
                b'"' => {
                    self.next();
                    return match output {
                        Cow::Borrowed(output) => match std::str::from_utf8(output) {
                            Ok(output) => Ok(Cow::Borrowed(output)),
                            Err(err) => Err(error::Repr::InvalidUtf8InDisplayString(
                                start + err.valid_up_to(),
                            )),
                        },
                        Cow::Owned(output) => match StdString::from_utf8(output) {
                            Ok(output) => Ok(Cow::Owned(output)),
                            Err(err) => Err(error::Repr::InvalidUtf8InDisplayString(
                                start + err.utf8_error().valid_up_to(),
                            )),
                        },
                    };
                }
                0x00..=0x1f | 0x7f..=0xff => {
                    return Err(error::Repr::InvalidDisplayStringCharacter(self.index));
                }
                b'%' => {
                    self.next();

                    let mut octet = 0;

                    for _ in 0..2 {
                        octet = (octet << 4)
                            + match self.peek() {
                                Some(c @ b'0'..=b'9') => {
                                    self.next();
                                    c - b'0'
                                }
                                Some(c @ b'a'..=b'f') => {
                                    self.next();
                                    c - b'a' + 10
                                }
                                None => {
                                    return Err(error::Repr::UnterminatedEscapeSequence(self.index))
                                }
                                Some(_) => {
                                    return Err(error::Repr::InvalidEscapeSequence(self.index))
                                }
                            };
                    }

                    output.to_mut().push(octet);
                }
                _ => {
                    self.next();
                    match output {
                        Cow::Borrowed(ref mut output) => *output = &self.input[start..self.index],
                        Cow::Owned(ref mut output) => output.push(curr_char),
                    }
                }
            }
        }
        Err(error::Repr::UnterminatedDisplayString(self.index))
    }

    pub(crate) fn parse_parameters(
        &mut self,
        mut visitor: impl ParameterVisitor<'de>,
    ) -> Result<(), error::Repr> {
        // https://httpwg.org/specs/rfc9651.html#parse-param

        while let Some(b';') = self.peek() {
            self.next();
            self.consume_sp_chars();

            let param_name = self.parse_key()?;
            let param_value = match self.peek() {
                Some(b'=') => {
                    self.next();
                    self.parse_bare_item()?
                }
                _ => BareItemFromInput::Boolean(true),
            };
            // Note: It is up to the visitor to properly handle duplicate keys.
            visitor.parameter(param_name, param_value)?;
        }

        visitor.finish()?;
        Ok(())
    }

    pub(crate) fn parse_key(&mut self) -> Result<&'de KeyRef, error::Repr> {
        // https://httpwg.org/specs/rfc9651.html#parse-key

        match self.parse_non_empty_str(
            utils::is_allowed_start_key_char,
            utils::is_allowed_inner_key_char,
        ) {
            None => Err(error::Repr::ExpectedStartOfKey(self.index)),
            Some(str) => Ok(KeyRef::from_validated_str(str)),
        }
    }

    fn consume_ows_chars(&mut self) {
        while let Some(b' ' | b'\t') = self.peek() {
            self.next();
        }
    }

    fn consume_sp_chars(&mut self) {
        while let Some(b' ') = self.peek() {
            self.next();
        }
    }

    #[cfg(test)]
    pub(crate) fn remaining(&self) -> &[u8] {
        &self.input[self.index..]
    }
}