tina-core 0.0.2

Tina platform
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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
//! content-disposition 处理
use crate::regex::Regex;
use http::HeaderValue;
use once_cell::sync::Lazy;
use std::fmt::{self, Display};
use std::str::FromStr;

use crate::tina::data::app_error::AppError;
use crate::tina::data::AppResult;
use language_tags::LanguageTag;
use percent_encoding::{AsciiSet, CONTROLS};

/// Split at the index of the first `needle` if it exists or at the end.
fn split_once(haystack: &str, needle: char) -> (&str, &str) {
    haystack.find(needle).map_or_else(
        || (haystack, ""),
        |sc| {
            let (first, last) = haystack.split_at(sc);
            (first, last.split_at(1).1)
        },
    )
}

/// Split at the index of the first `needle` if it exists or at the end, trim the right of the
/// first part and the left of the last part.
fn split_once_and_trim(haystack: &str, needle: char) -> (&str, &str) {
    let (first, last) = split_once(haystack, needle);
    (first.trim_end(), last.trim_start())
}

/// The implied disposition of the content of the HTTP body.
#[derive(Clone, Debug, PartialEq)]
pub enum DispositionType {
    /// Inline implies default processing
    Inline,
    /// Attachment implies that the recipient should prompt the user to save the response locally,
    /// rather than process it normally (as per its media type).
    Attachment,
    /// Used in *multipart/form-data* as defined in
    /// [RFC7578](https://tools.ietf.org/html/rfc7578) to carry the field name and the file name.
    FormData,
    /// Extension type. Should be handled by recipients the same way as Attachment
    Ext(String),
}

impl<'a> From<&'a str> for DispositionType {
    fn from(origin: &'a str) -> DispositionType {
        if origin.eq_ignore_ascii_case("inline") {
            DispositionType::Inline
        } else if origin.eq_ignore_ascii_case("attachment") {
            DispositionType::Attachment
        } else if origin.eq_ignore_ascii_case("form-data") {
            DispositionType::FormData
        } else {
            DispositionType::Ext(origin.to_owned())
        }
    }
}

/// Parameter in [`ContentDisposition`].
///
/// # Examples
/// ```
/// ```
#[derive(Clone, Debug, PartialEq)]
pub enum DispositionParam {
    /// For [`DispositionType::FormData`] (i.e. *multipart/form-data*), the name of an field from
    /// the form.
    Name(String),
    /// A plain file name.
    ///
    /// It is [not supposed](https://tools.ietf.org/html/rfc6266#appendix-D) to contain any
    /// non-ASCII characters when used in a *Content-Disposition* HTTP response header, where
    /// [`FilenameExt`](DispositionParam::FilenameExt) with charset UTF-8 may be used instead
    /// in case there are Unicode characters in file names.
    Filename(String),
    /// An extended file name. It must not exist for `ContentType::Formdata` according to
    /// [RFC7578 Section 4.2](https://tools.ietf.org/html/rfc7578#section-4.2).
    FilenameExt(ExtendedValue),
    /// An unrecognized regular parameter as defined in
    /// [RFC5987](https://tools.ietf.org/html/rfc5987) as *reg-parameter*, in
    /// [RFC6266](https://tools.ietf.org/html/rfc6266) as *token "=" value*. Recipients should
    /// ignore unrecognizable parameters.
    Unknown(String, String),
    /// An unrecognized extended parameter as defined in
    /// [RFC5987](https://tools.ietf.org/html/rfc5987) as *ext-parameter*, in
    /// [RFC6266](https://tools.ietf.org/html/rfc6266) as *ext-token "=" ext-value*. The single
    /// trailing asterisk is not included. Recipients should ignore unrecognizable parameters.
    UnknownExt(String, ExtendedValue),
}

impl DispositionParam {
    /// Returns `true` if the parameter is [`Name`](DispositionParam::Name).
    #[inline]
    pub fn is_name(&self) -> bool {
        self.as_name().is_some()
    }

