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
//! Internal types for the `mime` crate.
//!
//! Nothing to see here. Move along.

use std::error::Error;
use std::{fmt, slice};

pub mod constants;
mod rfc7231;

use self::constants::Atoms;
use self::sealed::Sealed;

pub struct Parser {
    can_range: bool,
}

#[derive(Clone)]
pub struct Mime {
    source: Source,
    slash: u16,
    plus: Option<u16>,
    params: ParamSource,
}

#[derive(Clone)]
pub enum Source {
    Atom(u8, &'static str),
    Dynamic(String),
}

impl AsRef<str> for Source {
    fn as_ref(&self) -> &str {
        match *self {
            Source::Atom(_, s) => s,
            Source::Dynamic(ref s) => s,
        }
    }
}

type Indexed = (u16, u16);
type IndexedPair = (Indexed, Indexed);

#[derive(Clone)]
pub enum ParamSource {
    None,
    Utf8(u16),
    One(u16, IndexedPair),
    Two(u16, IndexedPair, IndexedPair),
    Custom(u16, Vec<IndexedPair>),
}

pub enum InternParams {
    Utf8(usize),
    None,
}

#[derive(Debug)]
pub enum ParseError {
    MissingSlash,
    MissingEqual,
    MissingQuote,
    InvalidToken {
        pos: usize,
        byte: Byte,
    },
    InvalidRange,
    TooLong,
}

#[derive(Clone, Copy)]
pub struct Byte(u8);

impl fmt::Debug for Byte {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.0 {
            b'\n' => f.write_str("'\\n'"),
            b'\r' => f.write_str("'\\r'"),
            b'\t' => f.write_str("'\\t'"),
            b'\\' => f.write_str("'\\'"),
            b'\0' => f.write_str("'\\0'"),
            0x20..=0x7f => write!(f, "'{}'", self.0 as char),
            _ => write!(f, "'\\x{:02x}'", self.0),
        }
    }
}

impl Error for ParseError {
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let description = match self {
            ParseError::MissingSlash => "a slash (/) was missing between the type and subtype",
            ParseError::MissingEqual => "an equals sign (=) was missing between a parameter and its value",
            ParseError::MissingQuote => "a quote (\") was missing from a parameter value",
            ParseError::InvalidToken { .. } => "invalid token",
            ParseError::InvalidRange => "unexpected asterisk",
            ParseError::TooLong => "the string is too long",
        };
        if let ParseError::InvalidToken { pos, byte } = *self {
            write!(f, "{}, {:?} at position {}", description, byte, pos)
        } else {
            f.write_str(description)
        }
    }
}

// ===== impl Mime =====

impl Mime {
    #[inline]
    pub fn type_(&self) -> &str {
        &self.source.as_ref()[..self.slash as usize]
    }

    #[inline]
    pub fn subtype(&self) -> &str {
        let end = self.semicolon_or_end();
        &self.source.as_ref()[self.slash as usize + 1..end]
    }

    #[doc(hidden)]
    pub fn private_subtype_offset(&self) -> u16 {
        self.slash
    }

    #[inline]
    pub fn suffix(&self) -> Option<&str> {
        let end = self.semicolon_or_end();
        self.plus.map(|idx| &self.source.as_ref()[idx as usize + 1..end])
    }

    #[doc(hidden)]
    pub fn private_suffix_offset(&self) -> Option<u16> {
        self.plus
    }

    #[inline]
    pub fn params(&self) -> Params {
        let inner = match self.params {
            ParamSource::Utf8(_) => ParamsInner::Utf8,
            ParamSource::One(_, a) => ParamsInner::Inlined(&self.source, Inline::One(a)),
            ParamSource::Two(_, a, b) => ParamsInner::Inlined(&self.source, Inline::Two(a, b)),
            ParamSource::Custom(_, ref params) => {
                ParamsInner::Custom {
                    source: &self.source,
                    params: params.iter(),
                }
            }
            ParamSource::None => ParamsInner::None,
        };

        Params(inner)
    }

    #[doc(hidden)]
    pub fn private_params_source(&self) -> &ParamSource {
        &self.params
    }

