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
/*!
The `read_char` crate provides easy way to read `char` from any `Read` instance.
*/
#![deny(missing_docs)]

use std::io::Read;
use std::fmt::{Display,Formatter};
use smallvec::SmallVec;

/// The kind of error that can occur when reading char(s) from `Read`.
#[derive(Debug)]
pub enum Error {
    /// Encountered invalid byte sequence.
    NotAnUtf8(Vec<u8>),
    /// Underlying `Read` instance returned an error.
    Io(std::io::Error),
    /// End Of File was reached.
    EOF,
}

impl Display for Error {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        match self {
            Error::EOF => write!(f, "end of file"),
            Error::NotAnUtf8(b) => write!(f, "invalid utf-8 sequence: {:?}", b),
            Error::Io(e) => write!(f, "i/o error: {}", e),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Error::Io(e) => Some(e),
            _ => None,
        }
    }
}

const MAX_UNICODE_LEN : usize = 6;

/// Reads next valid utf-8 encoded char form `r`.
#[inline]
pub fn read_next_char<R: Read>(r: &mut R) -> Result<char, Error> {
    let mut offset = 0;
    let mut buf = SmallVec::<[u8; MAX_UNICODE_LEN+1]>::new();
    buf.push(0);
    loop {
        debug_assert!(!buf.spilled());
        if buf.len() > MAX_UNICODE_LEN {
            return Err(Error::NotAnUtf8(buf.to_vec()));
        }
        match r.read(&mut buf[offset..offset+1]) {
            Err(e) => return Err(Error::Io(e)),
            Ok(0) => return Err(Error::EOF),
            Ok(_) => {},
        };
        match std::str::from_utf8(&buf) {
            Ok(s) => {
                return Ok(s.chars().next().unwrap());
            },
            Err(_) => {
                buf.push(0);
                offset += 1;
            }
        }
    }
}

/// Iterator that reads char(s) from `Read` instance.
pub struct ReadIter<R: Read> {
    r: R
}

impl<R: Read> ReadIter<R> {
    /// Returns new `ReadIter` instance that reads from `r`.
    pub fn new(r: R) -> Self {
        ReadIter{r}
    }
}

impl<R: Read> Iterator for ReadIter<R> {
    type Item = Result<char, Error>;

    fn next(&mut self) -> Option<Self::Item> {
        match read_next_char(&mut self.r) {
            Err(Error::EOF) => None,
            e @ Err(_) => Some(e),
            c @ Ok(_) => Some(c),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;
    use proptest::prelude::*;

    #[test]
    fn char_iter() {
        let input = "foo bar baz";
        let iter = ReadIter::new(Cursor::new(&input));
        let output : Result<String,_> = iter.collect();
        assert_eq!(input, output.unwrap());
    }

    #[test]
    fn char_iter_unicode() {
        let input = "ążł¥アあ𝓐";
        let iter = ReadIter::new(Cursor::new(&input));
        let output : Result<String,_> = iter.collect();
        assert_eq!(input, output.unwrap());
    }

    #[test]
    fn incorrect_input() {
        let input = vec![195, 195, 195, 195, 195, 195, 0];
        let iter = ReadIter::new(Cursor::new(&input));
        let output : Result<Vec<_>,_> = iter.collect();
        assert!(output.is_err());
        if let Err(Error::NotAnUtf8(b)) = output {
            assert_eq!(input, b);
        } else {
            panic!("invalid error: {:?}", output)
        }
    }

    proptest! {
        #[test]
        fn any_correct_string(input in ".*") {
            let iter = ReadIter::new(Cursor::new(&input));
            let output : Result<String,_> = iter.collect();
            assert_eq!(input, output.unwrap());
        }

        #[test]
        fn incorrect_suffix_doesnt_prevent_prefix_decoding(prefix in ".*") {
            let mut input : Vec<u8> = prefix.clone().into();
            input.append(&mut vec![195, 195, 195, 195, 195, 195, 0]);
            let iter = ReadIter::new(Cursor::new(&input));
            let output : Result<String, _> = iter.take(prefix.chars().count()).collect();
            assert_eq!(prefix, output.unwrap());
        }

        #[test]
        fn incorrect_suffix_breaks_collect(prefix in ".*") {
            let mut input : Vec<u8> = prefix.clone().into();
            input.append(&mut vec![195, 195, 195, 195, 195, 195, 0]);
            let iter = ReadIter::new(Cursor::new(&input));
            let output : Result<String,_> = iter.collect();
            if let Err(Error::NotAnUtf8(_)) = output {
            } else {
                panic!("invalid error: {:?}", output)
            }
        }
    }
}