parse-net 0.3.0

Grammar for Internet message fields: RFC 9110 field syntax, media types, RFC 9651 Structured Fields, HTTP and RFC 5322 dates, negotiation, entity tags, ranges, Content-Disposition, Cache-Control, Forwarded, auth challenges, and the email lexical layer. no_std, no allocation, sans-IO, zero dependencies.
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
//! Media types: `type "/" subtype parameters` (RFC 9110 section 8.3.1), and
//! the RFC 2046 multipart boundary.
//!
//! Type, subtype, and parameter names are case-insensitive; parameter values
//! are case-sensitive unless the parameter's definition says otherwise
//! (`charset` is case-insensitive, RFC 9110 section 8.3.2).
//!
//! # Examples
//!
//! ```
//! use parse_net as pn;
//!
//! let mt = pn::parse_media_type(b"Multipart/Form-Data; boundary=\"----x y\"")?;
//! assert!(mt.is_multipart_form_data() && mt.is("multipart", "form-data"));
//! assert_eq!(mt.boundary()?.map(|b| b.as_bytes()), Some(&b"----x y"[..]));
//!
//! assert_eq!(pn::parse_media_type(b"text/*").unwrap_err().kind(), pn::ErrorKind::Wildcard);
//!
//! let mut buf = [0u8; 64];
//! let mut out = pn::SliceSink::new(&mut buf);
//! pn::media::write("text", "plain", &[("charset", "utf-8")], &mut out)?;
//! assert_eq!(out.written(), b"text/plain; charset=utf-8");
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use crate::{
    class,
    error::{ErrorKind, ParseError, Result, WriteError, err},
    limits::Limits,
    param::{self, Params},
    scan::control_kind,
    text::{Word, is_token, skip_ows, trim_ows},
    write::{Sink, reserve, word_len, write_word},
};

/// Parses a `Content-Type` style media type with the default [`Limits`].
///
/// # Errors
///
/// As [`parse`].
///
/// # Examples
///
/// ```
/// let mt = parse_net::parse_media_type(b"text/html; charset=UTF-8")?;
/// assert!(mt.essence_is("text/html"));
/// assert!(mt.charset().is_some_and(|c| c.eq_ignore_ascii_case(b"utf-8")));
/// # Ok::<(), parse_net::ParseError>(())
/// ```
pub fn parse_media_type(value: &[u8]) -> Result<MediaType<'_>> {
    parse(value, &Limits::DEFAULT)
}

/// The error for a byte that ends a media type where it may not.
fn bad_byte(value: &[u8], at: usize) -> ParseError {
    match value.get(at) {
        Some(&b) if b < 0x20 || b == 0x7f => ParseError::new(control_kind(b), at),
        _ => ParseError::new(ErrorKind::InvalidMediaType, at),
    }
}

/// Parses `type "/" subtype` at the start of `value` (OWS already skipped);
/// returns both and the bytes used.
fn essence(value: &[u8], base: usize) -> Result<(&[u8], &[u8], usize)> {
    let type_len = value.iter().take_while(|&&b| class::is_tchar(b)).count();
    if type_len == 0 {
        return Err(bad_byte(value, 0).shifted(base));
    }
    if value.get(type_len) != Some(&b'/') {
        return Err(bad_byte(value, type_len).shifted(base));
    }
    let sub_start = type_len + 1;
    let sub_len = value
        .get(sub_start..)
        .unwrap_or(&[])
        .iter()
        .take_while(|&&b| class::is_tchar(b))
        .count();
    if sub_len == 0 {
        return Err(bad_byte(value, sub_start).shifted(base));
    }
    let type_ = value.get(..type_len).unwrap_or(&[]);
    let subtype = value.get(sub_start..sub_start + sub_len).unwrap_or(&[]);
    Ok((type_, subtype, sub_start + sub_len))
}

