1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
use std::io::{self, Read}; pub struct Chunks<R> { read: R, size: usize, hint: (usize, Option<usize>), } impl<R> Chunks<R> { pub fn new(read: R, size: usize) -> Self { Self { read, size, hint: (0, None), } } } impl<R> Iterator for Chunks<R> where R: Read, { type Item = io::Result<Vec<u8>>; fn next(&mut self) -> Option<Self::Item> { let mut chunk = Vec::with_capacity(self.size); match self .read .by_ref() .take(chunk.capacity() as u64) .read_to_end(&mut chunk) { Ok(n) => { if n != 0 { Some(Ok(chunk)) } else { None } } Err(e) => Some(Err(e)), } } fn size_hint(&self) -> (usize, Option<usize>) { self.hint } } pub(crate) trait ReadPlus: Read { fn chunks(self, size: usize) -> Chunks<Self> where Self: Sized, { Chunks::new(self, size) } } impl<T: ?Sized> ReadPlus for T where T: Read {}