    pub fn param<'a>(&'a self, attr: &str) -> Option<&'a str> {
        self.params().find(|e| attr == e.0).map(|e| e.1)
    }

    #[inline]
    pub fn has_params(&self) -> bool {
        self.semicolon().is_some()
    }

    #[inline]
    pub fn without_params(self) -> Self {
        let semicolon = match self.semicolon() {
            None => return self,
            Some(i) => i,
        };

        let mut mtype = self;
        mtype.params = ParamSource::None;
        mtype.source = Atoms::intern(
            &mtype.source.as_ref()[..semicolon],
            mtype.slash,
            InternParams::None,
        );
        mtype
    }

    #[inline]
    fn semicolon(&self) -> Option<usize> {
        match self.params {
            ParamSource::Utf8(i) |
            ParamSource::One(i, ..) |
            ParamSource::Two(i, ..) |
            ParamSource::Custom(i, _) => Some(i as usize),
            ParamSource::None => None,
        }
    }

    #[inline]
    fn semicolon_or_end(&self) -> usize {
        self.semicolon().unwrap_or_else(|| self.source.as_ref().len())
    }

    #[doc(hidden)]
    pub fn private_atom(&self) -> u8 {
        self.atom()
    }

    fn atom(&self) -> u8 {
        match self.source {
            Source::Atom(a, _) => a,
            Source::Dynamic(_) => 0,
        }
    }

    pub fn essence(&self) -> &str {
        &self.source.as_ref()[..self.semicolon_or_end()]
    }

    #[doc(hidden)]
    pub const unsafe fn private_from_proc_macro(
        source: Source,
        slash: u16,
        plus: Option<u16>,
        params: ParamSource,
    ) -> Mime {
        Mime {
            source,
            slash,
            plus,
            params,
        }
    }
}

impl AsRef<str> for Mime {
    #[inline]
    fn as_ref(&self) -> &str {
        self.source.as_ref()
    }
}

impl fmt::Debug for Mime {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(self.source.as_ref(), f)
    }
}

impl fmt::Display for Mime {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(self.source.as_ref(), f)
    }
}

#[inline]
fn as_u16(i: usize) -> u16 {
    debug_assert!(i <= std::u16::MAX as usize, "as_u16 overflow");
    i as u16
}

#[inline]
fn range(index: (u16, u16)) -> std::ops::Range<usize> {
    index.0 as usize .. index.1 as usize
}

// ===== impl Parser =====

impl Parser {
    #[inline]
    pub fn can_range() -> Self {
        Parser {
            can_range: true,
        }
    }

    #[inline]
    pub fn cannot_range() -> Self {
        Parser {
            can_range: false,
        }
    }

    pub fn parse(&self, src: impl Parse) -> Result<Mime, ParseError> {
        rfc7231::parse(self, src)
    }
}


fn lower_ascii_with_params(s: &str, semi: usize, params: &[IndexedPair]) -> String {
    let mut owned = s.to_owned();
    owned[..semi].make_ascii_lowercase();

    for &(name, value) in params {
        owned[range(name)].make_ascii_lowercase();
        // Since we just converted this part of the string to lowercase,
        // we can skip the `Name == &str` unicase check and do a faster
        // memcmp instead.
        if &owned[range(name)] == "charset" {
            owned[range(value)].make_ascii_lowercase();
        }
    }

    owned
}


// Params ===================


enum ParamsInner<'a> {
    Utf8,
    Inlined(&'a Source, Inline),
    Custom {
        source: &'a Source,
        params: slice::Iter<'a, IndexedPair>,
    },
    None,
}


enum Inline {
    Done,
    One(IndexedPair),
    Two(IndexedPair, IndexedPair),
}

/// An iterator over the parameters of a MIME.
pub struct Params<'a>(ParamsInner<'a>);

impl<'a> fmt::Debug for Params<'a> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("Params").finish()
    }
}

impl<'a> Iterator for Params<'a> {
    type Item = (&'a str, &'a str);

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        match self.0 {
            ParamsInner::Utf8 => {
                let value = ("charset", "utf-8");
                self.0 = ParamsInner::None;
                Some(value)
            },
            ParamsInner::Inlined(source, ref mut inline) => {
                let next = match *inline {
                    Inline::Done => {
                        None
                    }
                    Inline::One(one) => {
                        *inline = Inline::Done;
                        Some(one)
                    },
                    Inline::Two(one, two) => {
                        *inline = Inline::One(two);
                        Some(one)
                    },
                };
                next.map(|(name, value)| {
                    let name = &source.as_ref()[range(name)];
                    let value = &source.as_ref()[range(value)];
                    (name, value)
                })
            },
            ParamsInner::Custom { source, ref mut params } => {
                params.next().map(|&(name, value)| {
                    let name = &source.as_ref()[range(name)];
                    let value = &source.as_ref()[range(value)];
                    (name, value)
                })
            },
            ParamsInner::None => None,
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        match self.0 {
            ParamsInner::Utf8 => (1, Some(1)),
            ParamsInner::Inlined(_, Inline::Done) => (0, Some(0)),
            ParamsInner::Inlined(_, Inline::One(..)) => (1, Some(1)),
            ParamsInner::Inlined(_, Inline::Two(..)) => (2, Some(2)),
            ParamsInner::Custom { ref params, .. } => params.size_hint(),
            ParamsInner::None => (0, Some(0)),
        }
    }
}

mod sealed {
    pub trait Sealed {
        fn as_str(&self) -> &str;
    }
}

pub trait Parse: Sealed {}

impl<'a> Sealed for &'a str {
    fn as_str(&self) -> &str {
        self
    }
}

impl<'a> Parse for &'a str {}

impl<'a> Sealed for &'a String {
    fn as_str(&self) -> &str {
        *self
    }
}

impl<'a> Parse for &'a String {}