Skip to main content

utf8_decode/
infallible.rs

1use crate::{TryDecoder, Utf8Error};
2
3/// UTF-8 decoder iterator.
4///
5/// Transforms the given [`u8`] iterator into a [`Result<char, Utf8Error>`]
6/// iterator.
7///
8/// ## Example
9///
10/// The `Decoder` iterator can be used, for instance, to decode `u8` slices.
11///
12/// ```rust
13/// use utf8_decode::Decoder;
14/// # fn main() -> std::io::Result<()> {
15/// let bytes = [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33];
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/// # Ok(())
26/// # }
27/// ```
28pub struct Decoder<R>(TryDecoder<InfallibleInput<R>>);
29
30impl<R> Decoder<R> {
31    /// Creates a new `Decoder` iterator from the given [`u8`] source iterator.
32    pub fn new(source: R) -> Self {
33        Self(TryDecoder::new(InfallibleInput(source)))
34    }
35}
36
37impl<R> Iterator for Decoder<R>
38where
39    R: Iterator<Item = u8>,
40{
41    type Item = Result<char, Utf8Error>;
42
43    fn next(&mut self) -> Option<Result<char, Utf8Error>> {
44        self.0.next()
45    }
46}
47
48struct InfallibleInput<T>(T);
49
50impl<T> Iterator for InfallibleInput<T>
51where
52    T: Iterator<Item = u8>,
53{
54    type Item = Result<u8, Utf8Error>;
55
56    fn next(&mut self) -> Option<Self::Item> {
57        self.0.next().map(Ok)
58    }
59}