    /// Returns `true` if the parameter is [`Filename`](DispositionParam::Filename).
    #[inline]
    pub fn is_filename(&self) -> bool {
        self.as_filename().is_some()
    }

    /// Returns `true` if the parameter is [`FilenameExt`](DispositionParam::FilenameExt).
    #[inline]
    pub fn is_filename_ext(&self) -> bool {
        self.as_filename_ext().is_some()
    }

    /// Returns `true` if the parameter is [`Unknown`](DispositionParam::Unknown) and the `name`
    #[inline]
    /// matches.
    pub fn is_unknown<T: AsRef<str>>(&self, name: T) -> bool {
        self.as_unknown(name).is_some()
    }

    /// Returns `true` if the parameter is [`UnknownExt`](DispositionParam::UnknownExt) and the
    /// `name` matches.
    #[inline]
    pub fn is_unknown_ext<T: AsRef<str>>(&self, name: T) -> bool {
        self.as_unknown_ext(name).is_some()
    }

    /// Returns the name if applicable.
    #[inline]
    pub fn as_name(&self) -> Option<&str> {
        match self {
            DispositionParam::Name(ref name) => Some(name.as_str()),
            _ => None,
        }
    }

    /// Returns the filename if applicable.
    #[inline]
    pub fn as_filename(&self) -> Option<&str> {
        match self {
            DispositionParam::Filename(ref filename) => Some(filename.as_str()),
            _ => None,
        }
    }

    /// Returns the filename* if applicable.
    #[inline]
    pub fn as_filename_ext(&self) -> Option<&ExtendedValue> {
        match self {
            DispositionParam::FilenameExt(ref value) => Some(value),
            _ => None,
        }
    }

    /// Returns the value of the unrecognized regular parameter if it is
    /// [`Unknown`](DispositionParam::Unknown) and the `name` matches.
    #[inline]
    pub fn as_unknown<T: AsRef<str>>(&self, name: T) -> Option<&str> {
        match self {
            DispositionParam::Unknown(ref ext_name, ref value) if ext_name.eq_ignore_ascii_case(name.as_ref()) => Some(value.as_str()),
            _ => None,
        }
    }

    /// Returns the value of the unrecognized extended parameter if it is
    /// [`Unknown`](DispositionParam::Unknown) and the `name` matches.
    #[inline]
    pub fn as_unknown_ext<T: AsRef<str>>(&self, name: T) -> Option<&ExtendedValue> {
        match self {
            DispositionParam::UnknownExt(ref ext_name, ref value) if ext_name.eq_ignore_ascii_case(name.as_ref()) => Some(value),
            _ => None,
        }
    }
}

/// A *Content-Disposition* header. It is compatible to be used either as
/// [a response header for the main body](https://mdn.io/Content-Disposition#As_a_response_header_for_the_main_body)
/// as (re)defined in [RFC6266](https://tools.ietf.org/html/rfc6266), or as
/// [a header for a multipart body](https://mdn.io/Content-Disposition#As_a_header_for_a_multipart_body)
/// as (re)defined in [RFC7587](https://tools.ietf.org/html/rfc7578).
///
/// In a regular HTTP response, the *Content-Disposition* response header is a header indicating if
/// the content is expected to be displayed *inline* in the browser, that is, as a Web page or as
/// part of a Web page, or as an attachment, that is downloaded and saved locally, and also can be
/// used to attach additional metadata, such as the filename to use when saving the response payload
/// locally.
///
/// In a *multipart/form-data* body, the HTTP *Content-Disposition* general header is a header that
/// can be used on the subpart of a multipart body to give information about the field it applies to.
/// The subpart is delimited by the boundary defined in the *Content-Type* header. Used on the body
/// itself, *Content-Disposition* has no effect.
///
/// # ABNF

