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 kind(&self) -> ErrorKind {
32      self.kind
33    }
34
35    pub fn into_inner(self) -> Option<Box<dyn Send + Sync>> {
36      Some(self.error)
37    }
38  }
39
40  pub type Result<T> = core::result::Result<T, Error>;
41
42  pub trait Read {
43    fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
44
45    fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
46      let read = self.read(buf)?;
47      if read != buf.len() {
48        Err(Error::new(ErrorKind::UnexpectedEof, "reader ran out of bytes"))?;
49      }
50      Ok(())
51    }
52  }
53
54  impl Read for &[u8] {
55    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
56      let read = buf.len().min(self.len());
57      buf[.. read].copy_from_slice(&self[.. read]);
58      *self = &self[read ..];
59      Ok(read)
60    }
61  }
62
63  pub trait Write {
64    fn write(&mut self, buf: &[u8]) -> Result<usize>;
65    fn write_all(&mut self, buf: &[u8]) -> Result<()> {
66      if self.write(buf)? != buf.len() {
67        Err(Error::new(ErrorKind::UnexpectedEof, "writer ran out of bytes"))?;
68      }
69      Ok(())
70    }
71  }
72
73  impl Write for Vec<u8> {
74    fn write(&mut self, buf: &[u8]) -> Result<usize> {
75      self.extend(buf);
76      Ok(buf.len())
77    }
78  }
79}
80
81#[cfg(not(feature = "std"))]
82pub use shims::*;