1 //! Reimplements core logic and types from `std::io` in an `alloc`-friendly 2 //! fashion. 3 4 use alloc::vec::Vec; 5 use core::fmt::{self, Display}; 6 use core::result; 7 8 pub enum ErrorKind { 9 Other, 10 } 11 12 // IO errors can never occur in no-std mode. All our no-std IO implementations 13 // are infallible. 14 pub struct Error; 15 16 impl Display for Error { fmt(&self, _formatter: &mut fmt::Formatter<'_>) -> fmt::Result17 fn fmt(&self, _formatter: &mut fmt::Formatter<'_>) -> fmt::Result { 18 unreachable!() 19 } 20 } 21 22 impl Error { new(_kind: ErrorKind, _error: &'static str) -> Error23 pub(crate) fn new(_kind: ErrorKind, _error: &'static str) -> Error { 24 Error 25 } 26 } 27 28 pub type Result<T> = result::Result<T, Error>; 29 30 pub trait Write { write(&mut self, buf: &[u8]) -> Result<usize>31 fn write(&mut self, buf: &[u8]) -> Result<usize>; 32 write_all(&mut self, buf: &[u8]) -> Result<()>33 fn write_all(&mut self, buf: &[u8]) -> Result<()> { 34 // All our Write impls in no_std mode always write the whole buffer in 35 // one call infallibly. 36 let result = self.write(buf); 37 debug_assert!(result.is_ok()); 38 debug_assert_eq!(result.unwrap_or(0), buf.len()); 39 Ok(()) 40 } 41 flush(&mut self) -> Result<()>42 fn flush(&mut self) -> Result<()>; 43 } 44 45 impl<W: Write> Write for &mut W { 46 #[inline] write(&mut self, buf: &[u8]) -> Result<usize>47 fn write(&mut self, buf: &[u8]) -> Result<usize> { 48 (*self).write(buf) 49 } 50 51 #[inline] write_all(&mut self, buf: &[u8]) -> Result<()>52 fn write_all(&mut self, buf: &[u8]) -> Result<()> { 53 (*self).write_all(buf) 54 } 55 56 #[inline] flush(&mut self) -> Result<()>57 fn flush(&mut self) -> Result<()> { 58 (*self).flush() 59 } 60 } 61 62 impl Write for Vec<u8> { 63 #[inline] write(&mut self, buf: &[u8]) -> Result<usize>64 fn write(&mut self, buf: &[u8]) -> Result<usize> { 65 self.extend_from_slice(buf); 66 Ok(buf.len()) 67 } 68 69 #[inline] write_all(&mut self, buf: &[u8]) -> Result<()>70 fn write_all(&mut self, buf: &[u8]) -> Result<()> { 71 self.extend_from_slice(buf); 72 Ok(()) 73 } 74 75 #[inline] flush(&mut self) -> Result<()>76 fn flush(&mut self) -> Result<()> { 77 Ok(()) 78 } 79 } 80