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
use super::{Bufferable, Status};
use std::io::{self, IoSliceMut, Read};

/// An extension of [`Read`], with `read_with_status` and
/// `read_vectored_with_status` which return status information and zero is not
/// special-cased. It also allows streams to specify a `minimum_buffer_size`.
pub trait ReadLayered: Read + Bufferable {
    /// Like [`Read::read`], but also returns a `Status`.
    fn read_with_status(&mut self, buf: &mut [u8]) -> io::Result<(usize, Status)>;

    /// Like [`Read::read_vectored`], but also returns a `Status`.
    #[inline]
    fn read_vectored_with_status(
        &mut self,
        bufs: &mut [IoSliceMut<'_>],
    ) -> io::Result<(usize, Status)> {
        default_read_vectored_with_status(self, bufs)
    }

    /// Like `Read::read_exact`, but uses `read_with_status` to avoid
    /// performing an extra `read` at the end.
    #[inline]
    fn read_exact_using_status(&mut self, buf: &mut [u8]) -> io::Result<Status> {
        default_read_exact_using_status(self, buf)
    }

    /// Some streams require a buffer of at least a certain size.
    #[inline]
    fn minimum_buffer_size(&self) -> usize {
        0
    }
}

/// Default implementation of [`Read::read`] in terms of
/// [`ReadLayered::read_with_status`].
#[inline]
pub fn default_read<Inner: ReadLayered + ?Sized>(
    inner: &mut Inner,
    buf: &mut [u8],
) -> io::Result<usize> {
    inner.read_with_status(buf).and_then(to_std_io_read_result)
}

/// Default implementation of [`Read::read_vectored`] in terms of
/// [`ReadLayered::read_vectored_with_status`].
pub fn default_read_vectored<Inner: ReadLayered + ?Sized>(
    inner: &mut Inner,
    bufs: &mut [IoSliceMut<'_>],
) -> io::Result<usize> {
    inner
        .read_vectored_with_status(bufs)
        .and_then(to_std_io_read_result)
}

/// Default implementation of [`Read::read_to_end`] in terms of
/// [`ReadLayered::read_with_status`].
#[allow(clippy::indexing_slicing)]
pub fn default_read_to_end<Inner: ReadLayered + ?Sized>(
    inner: &mut Inner,
    buf: &mut Vec<u8>,
) -> io::Result<usize> {
    let start_len = buf.len();
    let buffer_size = inner.suggested_buffer_size();
    let mut read_len = buffer_size;
    loop {
        let read_pos = buf.len();

        // Allocate space in the buffer. This needlessly zeros out the
        // memory, however the current way to avoid it is to be part of the
        // standard library so that we can make assumptions about the
        // compiler not exploiting undefined behavior.
        // https://github.com/rust-lang/rust/issues/42788 for details.
        buf.resize(read_pos + read_len, 0);

        match inner.read_with_status(&mut buf[read_pos..]) {
            Ok((size, status)) => {
                buf.resize(read_pos + size, 0);
                match status {
                    Status::Open(_) => {
                        read_len -= size;
                        if read_len < inner.minimum_buffer_size() {
                            read_len += buffer_size;
                        }
                    }
                    Status::End => return Ok(buf.len() - start_len),
                }
            }
            Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
            Err(e) => {
                buf.resize(start_len, 0);
                return Err(e);
            }
        }
    }
}

/// Default implementation of [`Read::read_to_string`] in terms of
/// [`Read::read_to_end`].
pub fn default_read_to_string<Inner: ReadLayered + ?Sized>(
    inner: &mut Inner,
    buf: &mut String,
) -> io::Result<usize> {
    // Allocate a `Vec` and read into it. This needlessly allocates,
    // rather than reading directly into `buf`'s buffer, but similarly
    // avoids issues of undefined behavior for now.
    let mut vec = Vec::new();
    let size = inner.read_to_end(&mut vec)?;
    let new = String::from_utf8(vec).map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
    buf.push_str(&new);
    Ok(size)
}

/// Default implementation of [`ReadLayered::read_exact_using_status`] in terms
/// of [`ReadLayered::read_with_status`].
#[allow(clippy::indexing_slicing)]
pub fn default_read_exact_using_status<Inner: ReadLayered + ?Sized>(
    inner: &mut Inner,
    mut buf: &mut [u8],
) -> io::Result<Status> {
    let mut result_status = Status::active();

    while !buf.is_empty() {
        match inner.read_with_status(buf) {
            Ok((size, status)) => {
                let t = buf;
                buf = &mut t[size..];
                if status.is_end() {
                    result_status = status;
                    break;
                }
            }
            Err(e) => return Err(e),
        }
    }

    if buf.is_empty() {
        Ok(result_status)
    } else {
        Err(io::Error::new(
            io::ErrorKind::UnexpectedEof,
            "failed to fill whole buffer",
        ))
    }
}

/// Default implementation of [`ReadLayered::read_vectored_with_status`] in
/// terms of [`ReadLayered::read_with_status`].
pub fn default_read_vectored_with_status<Inner: ReadLayered + ?Sized>(
    inner: &mut Inner,
    bufs: &mut [IoSliceMut<'_>],
) -> io::Result<(usize, Status)> {
    let buf = bufs
        .iter_mut()
        .find(|b| !b.is_empty())
        .map_or(&mut [][..], |b| &mut **b);
    inner.read_with_status(buf)
}

/// Default implementation of [`Read::is_read_vectored`] accompanying
/// [`default_read_vectored_with_status`].
#[cfg(can_vector)]
pub fn default_is_read_vectored<Inner: ReadLayered + ?Sized>(_inner: &Inner) -> bool {
    false
}

/// Translate from `read_with_status`'s return value with independent size and
/// status to a [`std::io::Read::read`] return value where 0 is special-cased
/// to mean end-of-stream, an `io::ErrorKind::Interrupted` error is used to
/// indicate a zero-length read, and pushes are not reported.
pub fn to_std_io_read_result(size_and_status: (usize, Status)) -> io::Result<usize> {
    match size_and_status {
        (0, Status::Open(_)) => Err(io::Error::new(
            io::ErrorKind::Interrupted,
            "read zero bytes from stream",
        )),
        (size, _) => Ok(size),
    }
}

impl<R: ReadLayered> ReadLayered for Box<R> {
    #[inline]
    fn read_with_status(&mut self, buf: &mut [u8]) -> io::Result<(usize, Status)> {
        self.as_mut().read_with_status(buf)
    }

    #[inline]
    fn read_vectored_with_status(
        &mut self,
        bufs: &mut [IoSliceMut<'_>],
    ) -> io::Result<(usize, Status)> {
        self.as_mut().read_vectored_with_status(bufs)
    }

    #[inline]
    fn minimum_buffer_size(&self) -> usize {
        self.as_ref().minimum_buffer_size()
    }
}

impl<R: ReadLayered> ReadLayered for &mut R {
    #[inline]
    fn read_with_status(&mut self, buf: &mut [u8]) -> io::Result<(usize, Status)> {
        (**self).read_with_status(buf)
    }

    #[inline]
    fn read_vectored_with_status(
        &mut self,
        bufs: &mut [IoSliceMut<'_>],
    ) -> io::Result<(usize, Status)> {
        (**self).read_vectored_with_status(bufs)
    }

    #[inline]
    fn minimum_buffer_size(&self) -> usize {
        (**self).minimum_buffer_size()
    }
}