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
use std::io::{Result, Error, ErrorKind};
use std::convert::TryFrom;
mod safe;
pub use safe::Decoder;
fn next_byte<I: Iterator<Item=Result<u8>>>(iter: &mut I) -> Result<u32> {
match iter.next() {
Some(Ok(c)) => {
if c & 0xC0 == 0x80 {
Ok((c & 0x3F) as u32)
} else {
Err(Error::new(ErrorKind::InvalidData, "invalid UTF-8 sequence."))
}
},
Some(Err(e)) => Err(e),
None => Err(Error::new(ErrorKind::UnexpectedEof, "unexpected end of UTF-8 sequence."))
}
}
fn raw_decode_from<I: Iterator<Item=Result<u8>>>(a: u32, iter: &mut I) -> Result<u32> {
if a & 0x80 == 0x00 {
Ok(a)
} else if a & 0xE0 == 0xC0 {
let b = next_byte(iter)?;
Ok((a & 0x1F) << 6 | b)
} else if a & 0xF0 == 0xE0 {
let b = next_byte(iter)?;
let c = next_byte(iter)?;
Ok((a & 0x0F) << 12 | b << 6 | c)
} else if a & 0xF8 == 0xF0 {
let b = next_byte(iter)?;
let c = next_byte(iter)?;
let d = next_byte(iter)?;
Ok((a & 0x07) << 18 | b << 12 | c << 6 | d)
} else {
Err(Error::new(ErrorKind::InvalidData, "invalid UTF-8 sequence."))
}
}
fn decode_from<I: Iterator<Item=Result<u8>>>(a: u32, iter: &mut I) -> Result<char> {
match char::try_from(raw_decode_from(a, iter)?) {
Ok(c) => Ok(c),
Err(_) => Err(Error::new(ErrorKind::InvalidData, "invalid UTF-8 sequence."))
}
}
pub fn decode<I: Iterator<Item=Result<u8>>>(iter: &mut I) -> Option<Result<char>> {
match iter.next() {
Some(Ok(a)) => Some(decode_from(a as u32, iter)),
Some(Err(e)) => Some(Err(e)),
None => None
}
}
pub struct UnsafeDecoder<R: Iterator<Item=Result<u8>>> {
bytes: R
}
impl<R: Iterator<Item=Result<u8>>> UnsafeDecoder<R> {
pub fn new(source: R) -> UnsafeDecoder<R> {
UnsafeDecoder {
bytes: source
}
}
}
impl<R: Iterator<Item=Result<u8>>> Iterator for UnsafeDecoder<R> {
type Item = Result<char>;
fn next(&mut self) -> Option<Result<char>> {
decode(&mut self.bytes)
}
}