utf8_decode/
lib.rs

1//! This crates provides incremental UTF-8 decoders implementing the [`Iterator`](std::iter::Iterator) trait.
2//! Thoses iterators are wrappers around [`u8`] bytes iterators.
3//!
4//! ## Decoder
5//!
6//! The [`Decoder`](safe::Decoder) struct wraps [`u8`] iterators.
7//! You can use it, for instance, to decode `u8` slices.
8//!
9//! ```rust
10//! extern crate utf8_decode;
11//!
12//! use utf8_decode::Decoder;
13//!
14//! fn main() -> std::io::Result<()> {
15//!     let bytes = [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 32, 240, 159, 140, 141];
16//!
17//!     let decoder = Decoder::new(bytes.iter().cloned());
18//!
19//!     let mut string = String::new();
20//!     for c in decoder {
21//!         string.push(c?);
22//!     }
23//!
24//!     println!("{}", string);
25//!
26//!     Ok(())
27//! }
28//! ```
29//!
30//! ## UnsafeDecoder
31//!
32//! The [`UnsafeDecoder`] wraps [`std::io::Result<u8>`](std::io::Result) iterators.
33//! You can use it, for instance, to decode UTF-8 encoded files.
34//!
35//! ```rust
36//! extern crate utf8_decode;
37//!
38//! use std::fs::File;
39//! use std::io::Read;
40//! use utf8_decode::UnsafeDecoder;
41//!
42//! fn main() -> std::io::Result<()> {
43//!     let file = File::open("examples/file.txt")?;
44//!
45//!     let decoder = UnsafeDecoder::new(file.bytes());
46//!
47//!     let mut string = String::new();
48//!     for c in decoder {
49//!         string.push(c?);
50//!     }
51//!
52//!     println!("{}", string);
53//!
54//!     Ok(())
55//! }
56//! ```
57
58use std::io::{Result, Error, ErrorKind};
59use std::convert::TryFrom;
60
61mod safe;
62pub use safe::{Decoder, decode};
63
64/// Read the next byte of the UTF-8 character out of the given byte iterator.
65/// The byte is returned as a `u32` for later shifting.
66/// Returns an `InvalidData` error if the byte is not part of a valid UTF-8 sequence.
67/// Returns an `UnexpectedEof` error if the input iterator returns `None`.
68fn next_byte<I: Iterator<Item=Result<u8>>>(iter: &mut I) -> Result<u32> {
69    match iter.next() {
70        Some(Ok(c)) => {
71            if c & 0xC0 == 0x80 {
72                Ok((c & 0x3F) as u32)
73            } else {
74                Err(Error::new(ErrorKind::InvalidData, "invalid UTF-8 sequence."))
75            }
76        },
77        Some(Err(e)) => Err(e),
78        None => Err(Error::new(ErrorKind::UnexpectedEof, "unexpected end of UTF-8 sequence."))
79    }
80}
81
82/// Read the next Unicode codepoint given its first byte.
83/// The first input byte is given as a `u32` for later shifting.
84/// Returns an `InvalidData` error the input iterator does not output a valid UTF-8 sequence.
85/// Returns an `UnexpectedEof` error if the input iterator returns `None` before the end of the
86/// UTF-8 character.
87fn raw_decode_from<I: Iterator<Item=Result<u8>>>(a: u32, iter: &mut I) -> Result<u32> {
88    if a & 0x80 == 0x00 {
89        Ok(a)
90    } else if a & 0xE0 == 0xC0 {
91        let b = next_byte(iter)?;
92        Ok((a & 0x1F) << 6 | b)
93    } else if a & 0xF0 == 0xE0 {
94        let b = next_byte(iter)?;
95        let c = next_byte(iter)?;
96        Ok((a & 0x0F) << 12 | b << 6 | c)
97    } else if a & 0xF8 == 0xF0 {
98        let b = next_byte(iter)?;
99        let c = next_byte(iter)?;
100        let d = next_byte(iter)?;
101        Ok((a & 0x07) << 18 | b << 12 | c << 6 | d)
102    } else {
103        Err(Error::new(ErrorKind::InvalidData, "invalid UTF-8 sequence."))
104    }
105}
106
107/// Read the next Unicode character given its first byte.
108/// Returns an `InvalidData` error the input iterator does not output a valid UTF-8 sequence.
109/// Returns an `UnexpectedEof` error if the input iterator returns `None` before the end of the
110/// UTF-8 character.
111fn decode_from<I: Iterator<Item=Result<u8>>>(a: u32, iter: &mut I) -> Result<char> {
112    match char::try_from(raw_decode_from(a, iter)?) {
113        Ok(c) => Ok(c),
114        Err(_) => Err(Error::new(ErrorKind::InvalidData, "invalid UTF-8 sequence."))
115    }
116}
117
118/// Read the next Unicode character out of the given [`Result<u8>`](Iterator) iterator.
119///
120/// Returns `None` is the input iterator directly outputs `None`.
121/// Returns an [`InvalidData`](std::io::ErrorKind::InvalidData) error the input iterator does not
122/// output a valid UTF-8 sequence.
123/// Returns an [`UnexpectedEof`](std::io::ErrorKind::UnexpectedEof) error if the input iterator
124/// returns `None` before the end of an UTF-8 character.
125pub fn decode_unsafe<I: Iterator<Item=Result<u8>>>(iter: &mut I) -> Option<Result<char>> {
126	match iter.next() {
127		Some(Ok(a)) => Some(decode_from(a as u32, iter)),
128		Some(Err(e)) => Some(Err(e)),
129		None => None
130	}
131}
132
133/// UTF-8 decoder iterator for unsafe input.
134///
135/// Transform the given [`io::Result<u8>`](std::io::Result) iterator into a [`io::Result<char>`](std::io::Result) iterator.
136/// This iterator can be useful to decode from an [`io::Read`](std::io::Read) source, but if your input
137/// iterator iterates directly over `u8`, then use the [`Decoder`](crate::Decoder) iterator instead.
138///
139/// ## Example
140/// The `UnsafeDecoder` iterator can be used, for instance, to decode UTF-8 encoded files.
141/// ```rust
142/// let file = File::open("file.txt")?;
143///
144/// let decoder = UnsafeDecoder::new(file.bytes());
145///
146/// let mut string = String::new();
147/// for c in decoder {
148///     string.push(c?);
149/// }
150/// ```
151///
152/// ## Errors
153/// A call to [`next`](Iterator::next) returns an [`InvalidData`](std::io::ErrorKind::InvalidData)
154/// error if the input iterator does not output a valid UTF-8 sequence, or an
155/// [`UnexpectedEof`](std::io::ErrorKind::UnexpectedEof) if the stream ends before the end of a
156/// valid character.
157pub struct UnsafeDecoder<R: Iterator<Item=Result<u8>>> {
158	bytes: R
159}
160
161impl<R: Iterator<Item=Result<u8>>> UnsafeDecoder<R> {
162    /// Creates a new `Decoder` iterator from the given [`Result<u8>`](std::io::Result) source
163    /// iterator.
164	pub fn new(source: R) -> UnsafeDecoder<R> {
165		UnsafeDecoder {
166			bytes: source
167		}
168	}
169}
170
171impl<R: Iterator<Item=Result<u8>>> Iterator for UnsafeDecoder<R> {
172	type Item = Result<char>;
173
174	fn next(&mut self) -> Option<Result<char>> {
175		decode_unsafe(&mut self.bytes)
176	}
177}