utf8_decode/safe.rs
1use std::io::{Result, Error, ErrorKind};
2use std::convert::TryFrom;
3
4/// Read the next byte of the UTF-8 character out of the given byte iterator.
5/// The byte is returned as a `u32` for later shifting.
6/// Returns an `InvalidData` error if the byte is not part of a valid UTF-8 sequence.
7/// Returns an `UnexpectedEof` error if the input iterator returns `None`.
8fn next_byte<I: Iterator<Item=u8>>(iter: &mut I) -> Result<u32> {
9 match iter.next() {
10 Some(c) => {
11 if c & 0xC0 == 0x80 {
12 Ok((c & 0x3F) as u32)
13 } else {
14 Err(Error::new(ErrorKind::InvalidData, "invalid UTF-8 sequence."))
15 }
16 },
17 None => Err(Error::new(ErrorKind::UnexpectedEof, "unexpected end of UTF-8 sequence."))
18 }
19}
20
21/// Read the next Unicode codepoint given its first byte.
22/// The first input byte is given as a `u32` for later shifting.
23/// Returns an `InvalidData` error the input iterator does not output a valid UTF-8 sequence.
24/// Returns an `UnexpectedEof` error if the input iterator returns `None` before the end of the
25/// UTF-8 character.
26fn raw_decode_from<I: Iterator<Item=u8>>(a: u32, iter: &mut I) -> Result<u32> {
27 if a & 0x80 == 0x00 {
28 Ok(a)
29 } else if a & 0xE0 == 0xC0 {
30 let b = next_byte(iter)?;
31 Ok((a & 0x1F) << 6 | b)
32 } else if a & 0xF0 == 0xE0 {
33 let b = next_byte(iter)?;
34 let c = next_byte(iter)?;
35 Ok((a & 0x0F) << 12 | b << 6 | c)
36 } else if a & 0xF8 == 0xF0 {
37 let b = next_byte(iter)?;
38 let c = next_byte(iter)?;
39 let d = next_byte(iter)?;
40 Ok((a & 0x07) << 18 | b << 12 | c << 6 | d)
41 } else {
42 Err(Error::new(ErrorKind::InvalidData, "invalid UTF-8 sequence."))
43 }
44}
45
46/// Read the next Unicode character given its first byte.
47/// Returns an `InvalidData` error the input iterator does not output a valid UTF-8 sequence.
48/// Returns an `UnexpectedEof` error if the input iterator returns `None` before the end of the
49/// UTF-8 character.
50fn decode_from<I: Iterator<Item=u8>>(a: u32, iter: &mut I) -> Result<char> {
51 match char::try_from(raw_decode_from(a, iter)?) {
52 Ok(c) => Ok(c),
53 Err(_) => Err(Error::new(ErrorKind::InvalidData, "invalid UTF-8 sequence."))
54 }
55}
56
57/// Read the next Unicode character out of the given [`u8`](u8) iterator.
58///
59/// Returns `None` is the input iterator directly outputs `None`.
60/// Returns an [`InvalidData`](std::io::ErrorKind::InvalidData) error the input iterator does not
61/// output a valid UTF-8 sequence.
62/// Returns an [`UnexpectedEof`](std::io::ErrorKind::UnexpectedEof) error if the input iterator
63/// returns `None` before the end of an UTF-8 character.
64pub fn decode<I: Iterator<Item=u8>>(iter: &mut I) -> Option<Result<char>> {
65 match iter.next() {
66 Some(a) => Some(decode_from(a as u32, iter)),
67 None => None
68 }
69}
70
71/// UTF-8 decoder iterator.
72///
73/// Transform the given [`u8`](u8) iterator into a [`io::Result<char>`](std::io::Result) iterator.
74/// This iterator cannot be used to decode an [`io::Read`](std::io::Read) source, since the input
75/// iterator would be over [`io::Result<u8>`](std::io::Result) and not `u8`. However in this case
76/// you can use the [`UnsafeDecoder`](crate::UnsafeDecoder) iterator.
77///
78/// ## Example
79/// The `Decoder` iterator can be used, for instance, to decode `u8` slices.
80/// ```rust
81/// let bytes = [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33];
82///
83/// let decoder = Decoder::new(bytes.iter().cloned());
84///
85/// let mut string = String::new();
86/// for c in decoder {
87/// string.push(c?);
88/// }
89///
90/// println!("{}", string);
91/// ```
92///
93/// ## Errors
94/// A call to [`next`](Iterator::next) returns an [`InvalidData`](std::io::ErrorKind::InvalidData)
95/// error if the input iterator does not output a valid UTF-8 sequence, or an
96/// [`UnexpectedEof`](std::io::ErrorKind::UnexpectedEof) if the stream ends before the end of a
97/// valid character.
98pub struct Decoder<R: Iterator<Item=u8>> {
99 bytes: R
100}
101
102impl<R: Iterator<Item=u8>> Decoder<R> {
103 /// Creates a new `Decoder` iterator from the given `u8` source iterator.
104 pub fn new(source: R) -> Decoder<R> {
105 Decoder {
106 bytes: source
107 }
108 }
109}
110
111impl<R: Iterator<Item=u8>> Iterator for Decoder<R> {
112 type Item = Result<char>;
113
114 fn next(&mut self) -> Option<Result<char>> {
115 decode(&mut self.bytes)
116 }
117}