/// Parses a media type, as in `Content-Type`.
///
/// Type and subtype are tokens around `/`; OWS is allowed only before `;` and
/// around the whole value; parameters follow the RFC 9110 grammar with the
/// duplicate policy of `limits` (refusal by default, so `charset` or
/// `boundary` given twice is refused).
///
/// # Errors
///
/// [`ErrorKind::InvalidMediaType`] for a missing `/`, an empty or non-token
/// type or subtype, whitespace inside the essence, or bytes after the
/// parameters; [`ErrorKind::Wildcard`] for `*` as type or subtype; a control
/// kind for a control byte; the parameter errors of
/// [`param::parse`].
///
/// # Examples
///
/// ```
/// use parse_net::{media, ErrorKind, Limits};
///
/// let err = media::parse(b"text/ html", &Limits::DEFAULT).unwrap_err();
/// assert_eq!((err.kind(), err.offset()), (ErrorKind::InvalidMediaType, 5));
/// assert_eq!(err.to_string(), "invalid media type at offset 5");
/// ```
pub fn parse<'a>(value: &'a [u8], limits: &Limits) -> Result<MediaType<'a>> {
    let lead = skip_ows(value);
    let trimmed = trim_ows(value);
    let (type_, subtype, used) = essence(trimmed, lead)?;
    if type_ == b"*" {
        return err(ErrorKind::Wildcard, lead);
    }
    if subtype == b"*" {
        return err(ErrorKind::Wildcard, lead + type_.len() + 1);
    }
    let rest = trimmed.get(used..).unwrap_or(&[]);
    let (params, n) = param::parse(rest, limits).map_err(|e| e.shifted(lead + used))?;
    let end = used + n;
    if end < trimmed.len() {
        let at = end + skip_ows(trimmed.get(end..).unwrap_or(&[]));
        return Err(bad_byte(trimmed, at).shifted(lead));
    }
    Ok(MediaType {
        type_,
        subtype,
        params,
    })
}

/// Writes `type/subtype` and then `; name=value` for each pair, values as a
/// token when they are one and as a quoted string otherwise.
///
/// # Errors
///
/// [`WriteError::NotToken`] for a type, subtype, or name that is not a token
/// (or is `*`); [`WriteError::Forbidden`] for a control byte in a value;
/// [`WriteError::Full`]. Nothing is written on error when the sink reports
/// its room.
///
/// # Examples
///
/// ```
/// use parse_net::{media, SliceSink};
///
/// let mut buf = [0u8; 64];
/// let mut out = SliceSink::new(&mut buf);
/// media::write("multipart", "form-data", &[("boundary", "a b")], &mut out)?;
/// assert_eq!(out.written(), b"multipart/form-data; boundary=\"a b\"");
/// # Ok::<(), parse_net::WriteError>(())
/// ```
pub fn write(
    type_: &str,
    subtype: &str,
    params: &[(&str, &str)],
    out: &mut impl Sink,
) -> core::result::Result<(), WriteError> {
    let (t, s) = (type_.as_bytes(), subtype.as_bytes());
    if !is_token(t) || !is_token(s) || t == b"*" || s == b"*" {
        return Err(WriteError::NotToken);
    }
    let mut len = t.len().saturating_add(1).saturating_add(s.len());
    for (name, value) in params {
        if !is_token(name.as_bytes()) {
            return Err(WriteError::NotToken);
        }
        let v = word_len(value.as_bytes())?;
        len = len
            .saturating_add(3)
            .saturating_add(name.len())
            .saturating_add(v);
    }
    reserve(out, len)?;
    out.put(t)?;
    out.put(b"/")?;
    out.put(s)?;
    for (name, value) in params {
        out.put(b"; ")?;
        out.put(name.as_bytes())?;
        out.put(b"=")?;
        write_word(value.as_bytes(), out)?;
    }
    Ok(())
}

/// A validated media type.
///
/// # Examples
///
/// ```
/// let ld = parse_net::parse_media_type(b"application/ld+json")?;
/// assert_eq!(ld.suffix(), Some(&b"json"[..]));
/// assert!(ld.is_json());
/// # Ok::<(), parse_net::ParseError>(())
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct MediaType<'a> {
    type_: &'a [u8],
    subtype: &'a [u8],
    params: Params<'a>,
}

