std_shims/
io.rs

1#[cfg(feature = "std")]
2pub use std::io::*;
3
4#[cfg(not(feature = "std"))]
5mod shims {
6  use core::fmt::{Debug, Formatter};
7  use alloc::{boxed::Box, vec::Vec};
8
9  #[derive(Clone, Copy, PartialEq, Eq, Debug)]
10  pub enum ErrorKind {
11    UnexpectedEof,
12    Other,
13  }
14
15  pub struct Error {
16    kind: ErrorKind,
17    error: Box<dyn Send + Sync>,
18  }
19
20  impl Debug for Error {
21    fn fmt(&self, fmt: &mut Formatter<'_>) -> core::result::Result<(), core::fmt::Error> {
22      fmt.debug_struct("Error").field("kind", &self.kind).finish_non_exhaustive()
23    }
24  }
25
26  impl Error {
27    pub fn new<E: 'static + Send + Sync>(kind: ErrorKind, error: E) -> Error {
28      Error { kind, error: Box::new(error) }
29    }
30
31    pub fn other<E: 'static + Send + Sync>(error: E) -> Error {
32      Error { kind: ErrorKind::Other, error: Box::new(error) }
33    }
34
35    pub fn kind(&self) -> ErrorKind {
36      self.kind
37    }
38
39    pub fn into_inner(self) -> Option<Box<dyn Send + Sync>> {
40      Some(self.error)
41    }
42  }
43
44  pub type Result<T> = core::result::Result<T, Error>;
45
46  pub trait Read {
47    fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
48
49    fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
50      let read = self.read(buf)?;
51      if read != buf.len() {
52        Err(Error::new(ErrorKind::UnexpectedEof, "reader ran out of bytes"))?;
53      }
54      Ok(())
55    }
56  }
57
58  impl Read for &[u8] {
59    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
60      let read = buf.len().min(self.len());
61      buf[.. read].copy_from_slice(&self[.. read]);
62      *self = &self[read ..];
63      Ok(read)
64    }
65  }
66
67  impl<R: Read> Read for &mut R {
68    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
69      R::read(*self, buf)
70    }
71  }
72
73  pub trait BufRead: Read {
74    fn fill_buf(&mut self) -> Result<&[u8]>;
75    fn consume(&mut self, amt: usize);
76  }
77
78  impl BufRead for &[u8] {
79    fn fill_buf(&mut self) -> Result<&[u8]> {
80      Ok(*self)
81    }
82    fn consume(&mut self, amt: usize) {
83      *self = &self[amt ..];
84    }
85  }
86
87  pub trait Write {
88    fn write(&mut self, buf: &[u8]) -> Result<usize>;
89    fn write_all(&mut self, buf: &[u8]) -> Result<()> {
90      if self.write(buf)? != buf.len() {
91        Err(Error::new(ErrorKind::UnexpectedEof, "writer ran out of bytes"))?;
92      }
93      Ok(())
94    }
95  }
96
97  impl Write for Vec<u8> {
98    fn write(&mut self, buf: &[u8]) -> Result<usize> {
99      self.extend(buf);
100      Ok(buf.len())
101    }
102  }
103}
104
105#[cfg(not(feature = "std"))]
106pub use shims::*;