-
Notifications
You must be signed in to change notification settings - Fork 2
/
streams.rs
47 lines (43 loc) · 1.24 KB
/
streams.rs
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
use super::lexer_stream::LexerStream;
use crate::error_handling::Error::IOError;
use crate::error_handling::Result;
use std::io::{self, BufReader, Read};
const BUF_SIZE: usize = 4096 * 8;
pub struct BufferedFileStream {
buf_reader: BufReader<std::fs::File>,
pos: usize,
end: usize,
buffer: [u8; BUF_SIZE],
}
impl BufferedFileStream {
pub fn new(path: &str) -> Result<Self> {
match std::fs::File::open(path) {
Ok(file) => Ok(Self {
buf_reader: BufReader::new(file),
pos: 0,
end: 0,
buffer: [0; BUF_SIZE],
}),
Err(e) => Err(IOError(e)),
}
}
}
impl LexerStream for BufferedFileStream {
fn get_next_char(&mut self) -> Result<Option<u8>> {
if self.pos == self.end {
match self.buf_reader.read(&mut self.buffer) {
Ok(byte_read) => {
if 0 == byte_read {
return Ok(None);
}
self.end = byte_read;
self.pos = 0;
}
Err(e) => return Err(IOError(e)),
}
}
let c = self.buffer[self.pos];
self.pos += 1;
Ok(Some(c))
}
}