impl<'a> MediaType<'a> {
    /// The type, as sent.
    #[must_use]
    pub const fn type_(&self) -> &'a [u8] {
        self.type_
    }

    /// The subtype, as sent.
    #[must_use]
    pub const fn subtype(&self) -> &'a [u8] {
        self.subtype
    }

    /// The structured syntax suffix: the part of the subtype after its last
    /// `+` (`json` of `ld+json`), when there is one.
    #[must_use]
    pub fn suffix(&self) -> Option<&'a [u8]> {
        let plus = self.subtype.iter().rposition(|&b| b == b'+')?;
        self.subtype.get(plus + 1..).filter(|s| !s.is_empty())
    }

    /// Whether `type/subtype` equals `essence`, ignoring ASCII case.
    #[must_use]
    pub fn essence_is(&self, essence: &str) -> bool {
        match essence.split_once('/') {
            Some((t, s)) => self.is(t, s),
            None => false,
        }
    }

    /// Whether the type and subtype equal `type_` and `subtype`, ignoring
    /// ASCII case.
    #[must_use]
    pub fn is(&self, type_: &str, subtype: &str) -> bool {
        self.type_.eq_ignore_ascii_case(type_.as_bytes())
            && self.subtype.eq_ignore_ascii_case(subtype.as_bytes())
    }

    /// The parameters.
    #[must_use]
    pub const fn params(&self) -> Params<'a> {
        self.params
    }

    /// The value of the parameter `name` (ASCII case-insensitive).
    #[must_use]
    pub fn param(&self, name: &str) -> Option<Word<'a>> {
        self.params.get(name)
    }

    /// The `charset` parameter. Compare it case-insensitively.
    #[must_use]
    pub fn charset(&self) -> Option<Word<'a>> {
        self.params.get("charset")
    }

    /// The `boundary` parameter, validated by RFC 2046 section 5.1.1: 1 to 70
    /// `bchars`, the last not a space. `Ok(None)` when absent.
    ///
    /// # Errors
    ///
    /// [`ErrorKind::InvalidBoundary`], with the offset inside the boundary
    /// value.
    pub fn boundary(&self) -> Result<Option<Boundary<'a>>> {
        let Some(word) = self.params.get("boundary") else {
            return Ok(None);
        };
        let bytes = match word {
            Word::Token(t) => t,
            // `\` is not a bchar, so a quoted boundary cannot carry escapes.
            Word::Quoted(q) if q.has_escapes() => {
                let at = q.raw().iter().position(|&b| b == b'\\').unwrap_or(0);
                return err(ErrorKind::InvalidBoundary, at);
            }
            Word::Quoted(q) => q.raw(),
        };
        if bytes.is_empty() {
            return err(ErrorKind::InvalidBoundary, 0);
        }
        if let Some(at) = bytes
            .iter()
            .position(|&b| !(class::is_bchar_nospace(b) || b == b' '))
        {
            return err(ErrorKind::InvalidBoundary, at);
        }
        if bytes.len() > 70 {
            return err(ErrorKind::InvalidBoundary, 70);
        }
        if bytes.last() == Some(&b' ') {
            return err(ErrorKind::InvalidBoundary, bytes.len() - 1);
        }
        Ok(Some(Boundary(bytes)))
    }

    /// Whether this is `application/json` or has the `+json` suffix.
    #[must_use]
    pub fn is_json(&self) -> bool {
        self.is("application", "json")
            || self
                .suffix()
                .is_some_and(|s| s.eq_ignore_ascii_case(b"json"))
    }

    /// Whether this is `application/x-www-form-urlencoded`.
    #[must_use]
    pub fn is_form_urlencoded(&self) -> bool {
        self.is("application", "x-www-form-urlencoded")
    }

    /// Whether this is `multipart/form-data`.
    #[must_use]
    pub fn is_multipart_form_data(&self) -> bool {
        self.is("multipart", "form-data")
    }

    /// Writes the media type with the type, subtype, and parameter names in
    /// lowercase and the values as sent, separated by `; `.
    ///
    /// # Errors
    ///
    /// [`WriteError::Full`]; nothing is written when the sink reports its
    /// room.
    ///
    /// # Examples
    ///
    /// ```
    /// use parse_net::{parse_media_type, SliceSink};
    ///
    /// let mt = parse_media_type(b"Text/HTML;Charset=\"UTF-8\"")?;
    /// let mut buf = [0u8; 64];
    /// let mut out = SliceSink::new(&mut buf);
    /// mt.write_canonical(&mut out).expect("room");
    /// assert_eq!(out.written(), b"text/html; charset=\"UTF-8\"");
    /// # Ok::<(), parse_net::ParseError>(())
    /// ```
    pub fn write_canonical(&self, out: &mut impl Sink) -> core::result::Result<(), WriteError> {
        let mut len = self.type_.len() + 1 + self.subtype.len();
        for p in self.params.iter() {
            len = len.saturating_add(3 + p.name.len() + raw_word_len(&p.value));
        }
        reserve(out, len)?;
        put_lower(self.type_, out)?;
        out.put(b"/")?;
        put_lower(self.subtype, out)?;
        for p in self.params.iter() {
            out.put(b"; ")?;
            put_lower(p.name, out)?;
            out.put(b"=")?;
            match p.value {
                Word::Token(t) => out.put(t)?,
                Word::Quoted(q) => {
                    out.put(b"\"")?;
                    out.put(q.raw())?;
                    out.put(b"\"")?;
                }
            }
        }
        Ok(())
    }
}

