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
#![cfg_attr(test, deny(missing_docs))]
#![cfg_attr(test, deny(warnings))]

//! The crate provides an enum representing all charset names used in Media Types
//! and HTTP header values. The list can be found at [the IANA Character Sets
//! registry](http://www.iana.org/assignments/character-sets/character-sets.xhtml).
//!
//! Charset names can be parsed from string, formatted to string and compared.
//! Charset names can be parsed from string, formatted to string and compared.
//! Unregistered charsets are represented using an `Unregistered` variant.

use std::fmt::{self, Display};
use std::str::FromStr;
use std::ascii::AsciiExt;
use std::error::Error as ErrorTrait;

pub use self::Charset::*;

/// An error type used for this crate.
///
/// It may be extended in the future to give more information.
#[derive(Debug, Eq, PartialEq)]
pub enum Error {
    /// Parsing as as charset failed.
    Invalid,
}

impl ErrorTrait for Error {
    fn description(&self) -> &str {
        return "The given charset is invalid";
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(self.description())
    }
}

/// Result type used for this library.
pub type Result<T> = ::std::result::Result<T, Error>;

/// A Mime charset.
///
/// The string representation is normalised to upper case.
///
/// See http://www.iana.org/assignments/character-sets/character-sets.xhtml
#[derive(Clone, Debug, Eq, Ord, PartialOrd)]
pub enum Charset {
    /// US ASCII
    UsAscii,
    /// ISO-8859-1
    Iso88591,
    /// ISO-8859-2
    Iso88592,
    /// ISO-8859-3
    Iso88593,
    /// ISO-8859-4
    Iso88594,
    /// ISO-8859-5
    Iso88595,
    /// ISO-8859-6
    Iso88596,
    /// ISO-8859-7
    Iso88597,
    /// ISO-8859-8
    Iso88598,
    /// ISO-8859-9
    Iso88599,
    /// ISO-8859-10
    Iso885910,
    /// Shift_JIS
    ShiftJis,
    /// EUC-JP
    EucJp,
    /// ISO-2022-KR
    Iso2022Kr,
    /// EUC-KR
    EucKr,
    /// ISO-2022-JP
    Iso2022Jp,
    /// ISO-2022-JP-2
    Iso2022Jp2,
    /// ISO-8859-6-E
    Iso88596E,
    /// ISO-8859-6-I
    Iso88596I,
    /// ISO-8859-8-E
    Iso88598E,
    /// ISO-8859-8-I
    Iso88598I,
    /// GB2312
    Gb2312,
    /// Big5
    Big5,
    /// KOI8-R
    Koi8R,
    /// UTF-8
    Utf8,
    /// An arbitrary charset specified as a string
    Unregistered(String),
}

const MAPPING: [(Charset, &'static str); 25] = [(UsAscii, "US-ASCII"),
 (Iso88591, "ISO-8859-1"),
 (Iso88592, "ISO-8859-2"),
 (Iso88593, "ISO-8859-3"),
 (Iso88594, "ISO-8859-4"),
 (Iso88595, "ISO-8859-5"),
 (Iso88596, "ISO-8859-6"),
 (Iso88597, "ISO-8859-7"),
 (Iso88598, "ISO-8859-8"),
 (Iso88599, "ISO-8859-9"),
 (Iso885910, "ISO-8859-10"),
 (ShiftJis, "Shift-JIS"),
 (EucJp, "EUC-JP"),
 (Iso2022Kr, "ISO-2022-KR"),
 (EucKr, "EUC-KR"),
 (Iso2022Jp, "ISO-2022-JP"),
 (Iso2022Jp2, "ISO-2022-JP-2"),
 (Iso88596E, "ISO-8859-6-E"),
 (Iso88596I, "ISO-8859-6-I"),
 (Iso88598E, "ISO-8859-8-E"),
 (Iso88598I, "ISO-8859-8-I"),
 (Gb2312, "GB2312"),
 (Big5, "5"),
 (Koi8R, "KOI8-R"),
 (Utf8, "utf-8")];

impl Charset {
    fn name(&self) -> &str {
        if let &Unregistered(ref s) = self {
            return &s[..];
        }
        MAPPING.iter()
               .find(|&&(ref variant, _)| self == variant)
               .map(|&(_, name)| name)
               .unwrap()
    }
}

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

impl FromStr for Charset {
    type Err = ::Error;
    fn from_str(s: &str) -> ::Result<Charset> {
        Ok(MAPPING.iter()
                  .find(|&&(_, ref name)| name.eq_ignore_ascii_case(s))
                  .map(|&(ref variant, _)| variant.to_owned())
                  .unwrap_or(Unregistered(s.to_owned())))
    }
}

impl PartialEq for Charset {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (&UsAscii, &UsAscii) |
            (&Iso88591, &Iso88591) |
            (&Iso88592, &Iso88592) |
            (&Iso88593, &Iso88593) |
            (&Iso88594, &Iso88594) |
            (&Iso88595, &Iso88595) |
            (&Iso88596, &Iso88596) |
            (&Iso88597, &Iso88597) |
            (&Iso88598, &Iso88598) |
            (&Iso88599, &Iso88599) |
            (&Iso885910, &Iso885910) |
            (&ShiftJis, &ShiftJis) |
            (&EucJp, &EucJp) |
            (&Iso2022Kr, &Iso2022Kr) |
            (&EucKr, &EucKr) |
            (&Iso2022Jp, &Iso2022Jp) |
            (&Iso2022Jp2, &Iso2022Jp2) |
            (&Iso88596E, &Iso88596E) |
            (&Iso88596I, &Iso88596I) |
            (&Iso88598E, &Iso88598E) |
            (&Iso88598I, &Iso88598I) |
            (&Gb2312, &Gb2312) |
            (&Big5, &Big5) |
            (&Koi8R, &Koi8R) |
            (&Utf8, &Utf8) => true,
            (&Unregistered(ref s), &Unregistered(ref t)) => s.eq_ignore_ascii_case(t),
            _ => false,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse() {
        assert_eq!(UsAscii, "us-ascii".parse().unwrap());
        assert_eq!(UsAscii, "US-Ascii".parse().unwrap());
        assert_eq!(UsAscii, "US-ASCII".parse().unwrap());
        assert_eq!(ShiftJis, "Shift-JIS".parse().unwrap());
        assert_eq!(Unregistered("ABCD".to_owned()), "abcd".parse().unwrap());
    }

    #[test]
    fn test_display() {
        assert_eq!("US-ASCII", UsAscii.to_string());
        assert_eq!("ABCD", Unregistered("ABCD".to_owned()).to_string());
    }

    #[test]
    fn test_cmp() {
        assert!(Iso88593 == Iso88593);
        assert!(UsAscii != Iso88593);
        assert_eq!(Unregistered("foobar".to_owned()),
                   Unregistered("FOOBAR".to_owned()));
    }
}