Skip to content

Instantly share code, notes, and snippets.

@durka
Forked from anonymous/playground.rs
Last active August 29, 2015 14:26
Show Gist options
  • Save durka/f1d2bd36882bf8eb29ed to your computer and use it in GitHub Desktop.
Save durka/f1d2bd36882bf8eb29ed to your computer and use it in GitHub Desktop.
read_to_vec
use std::io::{Cursor, Read, self};
trait ReadExt {
fn read_to_vec(&mut self, buf: &mut Vec<u8>) -> io::Result<usize>;
}
impl<T: Read> ReadExt for T {
fn read_to_vec(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
self.take(buf.capacity() as u64).read_to_end(buf)
}
}
fn main() {
let mut source = Cursor::<&[u8]>::new(b"stuff");
let mut buf = Vec::<u8>::with_capacity(4);
source.read_to_vec(&mut buf).unwrap();
println!("{:?}", buf);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment