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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
use core::fmt;
use core::result::Result;

#[cfg(feature = "alloc")]
extern crate alloc;

#[cfg(feature = "alloc")]
use alloc::boxed::Box;

#[cfg(feature = "std")]
pub use stdio::*;

use crate::errors::Errors;

const BUF_SIZE: usize = 64;

#[cfg(feature = "std")]
pub type IODynError = std::io::Error;

#[cfg(not(feature = "std"))]
#[derive(Debug)]
pub struct IODynError(i32);

#[cfg(not(feature = "std"))]
impl fmt::Display for IODynError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "IO Error {}", self.0)
    }
}

pub trait Read: Errors {
    fn do_read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error>;

    #[cfg(feature = "alloc")]
    fn into_dyn_read(self) -> Box<dyn Read<Error = IODynError>>
    where
        Self: Sized + 'static,
        Self::Error: Into<IODynError>,
    {
        Box::new(DynIO(self))
    }
}

pub trait Write: Errors {
    fn do_write(&mut self, buf: &[u8]) -> Result<usize, Self::Error>;

    fn do_write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
        let mut size = 0;

        while size < buf.len() {
            size += self.do_write(&buf[size..])?;
        }

        Ok(())
    }

    fn do_flush(&mut self) -> Result<(), Self::Error> {
        Ok(())
    }

    #[cfg(feature = "alloc")]
    fn into_dyn_write(self) -> Box<dyn Write<Error = IODynError>>
    where
        Self: Sized + 'static,
        Self::Error: Into<IODynError>,
    {
        Box::new(DynIO(self))
    }
}

impl<'a, R> Read for &'a mut R
where
    R: Read,
{
    fn do_read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
        (*self).do_read(buf)
    }
}

#[cfg(feature = "alloc")]
impl Errors for Box<dyn Read<Error = IODynError>> {
    type Error = IODynError;
}

#[cfg(feature = "alloc")]
impl Read for Box<dyn Read<Error = IODynError>> {
    fn do_read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
        self.as_mut().do_read(buf)
    }
}

impl<'a, W> Write for &'a mut W
where
    W: Write,
{
    fn do_write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
        (*self).do_write(buf)
    }

    fn do_flush(&mut self) -> Result<(), Self::Error> {
        (*self).do_flush()
    }
}

#[cfg(feature = "alloc")]
impl Errors for Box<dyn Write<Error = IODynError>> {
    type Error = IODynError;
}

#[cfg(feature = "alloc")]
impl Write for Box<dyn Write<Error = IODynError>> {
    fn do_write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
        self.as_mut().do_write(buf)
    }

    fn do_flush(&mut self) -> Result<(), Self::Error> {
        self.as_mut().do_flush()
    }
}

struct DynIO<S>(S);

impl<S> Errors for DynIO<S>
where
    S: Errors,
    S::Error: Into<IODynError>,
{
    type Error = IODynError;
}

impl<R> Read for DynIO<R>
where
    R: Read,
    R::Error: Into<IODynError>,
{
    fn do_read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
        self.0.do_read(buf).map_err(Into::into)
    }
}

impl<W> Write for DynIO<W>
where
    W: Write,
    W::Error: Into<IODynError>,
{
    fn do_write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
        self.0.do_write(buf).map_err(Into::into)
    }

    fn do_flush(&mut self) -> Result<(), Self::Error> {
        self.0.do_flush().map_err(Into::into)
    }
}

pub struct Bytes<R, const N: usize> {
    reader: R,
    buf: [u8; N],
    index: usize,
    read: usize,
}

impl<R, const N: usize> Bytes<R, N>
where
    R: Read,
{
    pub fn new(reader: R) -> Self {
        Self {
            reader,
            buf: [0_u8; N],
            index: 1,
            read: 1,
        }
    }
}

