|
| 1 | +use core::{cmp, mem}; |
| 2 | + |
| 3 | +use Result; |
| 4 | + |
| 5 | +/// Non-blocking writer trait |
| 6 | +pub trait Write { |
| 7 | + /// An enumeration of possible errors |
| 8 | + /// |
| 9 | + /// May be `!` (`never_type`) for infallible implementations |
| 10 | + type Error; |
| 11 | + |
| 12 | + /// Push some bytes into this source from the specified buffer, returning how many bytes were |
| 13 | + /// written. |
| 14 | + /// |
| 15 | + /// If an object needs to block for a write it will return an `Err(nb::Error::WouldBlock)` |
| 16 | + /// return value. |
| 17 | + /// |
| 18 | + /// If the return value of this method is `Ok(n)`, then it must be guaranteed that `0 <= n <= |
| 19 | + /// buf.len()`. The `n` value indicates that `n` bytes from the buffer `buf` have been written |
| 20 | + /// to this source. If `n == 0 && buf.len() > 0` then it can be assumed that this writer has |
| 21 | + /// run out of space and will not be able to service future writes. |
| 22 | + fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error>; |
| 23 | + |
| 24 | + /// Attempt to flush the object, ensuring that any buffered data reach their destination. |
| 25 | + /// |
| 26 | + /// On success, returns `Ok(())`. |
| 27 | + /// |
| 28 | + /// If flushing cannot immediately complete, this method returns `Err(nb::Error::WouldBlock)`. |
| 29 | + fn flush(&mut self) -> Result<(), Self::Error>; |
| 30 | + |
| 31 | + /// Attempt to close the object. |
| 32 | + /// |
| 33 | + /// On success, returns `Ok(())`. |
| 34 | + /// |
| 35 | + /// If closing cannot immediately complete, this method returns `Err(nb::Error::WouldBlock)`. |
| 36 | + fn close(&mut self) -> Result<(), Self::Error>; |
| 37 | +} |
| 38 | + |
| 39 | +impl<'a, W: ?Sized + Write> Write for &'a mut W { |
| 40 | + type Error = W::Error; |
| 41 | + |
| 42 | + fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> { |
| 43 | + (**self).write(buf) |
| 44 | + } |
| 45 | + |
| 46 | + fn flush(&mut self) -> Result<(), Self::Error> { |
| 47 | + (**self).flush() |
| 48 | + } |
| 49 | + |
| 50 | + fn close(&mut self) -> Result<(), Self::Error> { |
| 51 | + (**self).close() |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +impl<'a> Write for &'a mut [u8] { |
| 56 | + type Error = !; |
| 57 | + |
| 58 | + fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> { |
| 59 | + let len = cmp::min(self.len(), buf.len()); |
| 60 | + let (head, tail) = mem::replace(self, &mut []).split_at_mut(len); |
| 61 | + head.copy_from_slice(&buf[..len]); |
| 62 | + *self = tail; |
| 63 | + Ok(len) |
| 64 | + } |
| 65 | + |
| 66 | + fn flush(&mut self) -> Result<(), Self::Error> { |
| 67 | + Ok(()) |
| 68 | + } |
| 69 | + |
| 70 | + fn close(&mut self) -> Result<(), Self::Error> { |
| 71 | + Ok(()) |
| 72 | + } |
| 73 | +} |
0 commit comments