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
use std::error::Error;
use std::fmt;
use std::str::FromStr;
#[derive(Debug, Copy, Clone)]
pub enum Encoding {
ASCII,
UTF16LE,
UTF16BE,
}
impl fmt::Display for Encoding {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self)
}
}
#[derive(Debug)]
pub struct EncodingNotFoundError {
encoding: String,
}
impl fmt::Display for EncodingNotFoundError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Encoding not found: {:?}", self.encoding)
}
}
impl EncodingNotFoundError {
fn new(encoding: String) -> Self {
EncodingNotFoundError { encoding }
}
}
impl Error for EncodingNotFoundError {}
impl FromStr for Encoding {
type Err = EncodingNotFoundError;
fn from_str(encoding: &str) -> Result<Self, Self::Err> {
let encoding: &str = &encoding.to_lowercase();
match encoding {
"utf-16le" => Ok(Encoding::UTF16LE),
"utf-16be" => Ok(Encoding::UTF16BE),
"ascii" => Ok(Encoding::ASCII),
"utf8" => Ok(Encoding::ASCII),
"utf-8" => Ok(Encoding::ASCII),
_ => Err(EncodingNotFoundError::new(encoding.to_owned())),
}
}
}