Skip to content
Snippets Groups Projects
Commit 83680dda authored by Carl Lerche's avatar Carl Lerche
Browse files

Implement Source for std::io::Read

parent bb122711
No related branches found
No related tags found
No related merge requests found
......@@ -444,19 +444,24 @@ impl<'a> Source for &'a Bytes {
}
}
impl<'a> Source for &'a mut (io::Read+'a) {
impl<'a, R: io::Read+'a> Source for &'a mut R {
type Error = io::Error;
fn fill<B: MutBuf>(self, _buf: &mut B) -> Result<usize, io::Error> {
unimplemented!();
}
}
fn fill<B: MutBuf>(self, buf: &mut B) -> Result<usize, io::Error> {
let mut cnt = 0;
impl<'a> Source for &'a mut (Iterator<Item=u8>+'a) {
type Error = BufError;
while buf.has_remaining() {
let i = try!(self.read(buf.mut_bytes()));
if i == 0 {
break;
}
buf.advance(i);
cnt += i;
}
fn fill<B: MutBuf>(self, _buf: &mut B) -> Result<usize, BufError> {
unimplemented!();
Ok(cnt)
}
}
......
......@@ -5,6 +5,8 @@ use rand::random;
extern crate bytes;
extern crate rand;
mod test_buf;
mod test_buf_fill;
mod test_byte_buf;
mod test_bytes;
mod test_rope;
......
use bytes::*;
use std::io;
#[test]
pub fn test_filling_buf_from_reader() {
let mut reader = chunks(vec![b"foo", b"bar", b"baz"]);
let mut buf = ByteBuf::mut_with_capacity(1024);
assert_eq!(9, buf.write(&mut reader).unwrap());
assert_eq!(b"foobarbaz".to_bytes(), buf.flip().to_bytes());
}
fn chunks(chunks: Vec<&'static [u8]>) -> Chunked {
Chunked { chunks: chunks }
}
struct Chunked {
chunks: Vec<&'static [u8]>,
}
impl io::Read for Chunked {
fn read(&mut self, dst: &mut [u8]) -> io::Result<usize> {
use std::cmp;
use std::slice::bytes;
if self.chunks.is_empty() {
return Ok(0);
}
let src = self.chunks[0];
let len = cmp::min(src.len(), dst.len());
bytes::copy_memory(&mut dst[..len], &src[..len]);
if len < src.len() {
self.chunks[0] = &src[len..];
} else {
self.chunks.remove(0);
}
Ok(len)
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment