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 59 60 61 62
#[cfg(test)] use std::io::{self, Read}; #[cfg(test)] pub struct WouldBlockReader<R> { inner: R, do_block: bool, } #[cfg(test)] impl<R: Read> WouldBlockReader<R> { pub fn new(inner: R) -> Self { WouldBlockReader { inner, do_block: false, } } } #[cfg(test)] impl<R: Read> Read for WouldBlockReader<R> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.do_block = !self.do_block; if self.do_block { Err(io::Error::new(io::ErrorKind::WouldBlock, "Would block")) } else if buf.is_empty() { Ok(0) } else { let mut byte = [0; 1]; if self.inner.read(&mut byte[..])? == 1 { buf[0] = byte[0]; Ok(1) } else { Ok(0) } } } } #[cfg(test)] pub fn nb_read_to_end<R: Read>(mut reader: R) -> io::Result<Vec<u8>> { let mut buf = vec![0; 1024]; let mut offset = 0; loop { match reader.read(&mut buf[offset..]) { Err(e) => { if e.kind() != io::ErrorKind::WouldBlock { return Err(e); } } Ok(0) => { buf.truncate(offset); break; } Ok(size) => { offset += size; if offset == buf.len() { buf.resize(offset * 2, 0); } } } } Ok(buf) }