1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
//! Custom I/O traits that roughly mirror `std::io::{Read, BufRead, Write}`.
//! This extra layer of indirection enables support of no-std environments.

use alloc::string::ToString;

use crate::Result;

/// A rough approximation of std::io::Read.
pub trait Read {
    /// Attempts to read some bytes into `buf` and returns the number of bytes read.
    /// A return value of Ok(0) means that the end of the stream was reached.
    ///
    /// Unlike with std::io::Read, implementations are expected to handle EINTR
    /// (i.e. std::io::ErrorKind::Interrupted) internally, by looping until either success
    /// is achieved or some other error is hit.
    fn read(&mut self, buf: &mut [u8]) -> Result<usize>;

    fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
        while !buf.is_empty() {
            match self.read(buf)? {
                0 => break,
                n => {
                    let tmp = buf;
                    buf = &mut tmp[n..];
                }
            }
        }
        if !buf.is_empty() {
            Err(crate::Error::failed(
                "failed to fill the whole buffer".to_string(),
            ))
        } else {
            Ok(())
        }
    }
}

/// A rough approximation of std::io::BufRead.
pub trait BufRead: Read {
    fn fill_buf(&mut self) -> Result<&[u8]>;
    fn consume(&mut self, amt: usize);
}

/// A rough approximation of std::io::Write.
pub trait Write {
    fn write_all(&mut self, buf: &[u8]) -> Result<()>;
}

#[cfg(feature = "std")]
mod std_impls {
    use crate::io::{BufRead, Read, Write};
    use crate::Result;

    impl<R> Read for R
    where
        R: std::io::Read,
    {
        fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
            loop {
                match std::io::Read::read(self, buf) {
                    Ok(n) => return Ok(n),
                    Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
                    Err(e) => return Err(e.into()),
                }
            }
        }
    }

    impl<R> BufRead for R
    where
        R: std::io::BufRead,
    {
        fn fill_buf(&mut self) -> Result<&[u8]> {
            Ok(std::io::BufRead::fill_buf(self)?)
        }
        fn consume(&mut self, amt: usize) {
            std::io::BufRead::consume(self, amt)
        }
    }

    impl<W> Write for W
    where
        W: std::io::Write,
    {
        fn write_all(&mut self, buf: &[u8]) -> Result<()> {
            std::io::Write::write_all(self, buf)?;
            Ok(())
        }
    }
}

#[cfg(not(feature = "std"))]
mod no_std_impls {
    use crate::io::{BufRead, Read, Write};
    use crate::{Error, Result};
    use alloc::string::ToString;

    impl<'a> Write for &'a mut [u8] {
        fn write_all(&mut self, buf: &[u8]) -> Result<()> {
            if buf.len() > self.len() {
                return Err(Error::failed("buffer is not large enough".to_string()));
            }
            let amt = buf.len();
            let (a, b) = core::mem::replace(self, &mut []).split_at_mut(amt);
            a.copy_from_slice(buf);
            *self = b;
            Ok(())
        }
    }

    impl Write for alloc::vec::Vec<u8> {
        fn write_all(&mut self, buf: &[u8]) -> Result<()> {
            self.extend_from_slice(buf);
            Ok(())
        }
    }

    impl<W: ?Sized> Write for &mut W
    where
        W: Write,
    {
        fn write_all(&mut self, buf: &[u8]) -> Result<()> {
            (**self).write_all(buf)
        }
    }

    impl<'a> Read for &'a [u8] {
        fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
            let amt = core::cmp::min(buf.len(), self.len());
            let (a, b) = self.split_at(amt);

            buf[..amt].copy_from_slice(a);
            *self = b;
            Ok(amt)
        }
    }

    impl<R: ?Sized> Read for &mut R
    where
        R: Read,
    {
        fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
            (**self).read(buf)
        }
    }

    impl<'a> BufRead for &'a [u8] {
        fn fill_buf(&mut self) -> Result<&[u8]> {
            Ok(*self)
        }
        fn consume(&mut self, amt: usize) {
            *self = &self[amt..]
        }
    }

    impl<R: ?Sized> BufRead for &mut R
    where
        R: BufRead,
    {
        fn fill_buf(&mut self) -> Result<&[u8]> {
            (**self).fill_buf()
        }
        fn consume(&mut self, amt: usize) {
            (**self).consume(amt)
        }
    }
}