/// ```text
/// content-disposition = "Content-Disposition" ":"
///                       disposition-type *( ";" disposition-parm )
///
/// disposition-type    = "inline" | "attachment" | disp-ext-type
///                       ; case-insensitive
///
/// disp-ext-type       = token
///
/// disposition-parm    = filename-parm | disp-ext-parm
///
/// filename-parm       = "filename" "=" value
///                     | "filename*" "=" ext-value
///
/// disp-ext-parm       = token "=" value
///                     | ext-token "=" ext-value
///
/// ext-token           = <the characters in token, followed by "*">
/// ```
///
/// # Note
///
/// filename is [not supposed](https://tools.ietf.org/html/rfc6266#appendix-D) to contain any
/// non-ASCII characters when used in a *Content-Disposition* HTTP response header, where
/// filename* with charset UTF-8 may be used instead in case there are Unicode characters in file
/// names.
/// filename is [acceptable](https://tools.ietf.org/html/rfc7578#section-4.2) to be UTF-8 encoded
/// directly in a *Content-Disposition* header for *multipart/form-data*, though.
///
/// filename* [must not](https://tools.ietf.org/html/rfc7578#section-4.2) be used within
/// *multipart/form-data*.
///
#[derive(Clone, Debug, PartialEq)]
pub struct ContentDisposition {
    /// The disposition type
    pub disposition: DispositionType,
    /// Disposition parameters
    pub parameters: Vec<DispositionParam>,
}

impl ContentDisposition {
    /// Parse a raw Content-Disposition header value.
    pub fn from_raw(hv: &HeaderValue) -> AppResult<Self> {
        // `header::from_one_raw_str` invokes `hv.to_str` which assumes `hv` contains only visible
        //  ASCII characters. So `hv.as_bytes` is necessary here.
        let hv = String::from_utf8(hv.as_bytes().to_vec()).map_err(crate::app_error_from!())?;
        let (disp_type, mut left) = split_once_and_trim(hv.as_str().trim(), ';');
        if disp_type.is_empty() {
            return Err(crate::app_system_error!("Invalid Header provided"));
        }
        let mut cd = ContentDisposition {
            disposition: disp_type.into(),
            parameters: Vec::new(),
        };

        while !left.is_empty() {
            let (param_name, new_left) = split_once_and_trim(left, '=');
            if param_name.is_empty() || param_name == "*" || new_left.is_empty() {
                return Err(crate::app_system_error!("Invalid Header provided"));
            }
            left = new_left;
            if let Some(param_name) = param_name.strip_suffix('*') {
                // extended parameters
                let (ext_value, new_left) = split_once_and_trim(left, ';');
                left = new_left;
                let ext_value = parse_extended_value(ext_value)?;

                let param = if param_name.eq_ignore_ascii_case("filename") {
                    DispositionParam::FilenameExt(ext_value)
                } else {
                    DispositionParam::UnknownExt(param_name.to_owned(), ext_value)
                };
                cd.parameters.push(param);
            } else {
                // regular parameters
                let value = if left.starts_with('"') {
                    // quoted-string: defined in RFC6266 -> RFC2616 Section 3.6
                    let mut escaping = false;
                    let mut quoted_string = vec![];
                    let mut end = None;
                    // search for closing quote
                    for (i, &c) in left.as_bytes().iter().skip(1).enumerate() {
                        if escaping {
                            escaping = false;
                            quoted_string.push(c);
                        } else if c == 0x5c {
                            // backslash
                            escaping = true;
                        } else if c == 0x22 {
                            // double quote
                            end = Some(i + 1); // cuz skipped 1 for the leading quote
                            break;
                        } else {
                            quoted_string.push(c);
                        }
                    }
                    left = &left[end.ok_or(crate::app_system_error!("Invalid Header provided"))? + 1..];
                    left = split_once(left, ';').1.trim_start();
                    // In fact, it should not be Err if the above code is correct.
                    String::from_utf8(quoted_string).map_err(crate::app_error_from!())?
                } else {
                    // token: won't contains semicolon according to RFC 2616 Section 2.2
                    let (token, new_left) = split_once_and_trim(left, ';');
                    left = new_left;
                    if token.is_empty() {
                        // quoted-string can be empty, but token cannot be empty
                        return Err(crate::app_system_error!("Invalid Header provided"));
                    }
                    token.to_owned()
                };

                let param = if param_name.eq_ignore_ascii_case("name") {
                    DispositionParam::Name(value)
                } else if param_name.eq_ignore_ascii_case("filename") {
                    // See also comments in test_from_raw_unnecessary_percent_decode.
                    DispositionParam::Filename(value)
                } else {
                    DispositionParam::Unknown(param_name.to_owned(), value)
                };
                cd.parameters.push(param);
            }
        }

        Ok(cd)
    }

