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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
//! Character sources.
//!
//! This is here so we can read from things that aren’t ASCII or UTF-8.
#![cfg(feature = "std")]

use super::scan::CharSource;
use std::boxed::Box;
use std::fs::File;
use std::io::Read;
use std::path::Path;
use std::vec::Vec;
use std::{char, error, fmt, io};

//------------ str -----------------------------------------------------------

impl<'a> CharSource for &'a str {
    fn next(&mut self) -> Result<Option<char>, io::Error> {
        let res = match self.chars().next() {
            Some(ch) => ch,
            None => return Ok(None),
        };
        *self = &self[res.len_utf8()..];
        Ok(Some(res))
    }
}

//------------ AsciiFile -----------------------------------------------------

/// A file that contains only ASCII characters.
///
//  This isn’t built atop a BufReader because we can optimize for our
//  strategy of reading from the buffer byte by byte.
pub struct AsciiFile {
    file: File,
    buf: Option<(Box<[u8]>, usize, usize)>,
}

impl AsciiFile {
    pub fn new(file: File) -> Self {
        AsciiFile {
            file,
            buf: unsafe {
                let mut buffer = Vec::with_capacity(CAP);
                buffer.set_len(CAP);
                Some((buffer.into_boxed_slice(), 0, 0))
            },
        }
    }

    /// Opens a file at the given path as an ASCII-only file.
    pub fn open<P: AsRef<Path>>(path: P) -> Result<Self, io::Error> {
        File::open(path).map(Self::new)
    }
}

impl CharSource for AsciiFile {
    fn next(&mut self) -> Result<Option<char>, io::Error> {
        let err =
            if let Some((ref mut buf, ref mut len, ref mut pos)) = self.buf {
                if *pos < *len {
                    let res = buf[*pos];
                    if res.is_ascii() {
                        *pos += 1;
                        return Ok(Some(res as char));
                    }
                    Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        AsciiError(res),
                    ))
                } else {
                    match self.file.read(buf) {
                        Ok(0) => Ok(None),
                        Ok(read_len) => {
                            *len = read_len;
                            let res = buf[0];
                            if res.is_ascii() {
                                *pos = 1;
                                return Ok(Some(res as char));
                            }
                            Err(io::Error::new(
                                io::ErrorKind::InvalidData,
                                AsciiError(res),
                            ))
                        }
                        Err(err) => Err(err),
                    }
                }
            } else {
                return Ok(None);
            };
        self.buf = None;
        err
    }
}

//------------ Utf8File ------------------------------------------------------

/// A file that contains UTF-8 encoded text.
pub struct Utf8File(OctetFile);

impl Utf8File {
    pub fn new(file: File) -> Self {
        Utf8File(OctetFile::new(file))
    }

    /// Opens a file at the given path as an ASCII-only file.
    pub fn open<P: AsRef<Path>>(path: P) -> Result<Self, io::Error> {
        File::open(path).map(Self::new)
    }
}

impl CharSource for Utf8File {
    fn next(&mut self) -> Result<Option<char>, io::Error> {
        let first = match self.0.next()? {
            Some(ch) => ch,
            None => return Ok(None),
        };
        if first.is_ascii() {
            //first < 0x80  {
            return Ok(Some(first as char));
        }
        let second = match self.0.next()? {
            Some(ch) => ch,
            None => {
                return Err(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    "unexpected EOF",
                ))
            }
        };
        if first < 0xC0 || second < 0x80 {
            return Err(Utf8Error.into());
        }
        if first < 0xE0 {
            return Ok(Some(unsafe {
                char::from_u32_unchecked(
                    (u32::from(first & 0x1F)) << 6 | u32::from(second & 0x3F),
                )
            }));
        }
        let third = match self.0.next()? {
            Some(ch) => ch,
            None => {
                return Err(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    "unexpected EOF",
                ))
            }
        };
        if third < 0x80 {
            return Err(Utf8Error.into());
        }
        if first < 0xF0 {
            return Ok(Some(unsafe {
                char::from_u32_unchecked(
                    (u32::from(first & 0x0F)) << 12
                        | (u32::from(second & 0x3F)) << 6
                        | u32::from(third & 0x3F),
                )
            }));
        }
        let fourth = match self.0.next()? {
            Some(ch) => ch,
            None => {
                return Err(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    "unexpected EOF",
                ))
            }
        };
        if first > 0xF7 || fourth < 0x80 {
            return Err(Utf8Error.into());
        }
        Ok(Some(unsafe {
            char::from_u32_unchecked(
                (u32::from(first & 0x07)) << 18
                    | (u32::from(second & 0x3F)) << 12
                    | (u32::from(third & 0x3F)) << 6
                    | u32::from(fourth & 0x3F),
            )
        }))
    }
}

impl From<Utf8Error> for io::Error {
    fn from(err: Utf8Error) -> Self {
        io::Error::new(io::ErrorKind::Other, err)
    }
}

//------------ OctetFile -----------------------------------------------------

//  This isn’t built atop a BufReader because we can optimize for our
//  strategy of reading from the buffer byte by byte.
pub struct OctetFile {
    file: File,
    buf: Option<(Box<[u8]>, usize, usize)>,
}

const CAP: usize = 8 * 1024;

impl OctetFile {
    pub fn new(file: File) -> Self {
        OctetFile {
            file,
            buf: unsafe {
                let mut buffer = Vec::with_capacity(CAP);
                buffer.set_len(CAP);
                Some((buffer.into_boxed_slice(), 0, 0))
            },
        }
    }

    /// Opens a file at the given path as an ASCII-only file.
    pub fn open<P: AsRef<Path>>(path: P) -> Result<Self, io::Error> {
        File::open(path).map(Self::new)
    }

    #[inline]
    fn next(&mut self) -> Result<Option<u8>, io::Error> {
        let err =
            if let Some((ref mut buf, ref mut len, ref mut pos)) = self.buf {
                if *pos < *len {
                    let res = buf[*pos];
                    *pos += 1;
                    return Ok(Some(res));
                } else {
                    match self.file.read(buf) {
                        Ok(0) => Ok(None),
                        Ok(read_len) => {
                            *len = read_len;
                            let res = buf[0];
                            if res.is_ascii() {
                                *pos = 1;
                                return Ok(Some(res));
                            }
                            Err(io::Error::new(
                                io::ErrorKind::InvalidData,
                                AsciiError(res),
                            ))
                        }
                        Err(err) => Err(err),
                    }
                }
            } else {
                return Ok(None);
            };
        self.buf = None;
        err
    }
}

//=========== Error Types ===================================================

//------------ AsciiError ----------------------------------------------------

/// An error happened while reading an ASCII-only file.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct AsciiError(u8);

//--- Display and Error

impl fmt::Display for AsciiError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "invalid ASCII character '{}'", self.0)
    }
}

impl error::Error for AsciiError {}

//------------ Utf8Error -----------------------------------------------------

/// An error happened while reading a file encoded with UTF-8.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Utf8Error;

//--- Display and Error

impl fmt::Display for Utf8Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("invalid UTF-8 sequence")
    }
}

impl error::Error for Utf8Error {}