Skip to main content

alloc/io/
impls.rs

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