Skip to main content

ax_io/read/
impls.rs

1#[cfg(feature = "alloc")]
2use alloc::{boxed::Box, collections::VecDeque, string::String, vec::Vec};
3use core::{cmp, io::BorrowedCursor};
4
5use crate::{BufRead, Error, Read, Result};
6
7// =============================================================================
8// Forwarding implementations
9
10impl<R: Read + ?Sized> Read for &mut R {
11    #[inline]
12    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
13        (**self).read(buf)
14    }
15
16    #[inline]
17    fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
18        (**self).read_exact(buf)
19    }
20
21    #[inline]
22    fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> Result<()> {
23        (**self).read_buf(cursor)
24    }
25
26    #[inline]
27    fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<()> {
28        (**self).read_buf_exact(cursor)
29    }
30
31    #[inline]
32    #[cfg(feature = "alloc")]
33    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
34        (**self).read_to_end(buf)
35    }
36
37    #[inline]
38    #[cfg(feature = "alloc")]
39    fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
40        (**self).read_to_string(buf)
41    }
42}
43
44impl<B: BufRead + ?Sized> BufRead for &mut B {
45    #[inline]
46    fn fill_buf(&mut self) -> Result<&[u8]> {
47        (**self).fill_buf()
48    }
49
50    #[inline]
51    fn consume(&mut self, amt: usize) {
52        (**self).consume(amt)
53    }
54
55    #[inline]
56    fn has_data_left(&mut self) -> Result<bool> {
57        (**self).has_data_left()
58    }
59
60    #[inline]
61    fn skip_until(&mut self, byte: u8) -> Result<usize> {
62        (**self).skip_until(byte)
63    }
64
65    #[inline]
66    #[cfg(feature = "alloc")]
67    fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
68        (**self).read_until(byte, buf)
69    }
70
71    #[inline]
72    #[cfg(feature = "alloc")]
73    fn read_line(&mut self, buf: &mut String) -> Result<usize> {
74        (**self).read_line(buf)
75    }
76}
77
78#[cfg(feature = "alloc")]
79impl<R: Read + ?Sized> Read for Box<R> {
80    #[inline]
81    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
82        (**self).read(buf)
83    }
84
85    #[inline]
86    fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
87        (**self).read_exact(buf)
88    }
89
90    #[inline]
91    fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> Result<()> {
92        (**self).read_buf(cursor)
93    }
94
95    #[inline]
96    fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<()> {
97        (**self).read_buf_exact(cursor)
98    }
99
100    #[inline]
101    #[cfg(feature = "alloc")]
102    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
103        (**self).read_to_end(buf)
104    }
105
106    #[inline]
107    #[cfg(feature = "alloc")]
108    fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
109        (**self).read_to_string(buf)
110    }
111}
112
113#[cfg(feature = "alloc")]
114impl<B: BufRead + ?Sized> BufRead for Box<B> {
115    #[inline]
116    fn fill_buf(&mut self) -> Result<&[u8]> {
117        (**self).fill_buf()
118    }
119
120    #[inline]
121    fn consume(&mut self, amt: usize) {
122        (**self).consume(amt)
123    }
124
125    #[inline]
126    fn has_data_left(&mut self) -> Result<bool> {
127        (**self).has_data_left()
128    }
129
130    #[inline]
131    fn skip_until(&mut self, byte: u8) -> Result<usize> {
132        (**self).skip_until(byte)
133    }
134
135    #[inline]
136    #[cfg(feature = "alloc")]
137    fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
138        (**self).read_until(byte, buf)
139    }
140
141    #[inline]
142    #[cfg(feature = "alloc")]
143    fn read_line(&mut self, buf: &mut String) -> Result<usize> {
144        (**self).read_line(buf)
145    }
146}
147
148// =============================================================================
149// In-memory buffer implementations
150
151impl Read for &[u8] {
152    #[inline]
153    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
154        let amt = cmp::min(buf.len(), self.len());
155        let (a, b) = self.split_at(amt);
156
157        // First check if the amount of bytes we want to read is small:
158        // `copy_from_slice` will generally expand to a call to `memcpy`, and
159        // for a single byte the overhead is significant.
160        if amt == 1 {
161            buf[0] = a[0];
162        } else {
163            buf[..amt].copy_from_slice(a);
164        }
165
166        *self = b;
167        Ok(amt)
168    }
169
170    #[inline]
171    fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
172        if buf.len() > self.len() {
173            // `read_exact` makes no promise about the content of `buf` if it
174            // fails so don't bother about that.
175            *self = &self[self.len()..];
176            return Err(Error::UnexpectedEof);
177        }
178        let (a, b) = self.split_at(buf.len());
179
180        // First check if the amount of bytes we want to read is small:
181        // `copy_from_slice` will generally expand to a call to `memcpy`, and
182        // for a single byte the overhead is significant.
183        if buf.len() == 1 {
184            buf[0] = a[0];
185        } else {
186            buf.copy_from_slice(a);
187        }
188
189        *self = b;
190        Ok(())
191    }
192
193    #[inline]
194    fn read_buf(&mut self, mut cursor: BorrowedCursor<'_>) -> Result<()> {
195        let amt = cmp::min(cursor.capacity(), self.len());
196        let (a, b) = self.split_at(amt);
197
198        cursor.append(a);
199
200        *self = b;
201        Ok(())
202    }
203
204    #[inline]
205    fn read_buf_exact(&mut self, mut cursor: BorrowedCursor<'_>) -> Result<()> {
206        if cursor.capacity() > self.len() {
207            // Append everything we can to the cursor.
208            cursor.append(self);
209            *self = &self[self.len()..];
210            return Err(Error::UnexpectedEof);
211        }
212        let (a, b) = self.split_at(cursor.capacity());
213
214        cursor.append(a);
215
216        *self = b;
217        Ok(())
218    }
219
220    #[inline]
221    #[cfg(feature = "alloc")]
222    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
223        let len = self.len();
224        buf.try_reserve(len).map_err(|_| Error::NoMemory)?;
225        buf.extend_from_slice(self);
226        *self = &self[len..];
227        Ok(len)
228    }
229
230    #[inline]
231    #[cfg(feature = "alloc")]
232    fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
233        let content = str::from_utf8(self).map_err(|_| Error::IllegalBytes)?;
234        let len = self.len();
235        buf.try_reserve(len).map_err(|_| Error::NoMemory)?;
236        buf.push_str(content);
237        *self = &self[len..];
238        Ok(len)
239    }
240}
241
242impl BufRead for &[u8] {
243    #[inline]
244    fn fill_buf(&mut self) -> Result<&[u8]> {
245        Ok(*self)
246    }
247
248    #[inline]
249    fn consume(&mut self, amt: usize) {
250        *self = &self[amt..];
251    }
252}
253
254#[cfg(feature = "alloc")]
255impl Read for VecDeque<u8> {
256    #[inline]
257    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
258        let (ref mut front, _) = self.as_slices();
259        let n = Read::read(front, buf)?;
260        self.drain(..n);
261        Ok(n)
262    }
263
264    #[inline]
265    fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
266        let (front, back) = self.as_slices();
267
268        // Use only the front buffer if it is big enough to fill `buf`, else use
269        // the back buffer too.
270        match buf.split_at_mut_checked(front.len()) {
271            None => buf.copy_from_slice(&front[..buf.len()]),
272            Some((buf_front, buf_back)) => match back.split_at_checked(buf_back.len()) {
273                Some((back, _)) => {
274                    buf_front.copy_from_slice(front);
275                    buf_back.copy_from_slice(back);
276                }
277                None => {
278                    self.clear();
279                    return Err(Error::UnexpectedEof);
280                }
281            },
282        }
283
284        self.drain(..buf.len());
285        Ok(())
286    }
287
288    #[inline]
289    fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> Result<()> {
290        let (ref mut front, _) = self.as_slices();
291        let n = cmp::min(cursor.capacity(), front.len());
292        Read::read_buf(front, cursor)?;
293        self.drain(..n);
294        Ok(())
295    }
296
297    #[inline]
298    fn read_buf_exact(&mut self, mut cursor: BorrowedCursor<'_>) -> Result<()> {
299        let len = cursor.capacity();
300        let (front, back) = self.as_slices();
301
302        match front.split_at_checked(cursor.capacity()) {
303            Some((front, _)) => cursor.append(front),
304            None => {
305                cursor.append(front);
306                match back.split_at_checked(cursor.capacity()) {
307                    Some((back, _)) => cursor.append(back),
308                    None => {
309                        cursor.append(back);
310                        self.clear();
311                        return Err(Error::UnexpectedEof);
312                    }
313                }
314            }
315        }
316
317        self.drain(..len);
318        Ok(())
319    }
320
321    #[inline]
322    #[cfg(feature = "alloc")]
323    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
324        // The total len is known upfront so we can reserve it in a single call.
325        let len = self.len();
326        buf.try_reserve(len).map_err(|_| Error::NoMemory)?;
327        let (front, back) = self.as_slices();
328        buf.extend_from_slice(front);
329        buf.extend_from_slice(back);
330        self.clear();
331        Ok(len)
332    }
333
334    #[inline]
335    #[cfg(feature = "alloc")]
336    fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
337        // SAFETY: We only append to the buffer
338        unsafe { super::append_to_string(buf, |buf| self.read_to_end(buf)) }
339    }
340}
341
342#[cfg(feature = "alloc")]
343impl BufRead for VecDeque<u8> {
344    /// Returns the contents of the "front" slice as returned by
345    /// [`as_slices`][`VecDeque::as_slices`]. If the contained byte slices of the `VecDeque` are
346    /// discontiguous, multiple calls to `fill_buf` will be needed to read the entire content.
347    #[inline]
348    fn fill_buf(&mut self) -> Result<&[u8]> {
349        let (front, _) = self.as_slices();
350        Ok(front)
351    }
352
353    #[inline]
354    fn consume(&mut self, amt: usize) {
355        self.drain(..amt);
356    }
357}