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
use std::io::{Read, Error};
#[derive(Debug)]
struct Bom ( u8, u8, u8, u8 );
#[derive(Clone,Debug,PartialEq,Eq)]
enum Flavour {
UCS,
UTF,
EBCDIC,
ASCII,
Unknown,
}
#[derive(Clone,Debug,PartialEq,Eq)]
enum ByteOrder {
BigEndian,
LittleEndian,
Unusual2143,
Unusual3412,
NotApplicable
}
#[derive(Clone,Debug,PartialEq,Eq)]
enum Width {
EightBit = 8,
SixteenBit = 16,
ThirtyTwoBit = 32
}
#[derive(Clone,Debug,PartialEq,Eq)]
struct Descriptor (Flavour, Width, ByteOrder);
const UCS_4_BE: Descriptor = Descriptor(Flavour::UCS, Width::ThirtyTwoBit, ByteOrder::BigEndian);
const UCS_4_LE: Descriptor = Descriptor(Flavour::UCS, Width::ThirtyTwoBit, ByteOrder::LittleEndian);
const UCS_4_2143: Descriptor = Descriptor(Flavour::UCS, Width::ThirtyTwoBit, ByteOrder::Unusual2143);
const UCS_4_3412: Descriptor = Descriptor(Flavour::UCS, Width::ThirtyTwoBit, ByteOrder::Unusual3412);
const UTF_16_BE: Descriptor = Descriptor(Flavour::UTF, Width::SixteenBit, ByteOrder::BigEndian);
const UTF_16_LE: Descriptor = Descriptor(Flavour::UTF, Width::SixteenBit, ByteOrder::LittleEndian);
const UTF_8: Descriptor = Descriptor(Flavour::UTF, Width::EightBit, ByteOrder::NotApplicable);
const EBCDIC: Descriptor = Descriptor(Flavour::EBCDIC, Width::EightBit, ByteOrder::NotApplicable);
const ASCII_32BIT_BE: Descriptor = Descriptor(Flavour::Unknown, Width::ThirtyTwoBit, ByteOrder::BigEndian);
const ASCII_32BIT_LE: Descriptor = Descriptor(Flavour::Unknown, Width::ThirtyTwoBit, ByteOrder::LittleEndian);
const ASCII_16BIT_BE: Descriptor = Descriptor(Flavour::Unknown, Width::SixteenBit, ByteOrder::BigEndian);
const ASCII_16BIT_LE: Descriptor = Descriptor(Flavour::Unknown, Width::SixteenBit, ByteOrder::LittleEndian);
const ASCII_8BIT: Descriptor = Descriptor(Flavour::ASCII, Width::EightBit, ByteOrder::NotApplicable);
pub fn detect<R: Read>(reader: &mut R, hint: Option<String>) -> Result<Vec<String>, Error> {
let mut first_four_bytes = [0u8; 4];
try!(reader.read(&mut first_four_bytes));
let bom = Bom(
first_four_bytes[0],
first_four_bytes[1],
first_four_bytes[2],
first_four_bytes[3]
);
let possible_encoding = detect_byte_order_mark(&bom);
let mut buf = [0u8; 512];
try!(reader.read(&mut buf));
let mut candidates = Vec::with_capacity(3);
search("encoding=", &buf.to_vec(), possible_encoding.as_ref())
.or_else(|| search("charset=", &buf.to_vec(), possible_encoding.as_ref()))
.map(normalise)
.map(|encoding| push_if_not_contains(&mut candidates, endianify(&encoding, possible_encoding.as_ref())));
hint.map(normalise)
.map(|encoding| push_if_not_contains(&mut candidates, endianify(&encoding, possible_encoding.as_ref())));
match possible_encoding {
Some(UCS_4_LE) => Some("ucs-4le"),
Some(UCS_4_BE) => Some("ucs-4be"),
Some(UTF_16_LE) => Some("utf-16le"),
Some(UTF_16_BE) => Some("utf-16be"),
Some(Descriptor(Flavour::UTF, Width::EightBit, _)) => Some("utf-8"),
Some(EBCDIC) => Some("ebcdic"),
_ => None
}.map(|encoding| push_if_not_contains(&mut candidates, encoding.to_string()));
if candidates.is_empty() && String::from_utf8(buf.to_vec()).is_ok() {
candidates.push("utf-8".to_string());
}
return Ok(candidates);
}
fn detect_byte_order_mark(bom: &Bom) -> Option<Descriptor> {
match *bom {
Bom(0x00, 0x00, 0xFE, 0xFF) => Some(UCS_4_BE),
Bom(0xFF, 0xFE, 0x00, 0x00) => Some(UCS_4_LE),
Bom(0x00, 0x00, 0xFF, 0xFE) => Some(UCS_4_2143),
Bom(0xFE, 0xFF, 0x00, 0x00) => Some(UCS_4_3412),
Bom(0xFE, 0xFF, c , d ) if c > 0 || d > 0 => Some(UTF_16_BE),
Bom(0xFF, 0xFE, c , d ) if c > 0 || d > 0 => Some(UTF_16_LE),
Bom(0xEF, 0xBB, 0xBF, _ ) => Some(UTF_8),
Bom(0x00, 0x00, 0x00, 0x3C) => Some(ASCII_32BIT_BE),
Bom(0x3C, 0x00, 0x00, 0x00) => Some(ASCII_32BIT_LE),
Bom(0x00, 0x00, 0x3C, 0x00) => Some(Descriptor(Flavour::Unknown, Width::ThirtyTwoBit, ByteOrder::Unusual2143)),
Bom(0x00, 0x3C, 0x00, 0x00) => Some(Descriptor(Flavour::Unknown, Width::ThirtyTwoBit, ByteOrder::Unusual3412)),
Bom(0x00, 0x3C, 0x00, 0x3F) => Some(ASCII_16BIT_BE),
Bom(0x3C, 0x00, 0x3F, 0x00) => Some(ASCII_16BIT_LE),
Bom(0x3C, 0x3F, 0x78, 0x6D) => Some(ASCII_8BIT),
Bom(0x4C, 0x6F, 0xA7, 0x94) => Some(EBCDIC),
_ => None,
}
}
fn normalise<S: AsRef<str>>(encoding: S) -> String {
encoding.as_ref().to_lowercase()
.replace("us-ascii", "ascii")
.replace("utf8", "utf-8")
.replace("shift-jis", "shift_jis")
}
fn push_if_not_contains<T: PartialEq>(vec: &mut Vec<T>, item: T) {
if !vec.contains(&item) {
vec.push(item);
}
}
fn endianify(encoding: &str, descriptor: Option<&Descriptor>) -> String {
let ascii = ASCII_8BIT;
let &Descriptor(_, _, ref order) = descriptor.unwrap_or(&ascii);
match encoding {
"utf-16" => {
match *order {
ByteOrder::LittleEndian => "utf-16le".to_string(),
ByteOrder::BigEndian => "utf-16be".to_string(),
_ => encoding.to_string()
}
},
_ => encoding.to_string()
}
}
fn search(needle: &str, haystack: &Vec<u8>, descriptor: Option<&Descriptor>) -> Option<String> {
let ascii = ASCII_8BIT;
let &Descriptor(_, ref width, ref order) = descriptor.unwrap_or(&ascii);
let chunk_size = (width.clone() as usize) / 8;
let mut index = match *order {
ByteOrder::NotApplicable | ByteOrder::LittleEndian => 0,
ByteOrder::BigEndian => chunk_size - 1,
ByteOrder::Unusual2143 => 2,
ByteOrder::Unusual3412 => 1,
};
let mut ascii_bytes = Vec::with_capacity(haystack.len() / chunk_size);
while index < haystack.len() {
ascii_bytes.push(haystack[index]);
index += chunk_size;
}
let ascii_haystack = String::from_utf8_lossy(&ascii_bytes);
ascii_haystack.find(needle).map(|pos| {
ascii_haystack[pos + needle.len()..].chars()
.skip_while(|char| *char == '"' || *char == '\'')
.take_while(|char| *char != '"' && *char != '\'').collect()
})
}