/// The length of a word written as it was sent.
fn raw_word_len(w: &Word<'_>) -> usize {
    match w {
        Word::Token(t) => t.len(),
        Word::Quoted(q) => q.raw().len() + 2,
    }
}

/// Writes `s` in ASCII lowercase, through a small stack buffer.
fn put_lower(s: &[u8], out: &mut impl Sink) -> core::result::Result<(), WriteError> {
    let mut buf = [0u8; 64];
    for chunk in s.chunks(buf.len()) {
        let dst = buf.get_mut(..chunk.len()).unwrap_or(&mut []);
        for (d, &c) in dst.iter_mut().zip(chunk) {
            *d = c.to_ascii_lowercase();
        }
        out.put(dst)?;
    }
    Ok(())
}

/// A validated multipart boundary, unquoted.
///
/// # Examples
///
/// ```
/// let mt = parse_net::parse_media_type(b"multipart/mixed; boundary=gc0p4Jq0M2Yt08j34c0p")?;
/// assert_eq!(mt.boundary()?.map(|b| b.as_bytes()), Some(&b"gc0p4Jq0M2Yt08j34c0p"[..]));
/// # Ok::<(), parse_net::ParseError>(())
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Boundary<'a>(&'a [u8]);

impl<'a> Boundary<'a> {
    /// The boundary bytes.
    #[must_use]
    pub const fn as_bytes(&self) -> &'a [u8] {
        self.0
    }
}

#[cfg(test)]
mod tests {
    use std::{vec, vec::Vec};

    use super::*;
    use crate::write::SliceSink;

