Skip to content

Instantly share code, notes, and snippets.

@beefsack
Created April 6, 2015 03:09
Show Gist options
  • Select an option

  • Save beefsack/38d58848f9d5c078d1f9 to your computer and use it in GitHub Desktop.

Select an option

Save beefsack/38d58848f9d5c078d1f9 to your computer and use it in GitHub Desktop.
extern crate std;
const DEFAULT_BUF_SIZE: usize = 64 * 1024;
pub struct PeekReader<R> {
inner: R,
buf: Vec<u8>,
pos: usize,
cap: usize,
}
pub trait PeekRead: std::io::Read {
fn peek(&mut self, buf: &mut [u8]) -> std::io::Result<usize>;
}
impl<R: std::io::Read> PeekReader<R> {
pub fn new(inner: R) -> PeekReader<R> {
PeekReader::with_capacity(DEFAULT_BUF_SIZE, inner)
}
pub fn with_capacity(cap: usize, inner: R) -> PeekReader<R> {
let mut buf = Vec::with_capacity(cap);
buf.extend(std::iter::repeat(0).take(cap));
PeekReader {
inner: inner,
buf: buf,
pos: 0,
cap: 0,
}
}
pub fn consume(&mut self, amt: usize) {
self.pos = std::cmp::min(self.pos + amt, self.cap);
}
}
impl <R: std::io::Read> std::io::Read for PeekReader<R> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
if self.pos == self.cap {
return self.inner.read(buf);
}
let nread = try!((&self.buf[self.pos..self.cap]).read(buf));
self.consume(nread);
Ok(nread)
}
}
impl <R: std::io::Read> PeekRead for PeekReader<R> {
fn peek(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let b_len = buf.len();
if b_len > self.cap - self.pos {
if self.pos > 0 && b_len > self.buf.len() - self.pos {
// need to read more than the size of the buffer, move items to start
for _ in 0..self.pos {
self.buf.remove(0);
}
self.cap -= self.pos;
self.pos = 0;
}
if b_len > self.buf.len() {
// peek buffer too small, need to resize
self.buf.resize(b_len, 0);
}
}
(&self.buf[self.pos..self.cap]).read(buf)
}
}
@beefsack
Copy link
Author

beefsack commented Apr 6, 2015

Error as follows:

src/parser/io.rs:65:41: 65:50 error: type `&[u8]` does not implement any method in scope named `read`
src/parser/io.rs:65         (&self.buf[self.pos..self.cap]).read(buf)
                                                            ^~~~~~~~~
src/parser/io.rs:65:50: 65:50 help: methods from traits can only be called if the trait is in scope; the following traits are implemented but not in scope, perhaps add a `use` for one of them:
src/parser/io.rs:65:50: 65:50 help: candidate #1: use `std::io::Read`
src/parser/io.rs:65:50: 65:50 help: candidate #2: use `std::old_io::Reader`
error: aborting due to previous error

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment