std/io/
impls.rs

1#[cfg(test)]
2mod tests;
3
4use crate::alloc::Allocator;
5use crate::collections::VecDeque;
6use crate::io::{self, BorrowedCursor, BufRead, IoSlice, IoSliceMut, Read, Seek, SeekFrom, Write};
7use crate::{cmp, fmt, mem, str};
8
9// =============================================================================
10// Forwarding implementations
11
12#[stable(feature = "rust1", since = "1.0.0")]
13impl<R: Read + ?Sized> Read for &mut R {
14    #[inline]
15    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
16        (**self).read(buf)
17    }
18
19    #[inline]
20    fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
21        (**self).read_buf(cursor)
22    }
23
24    #[inline]
25    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
26        (**self).read_vectored(bufs)
27    }
28
29    #[inline]
30    fn is_read_vectored(&self) -> bool {
31        (**self).is_read_vectored()
32    }
33
34    #[inline]
35    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
36        (**self).read_to_end(buf)
37    }
38
39    #[inline]
40    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
41        (**self).read_to_string(buf)
42    }
43
44    #[inline]
45    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
46        (**self).read_exact(buf)
47    }
48    #[inline]
49    fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
50        (**self).read_buf_exact(cursor)
51    }
52}
53#[stable(feature = "rust1", since = "1.0.0")]
54impl<W: Write + ?Sized> Write for &mut W {
55    #[inline]
56    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
57        (**self).write(buf)
58    }
59
60    #[inline]
61    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
62        (**self).write_vectored(bufs)
63    }
64
65    #[inline]
66    fn is_write_vectored(&self) -> bool {
67        (**self).is_write_vectored()
68    }
69
70    #[inline]
71    fn flush(&mut self) -> io::Result<()> {
72        (**self).flush()
73    }
74
75    #[inline]
76    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
77        (**self).write_all(buf)
78    }
79
80    #[inline]
81    fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
82        (**self).write_fmt(fmt)
83    }
84}
85#[stable(feature = "rust1", since = "1.0.0")]
86impl<S: Seek + ?Sized> Seek for &mut S {
87    #[inline]
88    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
89        (**self).seek(pos)
90    }
91
92    #[inline]
93    fn stream_position(&mut self) -> io::Result<u64> {
94        (**self).stream_position()
95    }
96}
97#[stable(feature = "rust1", since = "1.0.0")]
98impl<B: BufRead + ?Sized> BufRead for &mut B {
99    #[inline]
100    fn fill_buf(&mut self) -> io::Result<&[u8]> {
101        (**self).fill_buf()
102    }
103
104    #[inline]
105    fn consume(&mut self, amt: usize) {
106        (**self).consume(amt)
107    }
108
109    #[inline]
110    fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<usize> {
111        (**self).read_until(byte, buf)
112    }
113
114    #[inline]
115    fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
116        (**self).read_line(buf)
117    }
118}
119
120#[stable(feature = "rust1", since = "1.0.0")]
121impl<R: Read + ?Sized> Read for Box<R> {
122    #[inline]
123    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
124        (**self).read(buf)
125    }
126
127    #[inline]
128    fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
129        (**self).read_buf(cursor)
130    }
131
132    #[inline]
133    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
134        (**self).read_vectored(bufs)
135    }
136
137    #[inline]
138    fn is_read_vectored(&self) -> bool {
139        (**self).is_read_vectored()
140    }
141
142    #[inline]
143    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
144        (**self).read_to_end(buf)
145    }
146
147    #[inline]
148    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
149        (**self).read_to_string(buf)
150    }
151
152    #[inline]
153    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
154        (**self).read_exact(buf)
155    }
156    #[inline]
157    fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
158        (**self).read_buf_exact(cursor)
159    }
160}
161#[stable(feature = "rust1", since = "1.0.0")]
162impl<W: Write + ?Sized> Write for Box<W> {
163    #[inline]
164    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
165        (**self).write(buf)
166    }
167
168    #[inline]
169    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
170        (**self).write_vectored(bufs)
171    }
172
173    #[inline]
174    fn is_write_vectored(&self) -> bool {
175        (**self).is_write_vectored()
176    }
177
178    #[inline]
179    fn flush(&mut self) -> io::Result<()> {
180        (**self).flush()
181    }
182
183    #[inline]
184    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
185        (**self).write_all(buf)
186    }
187
188    #[inline]
189    fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
190        (**self).write_fmt(fmt)
191    }
192}
193#[stable(feature = "rust1", since = "1.0.0")]
194impl<S: Seek + ?Sized> Seek for Box<S> {
195    #[inline]
196    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
197        (**self).seek(pos)
198    }
199
200    #[inline]
201    fn stream_position(&mut self) -> io::Result<u64> {
202        (**self).stream_position()
203    }
204}
205#[stable(feature = "rust1", since = "1.0.0")]
206impl<B: BufRead + ?Sized> BufRead for Box<B> {
207    #[inline]
208    fn fill_buf(&mut self) -> io::Result<&[u8]> {
209        (**self).fill_buf()
210    }
211
212    #[inline]
213    fn consume(&mut self, amt: usize) {
214        (**self).consume(amt)
215    }
216
217    #[inline]
218    fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<usize> {
219        (**self).read_until(byte, buf)
220    }
221
222    #[inline]
223    fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
224        (**self).read_line(buf)
225    }
226}
227
228// =============================================================================
229// In-memory buffer implementations
230
231/// Read is implemented for `&[u8]` by copying from the slice.
232///
233/// Note that reading updates the slice to point to the yet unread part.
234/// The slice will be empty when EOF is reached.
235#[stable(feature = "rust1", since = "1.0.0")]
236impl Read for &[u8] {
237    #[inline]
238    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
239        let amt = cmp::min(buf.len(), self.len());
240        let (a, b) = self.split_at(amt);
241
242        // First check if the amount of bytes we want to read is small:
243        // `copy_from_slice` will generally expand to a call to `memcpy`, and
244        // for a single byte the overhead is significant.
245        if amt == 1 {
246            buf[0] = a[0];
247        } else {
248            buf[..amt].copy_from_slice(a);
249        }
250
251        *self = b;
252        Ok(amt)
253    }
254
255    #[inline]
256    fn read_buf(&mut self, mut cursor: BorrowedCursor<'_>) -> io::Result<()> {
257        let amt = cmp::min(cursor.capacity(), self.len());
258        let (a, b) = self.split_at(amt);
259
260        cursor.append(a);
261
262        *self = b;
263        Ok(())
264    }
265
266    #[inline]
267    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
268        let mut nread = 0;
269        for buf in bufs {
270            nread += self.read(buf)?;
271            if self.is_empty() {
272                break;
273            }
274        }
275
276        Ok(nread)
277    }
278
279    #[inline]
280    fn is_read_vectored(&self) -> bool {
281        true
282    }
283
284    #[inline]
285    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
286        if buf.len() > self.len() {
287            // `read_exact` makes no promise about the content of `buf` if it
288            // fails so don't bother about that.
289            *self = &self[self.len()..];
290            return Err(io::Error::READ_EXACT_EOF);
291        }
292        let (a, b) = self.split_at(buf.len());
293
294        // First check if the amount of bytes we want to read is small:
295        // `copy_from_slice` will generally expand to a call to `memcpy`, and
296        // for a single byte the overhead is significant.
297        if buf.len() == 1 {
298            buf[0] = a[0];
299        } else {
300            buf.copy_from_slice(a);
301        }
302
303        *self = b;
304        Ok(())
305    }
306
307    #[inline]
308    fn read_buf_exact(&mut self, mut cursor: BorrowedCursor<'_>) -> io::Result<()> {
309        if cursor.capacity() > self.len() {
310            // Append everything we can to the cursor.
311            cursor.append(*self);
312            *self = &self[self.len()..];
313            return Err(io::Error::READ_EXACT_EOF);
314        }
315        let (a, b) = self.split_at(cursor.capacity());
316
317        cursor.append(a);
318
319        *self = b;
320        Ok(())
321    }
322
323    #[inline]
324    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
325        let len = self.len();
326        buf.try_reserve(len)?;
327        buf.extend_from_slice(*self);
328        *self = &self[len..];
329        Ok(len)
330    }
331
332    #[inline]
333    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
334        let content = str::from_utf8(self).map_err(|_| io::Error::INVALID_UTF8)?;
335        let len = self.len();
336        buf.try_reserve(len)?;
337        buf.push_str(content);
338        *self = &self[len..];
339        Ok(len)
340    }
341}
342
343#[stable(feature = "rust1", since = "1.0.0")]
344impl BufRead for &[u8] {
345    #[inline]
346    fn fill_buf(&mut self) -> io::Result<&[u8]> {
347        Ok(*self)
348    }
349
350    #[inline]
351    fn consume(&mut self, amt: usize) {
352        *self = &self[amt..];
353    }
354}
355
356/// Write is implemented for `&mut [u8]` by copying into the slice, overwriting
357/// its data.
358///
359/// Note that writing updates the slice to point to the yet unwritten part.
360/// The slice will be empty when it has been completely overwritten.
361///
362/// If the number of bytes to be written exceeds the size of the slice, write operations will
363/// return short writes: ultimately, `Ok(0)`; in this situation, `write_all` returns an error of
364/// kind `ErrorKind::WriteZero`.
365#[stable(feature = "rust1", since = "1.0.0")]
366impl Write for &mut [u8] {
367    #[inline]
368    fn write(&mut self, data: &[u8]) -> io::Result<usize> {
369        let amt = cmp::min(data.len(), self.len());
370        let (a, b) = mem::take(self).split_at_mut(amt);
371        a.copy_from_slice(&data[..amt]);
372        *self = b;
373        Ok(amt)
374    }
375
376    #[inline]
377    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
378        let mut nwritten = 0;
379        for buf in bufs {
380            nwritten += self.write(buf)?;
381            if self.is_empty() {
382                break;
383            }
384        }
385
386        Ok(nwritten)
387    }
388
389    #[inline]
390    fn is_write_vectored(&self) -> bool {
391        true
392    }
393
394    #[inline]
395    fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
396        if self.write(data)? == data.len() { Ok(()) } else { Err(io::Error::WRITE_ALL_EOF) }
397    }
398
399    #[inline]
400    fn flush(&mut self) -> io::Result<()> {
401        Ok(())
402    }
403}
404
405/// Write is implemented for `Vec<u8>` by appending to the vector.
406/// The vector will grow as needed.
407#[stable(feature = "rust1", since = "1.0.0")]
408impl<A: Allocator> Write for Vec<u8, A> {
409    #[inline]
410    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
411        self.extend_from_slice(buf);
412        Ok(buf.len())
413    }
414
415    #[inline]
416    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
417        let len = bufs.iter().map(|b| b.len()).sum();
418        self.reserve(len);
419        for buf in bufs {
420            self.extend_from_slice(buf);
421        }
422        Ok(len)
423    }
424
425    #[inline]
426    fn is_write_vectored(&self) -> bool {
427        true
428    }
429
430    #[inline]
431    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
432        self.extend_from_slice(buf);
433        Ok(())
434    }
435
436    #[inline]
437    fn flush(&mut self) -> io::Result<()> {
438        Ok(())
439    }
440}
441
442/// Read is implemented for `VecDeque<u8>` by consuming bytes from the front of the `VecDeque`.
443#[stable(feature = "vecdeque_read_write", since = "1.63.0")]
444impl<A: Allocator> Read for VecDeque<u8, A> {
445    /// Fill `buf` with the contents of the "front" slice as returned by
446    /// [`as_slices`][`VecDeque::as_slices`]. If the contained byte slices of the `VecDeque` are
447    /// discontiguous, multiple calls to `read` will be needed to read the entire content.
448    #[inline]
449    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
450        let (ref mut front, _) = self.as_slices();
451        let n = Read::read(front, buf)?;
452        self.drain(..n);
453        Ok(n)
454    }
455
456    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
457        let (front, back) = self.as_slices();
458
459        // Use only the front buffer if it is big enough to fill `buf`, else use
460        // the back buffer too.
461        match buf.split_at_mut_checked(front.len()) {
462            None => buf.copy_from_slice(&front[..buf.len()]),
463            Some((buf_front, buf_back)) => match back.split_at_checked(buf_back.len()) {
464                Some((back, _)) => {
465                    buf_front.copy_from_slice(front);
466                    buf_back.copy_from_slice(back);
467                }
468                None => {
469                    self.clear();
470                    return Err(io::Error::READ_EXACT_EOF);
471                }
472            },
473        }
474
475        self.drain(..buf.len());
476        Ok(())
477    }
478
479    #[inline]
480    fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
481        let (ref mut front, _) = self.as_slices();
482        let n = cmp::min(cursor.capacity(), front.len());
483        Read::read_buf(front, cursor)?;
484        self.drain(..n);
485        Ok(())
486    }
487
488    fn read_buf_exact(&mut self, mut cursor: BorrowedCursor<'_>) -> io::Result<()> {
489        let len = cursor.capacity();
490        let (front, back) = self.as_slices();
491
492        match front.split_at_checked(cursor.capacity()) {
493            Some((front, _)) => cursor.append(front),
494            None => {
495                cursor.append(front);
496                match back.split_at_checked(cursor.capacity()) {
497                    Some((back, _)) => cursor.append(back),
498                    None => {
499                        cursor.append(back);
500                        self.clear();
501                        return Err(io::Error::READ_EXACT_EOF);
502                    }
503                }
504            }
505        }
506
507        self.drain(..len);
508        Ok(())
509    }
510
511    #[inline]
512    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
513        // The total len is known upfront so we can reserve it in a single call.
514        let len = self.len();
515        buf.try_reserve(len)?;
516
517        let (front, back) = self.as_slices();
518        buf.extend_from_slice(front);
519        buf.extend_from_slice(back);
520        self.clear();
521        Ok(len)
522    }
523
524    #[inline]
525    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
526        // SAFETY: We only append to the buffer
527        unsafe { io::append_to_string(buf, |buf| self.read_to_end(buf)) }
528    }
529}
530
531/// BufRead is implemented for `VecDeque<u8>` by reading bytes from the front of the `VecDeque`.
532#[stable(feature = "vecdeque_buf_read", since = "1.75.0")]
533impl<A: Allocator> BufRead for VecDeque<u8, A> {
534    /// Returns the contents of the "front" slice as returned by
535    /// [`as_slices`][`VecDeque::as_slices`]. If the contained byte slices of the `VecDeque` are
536    /// discontiguous, multiple calls to `fill_buf` will be needed to read the entire content.
537    #[inline]
538    fn fill_buf(&mut self) -> io::Result<&[u8]> {
539        let (front, _) = self.as_slices();
540        Ok(front)
541    }
542
543    #[inline]
544    fn consume(&mut self, amt: usize) {
545        self.drain(..amt);
546    }
547}
548
549/// Write is implemented for `VecDeque<u8>` by appending to the `VecDeque`, growing it as needed.
550#[stable(feature = "vecdeque_read_write", since = "1.63.0")]
551impl<A: Allocator> Write for VecDeque<u8, A> {
552    #[inline]
553    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
554        self.extend(buf);
555        Ok(buf.len())
556    }
557
558    #[inline]
559    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
560        let len = bufs.iter().map(|b| b.len()).sum();
561        self.reserve(len);
562        for buf in bufs {
563            self.extend(&**buf);
564        }
565        Ok(len)
566    }
567
568    #[inline]
569    fn is_write_vectored(&self) -> bool {
570        true
571    }
572
573    #[inline]
574    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
575        self.extend(buf);
576        Ok(())
577    }
578
579    #[inline]
580    fn flush(&mut self) -> io::Result<()> {
581        Ok(())
582    }
583}
584
585#[unstable(feature = "read_buf", issue = "78485")]
586impl<'a> io::Write for core::io::BorrowedCursor<'a> {
587    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
588        let amt = cmp::min(buf.len(), self.capacity());
589        self.append(&buf[..amt]);
590        Ok(amt)
591    }
592
593    #[inline]
594    fn flush(&mut self) -> io::Result<()> {
595        Ok(())
596    }
597}