    /// Returns `true` if it is [`Inline`](DispositionType::Inline).
    pub fn is_inline(&self) -> bool {
        matches!(self.disposition, DispositionType::Inline)
    }

    /// Returns `true` if it is [`Attachment`](DispositionType::Attachment).
    pub fn is_attachment(&self) -> bool {
        matches!(self.disposition, DispositionType::Attachment)
    }

    /// Returns `true` if it is [`FormData`](DispositionType::FormData).
    pub fn is_form_data(&self) -> bool {
        matches!(self.disposition, DispositionType::FormData)
    }

    /// Returns `true` if it is [`Ext`](DispositionType::Ext) and the `disp_type` matches.
    pub fn is_ext<T: AsRef<str>>(&self, disp_type: T) -> bool {
        matches!(self.disposition, DispositionType::Ext(ref t) if t.eq_ignore_ascii_case(disp_type.as_ref()))
    }

    /// Return the value of *name* if exists.
    pub fn get_name(&self) -> Option<&str> {
        self.parameters.iter().filter_map(|p| p.as_name()).next()
    }

    /// Return the value of *filename* if exists.
    pub fn get_filename(&self) -> Option<&str> {
        self.parameters.iter().filter_map(|p| p.as_filename()).next()
    }

    /// Return the value of *filename\** if exists.
    pub fn get_filename_ext(&self) -> Option<&ExtendedValue> {
        self.parameters.iter().filter_map(|p| p.as_filename_ext()).next()
    }

    /// Return the value of the parameter which the `name` matches.
    pub fn get_unknown<T: AsRef<str>>(&self, name: T) -> Option<&str> {
        let name = name.as_ref();
        self.parameters.iter().filter_map(|p| p.as_unknown(name)).next()
    }

    /// Return the value of the extended parameter which the `name` matches.
    pub fn get_unknown_ext<T: AsRef<str>>(&self, name: T) -> Option<&ExtendedValue> {
        let name = name.as_ref();
        self.parameters.iter().filter_map(|p| p.as_unknown_ext(name)).next()
    }
}

impl fmt::Display for DispositionType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DispositionType::Inline => write!(f, "inline"),
            DispositionType::Attachment => write!(f, "attachment"),
            DispositionType::FormData => write!(f, "form-data"),
            DispositionType::Ext(ref s) => write!(f, "{}", s),
        }
    }
}

