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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
// Rust language amplification library providing multiple generic trait
// implementations, type wrappers, derive macros and other language enhancements
//
// Written in 2019-2022 by
//     Dr. Maxim Orlovsky <orlovsky@pandoracore.com>
//     Martin Habovstiak <martin.habovstiak@gmail.com>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the MIT License
// along with this software.
// If not, see <https://opensource.org/licenses/MIT>.

use std::cmp::Ordering;
use std::io;
use std::fmt::{Debug, Display, Formatter, self};
use std::error::Error as StdError;
use std::hash::{Hash, Hasher};

/// A simple way to count bytes written through [`io::Write`].
#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Default, Debug)]
pub struct WriteCounter {
    /// Count of bytes which passed through this writer
    pub count: usize,
}

impl io::Write for WriteCounter {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let len = buf.len();
        self.count += len;
        Ok(len)
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

/// Copyable & cloneable I/O error type represented by the error kind function.
///
/// Available only when both `std` and `derive` features are present.
///
/// # Example
/// ```
/// use amplify::{IoError, Error, Display, From};
///
/// #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, From, Debug, Display, Error)]
/// enum Error {
///     #[from(std::io::Error)]
///     #[display(inner)]
///     Io(IoError),
/// }
/// ```
pub struct IoError {
    kind: io::ErrorKind,
    display: String,
    debug: String,
    details: Option<Box<dyn StdError + Send + Sync>>,
}

impl IoError {
    /// Returns [`io::ErrorKind`] of this error.
    pub fn kind(&self) -> io::ErrorKind {
        self.kind
    }
}

impl Clone for IoError {
    fn clone(&self) -> Self {
        Self {
            kind: self.kind,
            display: self.display.clone(),
            debug: self.debug.clone(),
            details: None,
        }
    }
}

impl PartialEq for IoError {
    fn eq(&self, other: &Self) -> bool {
        self.kind == other.kind && self.debug == other.debug
    }
}

impl Eq for IoError {}

impl PartialOrd for IoError {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for IoError {
    fn cmp(&self, other: &Self) -> Ordering {
        match self.kind.cmp(&other.kind) {
            Ordering::Equal => self.debug.cmp(&other.debug),
            ordering => ordering,
        }
    }
}

impl Hash for IoError {
    fn hash<H: Hasher>(&self, state: &mut H) {
        state.write(self.debug.as_bytes())
    }
}

impl Display for IoError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let err = io::Error::from(self.clone());
        Display::fmt(&err, f)
    }
}

impl Debug for IoError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let err = io::Error::from(self.clone());
        Debug::fmt(&err, f)
    }
}

impl std::error::Error for IoError {}

impl From<io::Error> for IoError {
    fn from(err: io::Error) -> Self {
        IoError {
            kind: err.kind(),
            display: err.to_string(),
            debug: format!("{:?}", err),
            details: err.into_inner(),
        }
    }
}

impl From<io::ErrorKind> for IoError {
    fn from(kind: io::ErrorKind) -> Self {
        IoError {
            kind,
            display: kind.to_string(),
            debug: format!("{:?}", kind),
            details: None,
        }
    }
}

impl From<IoError> for io::Error {
    fn from(err: IoError) -> Self {
        match err.details {
            Some(details) => io::Error::new(err.kind, details),
            None => io::Error::from(err.kind),
        }
    }
}

/// Errors with [`io::ErrorKind::UnexpectedEof`] on [`Read`] and [`Write`]
/// operations if the `LIM` is reached.
#[derive(Clone, Debug)]
pub struct ConfinedIo<Io, const LIM: usize> {
    pos: usize,
    io: Io,
}

impl<Io, const LIM: usize> From<Io> for ConfinedIo<Io, LIM> {
    fn from(io: Io) -> Self {
        Self { pos: 0, io }
    }
}

impl<Io: Default, const LIM: usize> Default for ConfinedIo<Io, LIM> {
    fn default() -> Self {
        Self::new()
    }
}

impl<Io, const LIM: usize> ConfinedIo<Io, LIM> {
    /// Constructs new instance.
    pub fn new() -> Self
    where
        Io: Default,
    {
        Self::default()
    }

    /// Returns current position (number of bytes read or written).
    pub fn pos(&self) -> usize {
        self.pos
    }

    /// Returns reference to the inner I/O type.
    pub fn as_io(&self) -> &Io {
        &self.io
    }

    /// Converts into the inner I/O type.
    pub fn into_io(self) -> Io {
        self.io
    }

    /// Returns clone of the inner I/O type.
    pub fn to_io(&self) -> Io
    where
        Io: Clone,
    {
        self.io.clone()
    }

    /// Checks if the position has reached the limit `LIM`.
    pub fn is_eof(&self) -> bool {
        self.pos >= LIM
    }
}

impl<Io: io::Write, const LIM: usize> io::Write for ConfinedIo<Io, LIM> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let len = buf.len();
        if self.pos + len >= LIM {
            return Err(io::ErrorKind::UnexpectedEof.into());
        }
        self.pos += len;
        self.io.write(buf)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.io.flush()
    }
}

impl<Io: io::Read, const LIM: usize> io::Read for ConfinedIo<Io, LIM> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let len = buf.len();
        if self.pos + len < LIM {
            self.pos += len;
            self.io.read(buf)
        } else if self.pos >= LIM {
            return Err(io::ErrorKind::UnexpectedEof.into());
        } else {
            let pos = self.pos;
            self.pos = LIM;
            self.io.read(&mut buf[..(len - (LIM - pos))])
        }
    }

    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
        let len = buf.len();
        if self.pos + len < LIM {
            self.pos += len;
            self.io.read_exact(buf)
        } else if self.pos >= LIM {
            return Err(io::ErrorKind::UnexpectedEof.into());
        } else {
            let pos = self.pos;
            self.pos = LIM;
            self.io.read_exact(&mut buf[..(len - (LIM - pos))])
        }
    }
}