Created
April 6, 2015 03:09
-
-
Save beefsack/38d58848f9d5c078d1f9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Error as follows: