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
use embedded_io::Error;

use crate::io::{Read, Write};

pub fn try_read_full<R: Read>(mut read: R, buf: &mut [u8]) -> Result<usize, (R::Error, usize)> {
    let mut offset = 0;
    let mut size = 0;

    loop {
        let size_read = read.read(&mut buf[offset..]).map_err(|e| (e, size))?;

        offset += size_read;
        size += size_read;

        if size_read == 0 || size == buf.len() {
            break;
        }
    }

    Ok(size)
}

#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum CopyError<R, W> {
    Read(R),
    Write(W),
}

impl<R: core::fmt::Debug, W: core::fmt::Debug> core::fmt::Display for CopyError<R, W> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{self:?}")
    }
}

#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl<R: core::fmt::Debug, W: core::fmt::Debug> std::error::Error for CopyError<R, W> {}

impl<R, W> Error for CopyError<R, W>
where
    R: Error,
    W: Error,
{
    fn kind(&self) -> embedded_io::ErrorKind {
        match self {
            Self::Read(e) => e.kind(),
            Self::Write(e) => e.kind(),
        }
    }
}

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

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

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

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

        let size_read = read.read(buf).map_err(CopyError::Read)?;
        if size_read == 0 {
            break;
        }

        write
            .write_all(&buf[0..size_read])
            .map_err(CopyError::Write)?;

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

    progress(copied, len);

    Ok(copied)
}

pub mod asynch {
    use crate::io::asynch::{Read, Write};

    pub use super::CopyError;

    pub async fn try_read_full<R: Read>(
        mut read: R,
        buf: &mut [u8],
    ) -> Result<usize, (R::Error, usize)> {
        let mut offset = 0;
        let mut size = 0;

        loop {
            let size_read = read.read(&mut buf[offset..]).await.map_err(|e| (e, size))?;

            offset += size_read;
            size += size_read;

            if size_read == 0 || size == buf.len() {
                break;
            }
        }

        Ok(size)
    }

    pub async fn copy<R, W>(
        read: R,
        write: W,
        buf: &mut [u8],
    ) -> Result<u64, CopyError<R::Error, W::Error>>
    where
        R: Read,
        W: Write,
    {
        copy_len(read, write, buf, u64::MAX).await
    }

    pub async fn copy_len<R, W>(
        read: R,
        write: W,
        buf: &mut [u8],
        len: u64,
    ) -> Result<u64, CopyError<R::Error, W::Error>>
    where
        R: Read,
        W: Write,
    {
        copy_len_with_progress(read, write, buf, len, |_, _| {}).await
    }

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

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

            let size_read = read.read(buf).await.map_err(CopyError::Read)?;
            if size_read == 0 {
                break;
            }

            write
                .write_all(&buf[0..size_read])
                .await
                .map_err(CopyError::Write)?;

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

        progress(copied, len);

        Ok(copied)
    }
}