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 pub trait BufRead: Read {
68 fn fill_buf(&mut self) -> Result<&[u8]>;
69 fn consume(&mut self, amt: usize);
70 }
71
72 impl BufRead for &[u8] {
73 fn fill_buf(&mut self) -> Result<&[u8]> {
74 Ok(*self)
75 }
76 fn consume(&mut self, amt: usize) {
77 *self = &self[amt ..];
78 }
79 }
80
81 pub trait Write {
82 fn write(&mut self, buf: &[u8]) -> Result<usize>;
83 fn write_all(&mut self, buf: &[u8]) -> Result<()> {
84 if self.write(buf)? != buf.len() {
85 Err(Error::new(ErrorKind::UnexpectedEof, "writer ran out of bytes"))?;
86 }
87 Ok(())
88 }
89 }
90
91 impl Write for Vec<u8> {
92 fn write(&mut self, buf: &[u8]) -> Result<usize> {
93 self.extend(buf);
94 Ok(buf.len())
95 }
96 }
97}
98
99#[cfg(not(feature = "std"))]
100pub use shims::*;