impl fmt::Display for DispositionParam {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // All ASCII control characters (0-30, 127) including horizontal tab, double quote, and
        // backslash should be escaped in quoted-string (i.e. "foobar").
        // Ref: RFC6266 S4.1 -> RFC2616 S3.6
        // filename-parm  = "filename" "=" value
        // value          = token | quoted-string
        // quoted-string  = ( <"> *(qdtext | quoted-pair ) <"> )
        // qdtext         = <any TEXT except <">>
        // quoted-pair    = "\" CHAR
        // TEXT           = <any OCTET except CTLs,
        //                  but including LWS>
        // LWS            = [CRLF] 1*( SP | HT )
        // OCTET          = <any 8-bit sequence of data>
        // CHAR           = <any US-ASCII character (octets 0 - 127)>
        // CTL            = <any US-ASCII control character
        //                  (octets 0 - 31) and DEL (127)>
        //
        // Ref: RFC7578 S4.2 -> RFC2183 S2 -> RFC2045 S5.1
        // parameter := attribute "=" value
        // attribute := token
        //              ; Matching of attributes
        //              ; is ALWAYS case-insensitive.
        // value := token / quoted-string
        // token := 1*<any (US-ASCII) CHAR except SPACE, CTLs,
        //             or tspecials>
        // tspecials :=  "(" / ")" / "<" / ">" / "@" /
        //               "," / ";" / ":" / "\" / <">
        //               "/" / "[" / "]" / "?" / "="
        //               ; Must be in quoted-string,
        //               ; to use within parameter values
        //
        //
        // See also comments in test_from_raw_unnecessary_percent_decode.
        static RE: Lazy<AppResult<Regex>> = Lazy::new(|| Regex::new("[\x00-\x08\x10-\x1F\x7F\"\\\\]").map_err(crate::app_error_from!()));
        let re = RE.as_ref().map_err(|err| {
            tracing::error!("{}", err);
            fmt::Error::default()
        })?;
        match self {
            DispositionParam::Name(ref value) => write!(f, "name={}", value),
            DispositionParam::Filename(ref value) => {
                write!(f, "filename=\"{}\"", re.replace_all(value, "\\$0").as_ref())
            }
            DispositionParam::Unknown(ref name, ref value) => write!(f, "{}=\"{}\"", name, re.replace_all(value, "\\$0").as_ref()),
            DispositionParam::FilenameExt(ref ext_value) => {
                write!(f, "filename*={}", ext_value)
            }
            DispositionParam::UnknownExt(ref name, ref ext_value) => {
                write!(f, "{}*={}", name, ext_value)
            }
        }
    }
}

impl From<ContentDisposition> for HeaderValue {
    fn from(value: ContentDisposition) -> Self {
        let str = value.to_string();
        HeaderValue::from_str(str.as_str()).unwrap_or_else(|_| panic!("ContentDisposition into HeaderValue failed: {}", str))
    }
}

impl fmt::Display for ContentDisposition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.disposition)?;
        self.parameters.iter().try_for_each(|param| write!(f, "; {}", param))
    }
}

/// The value part of an extended parameter consisting of three parts:
/// - The REQUIRED character set name (`charset`).
/// - The OPTIONAL language information (`language_tag`).
/// - A character sequence representing the actual value (`value`), separated by single quotes.
///
/// It is defined in [RFC 5987](https://tools.ietf.org/html/rfc5987#section-3.2).
#[derive(Clone, Debug, PartialEq)]
pub struct ExtendedValue {
    /// The character set that is used to encode the `value` to a string.
    pub charset: Charset,

    /// The human language details of the `value`, if available.
    pub language_tag: Option<LanguageTag>,

    /// The parameter value, as expressed in octets.
    pub value: Vec<u8>,
}

