Read_exact() won't work properly in non-blocking mode, any replacement?

read_exact() won’t work properly in non-blocking mode, they hit WouldBlock and start misbehaving.

My question: Is there any good replacement for this read_exact() implementation for non-blocking mode?

Here is the current implementation code in rustlib:

    #[stable(feature = "read_exact", since = "1.6.0")]
    fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
        while !buf.is_empty() {
            match self.read(buf) {
                Ok(0) => break,
                Ok(n) => { let tmp = buf; buf = &mut tmp[n..]; }
                Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
                Err(e) => return Err(e),
            }
        }
        if !buf.is_empty() {
            Err(Error::new(ErrorKind::UnexpectedEof,
                           "failed to fill whole buffer"))
        } else {
            Ok(())
        }
    }

You can use tokio::io::read_exact, which returns a future to work asynchrounously.

1 Like

Thanks @dodomorandi