From 319b8833d807b6bbd0982aecd45c5c8459ac063e Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Mon, 2 Sep 2013 14:23:57 -0400 Subject: [PATCH] Implement BufReader --- src/libstd/rt/io/mem.rs | 42 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 39 insertions(+), 3 deletions(-) diff --git a/src/libstd/rt/io/mem.rs b/src/libstd/rt/io/mem.rs index 277897e5d2e..b278f10aed0 100644 --- a/src/libstd/rt/io/mem.rs +++ b/src/libstd/rt/io/mem.rs @@ -171,13 +171,27 @@ impl<'self> BufReader<'self> { } impl<'self> Reader for BufReader<'self> { - fn read(&mut self, _buf: &mut [u8]) -> Option { fail!() } + fn read(&mut self, buf: &mut [u8]) -> Option { + { if self.eof() { return None; } } - fn eof(&mut self) -> bool { fail!() } + let write_len = min(buf.len(), self.buf.len() - self.pos); + { + let input = self.buf.slice(self.pos, self.pos + write_len); + let output = buf.mut_slice(0, write_len); + assert_eq!(input.len(), output.len()); + vec::bytes::copy_memory(output, input, write_len); + } + self.pos += write_len; + assert!(self.pos <= self.buf.len()); + + return Some(write_len); + } + + fn eof(&mut self) -> bool { self.pos == self.buf.len() } } impl<'self> Seek for BufReader<'self> { - fn tell(&self) -> u64 { fail!() } + fn tell(&self) -> u64 { self.pos as u64 } fn seek(&mut self, _pos: i64, _style: SeekStyle) { fail!() } } @@ -219,4 +233,26 @@ mod test { assert_eq!(reader.read(buf), None); assert!(reader.eof()); } + + #[test] + fn test_buf_reader() { + let in_buf = ~[0, 1, 2, 3, 4, 5, 6, 7]; + let mut reader = BufReader::new(in_buf); + let mut buf = []; + assert_eq!(reader.read(buf), Some(0)); + assert_eq!(reader.tell(), 0); + let mut buf = [0]; + assert_eq!(reader.read(buf), Some(1)); + assert_eq!(reader.tell(), 1); + assert_eq!(buf, [0]); + let mut buf = [0, ..4]; + assert_eq!(reader.read(buf), Some(4)); + assert_eq!(reader.tell(), 5); + assert_eq!(buf, [1, 2, 3, 4]); + assert_eq!(reader.read(buf), Some(3)); + assert_eq!(buf.slice(0, 3), [5, 6, 7]); + assert!(reader.eof()); + assert_eq!(reader.read(buf), None); + assert!(reader.eof()); + } }