|
| 1 | +use std::error::Error; |
| 2 | +use std::io; |
| 3 | +use std::num::NonZeroU64; |
| 4 | + |
| 5 | +use crate::io::streams::StreamError; |
| 6 | + |
| 7 | +impl Error for crate::io::error::Error {} |
| 8 | + |
| 9 | +impl io::Read for crate::io::streams::InputStream { |
| 10 | + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { |
| 11 | + let n = buf |
| 12 | + .len() |
| 13 | + .try_into() |
| 14 | + .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?; |
| 15 | + match self.blocking_read(n) { |
| 16 | + Ok(chunk) => { |
| 17 | + let n = chunk.len(); |
| 18 | + if n > buf.len() { |
| 19 | + return Err(io::Error::new( |
| 20 | + io::ErrorKind::Other, |
| 21 | + "more bytes read than requested", |
| 22 | + )); |
| 23 | + } |
| 24 | + buf[..n].copy_from_slice(&chunk); |
| 25 | + Ok(n) |
| 26 | + } |
| 27 | + Err(StreamError::Closed) => Ok(0), |
| 28 | + Err(StreamError::LastOperationFailed(e)) => { |
| 29 | + Err(io::Error::new(io::ErrorKind::Other, e.to_debug_string())) |
| 30 | + } |
| 31 | + } |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +impl io::Write for crate::io::streams::OutputStream { |
| 36 | + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { |
| 37 | + let n = loop { |
| 38 | + match self.check_write().map(NonZeroU64::new) { |
| 39 | + Ok(Some(n)) => { |
| 40 | + break n; |
| 41 | + } |
| 42 | + Ok(None) => { |
| 43 | + self.subscribe().block(); |
| 44 | + } |
| 45 | + Err(StreamError::Closed) => return Ok(0), |
| 46 | + Err(StreamError::LastOperationFailed(e)) => { |
| 47 | + return Err(io::Error::new(io::ErrorKind::Other, e.to_debug_string())) |
| 48 | + } |
| 49 | + }; |
| 50 | + }; |
| 51 | + let n = n |
| 52 | + .get() |
| 53 | + .try_into() |
| 54 | + .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?; |
| 55 | + let n = buf.len().min(n); |
| 56 | + crate::io::streams::OutputStream::write(self, &buf[..n]).map_err(|e| match e { |
| 57 | + StreamError::Closed => io::ErrorKind::UnexpectedEof.into(), |
| 58 | + StreamError::LastOperationFailed(e) => { |
| 59 | + io::Error::new(io::ErrorKind::Other, e.to_debug_string()) |
| 60 | + } |
| 61 | + })?; |
| 62 | + Ok(n) |
| 63 | + } |
| 64 | + |
| 65 | + fn flush(&mut self) -> io::Result<()> { |
| 66 | + self.blocking_flush() |
| 67 | + .map_err(|e| io::Error::new(io::ErrorKind::Other, e)) |
| 68 | + } |
| 69 | +} |
0 commit comments