mirror of
https://github.com/tokio-rs/bytes.git
synced 2026-08-25 00:00:22 +02:00
Implement Source for std::io::Read
This commit is contained in:
+14
-9
@@ -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;
|
type Error = io::Error;
|
||||||
|
|
||||||
fn fill<B: MutBuf>(self, _buf: &mut B) -> Result<usize, io::Error> {
|
fn fill<B: MutBuf>(self, buf: &mut B) -> Result<usize, io::Error> {
|
||||||
unimplemented!();
|
let mut cnt = 0;
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> Source for &'a mut (Iterator<Item=u8>+'a) {
|
while buf.has_remaining() {
|
||||||
type Error = BufError;
|
let i = try!(self.read(buf.mut_bytes()));
|
||||||
|
|
||||||
fn fill<B: MutBuf>(self, _buf: &mut B) -> Result<usize, BufError> {
|
if i == 0 {
|
||||||
unimplemented!();
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
buf.advance(i);
|
||||||
|
cnt += i;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(cnt)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ use rand::random;
|
|||||||
extern crate bytes;
|
extern crate bytes;
|
||||||
extern crate rand;
|
extern crate rand;
|
||||||
|
|
||||||
|
mod test_buf;
|
||||||
|
mod test_buf_fill;
|
||||||
mod test_byte_buf;
|
mod test_byte_buf;
|
||||||
mod test_bytes;
|
mod test_bytes;
|
||||||
mod test_rope;
|
mod test_rope;
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user