/// Parses extended header parameter values (`ext-value`), as defined in
/// [RFC 5987](https://tools.ietf.org/html/rfc5987#section-3.2).
///
/// Extended values are denoted by parameter names that end with `*`.
///
/// ## ABNF
///
/// ```text
/// ext-value     = charset  '\'' [ language ] '\'' value-chars
///               ; like RFC 2231's <extended-initial-value>
///               ; (see [RFC2231], Section 7)
///
/// charset       = "UTF-8" / "ISO-8859-1" / mime-charset
///
/// mime-charset  = 1*mime-charsetc
/// mime-charsetc = ALPHA / DIGIT
///               / "!" / "#" / "$" / "%" / "&"
///               / "+" / "-" / "^" / "_" / "`"
///               / "{" / "}" / "~"
///               ; as <mime-charset> in Section 2.3 of [RFC2978]
///               ; except that the single quote is not included
///               ; SHOULD be registered in the IANA charset registry
///
/// language      = <Language-Tag, defined in [RFC5646], Section 2.1>
///
/// value-chars   = *( pct-encoded / attr-char )
///
/// pct-encoded   = "%" HEXDIG HEXDIG
///               ; see [RFC3986], Section 2.1
///
/// attr-char     = ALPHA / DIGIT
///               / "!" / "#" / "$" / "&" / "+" / "-" / "."
///               / "^" / "_" / "`" / "|" / "~"
///               ; token except ( "*" / '\'' / "%" )
/// ```
pub fn parse_extended_value(val: &str) -> AppResult<ExtendedValue> {
    // Break into three pieces separated by the single-quote character
    let mut parts = val.splitn(3, '\'');

    // Interpret the first piece as a Charset
    let charset: Charset = match parts.next() {
        None => return Err(crate::app_system_error!("Invalid Header provided")),
        Some(n) => FromStr::from_str(n).map_err(crate::app_error_from!())?,
    };

    // Interpret the second piece as a language tag
    let language_tag: Option<LanguageTag> = match parts.next() {
        None => return Err(crate::app_system_error!("Invalid Header provided")),
        Some("") => None,
        Some(s) => match s.parse() {
            Ok(lt) => Some(lt),
            Err(_) => return Err(crate::app_system_error!("Invalid Header provided")),
        },
    };

    // Interpret the third piece as a sequence of value characters
    let value: Vec<u8> = match parts.next() {
        None => return Err(crate::app_system_error!("Invalid Header provided")),
        Some(v) => percent_encoding::percent_decode(v.as_bytes()).collect(),
    };

    Ok(ExtendedValue {
        charset,
        language_tag,
        value,
    })
}

impl std::fmt::Display for ExtendedValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let encoded_value = percent_encoding::percent_encode(&self.value[..], HTTP_VALUE);
        if let Some(ref lang) = self.language_tag {
            write!(f, "{}'{}'{}", self.charset, lang, encoded_value)
        } else {
            write!(f, "{}''{}", self.charset, encoded_value)
        }
    }
}

/// A Mime charset.
///
/// The string representation is normalized to upper case.
///
/// See <http://www.iana.org/assignments/character-sets/character-sets.xhtml>.
#[derive(Clone, Debug, PartialEq)]
#[allow(non_camel_case_types)]
pub enum Charset {
    /// US ASCII
    Us_Ascii,
    /// ISO-8859-1
    Iso_8859_1,
    /// ISO-8859-2
    Iso_8859_2,
    /// ISO-8859-3
    Iso_8859_3,
    /// ISO-8859-4
    Iso_8859_4,
    /// ISO-8859-5
    Iso_8859_5,
    /// ISO-8859-6
    Iso_8859_6,
    /// ISO-8859-7
    Iso_8859_7,
    /// ISO-8859-8
    Iso_8859_8,
    /// ISO-8859-9
    Iso_8859_9,
    /// ISO-8859-10
    Iso_8859_10,
    /// Shift_JIS
    Shift_Jis,
    /// EUC-JP
    Euc_Jp,
    /// ISO-2022-KR
    Iso_2022_Kr,
    /// EUC-KR
    Euc_Kr,
    /// ISO-2022-JP
    Iso_2022_Jp,
    /// ISO-2022-JP-2
    Iso_2022_Jp_2,
    /// ISO-8859-6-E
    Iso_8859_6_E,
    /// ISO-8859-6-I
    Iso_8859_6_I,
    /// ISO-8859-8-E
    Iso_8859_8_E,
    /// ISO-8859-8-I
    Iso_8859_8_I,
    /// GB2312
    Gb2312,
    /// Big5
    Big5,
    /// KOI8-R
    Koi8_R,
    /// An arbitrary charset specified as a string
    Ext(String),
}