    fn mt(s: &[u8]) -> Result<MediaType<'_>> {
        parse_media_type(s)
    }

    #[test]
    fn test_media_type_edge_cases() {
        assert!(mt(b"text/html").unwrap().is("text", "html"));
        assert!(mt(b"TEXT/HTML").unwrap().essence_is("text/html"));
        assert!(mt(b"text/html;").unwrap().params().is_empty());
        assert!(mt(b"text/html ;charset=utf-8").unwrap().charset().is_some());
        assert!(mt(b" text/html \t").is_ok());
        let e = mt(b"text/ html").unwrap_err();
        assert_eq!((e.kind(), e.offset()), (ErrorKind::InvalidMediaType, 5));
        let e = mt(b"text /html").unwrap_err();
        assert_eq!((e.kind(), e.offset()), (ErrorKind::InvalidMediaType, 4));
        assert_eq!(
            mt(b"text/").unwrap_err().kind(),
            ErrorKind::InvalidMediaType
        );
        assert_eq!(
            mt(b"/html").unwrap_err().kind(),
            ErrorKind::InvalidMediaType
        );
        assert_eq!(mt(b"").unwrap_err().kind(), ErrorKind::InvalidMediaType);
        assert_eq!(mt(b"text").unwrap_err().kind(), ErrorKind::InvalidMediaType);
        assert_eq!(mt(b"*/*").unwrap_err().kind(), ErrorKind::Wildcard);
        let e = mt(b"text/*").unwrap_err();
        assert_eq!((e.kind(), e.offset()), (ErrorKind::Wildcard, 5));
        assert_eq!(
            mt(b"text/html x").unwrap_err().kind(),
            ErrorKind::InvalidMediaType
        );
        assert_eq!(mt(b"text/html\r").unwrap_err().kind(), ErrorKind::BareCr);
        assert_eq!(
            mt(b"text/html;a=b\nc").unwrap_err().kind(),
            ErrorKind::LineFeed
        );
        let e = mt(b"text/html; charset=a; Charset=b").unwrap_err();
        assert_eq!((e.kind(), e.offset()), (ErrorKind::DuplicateParameter, 22));
    }

    #[test]
    fn test_media_type_suffix_and_predicates() {
        let v = mt(b"application/vnd.api+json").unwrap();
        assert_eq!(v.suffix(), Some(&b"json"[..]));
        assert!(v.is_json());
        assert!(mt(b"application/json").unwrap().is_json());
        assert!(!mt(b"application/jsonx").unwrap().is_json());
        assert_eq!(mt(b"application/a+").unwrap().suffix(), None);
        assert!(
            mt(b"application/x-www-form-urlencoded")
                .unwrap()
                .is_form_urlencoded()
        );
        assert!(!mt(b"text/html").unwrap().essence_is("texthtml"));
    }

    fn boundary(s: &[u8]) -> Result<Option<Vec<u8>>> {
        Ok(mt(s)?.boundary()?.map(|b| b.as_bytes().to_vec()))
    }

    #[test]
    fn test_boundary_rfc2046_rules() {
        assert_eq!(boundary(b"multipart/form-data").unwrap(), None);
        assert_eq!(
            boundary(b"multipart/form-data; boundary=")
                .unwrap_err()
                .kind(),
            ErrorKind::MissingValue
        );
        assert_eq!(
            boundary(b"multipart/form-data; boundary=\"\"")
                .unwrap_err()
                .kind(),
            ErrorKind::InvalidBoundary
        );
        let seventy = vec![b'a'; 70];
        let mut v = b"multipart/mixed; boundary=".to_vec();
        v.extend_from_slice(&seventy);
        assert_eq!(boundary(&v).unwrap(), Some(seventy));
        v.push(b'a');
        assert_eq!(boundary(&v).unwrap_err().kind(), ErrorKind::InvalidBoundary);
        assert_eq!(
            boundary(b"multipart/mixed; boundary=\"ab \"")
                .unwrap_err()
                .kind(),
            ErrorKind::InvalidBoundary
        );
        assert_eq!(
            boundary(b"multipart/mixed; boundary=\"a b\"").unwrap(),
            Some(b"a b".to_vec())
        );
        assert_eq!(
            boundary(b"multipart/mixed; boundary=\"a\\\\b\"")
                .unwrap_err()
                .kind(),
            ErrorKind::InvalidBoundary
        );
        assert_eq!(
            boundary(b"multipart/mixed; boundary=a*b")
                .unwrap_err()
                .kind(),
            ErrorKind::InvalidBoundary
        );
        assert_eq!(
            mt(b"multipart/mixed; boundary=a; boundary=b")
                .unwrap_err()
                .kind(),
            ErrorKind::DuplicateParameter
        );
    }

    #[test]
    fn test_media_write_refuses_bad_names_and_round_trips() {
        let mut buf = [0u8; 128];
        let mut out = SliceSink::new(&mut buf);
        assert_eq!(write("text", "*", &[], &mut out), Err(WriteError::NotToken));
        assert_eq!(
            write("te xt", "a", &[], &mut out),
            Err(WriteError::NotToken)
        );
        assert_eq!(
            write("a", "b", &[("x y", "1")], &mut out),
            Err(WriteError::NotToken)
        );
        assert_eq!(
            write("a", "b", &[("x", "1\r\n")], &mut out),
            Err(WriteError::Forbidden { at: 1 })
        );
        assert!(out.is_empty());
        write("a", "b", &[("x", "1 2"), ("y", "")], &mut out).unwrap();
        let back = mt(out.written()).unwrap();
        assert!(back.param("x").unwrap().eq_bytes(b"1 2"));
        assert!(back.param("y").unwrap().is_empty());
    }

    #[test]
    fn test_write_canonical_lowercases_names_only() {
        let v = mt(b"TEXT/Plain;  FORMAT=Flowed;x=\"A\\\"B\"").unwrap();
        let mut buf = [0u8; 64];
        let mut out = SliceSink::new(&mut buf);
        v.write_canonical(&mut out).unwrap();
        assert_eq!(out.written(), b"text/plain; format=Flowed; x=\"A\\\"B\"");
        let mut small = [0u8; 4];
        let mut out = SliceSink::new(&mut small);
        assert_eq!(v.write_canonical(&mut out), Err(WriteError::Full));
        assert!(out.is_empty());
    }
}