From 20f6a08c422a902bb6ae15caf19fb9b9f8ff354c Mon Sep 17 00:00:00 2001 From: Julian Orth Date: Wed, 15 Oct 2014 17:06:57 +0200 Subject: [PATCH] add try fill --- src/libstd/io/mod.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index 8592d48974a25..971ccc99c5458 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -593,6 +593,28 @@ pub trait Reader { Ok(read) } + /// Tries to fill the buffer. Returns the number of bytes read. + /// + /// This will continue to call `read` until the buffer has been filled. If `read` + /// returns 0 or EOF, the total number of bytes read will be returned. + /// + /// # Error + /// + /// If an error different from EOF occurs at any point, that error is returned, and no + /// further bytes are read. + fn try_fill(&mut self, buf: &mut [u8]) -> IoResult { + let mut read = 0; + while read < buf.len() { + match self.read(buf[mut read..]) { + Ok(0) => break, + Err(ref e) if e.kind == EndOfFile => break, + Ok(n) => read += n, + Err(e) => return Err(e), + } + } + Ok(read) + } + /// Reads a single byte. Returns `Err` on EOF. fn read_byte(&mut self) -> IoResult { let mut buf = [0];