rust_strings/
encodings.rs

1use std::error::Error;
2use std::fmt;
3use std::str::FromStr;
4
5#[derive(Debug, Copy, Clone)]
6pub enum Encoding {
7    ASCII,
8    UTF16LE,
9    UTF16BE,
10}
11
12impl fmt::Display for Encoding {
13    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
14        write!(f, "{:?}", self)
15    }
16}
17
18#[derive(Debug)]
19pub struct EncodingNotFoundError {
20    encoding: String,
21}
22
23impl fmt::Display for EncodingNotFoundError {
24    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
25        write!(f, "Encoding not found: {:?}", self.encoding)
26    }
27}
28
29impl EncodingNotFoundError {
30    fn new(encoding: String) -> Self {
31        EncodingNotFoundError { encoding }
32    }
33}
34
35impl Error for EncodingNotFoundError {}
36
37impl FromStr for Encoding {
38    type Err = EncodingNotFoundError;
39
40    fn from_str(encoding: &str) -> Result<Self, Self::Err> {
41        let encoding: &str = &encoding.to_lowercase();
42        match encoding {
43            "utf-16le" => Ok(Encoding::UTF16LE),
44            "utf-16be" => Ok(Encoding::UTF16BE),
45            "ascii" => Ok(Encoding::ASCII),
46            "utf8" => Ok(Encoding::ASCII),
47            "utf-8" => Ok(Encoding::ASCII),
48            _ => Err(EncodingNotFoundError::new(encoding.to_owned())),
49        }
50    }
51}