impl Charset {
    fn label(&self) -> &str {
        match self {
            Charset::Us_Ascii => "US-ASCII",
            Charset::Iso_8859_1 => "ISO-8859-1",
            Charset::Iso_8859_2 => "ISO-8859-2",
            Charset::Iso_8859_3 => "ISO-8859-3",
            Charset::Iso_8859_4 => "ISO-8859-4",
            Charset::Iso_8859_5 => "ISO-8859-5",
            Charset::Iso_8859_6 => "ISO-8859-6",
            Charset::Iso_8859_7 => "ISO-8859-7",
            Charset::Iso_8859_8 => "ISO-8859-8",
            Charset::Iso_8859_9 => "ISO-8859-9",
            Charset::Iso_8859_10 => "ISO-8859-10",
            Charset::Shift_Jis => "Shift-JIS",
            Charset::Euc_Jp => "EUC-JP",
            Charset::Iso_2022_Kr => "ISO-2022-KR",
            Charset::Euc_Kr => "EUC-KR",
            Charset::Iso_2022_Jp => "ISO-2022-JP",
            Charset::Iso_2022_Jp_2 => "ISO-2022-JP-2",
            Charset::Iso_8859_6_E => "ISO-8859-6-E",
            Charset::Iso_8859_6_I => "ISO-8859-6-I",
            Charset::Iso_8859_8_E => "ISO-8859-8-E",
            Charset::Iso_8859_8_I => "ISO-8859-8-I",
            Charset::Gb2312 => "GB2312",
            Charset::Big5 => "big5",
            Charset::Koi8_R => "KOI8-R",
            Charset::Ext(ref s) => s,
        }
    }
}

impl Display for Charset {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.label())
    }
}

impl FromStr for Charset {
    type Err = AppError;

    fn from_str(s: &str) -> AppResult<Charset> {
        Ok(match s.to_ascii_uppercase().as_ref() {
            "US-ASCII" => Charset::Us_Ascii,
            "ISO-8859-1" => Charset::Iso_8859_1,
            "ISO-8859-2" => Charset::Iso_8859_2,
            "ISO-8859-3" => Charset::Iso_8859_3,
            "ISO-8859-4" => Charset::Iso_8859_4,
            "ISO-8859-5" => Charset::Iso_8859_5,
            "ISO-8859-6" => Charset::Iso_8859_6,
            "ISO-8859-7" => Charset::Iso_8859_7,
            "ISO-8859-8" => Charset::Iso_8859_8,
            "ISO-8859-9" => Charset::Iso_8859_9,
            "ISO-8859-10" => Charset::Iso_8859_10,
            "SHIFT-JIS" => Charset::Shift_Jis,
            "EUC-JP" => Charset::Euc_Jp,
            "ISO-2022-KR" => Charset::Iso_2022_Kr,
            "EUC-KR" => Charset::Euc_Kr,
            "ISO-2022-JP" => Charset::Iso_2022_Jp,
            "ISO-2022-JP-2" => Charset::Iso_2022_Jp_2,
            "ISO-8859-6-E" => Charset::Iso_8859_6_E,
            "ISO-8859-6-I" => Charset::Iso_8859_6_I,
            "ISO-8859-8-E" => Charset::Iso_8859_8_E,
            "ISO-8859-8-I" => Charset::Iso_8859_8_I,
            "GB2312" => Charset::Gb2312,
            "BIG5" => Charset::Big5,
            "KOI8-R" => Charset::Koi8_R,
            s => Charset::Ext(s.to_owned()),
        })
    }
}

/// This encode set is used for HTTP header values and is defined at
/// https://tools.ietf.org/html/rfc5987#section-3.2.
pub const HTTP_VALUE: &AsciiSet = &CONTROLS
    .add(b' ')
    .add(b'"')
    .add(b'%')
    .add(b'\'')
    .add(b'(')
    .add(b')')
    .add(b'*')
    .add(b',')
    .add(b'/')
    .add(b':')
    .add(b';')
    .add(b'<')
    .add(b'-')
    .add(b'>')
    .add(b'?')
    .add(b'[')
    .add(b'\\')
    .add(b']')
    .add(b'{')
    .add(b'}');