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, IoSlice, IoSliceMut, Read, Write};
7use crate::sync::Arc;
8use crate::{cmp, fmt, mem, 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<W: Write + ?Sized> Write for &mut W {
57    #[inline]
58    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
59        (**self).write(buf)
60    }
61
62    #[inline]
63    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
64        (**self).write_vectored(bufs)
65    }
66
67    #[inline]
68    fn is_write_vectored(&self) -> bool {
69        (**self).is_write_vectored()
70    }
71
72    #[inline]
73    fn flush(&mut self) -> io::Result<()> {
74        (**self).flush()
75    }
76
77    #[inline]
78    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
79        (**self).write_all(buf)
80    }
81
82    #[inline]
83    fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
84        (**self).write_all_vectored(bufs)
85    }
86
87    #[inline]
88    fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
89        (**self).write_fmt(fmt)
90    }
91}
92#[stable(feature = "rust1", since = "1.0.0")]
93impl<B: BufRead + ?Sized> BufRead for &mut B {
94    #[inline]
95    fn fill_buf(&mut self) -> io::Result<&[u8]> {
96        (**self).fill_buf()
97    }
98
99    #[inline]
100    fn consume(&mut self, amt: usize) {
101        (**self).consume(amt)
102    }
103
104    #[inline]
105    fn has_data_left(&mut self) -> io::Result<bool> {
106        (**self).has_data_left()
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 skip_until(&mut self, byte: u8) -> io::Result<usize> {
116        (**self).skip_until(byte)
117    }
118
119    #[inline]
120    fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
121        (**self).read_line(buf)
122    }
123}
124
125#[stable(feature = "rust1", since = "1.0.0")]
126impl<R: Read + ?Sized> Read for Box<R> {
127    #[inline]
128    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
129        (**self).read(buf)
130    }
131
132    #[inline]
133    fn read_buf(&mut self, cursor: BorrowedCursor<'_, u8>) -> io::Result<()> {
134        (**self).read_buf(cursor)
135    }
136
137    #[inline]
138    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
139        (**self).read_vectored(bufs)
140    }
141
142    #[inline]
143    fn is_read_vectored(&self) -> bool {
144        (**self).is_read_vectored()
145    }
146
147    #[inline]
148    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
149        (**self).read_to_end(buf)
150    }
151
152    #[inline]
153    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
154        (**self).read_to_string(buf)
155    }
156
157    #[inline]
158    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
159        (**self).read_exact(buf)
160    }
161
162    #[inline]
163    fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_, u8>) -> io::Result<()> {
164        (**self).read_buf_exact(cursor)
165    }
166}
167#[stable(feature = "rust1", since = "1.0.0")]
168impl<W: Write + ?Sized> Write for Box<W> {
169    #[inline]
170    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
171        (**self).write(buf)
172    }
173
174    #[inline]
175    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
176        (**self).write_vectored(bufs)
177    }
178
179    #[inline]
180    fn is_write_vectored(&self) -> bool {
181        (**self).is_write_vectored()
182    }
183
184    #[inline]
185    fn flush(&mut self) -> io::Result<()> {
186        (**self).flush()
187    }
188
189    #[inline]
190    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
191        (**self).write_all(buf)
192    }
193
194    #[inline]
195    fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
196        (**self).write_all_vectored(bufs)
197    }
198
199    #[inline]
200    fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
201        (**self).write_fmt(fmt)
202    }
203}
204#[stable(feature = "rust1", since = "1.0.0")]
205impl<B: BufRead + ?Sized> BufRead for Box<B> {
206    #[inline]
207    fn fill_buf(&mut self) -> io::Result<&[u8]> {
208        (**self).fill_buf()
209    }
210
211    #[inline]
212    fn consume(&mut self, amt: usize) {
213        (**self).consume(amt)
214    }
215
216    #[inline]
217    fn has_data_left(&mut self) -> io::Result<bool> {
218        (**self).has_data_left()
219    }
220
221    #[inline]
222    fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<usize> {
223        (**self).read_until(byte, buf)
224    }
225
226    #[inline]
227    fn skip_until(&mut self, byte: u8) -> io::Result<usize> {
228        (**self).skip_until(byte)
229    }
230
231    #[inline]
232    fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
233        (**self).read_line(buf)
234    }
235}
236
237// =============================================================================
238// In-memory buffer implementations
239
240/// Read is implemented for `&[u8]` by copying from the slice.
241///
242/// Note that reading updates the slice to point to the yet unread part.
243/// The slice will be empty when EOF is reached.
244#[stable(feature = "rust1", since = "1.0.0")]
245impl Read for &[u8] {
246    #[inline]
247    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
248        let amt = cmp::min(buf.len(), self.len());
249        let (a, b) = self.split_at(amt);
250
251        // First check if the amount of bytes we want to read is small:
252        // `copy_from_slice` will generally expand to a call to `memcpy`, and
253        // for a single byte the overhead is significant.
254        if amt == 1 {
255            buf[0] = a[0];
256        } else {
257            buf[..amt].copy_from_slice(a);
258        }
259
260        *self = b;
261        Ok(amt)
262    }
263
264    #[inline]
265    fn read_buf(&mut self, mut cursor: BorrowedCursor<'_, u8>) -> io::Result<()> {
266        let amt = cmp::min(cursor.capacity(), self.len());
267        let (a, b) = self.split_at(amt);
268
269        cursor.append(a);
270
271        *self = b;
272        Ok(())
273    }
274
275    #[inline]
276    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
277        let mut nread = 0;
278        for buf in bufs {
279            nread += self.read(buf)?;
280            if self.is_empty() {
281                break;
282            }
283        }
284
285        Ok(nread)
286    }
287
288    #[inline]
289    fn is_read_vectored(&self) -> bool {
290        true
291    }
292
293    #[inline]
294    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
295        if buf.len() > self.len() {
296            // `read_exact` makes no promise about the content of `buf` if it
297            // fails so don't bother about that.
298            *self = &self[self.len()..];
299            return Err(io::Error::READ_EXACT_EOF);
300        }
301        let (a, b) = self.split_at(buf.len());
302
303        // First check if the amount of bytes we want to read is small:
304        // `copy_from_slice` will generally expand to a call to `memcpy`, and
305        // for a single byte the overhead is significant.
306        if buf.len() == 1 {
307            buf[0] = a[0];
308        } else {
309            buf.copy_from_slice(a);
310        }
311
312        *self = b;
313        Ok(())
314    }
315
316    #[inline]
317    fn read_buf_exact(&mut self, mut cursor: BorrowedCursor<'_, u8>) -> io::Result<()> {
318        if cursor.capacity() > self.len() {
319            // Append everything we can to the cursor.
320            cursor.append(*self);
321            *self = &self[self.len()..];
322            return Err(io::Error::READ_EXACT_EOF);
323        }
324        let (a, b) = self.split_at(cursor.capacity());
325
326        cursor.append(a);
327
328        *self = b;
329        Ok(())
330    }
331
332    #[inline]
333    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
334        let len = self.len();
335        buf.try_reserve(len)?;
336        buf.extend_from_slice(*self);
337        *self = &self[len..];
338        Ok(len)
339    }
340
341    #[inline]
342    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
343        let content = str::from_utf8(self).map_err(|_| io::Error::INVALID_UTF8)?;
344        let len = self.len();
345        buf.try_reserve(len)?;
346        buf.push_str(content);
347        *self = &self[len..];
348        Ok(len)
349    }
350}
351
352#[stable(feature = "rust1", since = "1.0.0")]
353impl BufRead for &[u8] {
354    #[inline]
355    fn fill_buf(&mut self) -> io::Result<&[u8]> {
356        Ok(*self)
357    }
358
359    #[inline]
360    fn consume(&mut self, amt: usize) {
361        *self = &self[amt..];
362    }
363}
364
365/// Write is implemented for `&mut [u8]` by copying into the slice, overwriting
366/// its data.
367///
368/// Note that writing updates the slice to point to the yet unwritten part.
369/// The slice will be empty when it has been completely overwritten.
370///
371/// If the number of bytes to be written exceeds the size of the slice, write operations will
372/// return short writes: ultimately, `Ok(0)`; in this situation, `write_all` returns an error of
373/// kind `ErrorKind::WriteZero`.
374#[stable(feature = "rust1", since = "1.0.0")]
375impl Write for &mut [u8] {
376    #[inline]
377    fn write(&mut self, data: &[u8]) -> io::Result<usize> {
378        let amt = cmp::min(data.len(), self.len());
379        let (a, b) = mem::take(self).split_at_mut(amt);
380        a.copy_from_slice(&data[..amt]);
381        *self = b;
382        Ok(amt)
383    }
384
385    #[inline]
386    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
387        let mut nwritten = 0;
388        for buf in bufs {
389            nwritten += self.write(buf)?;
390            if self.is_empty() {
391                break;
392            }
393        }
394
395        Ok(nwritten)
396    }
397
398    #[inline]
399    fn is_write_vectored(&self) -> bool {
400        true
401    }
402
403    #[inline]
404    fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
405        if self.write(data)? < data.len() { Err(io::Error::WRITE_ALL_EOF) } else { Ok(()) }
406    }
407
408    #[inline]
409    fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
410        for buf in bufs {
411            if self.write(buf)? < buf.len() {
412                return Err(io::Error::WRITE_ALL_EOF);
413            }
414        }
415        Ok(())
416    }
417
418    #[inline]
419    fn flush(&mut self) -> io::Result<()> {
420        Ok(())
421    }
422}
423
424/// Write is implemented for `Vec<u8>` by appending to the vector.
425/// The vector will grow as needed.
426#[stable(feature = "rust1", since = "1.0.0")]
427impl<A: Allocator> Write for Vec<u8, A> {
428    #[inline]
429    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
430        self.extend_from_slice(buf);
431        Ok(buf.len())
432    }
433
434    #[inline]
435    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
436        let len = bufs.iter().map(|b| b.len()).sum();
437        self.reserve(len);
438        for buf in bufs {
439            self.extend_from_slice(buf);
440        }
441        Ok(len)
442    }
443
444    #[inline]
445    fn is_write_vectored(&self) -> bool {
446        true
447    }
448
449    #[inline]
450    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
451        self.extend_from_slice(buf);
452        Ok(())
453    }
454
455    #[inline]
456    fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
457        self.write_vectored(bufs)?;
458        Ok(())
459    }
460
461    #[inline]
462    fn flush(&mut self) -> io::Result<()> {
463        Ok(())
464    }
465}
466
467/// Read is implemented for `VecDeque<u8>` by consuming bytes from the front of the `VecDeque`.
468#[stable(feature = "vecdeque_read_write", since = "1.63.0")]
469impl<A: Allocator> Read for VecDeque<u8, A> {
470    /// Fill `buf` with the contents of the "front" slice as returned by
471    /// [`as_slices`][`VecDeque::as_slices`]. If the contained byte slices of the `VecDeque` are
472    /// discontiguous, multiple calls to `read` will be needed to read the entire content.
473    #[inline]
474    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
475        let (ref mut front, _) = self.as_slices();
476        let n = Read::read(front, buf)?;
477        self.drain(..n);
478        Ok(n)
479    }
480
481    #[inline]
482    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
483        let (front, back) = self.as_slices();
484
485        // Use only the front buffer if it is big enough to fill `buf`, else use
486        // the back buffer too.
487        match buf.split_at_mut_checked(front.len()) {
488            None => buf.copy_from_slice(&front[..buf.len()]),
489            Some((buf_front, buf_back)) => match back.split_at_checked(buf_back.len()) {
490                Some((back, _)) => {
491                    buf_front.copy_from_slice(front);
492                    buf_back.copy_from_slice(back);
493                }
494                None => {
495                    self.clear();
496                    return Err(io::Error::READ_EXACT_EOF);
497                }
498            },
499        }
500
501        self.drain(..buf.len());
502        Ok(())
503    }
504
505    #[inline]
506    fn read_buf(&mut self, cursor: BorrowedCursor<'_, u8>) -> io::Result<()> {
507        let (ref mut front, _) = self.as_slices();
508        let n = cmp::min(cursor.capacity(), front.len());
509        Read::read_buf(front, cursor)?;
510        self.drain(..n);
511        Ok(())
512    }
513
514    #[inline]
515    fn read_buf_exact(&mut self, mut cursor: BorrowedCursor<'_, u8>) -> io::Result<()> {
516        let len = cursor.capacity();
517        let (front, back) = self.as_slices();
518
519        match front.split_at_checked(cursor.capacity()) {
520            Some((front, _)) => cursor.append(front),
521            None => {
522                cursor.append(front);
523                match back.split_at_checked(cursor.capacity()) {
524                    Some((back, _)) => cursor.append(back),
525                    None => {
526                        cursor.append(back);
527                        self.clear();
528                        return Err(io::Error::READ_EXACT_EOF);
529                    }
530                }
531            }
532        }
533
534        self.drain(..len);
535        Ok(())
536    }
537
538    #[inline]
539    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
540        // The total len is known upfront so we can reserve it in a single call.
541        let len = self.len();
542        buf.try_reserve(len)?;
543
544        let (front, back) = self.as_slices();
545        buf.extend_from_slice(front);
546        buf.extend_from_slice(back);
547        self.clear();
548        Ok(len)
549    }
550
551    #[inline]
552    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
553        // SAFETY: We only append to the buffer
554        unsafe { io::append_to_string(buf, |buf| self.read_to_end(buf)) }
555    }
556}
557
558/// BufRead is implemented for `VecDeque<u8>` by reading bytes from the front of the `VecDeque`.
559#[stable(feature = "vecdeque_buf_read", since = "1.75.0")]
560impl<A: Allocator> BufRead for VecDeque<u8, A> {
561    /// Returns the contents of the "front" slice as returned by
562    /// [`as_slices`][`VecDeque::as_slices`]. If the contained byte slices of the `VecDeque` are
563    /// discontiguous, multiple calls to `fill_buf` will be needed to read the entire content.
564    #[inline]
565    fn fill_buf(&mut self) -> io::Result<&[u8]> {
566        let (front, _) = self.as_slices();
567        Ok(front)
568    }
569
570    #[inline]
571    fn consume(&mut self, amt: usize) {
572        self.drain(..amt);
573    }
574}
575
576/// Write is implemented for `VecDeque<u8>` by appending to the `VecDeque`, growing it as needed.
577#[stable(feature = "vecdeque_read_write", since = "1.63.0")]
578impl<A: Allocator> Write for VecDeque<u8, A> {
579    #[inline]
580    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
581        self.extend(buf);
582        Ok(buf.len())
583    }
584
585    #[inline]
586    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
587        let len = bufs.iter().map(|b| b.len()).sum();
588        self.reserve(len);
589        for buf in bufs {
590            self.extend(&**buf);
591        }
592        Ok(len)
593    }
594
595    #[inline]
596    fn is_write_vectored(&self) -> bool {
597        true
598    }
599
600    #[inline]
601    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
602        self.extend(buf);
603        Ok(())
604    }
605
606    #[inline]
607    fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
608        self.write_vectored(bufs)?;
609        Ok(())
610    }
611
612    #[inline]
613    fn flush(&mut self) -> io::Result<()> {
614        Ok(())
615    }
616}
617
618#[unstable(feature = "read_buf", issue = "78485")]
619impl<'a> io::Write for core::io::BorrowedCursor<'a, u8> {
620    #[inline]
621    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
622        let amt = cmp::min(buf.len(), self.capacity());
623        self.append(&buf[..amt]);
624        Ok(amt)
625    }
626
627    #[inline]
628    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
629        let mut nwritten = 0;
630        for buf in bufs {
631            let n = self.write(buf)?;
632            nwritten += n;
633            if n < buf.len() {
634                break;
635            }
636        }
637        Ok(nwritten)
638    }
639
640    #[inline]
641    fn is_write_vectored(&self) -> bool {
642        true
643    }
644
645    #[inline]
646    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
647        if self.write(buf)? < buf.len() { Err(io::Error::WRITE_ALL_EOF) } else { Ok(()) }
648    }
649
650    #[inline]
651    fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
652        for buf in bufs {
653            if self.write(buf)? < buf.len() {
654                return Err(io::Error::WRITE_ALL_EOF);
655            }
656        }
657        Ok(())
658    }
659
660    #[inline]
661    fn flush(&mut self) -> io::Result<()> {
662        Ok(())
663    }
664}
665
666#[stable(feature = "io_traits_arc", since = "1.73.0")]
667impl<R: Read + ?Sized> Read for Arc<R>
668where
669    for<'a> &'a R: Read,
670    R: crate::io::IoHandle,
671{
672    #[inline]
673    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
674        (&**self).read(buf)
675    }
676
677    #[inline]
678    fn read_buf(&mut self, cursor: BorrowedCursor<'_, u8>) -> io::Result<()> {
679        (&**self).read_buf(cursor)
680    }
681
682    #[inline]
683    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
684        (&**self).read_vectored(bufs)
685    }
686
687    #[inline]
688    fn is_read_vectored(&self) -> bool {
689        (&**self).is_read_vectored()
690    }
691
692    #[inline]
693    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
694        (&**self).read_to_end(buf)
695    }
696
697    #[inline]
698    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
699        (&**self).read_to_string(buf)
700    }
701
702    #[inline]
703    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
704        (&**self).read_exact(buf)
705    }
706
707    #[inline]
708    fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_, u8>) -> io::Result<()> {
709        (&**self).read_buf_exact(cursor)
710    }
711}
712#[stable(feature = "io_traits_arc", since = "1.73.0")]
713impl<W: Write + ?Sized> Write for Arc<W>
714where
715    for<'a> &'a W: Write,
716    W: crate::io::IoHandle,
717{
718    #[inline]
719    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
720        (&**self).write(buf)
721    }
722
723    #[inline]
724    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
725        (&**self).write_vectored(bufs)
726    }
727
728    #[inline]
729    fn is_write_vectored(&self) -> bool {
730        (&**self).is_write_vectored()
731    }
732
733    #[inline]
734    fn flush(&mut self) -> io::Result<()> {
735        (&**self).flush()
736    }
737
738    #[inline]
739    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
740        (&**self).write_all(buf)
741    }
742
743    #[inline]
744    fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
745        (&**self).write_all_vectored(bufs)
746    }
747
748    #[inline]
749    fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
750        (&**self).write_fmt(fmt)
751    }
752}