impl<R, const N: usize> Iterator for Bytes<R, N>
where
    R: Read,
{
    type Item = Result<u8, R::Error>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.index == self.read && self.read > 0 {
            match self.reader.do_read(&mut self.buf) {
                Err(e) => return Some(Err(e)),
                Ok(read) => {
                    self.read = read;
                    self.index = 0;
                }
            }
        }

        if self.read == 0 {
            None
        } else {
            let result = self.buf[self.index];
            self.index += 1;

            Some(Ok(result))
        }
    }
}

#[derive(Debug)]
pub enum CopyError<R, W>
where
    R: fmt::Display + fmt::Debug,
    W: fmt::Display + fmt::Debug,
{
    ReadError(R),
    WriteError(W),
}

impl<R, W> fmt::Display for CopyError<R, W>
where
    R: fmt::Display + fmt::Debug,
    W: fmt::Display + fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CopyError::ReadError(r) => write!(f, "Read Error {}", r),
            CopyError::WriteError(w) => write!(f, "Write Error {}", w),
        }
    }
}

#[cfg(feature = "std")]
impl<R, W> std::error::Error for CopyError<R, W>
where
    R: fmt::Display + fmt::Debug,
    W: fmt::Display + fmt::Debug,
    // TODO
    // where
    //     R: std::error::Error + 'static,
    //     W: std::error::Error + 'static,
{
    // TODO
    // fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
    //     match self {
    //         CopyError::ReadError(r) => Some(r),
    //         CopyError::WriteError(w) => Some(w),
    //     }
    // }
}

pub fn copy<R, W>(read: R, write: W) -> Result<u64, CopyError<R::Error, W::Error>>
where
    R: Read,
    W: Write,
{
    copy_len(read, write, u64::MAX)
}

pub fn copy_len<R, W>(read: R, write: W, len: u64) -> Result<u64, CopyError<R::Error, W::Error>>
where
    R: Read,
    W: Write,
{
    copy_len_with_progress(read, write, len, |_, _| {})
}

pub fn copy_len_with_progress<R, W>(
    mut read: R,
    mut write: W,
    mut len: u64,
    progress: impl Fn(u64, u64),
) -> Result<u64, CopyError<R::Error, W::Error>>
where
    R: Read,
    W: Write,
{
    let mut buf = [0_u8; BUF_SIZE];

    let mut copied = 0;

    while len > 0 {
        progress(copied, len);

        let size_read = read.do_read(&mut buf).map_err(CopyError::ReadError)?;
        if size_read == 0 {
            break;
        }

        write
            .do_write_all(&buf[0..size_read])
            .map_err(CopyError::WriteError)?;

        copied += size_read as u64;
        len -= size_read as u64;
    }

    progress(copied, len);

    Ok(copied)
}

#[cfg(feature = "std")]
mod stdio {
    pub struct StdRead<T>(pub T);

    impl<R> crate::errors::Errors for StdRead<R>
    where
        R: std::io::Read,
    {
        type Error = std::io::Error;
    }

    impl<R> super::Read for StdRead<R>
    where
        R: std::io::Read,
    {
        fn do_read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
            self.0.read(buf)
        }
    }

    impl<R> std::io::Read for StdRead<R>
    where
        R: super::Read,
    {
        fn read(&mut self, buf: &mut [u8]) -> Result<usize, std::io::Error> {
            self.0
                .do_read(buf)
                .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))
        }
    }

    pub struct StdWrite<T>(pub T);

    impl<W> crate::errors::Errors for StdWrite<W>
    where
        W: std::io::Write,
    {
        type Error = std::io::Error;
    }

    impl<W> super::Write for StdWrite<W>
    where
        W: std::io::Write,
    {
        fn do_write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
            self.0.write(buf)
        }

        fn do_flush(&mut self) -> Result<(), Self::Error> {
            self.0.flush()
        }
    }

    impl<W> std::io::Write for StdWrite<W>
    where
        W: super::Write,
    {
        fn write(&mut self, buf: &[u8]) -> Result<usize, std::io::Error> {
            self.0
                .do_write(buf)
                .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))
        }

        fn flush(&mut self) -> Result<(), std::io::Error> {
            self.0
                .do_flush()
                .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))
        }
    }
}