Skip to main content

std/io/
impls.rs

1#[cfg(test)]
2mod tests;
3
4use crate::alloc::Allocator;
5use crate::collections::VecDeque;
6use crate::io::{self, BorrowedCursor, BufRead, IoSliceMut, Read};
7use crate::sync::Arc;
8use crate::{cmp, str};
9
10// =============================================================================
11// Forwarding implementations
12
13#[stable(feature = "rust1", since = "1.0.0")]
14impl<R: Read + ?Sized> Read for &mut R {
15    #[inline]
16    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
17        (**self).read(buf)
18    }
19
20    #[inline]
21    fn read_buf(&mut self, cursor: BorrowedCursor<'_, u8>) -> io::Result<()> {
22        (**self).read_buf(cursor)
23    }
24
25    #[inline]
26    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
27        (**self).read_vectored(bufs)
28    }
29
30    #[inline]
31    fn is_read_vectored(&self) -> bool {
32        (**self).is_read_vectored()
33    }
34
35    #[inline]
36    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
37        (**self).read_to_end(buf)
38    }
39
40    #[inline]
41    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
42        (**self).read_to_string(buf)
43    }
44
45    #[inline]
46    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
47        (**self).read_exact(buf)
48    }
49
50    #[inline]
51    fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_, u8>) -> io::Result<()> {
52        (**self).read_buf_exact(cursor)
53    }
54}
55#[stable(feature = "rust1", since = "1.0.0")]
56impl<B: BufRead + ?Sized> BufRead for &mut B {
57    #[inline]
58    fn fill_buf(&mut self) -> io::Result<&[u8]> {
59        (**self).fill_buf()
60    }
61
62    #[inline]
63    fn consume(&mut self, amt: usize) {
64        (**self).consume(amt)
65    }
66
67    #[inline]
68    fn has_data_left(&mut self) -> io::Result<bool> {
69        (**self).has_data_left()
70    }
71
72    #[inline]
73    fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<usize> {
74        (**self).read_until(byte, buf)
75    }
76
77    #[inline]
78    fn skip_until(&mut self, byte: u8) -> io::Result<usize> {
79        (**self).skip_until(byte)
80    }
81
82    #[inline]
83    fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
84        (**self).read_line(buf)
85    }
86}
87
88#[stable(feature = "rust1", since = "1.0.0")]
89impl<R: Read + ?Sized> Read for Box<R> {
90    #[inline]
91    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
92        (**self).read(buf)
93    }
94
95    #[inline]
96    fn read_buf(&mut self, cursor: BorrowedCursor<'_, u8>) -> io::Result<()> {
97        (**self).read_buf(cursor)
98    }
99
100    #[inline]
101    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
102        (**self).read_vectored(bufs)
103    }
104
105    #[inline]
106    fn is_read_vectored(&self) -> bool {
107        (**self).is_read_vectored()
108    }
109
110    #[inline]
111    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
112        (**self).read_to_end(buf)
113    }
114
115    #[inline]
116    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
117        (**self).read_to_string(buf)
118    }
119
120    #[inline]
121    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
122        (**self).read_exact(buf)
123    }
124
125    #[inline]
126    fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_, u8>) -> io::Result<()> {
127        (**self).read_buf_exact(cursor)
128    }
129}
130#[stable(feature = "rust1", since = "1.0.0")]
131impl<B: BufRead + ?Sized> BufRead for Box<B> {
132    #[inline]
133    fn fill_buf(&mut self) -> io::Result<&[u8]> {
134        (**self).fill_buf()
135    }
136
137    #[inline]
138    fn consume(&mut self, amt: usize) {
139        (**self).consume(amt)
140    }
141
142    #[inline]
143    fn has_data_left(&mut self) -> io::Result<bool> {
144        (**self).has_data_left()
145    }
146
147    #[inline]
148    fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<usize> {
149        (**self).read_until(byte, buf)
150    }
151
152    #[inline]
153    fn skip_until(&mut self, byte: u8) -> io::Result<usize> {
154        (**self).skip_until(byte)
155    }
156
157    #[inline]
158    fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
159        (**self).read_line(buf)
160    }
161}
162
163// =============================================================================
164// In-memory buffer implementations
165
166/// Read is implemented for `&[u8]` by copying from the slice.
167///
168/// Note that reading updates the slice to point to the yet unread part.
169/// The slice will be empty when EOF is reached.
170#[stable(feature = "rust1", since = "1.0.0")]
171impl Read for &[u8] {
172    #[inline]
173    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
174        let amt = cmp::min(buf.len(), self.len());
175        let (a, b) = self.split_at(amt);
176
177        // First check if the amount of bytes we want to read is small:
178        // `copy_from_slice` will generally expand to a call to `memcpy`, and
179        // for a single byte the overhead is significant.
180        if amt == 1 {
181            buf[0] = a[0];
182        } else {
183            buf[..amt].copy_from_slice(a);
184        }
185
186        *self = b;
187        Ok(amt)
188    }
189
190    #[inline]
191    fn read_buf(&mut self, mut cursor: BorrowedCursor<'_, u8>) -> io::Result<()> {
192        let amt = cmp::min(cursor.capacity(), self.len());
193        let (a, b) = self.split_at(amt);
194
195        cursor.append(a);
196
197        *self = b;
198        Ok(())
199    }
200
201    #[inline]
202    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
203        let mut nread = 0;
204        for buf in bufs {
205            nread += self.read(buf)?;
206            if self.is_empty() {
207                break;
208            }
209        }
210
211        Ok(nread)
212    }
213
214    #[inline]
215    fn is_read_vectored(&self) -> bool {
216        true
217    }
218
219    #[inline]
220    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
221        if buf.len() > self.len() {
222            // `read_exact` makes no promise about the content of `buf` if it
223            // fails so don't bother about that.
224            *self = &self[self.len()..];
225            return Err(io::Error::READ_EXACT_EOF);
226        }
227        let (a, b) = self.split_at(buf.len());
228
229        // First check if the amount of bytes we want to read is small:
230        // `copy_from_slice` will generally expand to a call to `memcpy`, and
231        // for a single byte the overhead is significant.
232        if buf.len() == 1 {
233            buf[0] = a[0];
234        } else {
235            buf.copy_from_slice(a);
236        }
237
238        *self = b;
239        Ok(())
240    }
241
242    #[inline]
243    fn read_buf_exact(&mut self, mut cursor: BorrowedCursor<'_, u8>) -> io::Result<()> {
244        if cursor.capacity() > self.len() {
245            // Append everything we can to the cursor.
246            cursor.append(*self);
247            *self = &self[self.len()..];
248            return Err(io::Error::READ_EXACT_EOF);
249        }
250        let (a, b) = self.split_at(cursor.capacity());
251
252        cursor.append(a);
253
254        *self = b;
255        Ok(())
256    }
257
258    #[inline]
259    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
260        let len = self.len();
261        buf.try_reserve(len)?;
262        buf.extend_from_slice(*self);
263        *self = &self[len..];
264        Ok(len)
265    }
266
267    #[inline]
268    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
269        let content = str::from_utf8(self).map_err(|_| io::Error::INVALID_UTF8)?;
270        let len = self.len();
271        buf.try_reserve(len)?;
272        buf.push_str(content);
273        *self = &self[len..];
274        Ok(len)
275    }
276}
277
278#[stable(feature = "rust1", since = "1.0.0")]
279impl BufRead for &[u8] {
280    #[inline]
281    fn fill_buf(&mut self) -> io::Result<&[u8]> {
282        Ok(*self)
283    }
284
285    #[inline]
286    fn consume(&mut self, amt: usize) {
287        *self = &self[amt..];
288    }
289}
290
291/// Read is implemented for `VecDeque<u8>` by consuming bytes from the front of the `VecDeque`.
292#[stable(feature = "vecdeque_read_write", since = "1.63.0")]
293impl<A: Allocator> Read for VecDeque<u8, A> {
294    /// Fill `buf` with the contents of the "front" slice as returned by
295    /// [`as_slices`][`VecDeque::as_slices`]. If the contained byte slices of the `VecDeque` are
296    /// discontiguous, multiple calls to `read` will be needed to read the entire content.
297    #[inline]
298    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
299        let (ref mut front, _) = self.as_slices();
300        let n = Read::read(front, buf)?;
301        self.drain(..n);
302        Ok(n)
303    }
304
305    #[inline]
306    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
307        let (front, back) = self.as_slices();
308
309        // Use only the front buffer if it is big enough to fill `buf`, else use
310        // the back buffer too.
311        match buf.split_at_mut_checked(front.len()) {
312            None => buf.copy_from_slice(&front[..buf.len()]),
313            Some((buf_front, buf_back)) => match back.split_at_checked(buf_back.len()) {
314                Some((back, _)) => {
315                    buf_front.copy_from_slice(front);
316                    buf_back.copy_from_slice(back);
317                }
318                None => {
319                    self.clear();
320                    return Err(io::Error::READ_EXACT_EOF);
321                }
322            },
323        }
324
325        self.drain(..buf.len());
326        Ok(())
327    }
328
329    #[inline]
330    fn read_buf(&mut self, cursor: BorrowedCursor<'_, u8>) -> io::Result<()> {
331        let (ref mut front, _) = self.as_slices();
332        let n = cmp::min(cursor.capacity(), front.len());
333        Read::read_buf(front, cursor)?;
334        self.drain(..n);
335        Ok(())
336    }
337
338    #[inline]
339    fn read_buf_exact(&mut self, mut cursor: BorrowedCursor<'_, u8>) -> io::Result<()> {
340        let len = cursor.capacity();
341        let (front, back) = self.as_slices();
342
343        match front.split_at_checked(cursor.capacity()) {
344            Some((front, _)) => cursor.append(front),
345            None => {
346                cursor.append(front);
347                match back.split_at_checked(cursor.capacity()) {
348                    Some((back, _)) => cursor.append(back),
349                    None => {
350                        cursor.append(back);
351                        self.clear();
352                        return Err(io::Error::READ_EXACT_EOF);
353                    }
354                }
355            }
356        }
357
358        self.drain(..len);
359        Ok(())
360    }
361
362    #[inline]
363    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
364        // The total len is known upfront so we can reserve it in a single call.
365        let len = self.len();
366        buf.try_reserve(len)?;
367
368        let (front, back) = self.as_slices();
369        buf.extend_from_slice(front);
370        buf.extend_from_slice(back);
371        self.clear();
372        Ok(len)
373    }
374
375    #[inline]
376    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
377        // SAFETY: We only append to the buffer
378        unsafe { io::append_to_string(buf, |buf| self.read_to_end(buf)) }
379    }
380}
381
382/// BufRead is implemented for `VecDeque<u8>` by reading bytes from the front of the `VecDeque`.
383#[stable(feature = "vecdeque_buf_read", since = "1.75.0")]
384impl<A: Allocator> BufRead for VecDeque<u8, A> {
385    /// Returns the contents of the "front" slice as returned by
386    /// [`as_slices`][`VecDeque::as_slices`]. If the contained byte slices of the `VecDeque` are
387    /// discontiguous, multiple calls to `fill_buf` will be needed to read the entire content.
388    #[inline]
389    fn fill_buf(&mut self) -> io::Result<&[u8]> {
390        let (front, _) = self.as_slices();
391        Ok(front)
392    }
393
394    #[inline]
395    fn consume(&mut self, amt: usize) {
396        self.drain(..amt);
397    }
398}
399
400#[stable(feature = "io_traits_arc", since = "1.73.0")]
401impl<R: Read + ?Sized> Read for Arc<R>
402where
403    for<'a> &'a R: Read,
404    R: crate::io::IoHandle,
405{
406    #[inline]
407    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
408        (&**self).read(buf)
409    }
410
411    #[inline]
412    fn read_buf(&mut self, cursor: BorrowedCursor<'_, u8>) -> io::Result<()> {
413        (&**self).read_buf(cursor)
414    }
415
416    #[inline]
417    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
418        (&**self).read_vectored(bufs)
419    }
420
421    #[inline]
422    fn is_read_vectored(&self) -> bool {
423        (&**self).is_read_vectored()
424    }
425
426    #[inline]
427    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
428        (&**self).read_to_end(buf)
429    }
430
431    #[inline]
432    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
433        (&**self).read_to_string(buf)
434    }
435
436    #[inline]
437    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
438        (&**self).read_exact(buf)
439    }
440
441    #[inline]
442    fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_, u8>) -> io::Result<()> {
443        (&**self).read_buf_exact(cursor)
444    }
445}