1 //! Traits, helpers, and type definitions for core I/O functionality.
3 //! The `std::io` module contains a number of common things you'll need
4 //! when doing input and output. The most core part of this module is
5 //! the [`Read`] and [`Write`] traits, which provide the
6 //! most general interface for reading and writing input and output.
10 //! Because they are traits, [`Read`] and [`Write`] are implemented by a number
11 //! of other types, and you can implement them for your types too. As such,
12 //! you'll see a few different types of I/O throughout the documentation in
13 //! this module: [`File`]s, [`TcpStream`]s, and sometimes even [`Vec<T>`]s. For
14 //! example, [`Read`] adds a [`read`][`Read::read`] method, which we can use on
19 //! use std::io::prelude::*;
20 //! use std::fs::File;
22 //! fn main() -> io::Result<()> {
23 //! let mut f = File::open("foo.txt")?;
24 //! let mut buffer = [0; 10];
26 //! // read up to 10 bytes
27 //! let n = f.read(&mut buffer)?;
29 //! println!("The bytes: {:?}", &buffer[..n]);
34 //! [`Read`] and [`Write`] are so important, implementors of the two traits have a
35 //! nickname: readers and writers. So you'll sometimes see 'a reader' instead
36 //! of 'a type that implements the [`Read`] trait'. Much easier!
38 //! ## Seek and BufRead
40 //! Beyond that, there are two important traits that are provided: [`Seek`]
41 //! and [`BufRead`]. Both of these build on top of a reader to control
42 //! how the reading happens. [`Seek`] lets you control where the next byte is
47 //! use std::io::prelude::*;
48 //! use std::io::SeekFrom;
49 //! use std::fs::File;
51 //! fn main() -> io::Result<()> {
52 //! let mut f = File::open("foo.txt")?;
53 //! let mut buffer = [0; 10];
55 //! // skip to the last 10 bytes of the file
56 //! f.seek(SeekFrom::End(-10))?;
58 //! // read up to 10 bytes
59 //! let n = f.read(&mut buffer)?;
61 //! println!("The bytes: {:?}", &buffer[..n]);
66 //! [`BufRead`] uses an internal buffer to provide a number of other ways to read, but
67 //! to show it off, we'll need to talk about buffers in general. Keep reading!
69 //! ## BufReader and BufWriter
71 //! Byte-based interfaces are unwieldy and can be inefficient, as we'd need to be
72 //! making near-constant calls to the operating system. To help with this,
73 //! `std::io` comes with two structs, [`BufReader`] and [`BufWriter`], which wrap
74 //! readers and writers. The wrapper uses a buffer, reducing the number of
75 //! calls and providing nicer methods for accessing exactly what you want.
77 //! For example, [`BufReader`] works with the [`BufRead`] trait to add extra
78 //! methods to any reader:
82 //! use std::io::prelude::*;
83 //! use std::io::BufReader;
84 //! use std::fs::File;
86 //! fn main() -> io::Result<()> {
87 //! let f = File::open("foo.txt")?;
88 //! let mut reader = BufReader::new(f);
89 //! let mut buffer = String::new();
91 //! // read a line into buffer
92 //! reader.read_line(&mut buffer)?;
94 //! println!("{}", buffer);
99 //! [`BufWriter`] doesn't add any new ways of writing; it just buffers every call
100 //! to [`write`][`Write::write`]:
104 //! use std::io::prelude::*;
105 //! use std::io::BufWriter;
106 //! use std::fs::File;
108 //! fn main() -> io::Result<()> {
109 //! let f = File::create("foo.txt")?;
111 //! let mut writer = BufWriter::new(f);
113 //! // write a byte to the buffer
114 //! writer.write(&[42])?;
116 //! } // the buffer is flushed once writer goes out of scope
122 //! ## Standard input and output
124 //! A very common source of input is standard input:
129 //! fn main() -> io::Result<()> {
130 //! let mut input = String::new();
132 //! io::stdin().read_line(&mut input)?;
134 //! println!("You typed: {}", input.trim());
139 //! Note that you cannot use the [`?` operator] in functions that do not return
140 //! a [`Result<T, E>`][`Result`]. Instead, you can call [`.unwrap()`]
141 //! or `match` on the return value to catch any possible errors:
146 //! let mut input = String::new();
148 //! io::stdin().read_line(&mut input).unwrap();
151 //! And a very common source of output is standard output:
155 //! use std::io::prelude::*;
157 //! fn main() -> io::Result<()> {
158 //! io::stdout().write(&[42])?;
163 //! Of course, using [`io::stdout`] directly is less common than something like
166 //! ## Iterator types
168 //! A large number of the structures provided by `std::io` are for various
169 //! ways of iterating over I/O. For example, [`Lines`] is used to split over
174 //! use std::io::prelude::*;
175 //! use std::io::BufReader;
176 //! use std::fs::File;
178 //! fn main() -> io::Result<()> {
179 //! let f = File::open("foo.txt")?;
180 //! let reader = BufReader::new(f);
182 //! for line in reader.lines() {
183 //! println!("{}", line?);
191 //! There are a number of [functions][functions-list] that offer access to various
192 //! features. For example, we can use three of these functions to copy everything
193 //! from standard input to standard output:
198 //! fn main() -> io::Result<()> {
199 //! io::copy(&mut io::stdin(), &mut io::stdout())?;
204 //! [functions-list]: #functions-1
208 //! Last, but certainly not least, is [`io::Result`]. This type is used
209 //! as the return type of many `std::io` functions that can cause an error, and
210 //! can be returned from your own functions as well. Many of the examples in this
211 //! module use the [`?` operator]:
216 //! fn read_input() -> io::Result<()> {
217 //! let mut input = String::new();
219 //! io::stdin().read_line(&mut input)?;
221 //! println!("You typed: {}", input.trim());
227 //! The return type of `read_input()`, [`io::Result<()>`][`io::Result`], is a very
228 //! common type for functions which don't have a 'real' return value, but do want to
229 //! return errors if they happen. In this case, the only purpose of this function is
230 //! to read the line and print it, so we use `()`.
232 //! ## Platform-specific behavior
234 //! Many I/O functions throughout the standard library are documented to indicate
235 //! what various library or syscalls they are delegated to. This is done to help
236 //! applications both understand what's happening under the hood as well as investigate
237 //! any possibly unclear semantics. Note, however, that this is informative, not a binding
238 //! contract. The implementation of many of these functions are subject to change over
239 //! time and may call fewer or more syscalls/library functions.
241 //! [`File`]: crate::fs::File
242 //! [`TcpStream`]: crate::net::TcpStream
243 //! [`io::stdout`]: stdout
244 //! [`io::Result`]: self::Result
245 //! [`?` operator]: ../../book/appendix-02-operators.html
246 //! [`Result`]: crate::result::Result
247 //! [`.unwrap()`]: crate::result::Result::unwrap
249 #![stable(feature = "rust1", since = "1.0.0")]
255 use crate::convert::TryInto;
257 use crate::mem::replace;
258 use crate::ops::{Deref, DerefMut};
262 use crate::sys_common::memchr;
264 #[stable(feature = "bufwriter_into_parts", since = "1.56.0")]
265 pub use self::buffered::WriterPanicked;
266 #[unstable(feature = "internal_output_capture", issue = "none")]
267 #[doc(no_inline, hidden)]
268 pub use self::stdio::set_output_capture;
269 #[unstable(feature = "print_internals", issue = "none")]
270 pub use self::stdio::{_eprint, _print};
271 #[unstable(feature = "stdio_locked", issue = "86845")]
272 pub use self::stdio::{stderr_locked, stdin_locked, stdout_locked};
273 #[stable(feature = "rust1", since = "1.0.0")]
275 buffered::{BufReader, BufWriter, IntoInnerError, LineWriter},
278 error::{Error, ErrorKind, Result},
279 stdio::{stderr, stdin, stdout, Stderr, StderrLock, Stdin, StdinLock, Stdout, StdoutLock},
280 util::{empty, repeat, sink, Empty, Repeat, Sink},
283 #[unstable(feature = "read_buf", issue = "78485")]
284 pub use self::readbuf::ReadBuf;
296 const DEFAULT_BUF_SIZE: usize = crate::sys_common::io::DEFAULT_BUF_SIZE;
298 pub(crate) use stdio::cleanup;
301 buf: &'a mut Vec<u8>,
305 impl Drop for Guard<'_> {
308 self.buf.set_len(self.len);
313 // Several `read_to_string` and `read_line` methods in the standard library will
314 // append data into a `String` buffer, but we need to be pretty careful when
315 // doing this. The implementation will just call `.as_mut_vec()` and then
316 // delegate to a byte-oriented reading method, but we must ensure that when
317 // returning we never leave `buf` in a state such that it contains invalid UTF-8
320 // To this end, we use an RAII guard (to protect against panics) which updates
321 // the length of the string when it is dropped. This guard initially truncates
322 // the string to the prior length and only after we've validated that the
323 // new contents are valid UTF-8 do we allow it to set a longer length.
325 // The unsafety in this function is twofold:
327 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
329 // 2. We're passing a raw buffer to the function `f`, and it is expected that
330 // the function only *appends* bytes to the buffer. We'll get undefined
331 // behavior if existing bytes are overwritten to have non-UTF-8 data.
332 pub(crate) unsafe fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
334 F: FnOnce(&mut Vec<u8>) -> Result<usize>,
336 let mut g = Guard { len: buf.len(), buf: buf.as_mut_vec() };
338 if str::from_utf8(&g.buf[g.len..]).is_err() {
340 Err(Error::new_const(ErrorKind::InvalidData, &"stream did not contain valid UTF-8"))
348 // This uses an adaptive system to extend the vector when it fills. We want to
349 // avoid paying to allocate and zero a huge chunk of memory if the reader only
350 // has 4 bytes while still making large reads if the reader does have a ton
351 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
352 // time is 4,500 times (!) slower than a default reservation size of 32 if the
353 // reader has a very small amount of data to return.
354 pub(crate) fn default_read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
355 let start_len = buf.len();
356 let start_cap = buf.capacity();
358 let mut initialized = 0; // Extra initialized bytes from previous loop iteration
360 if buf.len() == buf.capacity() {
361 buf.reserve(32); // buf is full, need more space
364 let mut read_buf = ReadBuf::uninit(buf.spare_capacity_mut());
366 // SAFETY: These bytes were initialized but not filled in the previous loop
368 read_buf.assume_init(initialized);
371 match r.read_buf(&mut read_buf) {
373 Err(e) if e.kind() == ErrorKind::Interrupted => continue,
374 Err(e) => return Err(e),
377 if read_buf.filled_len() == 0 {
378 return Ok(buf.len() - start_len);
381 // store how much was initialized but not filled
382 initialized = read_buf.initialized_len() - read_buf.filled_len();
383 let new_len = read_buf.filled_len() + buf.len();
385 // SAFETY: ReadBuf's invariants mean this much memory is init
387 buf.set_len(new_len);
390 if buf.len() == buf.capacity() && buf.capacity() == start_cap {
391 // The buffer might be an exact fit. Let's read into a probe buffer
392 // and see if it returns `Ok(0)`. If so, we've avoided an
393 // unnecessary doubling of the capacity. But if not, append the
394 // probe buffer to the primary buffer and let its capacity grow.
395 let mut probe = [0u8; 32];
398 match r.read(&mut probe) {
399 Ok(0) => return Ok(buf.len() - start_len),
401 buf.extend_from_slice(&probe[..n]);
404 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
405 Err(e) => return Err(e),
412 pub(crate) fn default_read_to_string<R: Read + ?Sized>(
416 // Note that we do *not* call `r.read_to_end()` here. We are passing
417 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
418 // method to fill it up. An arbitrary implementation could overwrite the
419 // entire contents of the vector, not just append to it (which is what
420 // we are expecting).
422 // To prevent extraneously checking the UTF-8-ness of the entire buffer
423 // we pass it to our hardcoded `default_read_to_end` implementation which
424 // we know is guaranteed to only read data into the end of the buffer.
425 unsafe { append_to_string(buf, |b| default_read_to_end(r, b)) }
428 pub(crate) fn default_read_vectored<F>(read: F, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
430 F: FnOnce(&mut [u8]) -> Result<usize>,
432 let buf = bufs.iter_mut().find(|b| !b.is_empty()).map_or(&mut [][..], |b| &mut **b);
436 pub(crate) fn default_write_vectored<F>(write: F, bufs: &[IoSlice<'_>]) -> Result<usize>
438 F: FnOnce(&[u8]) -> Result<usize>,
440 let buf = bufs.iter().find(|b| !b.is_empty()).map_or(&[][..], |b| &**b);
444 pub(crate) fn default_read_exact<R: Read + ?Sized>(this: &mut R, mut buf: &mut [u8]) -> Result<()> {
445 while !buf.is_empty() {
446 match this.read(buf) {
452 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
453 Err(e) => return Err(e),
457 Err(Error::new_const(ErrorKind::UnexpectedEof, &"failed to fill whole buffer"))
463 pub(crate) fn default_read_buf<F>(read: F, buf: &mut ReadBuf<'_>) -> Result<()>
465 F: FnOnce(&mut [u8]) -> Result<usize>,
467 let n = read(buf.initialize_unfilled())?;
472 /// The `Read` trait allows for reading bytes from a source.
474 /// Implementors of the `Read` trait are called 'readers'.
476 /// Readers are defined by one required method, [`read()`]. Each call to [`read()`]
477 /// will attempt to pull bytes from this source into a provided buffer. A
478 /// number of other methods are implemented in terms of [`read()`], giving
479 /// implementors a number of ways to read bytes while only needing to implement
482 /// Readers are intended to be composable with one another. Many implementors
483 /// throughout [`std::io`] take and provide types which implement the `Read`
486 /// Please note that each call to [`read()`] may involve a system call, and
487 /// therefore, using something that implements [`BufRead`], such as
488 /// [`BufReader`], will be more efficient.
492 /// [`File`]s implement `Read`:
496 /// use std::io::prelude::*;
497 /// use std::fs::File;
499 /// fn main() -> io::Result<()> {
500 /// let mut f = File::open("foo.txt")?;
501 /// let mut buffer = [0; 10];
503 /// // read up to 10 bytes
504 /// f.read(&mut buffer)?;
506 /// let mut buffer = Vec::new();
507 /// // read the whole file
508 /// f.read_to_end(&mut buffer)?;
510 /// // read into a String, so that you don't need to do the conversion.
511 /// let mut buffer = String::new();
512 /// f.read_to_string(&mut buffer)?;
514 /// // and more! See the other methods for more details.
519 /// Read from [`&str`] because [`&[u8]`][prim@slice] implements `Read`:
523 /// use std::io::prelude::*;
525 /// fn main() -> io::Result<()> {
526 /// let mut b = "This string will be read".as_bytes();
527 /// let mut buffer = [0; 10];
529 /// // read up to 10 bytes
530 /// b.read(&mut buffer)?;
532 /// // etc... it works exactly as a File does!
537 /// [`read()`]: Read::read
538 /// [`&str`]: prim@str
539 /// [`std::io`]: self
540 /// [`File`]: crate::fs::File
541 #[stable(feature = "rust1", since = "1.0.0")]
542 #[doc(notable_trait)]
543 #[cfg_attr(not(test), rustc_diagnostic_item = "IoRead")]
545 /// Pull some bytes from this source into the specified buffer, returning
546 /// how many bytes were read.
548 /// This function does not provide any guarantees about whether it blocks
549 /// waiting for data, but if an object needs to block for a read and cannot,
550 /// it will typically signal this via an [`Err`] return value.
552 /// If the return value of this method is [`Ok(n)`], then implementations must
553 /// guarantee that `0 <= n <= buf.len()`. A nonzero `n` value indicates
554 /// that the buffer `buf` has been filled in with `n` bytes of data from this
555 /// source. If `n` is `0`, then it can indicate one of two scenarios:
557 /// 1. This reader has reached its "end of file" and will likely no longer
558 /// be able to produce bytes. Note that this does not mean that the
559 /// reader will *always* no longer be able to produce bytes. As an example,
560 /// on Linux, this method will call the `recv` syscall for a [`TcpStream`],
561 /// where returning zero indicates the connection was shut down correctly. While
562 /// for [`File`], it is possible to reach the end of file and get zero as result,
563 /// but if more data is appended to the file, future calls to `read` will return
565 /// 2. The buffer specified was 0 bytes in length.
567 /// It is not an error if the returned value `n` is smaller than the buffer size,
568 /// even when the reader is not at the end of the stream yet.
569 /// This may happen for example because fewer bytes are actually available right now
570 /// (e. g. being close to end-of-file) or because read() was interrupted by a signal.
572 /// As this trait is safe to implement, callers cannot rely on `n <= buf.len()` for safety.
573 /// Extra care needs to be taken when `unsafe` functions are used to access the read bytes.
574 /// Callers have to ensure that no unchecked out-of-bounds accesses are possible even if
577 /// No guarantees are provided about the contents of `buf` when this
578 /// function is called, implementations cannot rely on any property of the
579 /// contents of `buf` being true. It is recommended that *implementations*
580 /// only write data to `buf` instead of reading its contents.
582 /// Correspondingly, however, *callers* of this method must not assume any guarantees
583 /// about how the implementation uses `buf`. The trait is safe to implement,
584 /// so it is possible that the code that's supposed to write to the buffer might also read
585 /// from it. It is your responsibility to make sure that `buf` is initialized
586 /// before calling `read`. Calling `read` with an uninitialized `buf` (of the kind one
587 /// obtains via [`MaybeUninit<T>`]) is not safe, and can lead to undefined behavior.
589 /// [`MaybeUninit<T>`]: crate::mem::MaybeUninit
593 /// If this function encounters any form of I/O or other error, an error
594 /// variant will be returned. If an error is returned then it must be
595 /// guaranteed that no bytes were read.
597 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
598 /// operation should be retried if there is nothing else to do.
602 /// [`File`]s implement `Read`:
605 /// [`File`]: crate::fs::File
606 /// [`TcpStream`]: crate::net::TcpStream
610 /// use std::io::prelude::*;
611 /// use std::fs::File;
613 /// fn main() -> io::Result<()> {
614 /// let mut f = File::open("foo.txt")?;
615 /// let mut buffer = [0; 10];
617 /// // read up to 10 bytes
618 /// let n = f.read(&mut buffer[..])?;
620 /// println!("The bytes: {:?}", &buffer[..n]);
624 #[stable(feature = "rust1", since = "1.0.0")]
625 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
627 /// Like `read`, except that it reads into a slice of buffers.
629 /// Data is copied to fill each buffer in order, with the final buffer
630 /// written to possibly being only partially filled. This method must
631 /// behave equivalently to a single call to `read` with concatenated
634 /// The default implementation calls `read` with either the first nonempty
635 /// buffer provided, or an empty one if none exists.
636 #[stable(feature = "iovec", since = "1.36.0")]
637 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
638 default_read_vectored(|b| self.read(b), bufs)
641 /// Determines if this `Read`er has an efficient `read_vectored`
644 /// If a `Read`er does not override the default `read_vectored`
645 /// implementation, code using it may want to avoid the method all together
646 /// and coalesce writes into a single buffer for higher performance.
648 /// The default implementation returns `false`.
649 #[unstable(feature = "can_vector", issue = "69941")]
650 fn is_read_vectored(&self) -> bool {
654 /// Read all bytes until EOF in this source, placing them into `buf`.
656 /// All bytes read from this source will be appended to the specified buffer
657 /// `buf`. This function will continuously call [`read()`] to append more data to
658 /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of
659 /// non-[`ErrorKind::Interrupted`] kind.
661 /// If successful, this function will return the total number of bytes read.
665 /// If this function encounters an error of the kind
666 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
669 /// If any other read error is encountered then this function immediately
670 /// returns. Any bytes which have already been read will be appended to
675 /// [`File`]s implement `Read`:
677 /// [`read()`]: Read::read
679 /// [`File`]: crate::fs::File
683 /// use std::io::prelude::*;
684 /// use std::fs::File;
686 /// fn main() -> io::Result<()> {
687 /// let mut f = File::open("foo.txt")?;
688 /// let mut buffer = Vec::new();
690 /// // read the whole file
691 /// f.read_to_end(&mut buffer)?;
696 /// (See also the [`std::fs::read`] convenience function for reading from a
699 /// [`std::fs::read`]: crate::fs::read
700 #[stable(feature = "rust1", since = "1.0.0")]
701 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
702 default_read_to_end(self, buf)
705 /// Read all bytes until EOF in this source, appending them to `buf`.
707 /// If successful, this function returns the number of bytes which were read
708 /// and appended to `buf`.
712 /// If the data in this stream is *not* valid UTF-8 then an error is
713 /// returned and `buf` is unchanged.
715 /// See [`read_to_end`] for other error semantics.
717 /// [`read_to_end`]: Read::read_to_end
721 /// [`File`]s implement `Read`:
723 /// [`File`]: crate::fs::File
727 /// use std::io::prelude::*;
728 /// use std::fs::File;
730 /// fn main() -> io::Result<()> {
731 /// let mut f = File::open("foo.txt")?;
732 /// let mut buffer = String::new();
734 /// f.read_to_string(&mut buffer)?;
739 /// (See also the [`std::fs::read_to_string`] convenience function for
740 /// reading from a file.)
742 /// [`std::fs::read_to_string`]: crate::fs::read_to_string
743 #[stable(feature = "rust1", since = "1.0.0")]
744 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
745 default_read_to_string(self, buf)
748 /// Read the exact number of bytes required to fill `buf`.
750 /// This function reads as many bytes as necessary to completely fill the
751 /// specified buffer `buf`.
753 /// No guarantees are provided about the contents of `buf` when this
754 /// function is called, implementations cannot rely on any property of the
755 /// contents of `buf` being true. It is recommended that implementations
756 /// only write data to `buf` instead of reading its contents. The
757 /// documentation on [`read`] has a more detailed explanation on this
762 /// If this function encounters an error of the kind
763 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
766 /// If this function encounters an "end of file" before completely filling
767 /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
768 /// The contents of `buf` are unspecified in this case.
770 /// If any other read error is encountered then this function immediately
771 /// returns. The contents of `buf` are unspecified in this case.
773 /// If this function returns an error, it is unspecified how many bytes it
774 /// has read, but it will never read more than would be necessary to
775 /// completely fill the buffer.
779 /// [`File`]s implement `Read`:
781 /// [`read`]: Read::read
782 /// [`File`]: crate::fs::File
786 /// use std::io::prelude::*;
787 /// use std::fs::File;
789 /// fn main() -> io::Result<()> {
790 /// let mut f = File::open("foo.txt")?;
791 /// let mut buffer = [0; 10];
793 /// // read exactly 10 bytes
794 /// f.read_exact(&mut buffer)?;
798 #[stable(feature = "read_exact", since = "1.6.0")]
799 fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
800 default_read_exact(self, buf)
803 /// Pull some bytes from this source into the specified buffer.
805 /// This is equivalent to the [`read`](Read::read) method, except that it is passed a [`ReadBuf`] rather than `[u8]` to allow use
806 /// with uninitialized buffers. The new data will be appended to any existing contents of `buf`.
808 /// The default implementation delegates to `read`.
809 #[unstable(feature = "read_buf", issue = "78485")]
810 fn read_buf(&mut self, buf: &mut ReadBuf<'_>) -> Result<()> {
811 default_read_buf(|b| self.read(b), buf)
814 /// Read the exact number of bytes required to fill `buf`.
816 /// This is equivalent to the [`read_exact`](Read::read_exact) method, except that it is passed a [`ReadBuf`] rather than `[u8]` to
817 /// allow use with uninitialized buffers.
818 #[unstable(feature = "read_buf", issue = "78485")]
819 fn read_buf_exact(&mut self, buf: &mut ReadBuf<'_>) -> Result<()> {
820 while buf.remaining() > 0 {
821 let prev_filled = buf.filled().len();
822 match self.read_buf(buf) {
824 Err(e) if e.kind() == ErrorKind::Interrupted => continue,
825 Err(e) => return Err(e),
828 if buf.filled().len() == prev_filled {
829 return Err(Error::new(ErrorKind::UnexpectedEof, "failed to fill buffer"));
836 /// Creates a "by reference" adaptor for this instance of `Read`.
838 /// The returned adapter also implements `Read` and will simply borrow this
843 /// [`File`]s implement `Read`:
845 /// [`File`]: crate::fs::File
849 /// use std::io::Read;
850 /// use std::fs::File;
852 /// fn main() -> io::Result<()> {
853 /// let mut f = File::open("foo.txt")?;
854 /// let mut buffer = Vec::new();
855 /// let mut other_buffer = Vec::new();
858 /// let reference = f.by_ref();
860 /// // read at most 5 bytes
861 /// reference.take(5).read_to_end(&mut buffer)?;
863 /// } // drop our &mut reference so we can use f again
865 /// // original file still usable, read the rest
866 /// f.read_to_end(&mut other_buffer)?;
870 #[stable(feature = "rust1", since = "1.0.0")]
871 fn by_ref(&mut self) -> &mut Self
878 /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
880 /// The returned type implements [`Iterator`] where the [`Item`] is
881 /// <code>[Result]<[u8], [io::Error]></code>.
882 /// The yielded item is [`Ok`] if a byte was successfully read and [`Err`]
883 /// otherwise. EOF is mapped to returning [`None`] from this iterator.
887 /// [`File`]s implement `Read`:
889 /// [`Item`]: Iterator::Item
890 /// [`File`]: crate::fs::File "fs::File"
891 /// [Result]: crate::result::Result "Result"
892 /// [io::Error]: self::Error "io::Error"
896 /// use std::io::prelude::*;
897 /// use std::fs::File;
899 /// fn main() -> io::Result<()> {
900 /// let mut f = File::open("foo.txt")?;
902 /// for byte in f.bytes() {
903 /// println!("{}", byte.unwrap());
908 #[stable(feature = "rust1", since = "1.0.0")]
909 fn bytes(self) -> Bytes<Self>
913 Bytes { inner: self }
916 /// Creates an adapter which will chain this stream with another.
918 /// The returned `Read` instance will first read all bytes from this object
919 /// until EOF is encountered. Afterwards the output is equivalent to the
920 /// output of `next`.
924 /// [`File`]s implement `Read`:
926 /// [`File`]: crate::fs::File
930 /// use std::io::prelude::*;
931 /// use std::fs::File;
933 /// fn main() -> io::Result<()> {
934 /// let mut f1 = File::open("foo.txt")?;
935 /// let mut f2 = File::open("bar.txt")?;
937 /// let mut handle = f1.chain(f2);
938 /// let mut buffer = String::new();
940 /// // read the value into a String. We could use any Read method here,
941 /// // this is just one example.
942 /// handle.read_to_string(&mut buffer)?;
946 #[stable(feature = "rust1", since = "1.0.0")]
947 fn chain<R: Read>(self, next: R) -> Chain<Self, R>
951 Chain { first: self, second: next, done_first: false }
954 /// Creates an adapter which will read at most `limit` bytes from it.
956 /// This function returns a new instance of `Read` which will read at most
957 /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
958 /// read errors will not count towards the number of bytes read and future
959 /// calls to [`read()`] may succeed.
963 /// [`File`]s implement `Read`:
965 /// [`File`]: crate::fs::File
967 /// [`read()`]: Read::read
971 /// use std::io::prelude::*;
972 /// use std::fs::File;
974 /// fn main() -> io::Result<()> {
975 /// let mut f = File::open("foo.txt")?;
976 /// let mut buffer = [0; 5];
978 /// // read at most five bytes
979 /// let mut handle = f.take(5);
981 /// handle.read(&mut buffer)?;
985 #[stable(feature = "rust1", since = "1.0.0")]
986 fn take(self, limit: u64) -> Take<Self>
990 Take { inner: self, limit }
994 /// Read all bytes from a [reader][Read] into a new [`String`].
996 /// This is a convenience function for [`Read::read_to_string`]. Using this
997 /// function avoids having to create a variable first and provides more type
998 /// safety since you can only get the buffer out if there were no errors. (If you
999 /// use [`Read::read_to_string`] you have to remember to check whether the read
1000 /// succeeded because otherwise your buffer will be empty or only partially full.)
1004 /// The downside of this function's increased ease of use and type safety is
1005 /// that it gives you less control over performance. For example, you can't
1006 /// pre-allocate memory like you can using [`String::with_capacity`] and
1007 /// [`Read::read_to_string`]. Also, you can't re-use the buffer if an error
1008 /// occurs while reading.
1010 /// In many cases, this function's performance will be adequate and the ease of use
1011 /// and type safety tradeoffs will be worth it. However, there are cases where you
1012 /// need more control over performance, and in those cases you should definitely use
1013 /// [`Read::read_to_string`] directly.
1015 /// Note that in some special cases, such as when reading files, this function will
1016 /// pre-allocate memory based on the size of the input it is reading. In those
1017 /// cases, the performance should be as good as if you had used
1018 /// [`Read::read_to_string`] with a manually pre-allocated buffer.
1022 /// This function forces you to handle errors because the output (the `String`)
1023 /// is wrapped in a [`Result`]. See [`Read::read_to_string`] for the errors
1024 /// that can occur. If any error occurs, you will get an [`Err`], so you
1025 /// don't have to worry about your buffer being empty or partially full.
1030 /// #![feature(io_read_to_string)]
1033 /// fn main() -> io::Result<()> {
1034 /// let stdin = io::read_to_string(io::stdin())?;
1035 /// println!("Stdin was:");
1036 /// println!("{}", stdin);
1040 #[unstable(feature = "io_read_to_string", issue = "80218")]
1041 pub fn read_to_string<R: Read>(mut reader: R) -> Result<String> {
1042 let mut buf = String::new();
1043 reader.read_to_string(&mut buf)?;
1047 /// A buffer type used with `Read::read_vectored`.
1049 /// It is semantically a wrapper around an `&mut [u8]`, but is guaranteed to be
1050 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
1052 #[stable(feature = "iovec", since = "1.36.0")]
1053 #[repr(transparent)]
1054 pub struct IoSliceMut<'a>(sys::io::IoSliceMut<'a>);
1056 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1057 unsafe impl<'a> Send for IoSliceMut<'a> {}
1059 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1060 unsafe impl<'a> Sync for IoSliceMut<'a> {}
1062 #[stable(feature = "iovec", since = "1.36.0")]
1063 impl<'a> fmt::Debug for IoSliceMut<'a> {
1064 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1065 fmt::Debug::fmt(self.0.as_slice(), fmt)
1069 impl<'a> IoSliceMut<'a> {
1070 /// Creates a new `IoSliceMut` wrapping a byte slice.
1074 /// Panics on Windows if the slice is larger than 4GB.
1075 #[stable(feature = "iovec", since = "1.36.0")]
1077 pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> {
1078 IoSliceMut(sys::io::IoSliceMut::new(buf))
1081 /// Advance the internal cursor of the slice.
1083 /// Also see [`IoSliceMut::advance_slices`] to advance the cursors of
1084 /// multiple buffers.
1089 /// #![feature(io_slice_advance)]
1091 /// use std::io::IoSliceMut;
1092 /// use std::ops::Deref;
1094 /// let mut data = [1; 8];
1095 /// let mut buf = IoSliceMut::new(&mut data);
1097 /// // Mark 3 bytes as read.
1099 /// assert_eq!(buf.deref(), [1; 5].as_ref());
1101 #[unstable(feature = "io_slice_advance", issue = "62726")]
1103 pub fn advance(&mut self, n: usize) {
1107 /// Advance the internal cursor of the slices.
1111 /// Elements in the slice may be modified if the cursor is not advanced to
1112 /// the end of the slice. For example if we have a slice of buffers with 2
1113 /// `IoSliceMut`s, both of length 8, and we advance the cursor by 10 bytes
1114 /// the first `IoSliceMut` will be untouched however the second will be
1115 /// modified to remove the first 2 bytes (10 - 8).
1120 /// #![feature(io_slice_advance)]
1122 /// use std::io::IoSliceMut;
1123 /// use std::ops::Deref;
1125 /// let mut buf1 = [1; 8];
1126 /// let mut buf2 = [2; 16];
1127 /// let mut buf3 = [3; 8];
1128 /// let mut bufs = &mut [
1129 /// IoSliceMut::new(&mut buf1),
1130 /// IoSliceMut::new(&mut buf2),
1131 /// IoSliceMut::new(&mut buf3),
1134 /// // Mark 10 bytes as read.
1135 /// IoSliceMut::advance_slices(&mut bufs, 10);
1136 /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1137 /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1139 #[unstable(feature = "io_slice_advance", issue = "62726")]
1141 pub fn advance_slices(bufs: &mut &mut [IoSliceMut<'a>], n: usize) {
1142 // Number of buffers to remove.
1144 // Total length of all the to be removed buffers.
1145 let mut accumulated_len = 0;
1146 for buf in bufs.iter() {
1147 if accumulated_len + buf.len() > n {
1150 accumulated_len += buf.len();
1155 *bufs = &mut replace(bufs, &mut [])[remove..];
1156 if !bufs.is_empty() {
1157 bufs[0].advance(n - accumulated_len)
1162 #[stable(feature = "iovec", since = "1.36.0")]
1163 impl<'a> Deref for IoSliceMut<'a> {
1167 fn deref(&self) -> &[u8] {
1172 #[stable(feature = "iovec", since = "1.36.0")]
1173 impl<'a> DerefMut for IoSliceMut<'a> {
1175 fn deref_mut(&mut self) -> &mut [u8] {
1176 self.0.as_mut_slice()
1180 /// A buffer type used with `Write::write_vectored`.
1182 /// It is semantically a wrapper around a `&[u8]`, but is guaranteed to be
1183 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
1185 #[stable(feature = "iovec", since = "1.36.0")]
1186 #[derive(Copy, Clone)]
1187 #[repr(transparent)]
1188 pub struct IoSlice<'a>(sys::io::IoSlice<'a>);
1190 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1191 unsafe impl<'a> Send for IoSlice<'a> {}
1193 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1194 unsafe impl<'a> Sync for IoSlice<'a> {}
1196 #[stable(feature = "iovec", since = "1.36.0")]
1197 impl<'a> fmt::Debug for IoSlice<'a> {
1198 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1199 fmt::Debug::fmt(self.0.as_slice(), fmt)
1203 impl<'a> IoSlice<'a> {
1204 /// Creates a new `IoSlice` wrapping a byte slice.
1208 /// Panics on Windows if the slice is larger than 4GB.
1209 #[stable(feature = "iovec", since = "1.36.0")]
1212 pub fn new(buf: &'a [u8]) -> IoSlice<'a> {
1213 IoSlice(sys::io::IoSlice::new(buf))
1216 /// Advance the internal cursor of the slice.
1218 /// Also see [`IoSlice::advance_slices`] to advance the cursors of multiple
1224 /// #![feature(io_slice_advance)]
1226 /// use std::io::IoSlice;
1227 /// use std::ops::Deref;
1229 /// let mut data = [1; 8];
1230 /// let mut buf = IoSlice::new(&mut data);
1232 /// // Mark 3 bytes as read.
1234 /// assert_eq!(buf.deref(), [1; 5].as_ref());
1236 #[unstable(feature = "io_slice_advance", issue = "62726")]
1238 pub fn advance(&mut self, n: usize) {
1242 /// Advance the internal cursor of the slices.
1246 /// Elements in the slice may be modified if the cursor is not advanced to
1247 /// the end of the slice. For example if we have a slice of buffers with 2
1248 /// `IoSlice`s, both of length 8, and we advance the cursor by 10 bytes the
1249 /// first `IoSlice` will be untouched however the second will be modified to
1250 /// remove the first 2 bytes (10 - 8).
1255 /// #![feature(io_slice_advance)]
1257 /// use std::io::IoSlice;
1258 /// use std::ops::Deref;
1260 /// let buf1 = [1; 8];
1261 /// let buf2 = [2; 16];
1262 /// let buf3 = [3; 8];
1263 /// let mut bufs = &mut [
1264 /// IoSlice::new(&buf1),
1265 /// IoSlice::new(&buf2),
1266 /// IoSlice::new(&buf3),
1269 /// // Mark 10 bytes as written.
1270 /// IoSlice::advance_slices(&mut bufs, 10);
1271 /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1272 /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1273 #[unstable(feature = "io_slice_advance", issue = "62726")]
1275 pub fn advance_slices(bufs: &mut &mut [IoSlice<'a>], n: usize) {
1276 // Number of buffers to remove.
1278 // Total length of all the to be removed buffers.
1279 let mut accumulated_len = 0;
1280 for buf in bufs.iter() {
1281 if accumulated_len + buf.len() > n {
1284 accumulated_len += buf.len();
1289 *bufs = &mut replace(bufs, &mut [])[remove..];
1290 if !bufs.is_empty() {
1291 bufs[0].advance(n - accumulated_len)
1296 #[stable(feature = "iovec", since = "1.36.0")]
1297 impl<'a> Deref for IoSlice<'a> {
1301 fn deref(&self) -> &[u8] {
1306 /// A trait for objects which are byte-oriented sinks.
1308 /// Implementors of the `Write` trait are sometimes called 'writers'.
1310 /// Writers are defined by two required methods, [`write`] and [`flush`]:
1312 /// * The [`write`] method will attempt to write some data into the object,
1313 /// returning how many bytes were successfully written.
1315 /// * The [`flush`] method is useful for adapters and explicit buffers
1316 /// themselves for ensuring that all buffered data has been pushed out to the
1319 /// Writers are intended to be composable with one another. Many implementors
1320 /// throughout [`std::io`] take and provide types which implement the `Write`
1323 /// [`write`]: Write::write
1324 /// [`flush`]: Write::flush
1325 /// [`std::io`]: self
1330 /// use std::io::prelude::*;
1331 /// use std::fs::File;
1333 /// fn main() -> std::io::Result<()> {
1334 /// let data = b"some bytes";
1336 /// let mut pos = 0;
1337 /// let mut buffer = File::create("foo.txt")?;
1339 /// while pos < data.len() {
1340 /// let bytes_written = buffer.write(&data[pos..])?;
1341 /// pos += bytes_written;
1347 /// The trait also provides convenience methods like [`write_all`], which calls
1348 /// `write` in a loop until its entire input has been written.
1350 /// [`write_all`]: Write::write_all
1351 #[stable(feature = "rust1", since = "1.0.0")]
1352 #[doc(notable_trait)]
1353 #[cfg_attr(not(test), rustc_diagnostic_item = "IoWrite")]
1355 /// Write a buffer into this writer, returning how many bytes were written.
1357 /// This function will attempt to write the entire contents of `buf`, but
1358 /// the entire write might not succeed, or the write may also generate an
1359 /// error. A call to `write` represents *at most one* attempt to write to
1360 /// any wrapped object.
1362 /// Calls to `write` are not guaranteed to block waiting for data to be
1363 /// written, and a write which would otherwise block can be indicated through
1364 /// an [`Err`] variant.
1366 /// If the return value is [`Ok(n)`] then it must be guaranteed that
1367 /// `n <= buf.len()`. A return value of `0` typically means that the
1368 /// underlying object is no longer able to accept bytes and will likely not
1369 /// be able to in the future as well, or that the buffer provided is empty.
1373 /// Each call to `write` may generate an I/O error indicating that the
1374 /// operation could not be completed. If an error is returned then no bytes
1375 /// in the buffer were written to this writer.
1377 /// It is **not** considered an error if the entire buffer could not be
1378 /// written to this writer.
1380 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the
1381 /// write operation should be retried if there is nothing else to do.
1386 /// use std::io::prelude::*;
1387 /// use std::fs::File;
1389 /// fn main() -> std::io::Result<()> {
1390 /// let mut buffer = File::create("foo.txt")?;
1392 /// // Writes some prefix of the byte string, not necessarily all of it.
1393 /// buffer.write(b"some bytes")?;
1399 #[stable(feature = "rust1", since = "1.0.0")]
1400 fn write(&mut self, buf: &[u8]) -> Result<usize>;
1402 /// Like [`write`], except that it writes from a slice of buffers.
1404 /// Data is copied from each buffer in order, with the final buffer
1405 /// read from possibly being only partially consumed. This method must
1406 /// behave as a call to [`write`] with the buffers concatenated would.
1408 /// The default implementation calls [`write`] with either the first nonempty
1409 /// buffer provided, or an empty one if none exists.
1414 /// use std::io::IoSlice;
1415 /// use std::io::prelude::*;
1416 /// use std::fs::File;
1418 /// fn main() -> std::io::Result<()> {
1419 /// let mut data1 = [1; 8];
1420 /// let mut data2 = [15; 8];
1421 /// let io_slice1 = IoSlice::new(&mut data1);
1422 /// let io_slice2 = IoSlice::new(&mut data2);
1424 /// let mut buffer = File::create("foo.txt")?;
1426 /// // Writes some prefix of the byte string, not necessarily all of it.
1427 /// buffer.write_vectored(&[io_slice1, io_slice2])?;
1432 /// [`write`]: Write::write
1433 #[stable(feature = "iovec", since = "1.36.0")]
1434 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize> {
1435 default_write_vectored(|b| self.write(b), bufs)
1438 /// Determines if this `Write`r has an efficient [`write_vectored`]
1441 /// If a `Write`r does not override the default [`write_vectored`]
1442 /// implementation, code using it may want to avoid the method all together
1443 /// and coalesce writes into a single buffer for higher performance.
1445 /// The default implementation returns `false`.
1447 /// [`write_vectored`]: Write::write_vectored
1448 #[unstable(feature = "can_vector", issue = "69941")]
1449 fn is_write_vectored(&self) -> bool {
1453 /// Flush this output stream, ensuring that all intermediately buffered
1454 /// contents reach their destination.
1458 /// It is considered an error if not all bytes could be written due to
1459 /// I/O errors or EOF being reached.
1464 /// use std::io::prelude::*;
1465 /// use std::io::BufWriter;
1466 /// use std::fs::File;
1468 /// fn main() -> std::io::Result<()> {
1469 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
1471 /// buffer.write_all(b"some bytes")?;
1472 /// buffer.flush()?;
1476 #[stable(feature = "rust1", since = "1.0.0")]
1477 fn flush(&mut self) -> Result<()>;
1479 /// Attempts to write an entire buffer into this writer.
1481 /// This method will continuously call [`write`] until there is no more data
1482 /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is
1483 /// returned. This method will not return until the entire buffer has been
1484 /// successfully written or such an error occurs. The first error that is
1485 /// not of [`ErrorKind::Interrupted`] kind generated from this method will be
1488 /// If the buffer contains no data, this will never call [`write`].
1492 /// This function will return the first error of
1493 /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns.
1495 /// [`write`]: Write::write
1500 /// use std::io::prelude::*;
1501 /// use std::fs::File;
1503 /// fn main() -> std::io::Result<()> {
1504 /// let mut buffer = File::create("foo.txt")?;
1506 /// buffer.write_all(b"some bytes")?;
1510 #[stable(feature = "rust1", since = "1.0.0")]
1511 fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
1512 while !buf.is_empty() {
1513 match self.write(buf) {
1515 return Err(Error::new_const(
1516 ErrorKind::WriteZero,
1517 &"failed to write whole buffer",
1520 Ok(n) => buf = &buf[n..],
1521 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1522 Err(e) => return Err(e),
1528 /// Attempts to write multiple buffers into this writer.
1530 /// This method will continuously call [`write_vectored`] until there is no
1531 /// more data to be written or an error of non-[`ErrorKind::Interrupted`]
1532 /// kind is returned. This method will not return until all buffers have
1533 /// been successfully written or such an error occurs. The first error that
1534 /// is not of [`ErrorKind::Interrupted`] kind generated from this method
1535 /// will be returned.
1537 /// If the buffer contains no data, this will never call [`write_vectored`].
1541 /// Unlike [`write_vectored`], this takes a *mutable* reference to
1542 /// a slice of [`IoSlice`]s, not an immutable one. That's because we need to
1543 /// modify the slice to keep track of the bytes already written.
1545 /// Once this function returns, the contents of `bufs` are unspecified, as
1546 /// this depends on how many calls to [`write_vectored`] were necessary. It is
1547 /// best to understand this function as taking ownership of `bufs` and to
1548 /// not use `bufs` afterwards. The underlying buffers, to which the
1549 /// [`IoSlice`]s point (but not the [`IoSlice`]s themselves), are unchanged and
1552 /// [`write_vectored`]: Write::write_vectored
1557 /// #![feature(write_all_vectored)]
1558 /// # fn main() -> std::io::Result<()> {
1560 /// use std::io::{Write, IoSlice};
1562 /// let mut writer = Vec::new();
1563 /// let bufs = &mut [
1564 /// IoSlice::new(&[1]),
1565 /// IoSlice::new(&[2, 3]),
1566 /// IoSlice::new(&[4, 5, 6]),
1569 /// writer.write_all_vectored(bufs)?;
1570 /// // Note: the contents of `bufs` is now undefined, see the Notes section.
1572 /// assert_eq!(writer, &[1, 2, 3, 4, 5, 6]);
1575 #[unstable(feature = "write_all_vectored", issue = "70436")]
1576 fn write_all_vectored(&mut self, mut bufs: &mut [IoSlice<'_>]) -> Result<()> {
1577 // Guarantee that bufs is empty if it contains no data,
1578 // to avoid calling write_vectored if there is no data to be written.
1579 IoSlice::advance_slices(&mut bufs, 0);
1580 while !bufs.is_empty() {
1581 match self.write_vectored(bufs) {
1583 return Err(Error::new_const(
1584 ErrorKind::WriteZero,
1585 &"failed to write whole buffer",
1588 Ok(n) => IoSlice::advance_slices(&mut bufs, n),
1589 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1590 Err(e) => return Err(e),
1596 /// Writes a formatted string into this writer, returning any error
1599 /// This method is primarily used to interface with the
1600 /// [`format_args!()`] macro, and it is rare that this should
1601 /// explicitly be called. The [`write!()`] macro should be favored to
1602 /// invoke this method instead.
1604 /// This function internally uses the [`write_all`] method on
1605 /// this trait and hence will continuously write data so long as no errors
1606 /// are received. This also means that partial writes are not indicated in
1609 /// [`write_all`]: Write::write_all
1613 /// This function will return any I/O error reported while formatting.
1618 /// use std::io::prelude::*;
1619 /// use std::fs::File;
1621 /// fn main() -> std::io::Result<()> {
1622 /// let mut buffer = File::create("foo.txt")?;
1625 /// write!(buffer, "{:.*}", 2, 1.234567)?;
1626 /// // turns into this:
1627 /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1631 #[stable(feature = "rust1", since = "1.0.0")]
1632 fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> Result<()> {
1633 // Create a shim which translates a Write to a fmt::Write and saves
1634 // off I/O errors. instead of discarding them
1635 struct Adapter<'a, T: ?Sized + 'a> {
1640 impl<T: Write + ?Sized> fmt::Write for Adapter<'_, T> {
1641 fn write_str(&mut self, s: &str) -> fmt::Result {
1642 match self.inner.write_all(s.as_bytes()) {
1645 self.error = Err(e);
1652 let mut output = Adapter { inner: self, error: Ok(()) };
1653 match fmt::write(&mut output, fmt) {
1656 // check if the error came from the underlying `Write` or not
1657 if output.error.is_err() {
1660 Err(Error::new_const(ErrorKind::Uncategorized, &"formatter error"))
1666 /// Creates a "by reference" adapter for this instance of `Write`.
1668 /// The returned adapter also implements `Write` and will simply borrow this
1674 /// use std::io::Write;
1675 /// use std::fs::File;
1677 /// fn main() -> std::io::Result<()> {
1678 /// let mut buffer = File::create("foo.txt")?;
1680 /// let reference = buffer.by_ref();
1682 /// // we can use reference just like our original buffer
1683 /// reference.write_all(b"some bytes")?;
1687 #[stable(feature = "rust1", since = "1.0.0")]
1688 fn by_ref(&mut self) -> &mut Self
1696 /// The `Seek` trait provides a cursor which can be moved within a stream of
1699 /// The stream typically has a fixed size, allowing seeking relative to either
1700 /// end or the current offset.
1704 /// [`File`]s implement `Seek`:
1706 /// [`File`]: crate::fs::File
1710 /// use std::io::prelude::*;
1711 /// use std::fs::File;
1712 /// use std::io::SeekFrom;
1714 /// fn main() -> io::Result<()> {
1715 /// let mut f = File::open("foo.txt")?;
1717 /// // move the cursor 42 bytes from the start of the file
1718 /// f.seek(SeekFrom::Start(42))?;
1722 #[stable(feature = "rust1", since = "1.0.0")]
1724 /// Seek to an offset, in bytes, in a stream.
1726 /// A seek beyond the end of a stream is allowed, but behavior is defined
1727 /// by the implementation.
1729 /// If the seek operation completed successfully,
1730 /// this method returns the new position from the start of the stream.
1731 /// That position can be used later with [`SeekFrom::Start`].
1735 /// Seeking can fail, for example because it might involve flushing a buffer.
1737 /// Seeking to a negative offset is considered an error.
1738 #[stable(feature = "rust1", since = "1.0.0")]
1739 fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1741 /// Rewind to the beginning of a stream.
1743 /// This is a convenience method, equivalent to `seek(SeekFrom::Start(0))`.
1747 /// Rewinding can fail, for example because it might involve flushing a buffer.
1752 /// use std::io::{Read, Seek, Write};
1753 /// use std::fs::OpenOptions;
1755 /// let mut f = OpenOptions::new()
1759 /// .open("foo.txt").unwrap();
1761 /// let hello = "Hello!\n";
1762 /// write!(f, "{}", hello).unwrap();
1763 /// f.rewind().unwrap();
1765 /// let mut buf = String::new();
1766 /// f.read_to_string(&mut buf).unwrap();
1767 /// assert_eq!(&buf, hello);
1769 #[stable(feature = "seek_rewind", since = "1.55.0")]
1770 fn rewind(&mut self) -> Result<()> {
1771 self.seek(SeekFrom::Start(0))?;
1775 /// Returns the length of this stream (in bytes).
1777 /// This method is implemented using up to three seek operations. If this
1778 /// method returns successfully, the seek position is unchanged (i.e. the
1779 /// position before calling this method is the same as afterwards).
1780 /// However, if this method returns an error, the seek position is
1783 /// If you need to obtain the length of *many* streams and you don't care
1784 /// about the seek position afterwards, you can reduce the number of seek
1785 /// operations by simply calling `seek(SeekFrom::End(0))` and using its
1786 /// return value (it is also the stream length).
1788 /// Note that length of a stream can change over time (for example, when
1789 /// data is appended to a file). So calling this method multiple times does
1790 /// not necessarily return the same length each time.
1795 /// #![feature(seek_stream_len)]
1797 /// io::{self, Seek},
1801 /// fn main() -> io::Result<()> {
1802 /// let mut f = File::open("foo.txt")?;
1804 /// let len = f.stream_len()?;
1805 /// println!("The file is currently {} bytes long", len);
1809 #[unstable(feature = "seek_stream_len", issue = "59359")]
1810 fn stream_len(&mut self) -> Result<u64> {
1811 let old_pos = self.stream_position()?;
1812 let len = self.seek(SeekFrom::End(0))?;
1814 // Avoid seeking a third time when we were already at the end of the
1815 // stream. The branch is usually way cheaper than a seek operation.
1817 self.seek(SeekFrom::Start(old_pos))?;
1823 /// Returns the current seek position from the start of the stream.
1825 /// This is equivalent to `self.seek(SeekFrom::Current(0))`.
1831 /// io::{self, BufRead, BufReader, Seek},
1835 /// fn main() -> io::Result<()> {
1836 /// let mut f = BufReader::new(File::open("foo.txt")?);
1838 /// let before = f.stream_position()?;
1839 /// f.read_line(&mut String::new())?;
1840 /// let after = f.stream_position()?;
1842 /// println!("The first line was {} bytes long", after - before);
1846 #[stable(feature = "seek_convenience", since = "1.51.0")]
1847 fn stream_position(&mut self) -> Result<u64> {
1848 self.seek(SeekFrom::Current(0))
1852 /// Enumeration of possible methods to seek within an I/O object.
1854 /// It is used by the [`Seek`] trait.
1855 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1856 #[stable(feature = "rust1", since = "1.0.0")]
1858 /// Sets the offset to the provided number of bytes.
1859 #[stable(feature = "rust1", since = "1.0.0")]
1860 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1862 /// Sets the offset to the size of this object plus the specified number of
1865 /// It is possible to seek beyond the end of an object, but it's an error to
1866 /// seek before byte 0.
1867 #[stable(feature = "rust1", since = "1.0.0")]
1868 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1870 /// Sets the offset to the current position plus the specified number of
1873 /// It is possible to seek beyond the end of an object, but it's an error to
1874 /// seek before byte 0.
1875 #[stable(feature = "rust1", since = "1.0.0")]
1876 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1879 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>) -> Result<usize> {
1882 let (done, used) = {
1883 let available = match r.fill_buf() {
1885 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1886 Err(e) => return Err(e),
1888 match memchr::memchr(delim, available) {
1890 buf.extend_from_slice(&available[..=i]);
1894 buf.extend_from_slice(available);
1895 (false, available.len())
1901 if done || used == 0 {
1907 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1908 /// to perform extra ways of reading.
1910 /// For example, reading line-by-line is inefficient without using a buffer, so
1911 /// if you want to read by line, you'll need `BufRead`, which includes a
1912 /// [`read_line`] method as well as a [`lines`] iterator.
1916 /// A locked standard input implements `BufRead`:
1920 /// use std::io::prelude::*;
1922 /// let stdin = io::stdin();
1923 /// for line in stdin.lock().lines() {
1924 /// println!("{}", line.unwrap());
1928 /// If you have something that implements [`Read`], you can use the [`BufReader`
1929 /// type][`BufReader`] to turn it into a `BufRead`.
1931 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1932 /// [`BufReader`] to the rescue!
1934 /// [`File`]: crate::fs::File
1935 /// [`read_line`]: BufRead::read_line
1936 /// [`lines`]: BufRead::lines
1939 /// use std::io::{self, BufReader};
1940 /// use std::io::prelude::*;
1941 /// use std::fs::File;
1943 /// fn main() -> io::Result<()> {
1944 /// let f = File::open("foo.txt")?;
1945 /// let f = BufReader::new(f);
1947 /// for line in f.lines() {
1948 /// println!("{}", line.unwrap());
1954 #[stable(feature = "rust1", since = "1.0.0")]
1955 pub trait BufRead: Read {
1956 /// Returns the contents of the internal buffer, filling it with more data
1957 /// from the inner reader if it is empty.
1959 /// This function is a lower-level call. It needs to be paired with the
1960 /// [`consume`] method to function properly. When calling this
1961 /// method, none of the contents will be "read" in the sense that later
1962 /// calling `read` may return the same contents. As such, [`consume`] must
1963 /// be called with the number of bytes that are consumed from this buffer to
1964 /// ensure that the bytes are never returned twice.
1966 /// [`consume`]: BufRead::consume
1968 /// An empty buffer returned indicates that the stream has reached EOF.
1972 /// This function will return an I/O error if the underlying reader was
1973 /// read, but returned an error.
1977 /// A locked standard input implements `BufRead`:
1981 /// use std::io::prelude::*;
1983 /// let stdin = io::stdin();
1984 /// let mut stdin = stdin.lock();
1986 /// let buffer = stdin.fill_buf().unwrap();
1988 /// // work with buffer
1989 /// println!("{:?}", buffer);
1991 /// // ensure the bytes we worked with aren't returned again later
1992 /// let length = buffer.len();
1993 /// stdin.consume(length);
1995 #[stable(feature = "rust1", since = "1.0.0")]
1996 fn fill_buf(&mut self) -> Result<&[u8]>;
1998 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1999 /// so they should no longer be returned in calls to `read`.
2001 /// This function is a lower-level call. It needs to be paired with the
2002 /// [`fill_buf`] method to function properly. This function does
2003 /// not perform any I/O, it simply informs this object that some amount of
2004 /// its buffer, returned from [`fill_buf`], has been consumed and should
2005 /// no longer be returned. As such, this function may do odd things if
2006 /// [`fill_buf`] isn't called before calling it.
2008 /// The `amt` must be `<=` the number of bytes in the buffer returned by
2013 /// Since `consume()` is meant to be used with [`fill_buf`],
2014 /// that method's example includes an example of `consume()`.
2016 /// [`fill_buf`]: BufRead::fill_buf
2017 #[stable(feature = "rust1", since = "1.0.0")]
2018 fn consume(&mut self, amt: usize);
2020 /// Check if the underlying `Read` has any data left to be read.
2022 /// This function may fill the buffer to check for data,
2023 /// so this functions returns `Result<bool>`, not `bool`.
2025 /// Default implementation calls `fill_buf` and checks that
2026 /// returned slice is empty (which means that there is no data left,
2027 /// since EOF is reached).
2032 /// #![feature(buf_read_has_data_left)]
2034 /// use std::io::prelude::*;
2036 /// let stdin = io::stdin();
2037 /// let mut stdin = stdin.lock();
2039 /// while stdin.has_data_left().unwrap() {
2040 /// let mut line = String::new();
2041 /// stdin.read_line(&mut line).unwrap();
2042 /// // work with line
2043 /// println!("{:?}", line);
2046 #[unstable(feature = "buf_read_has_data_left", reason = "recently added", issue = "86423")]
2047 fn has_data_left(&mut self) -> Result<bool> {
2048 self.fill_buf().map(|b| !b.is_empty())
2051 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
2053 /// This function will read bytes from the underlying stream until the
2054 /// delimiter or EOF is found. Once found, all bytes up to, and including,
2055 /// the delimiter (if found) will be appended to `buf`.
2057 /// If successful, this function will return the total number of bytes read.
2059 /// This function is blocking and should be used carefully: it is possible for
2060 /// an attacker to continuously send bytes without ever sending the delimiter
2065 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
2066 /// will otherwise return any errors returned by [`fill_buf`].
2068 /// If an I/O error is encountered then all bytes read so far will be
2069 /// present in `buf` and its length will have been adjusted appropriately.
2071 /// [`fill_buf`]: BufRead::fill_buf
2075 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2076 /// this example, we use [`Cursor`] to read all the bytes in a byte slice
2077 /// in hyphen delimited segments:
2080 /// use std::io::{self, BufRead};
2082 /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
2083 /// let mut buf = vec![];
2085 /// // cursor is at 'l'
2086 /// let num_bytes = cursor.read_until(b'-', &mut buf)
2087 /// .expect("reading from cursor won't fail");
2088 /// assert_eq!(num_bytes, 6);
2089 /// assert_eq!(buf, b"lorem-");
2092 /// // cursor is at 'i'
2093 /// let num_bytes = cursor.read_until(b'-', &mut buf)
2094 /// .expect("reading from cursor won't fail");
2095 /// assert_eq!(num_bytes, 5);
2096 /// assert_eq!(buf, b"ipsum");
2099 /// // cursor is at EOF
2100 /// let num_bytes = cursor.read_until(b'-', &mut buf)
2101 /// .expect("reading from cursor won't fail");
2102 /// assert_eq!(num_bytes, 0);
2103 /// assert_eq!(buf, b"");
2105 #[stable(feature = "rust1", since = "1.0.0")]
2106 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
2107 read_until(self, byte, buf)
2110 /// Read all bytes until a newline (the `0xA` byte) is reached, and append
2111 /// them to the provided buffer.
2113 /// This function will read bytes from the underlying stream until the
2114 /// newline delimiter (the `0xA` byte) or EOF is found. Once found, all bytes
2115 /// up to, and including, the delimiter (if found) will be appended to
2118 /// If successful, this function will return the total number of bytes read.
2120 /// If this function returns [`Ok(0)`], the stream has reached EOF.
2122 /// This function is blocking and should be used carefully: it is possible for
2123 /// an attacker to continuously send bytes without ever sending a newline
2130 /// This function has the same error semantics as [`read_until`] and will
2131 /// also return an error if the read bytes are not valid UTF-8. If an I/O
2132 /// error is encountered then `buf` may contain some bytes already read in
2133 /// the event that all data read so far was valid UTF-8.
2135 /// [`read_until`]: BufRead::read_until
2139 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2140 /// this example, we use [`Cursor`] to read all the lines in a byte slice:
2143 /// use std::io::{self, BufRead};
2145 /// let mut cursor = io::Cursor::new(b"foo\nbar");
2146 /// let mut buf = String::new();
2148 /// // cursor is at 'f'
2149 /// let num_bytes = cursor.read_line(&mut buf)
2150 /// .expect("reading from cursor won't fail");
2151 /// assert_eq!(num_bytes, 4);
2152 /// assert_eq!(buf, "foo\n");
2155 /// // cursor is at 'b'
2156 /// let num_bytes = cursor.read_line(&mut buf)
2157 /// .expect("reading from cursor won't fail");
2158 /// assert_eq!(num_bytes, 3);
2159 /// assert_eq!(buf, "bar");
2162 /// // cursor is at EOF
2163 /// let num_bytes = cursor.read_line(&mut buf)
2164 /// .expect("reading from cursor won't fail");
2165 /// assert_eq!(num_bytes, 0);
2166 /// assert_eq!(buf, "");
2168 #[stable(feature = "rust1", since = "1.0.0")]
2169 fn read_line(&mut self, buf: &mut String) -> Result<usize> {
2170 // Note that we are not calling the `.read_until` method here, but
2171 // rather our hardcoded implementation. For more details as to why, see
2172 // the comments in `read_to_end`.
2173 unsafe { append_to_string(buf, |b| read_until(self, b'\n', b)) }
2176 /// Returns an iterator over the contents of this reader split on the byte
2179 /// The iterator returned from this function will return instances of
2180 /// <code>[io::Result]<[Vec]\<u8>></code>. Each vector returned will *not* have
2181 /// the delimiter byte at the end.
2183 /// This function will yield errors whenever [`read_until`] would have
2184 /// also yielded an error.
2186 /// [io::Result]: self::Result "io::Result"
2187 /// [`read_until`]: BufRead::read_until
2191 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2192 /// this example, we use [`Cursor`] to iterate over all hyphen delimited
2193 /// segments in a byte slice
2196 /// use std::io::{self, BufRead};
2198 /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
2200 /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
2201 /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
2202 /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
2203 /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
2204 /// assert_eq!(split_iter.next(), None);
2206 #[stable(feature = "rust1", since = "1.0.0")]
2207 fn split(self, byte: u8) -> Split<Self>
2211 Split { buf: self, delim: byte }
2214 /// Returns an iterator over the lines of this reader.
2216 /// The iterator returned from this function will yield instances of
2217 /// <code>[io::Result]<[String]></code>. Each string returned will *not* have a newline
2218 /// byte (the `0xA` byte) or `CRLF` (`0xD`, `0xA` bytes) at the end.
2220 /// [io::Result]: self::Result "io::Result"
2224 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2225 /// this example, we use [`Cursor`] to iterate over all the lines in a byte
2229 /// use std::io::{self, BufRead};
2231 /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
2233 /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
2234 /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
2235 /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
2236 /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
2237 /// assert_eq!(lines_iter.next(), None);
2242 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
2243 #[stable(feature = "rust1", since = "1.0.0")]
2244 fn lines(self) -> Lines<Self>
2252 /// Adapter to chain together two readers.
2254 /// This struct is generally created by calling [`chain`] on a reader.
2255 /// Please see the documentation of [`chain`] for more details.
2257 /// [`chain`]: Read::chain
2258 #[stable(feature = "rust1", since = "1.0.0")]
2260 pub struct Chain<T, U> {
2266 impl<T, U> Chain<T, U> {
2267 /// Consumes the `Chain`, returning the wrapped readers.
2273 /// use std::io::prelude::*;
2274 /// use std::fs::File;
2276 /// fn main() -> io::Result<()> {
2277 /// let mut foo_file = File::open("foo.txt")?;
2278 /// let mut bar_file = File::open("bar.txt")?;
2280 /// let chain = foo_file.chain(bar_file);
2281 /// let (foo_file, bar_file) = chain.into_inner();
2285 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2286 pub fn into_inner(self) -> (T, U) {
2287 (self.first, self.second)
2290 /// Gets references to the underlying readers in this `Chain`.
2296 /// use std::io::prelude::*;
2297 /// use std::fs::File;
2299 /// fn main() -> io::Result<()> {
2300 /// let mut foo_file = File::open("foo.txt")?;
2301 /// let mut bar_file = File::open("bar.txt")?;
2303 /// let chain = foo_file.chain(bar_file);
2304 /// let (foo_file, bar_file) = chain.get_ref();
2308 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2309 pub fn get_ref(&self) -> (&T, &U) {
2310 (&self.first, &self.second)
2313 /// Gets mutable references to the underlying readers in this `Chain`.
2315 /// Care should be taken to avoid modifying the internal I/O state of the
2316 /// underlying readers as doing so may corrupt the internal state of this
2323 /// use std::io::prelude::*;
2324 /// use std::fs::File;
2326 /// fn main() -> io::Result<()> {
2327 /// let mut foo_file = File::open("foo.txt")?;
2328 /// let mut bar_file = File::open("bar.txt")?;
2330 /// let mut chain = foo_file.chain(bar_file);
2331 /// let (foo_file, bar_file) = chain.get_mut();
2335 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2336 pub fn get_mut(&mut self) -> (&mut T, &mut U) {
2337 (&mut self.first, &mut self.second)
2341 #[stable(feature = "rust1", since = "1.0.0")]
2342 impl<T: Read, U: Read> Read for Chain<T, U> {
2343 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2344 if !self.done_first {
2345 match self.first.read(buf)? {
2346 0 if !buf.is_empty() => self.done_first = true,
2350 self.second.read(buf)
2353 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
2354 if !self.done_first {
2355 match self.first.read_vectored(bufs)? {
2356 0 if bufs.iter().any(|b| !b.is_empty()) => self.done_first = true,
2360 self.second.read_vectored(bufs)
2364 #[stable(feature = "chain_bufread", since = "1.9.0")]
2365 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
2366 fn fill_buf(&mut self) -> Result<&[u8]> {
2367 if !self.done_first {
2368 match self.first.fill_buf()? {
2369 buf if buf.is_empty() => {
2370 self.done_first = true;
2372 buf => return Ok(buf),
2375 self.second.fill_buf()
2378 fn consume(&mut self, amt: usize) {
2379 if !self.done_first { self.first.consume(amt) } else { self.second.consume(amt) }
2383 impl<T, U> SizeHint for Chain<T, U> {
2385 fn lower_bound(&self) -> usize {
2386 SizeHint::lower_bound(&self.first) + SizeHint::lower_bound(&self.second)
2390 fn upper_bound(&self) -> Option<usize> {
2391 match (SizeHint::upper_bound(&self.first), SizeHint::upper_bound(&self.second)) {
2392 (Some(first), Some(second)) => first.checked_add(second),
2398 /// Reader adapter which limits the bytes read from an underlying reader.
2400 /// This struct is generally created by calling [`take`] on a reader.
2401 /// Please see the documentation of [`take`] for more details.
2403 /// [`take`]: Read::take
2404 #[stable(feature = "rust1", since = "1.0.0")]
2406 pub struct Take<T> {
2412 /// Returns the number of bytes that can be read before this instance will
2417 /// This instance may reach `EOF` after reading fewer bytes than indicated by
2418 /// this method if the underlying [`Read`] instance reaches EOF.
2424 /// use std::io::prelude::*;
2425 /// use std::fs::File;
2427 /// fn main() -> io::Result<()> {
2428 /// let f = File::open("foo.txt")?;
2430 /// // read at most five bytes
2431 /// let handle = f.take(5);
2433 /// println!("limit: {}", handle.limit());
2437 #[stable(feature = "rust1", since = "1.0.0")]
2438 pub fn limit(&self) -> u64 {
2442 /// Sets the number of bytes that can be read before this instance will
2443 /// return EOF. This is the same as constructing a new `Take` instance, so
2444 /// the amount of bytes read and the previous limit value don't matter when
2445 /// calling this method.
2451 /// use std::io::prelude::*;
2452 /// use std::fs::File;
2454 /// fn main() -> io::Result<()> {
2455 /// let f = File::open("foo.txt")?;
2457 /// // read at most five bytes
2458 /// let mut handle = f.take(5);
2459 /// handle.set_limit(10);
2461 /// assert_eq!(handle.limit(), 10);
2465 #[stable(feature = "take_set_limit", since = "1.27.0")]
2466 pub fn set_limit(&mut self, limit: u64) {
2470 /// Consumes the `Take`, returning the wrapped reader.
2476 /// use std::io::prelude::*;
2477 /// use std::fs::File;
2479 /// fn main() -> io::Result<()> {
2480 /// let mut file = File::open("foo.txt")?;
2482 /// let mut buffer = [0; 5];
2483 /// let mut handle = file.take(5);
2484 /// handle.read(&mut buffer)?;
2486 /// let file = handle.into_inner();
2490 #[stable(feature = "io_take_into_inner", since = "1.15.0")]
2491 pub fn into_inner(self) -> T {
2495 /// Gets a reference to the underlying reader.
2501 /// use std::io::prelude::*;
2502 /// use std::fs::File;
2504 /// fn main() -> io::Result<()> {
2505 /// let mut file = File::open("foo.txt")?;
2507 /// let mut buffer = [0; 5];
2508 /// let mut handle = file.take(5);
2509 /// handle.read(&mut buffer)?;
2511 /// let file = handle.get_ref();
2515 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2516 pub fn get_ref(&self) -> &T {
2520 /// Gets a mutable reference to the underlying reader.
2522 /// Care should be taken to avoid modifying the internal I/O state of the
2523 /// underlying reader as doing so may corrupt the internal limit of this
2530 /// use std::io::prelude::*;
2531 /// use std::fs::File;
2533 /// fn main() -> io::Result<()> {
2534 /// let mut file = File::open("foo.txt")?;
2536 /// let mut buffer = [0; 5];
2537 /// let mut handle = file.take(5);
2538 /// handle.read(&mut buffer)?;
2540 /// let file = handle.get_mut();
2544 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2545 pub fn get_mut(&mut self) -> &mut T {
2550 #[stable(feature = "rust1", since = "1.0.0")]
2551 impl<T: Read> Read for Take<T> {
2552 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2553 // Don't call into inner reader at all at EOF because it may still block
2554 if self.limit == 0 {
2558 let max = cmp::min(buf.len() as u64, self.limit) as usize;
2559 let n = self.inner.read(&mut buf[..max])?;
2560 self.limit -= n as u64;
2564 fn read_buf(&mut self, buf: &mut ReadBuf<'_>) -> Result<()> {
2565 // Don't call into inner reader at all at EOF because it may still block
2566 if self.limit == 0 {
2570 let prev_filled = buf.filled_len();
2572 if self.limit <= buf.remaining() as u64 {
2573 // if we just use an as cast to convert, limit may wrap around on a 32 bit target
2574 let limit = cmp::min(self.limit, usize::MAX as u64) as usize;
2576 let extra_init = cmp::min(limit as usize, buf.initialized_len() - buf.filled_len());
2578 // SAFETY: no uninit data is written to ibuf
2579 let ibuf = unsafe { &mut buf.unfilled_mut()[..limit] };
2581 let mut sliced_buf = ReadBuf::uninit(ibuf);
2583 // SAFETY: extra_init bytes of ibuf are known to be initialized
2585 sliced_buf.assume_init(extra_init);
2588 self.inner.read_buf(&mut sliced_buf)?;
2590 let new_init = sliced_buf.initialized_len();
2591 let filled = sliced_buf.filled_len();
2593 // sliced_buf / ibuf must drop here
2595 // SAFETY: new_init bytes of buf's unfilled buffer have been initialized
2597 buf.assume_init(new_init);
2600 buf.add_filled(filled);
2602 self.limit -= filled as u64;
2604 self.inner.read_buf(buf)?;
2607 self.limit -= buf.filled_len().saturating_sub(prev_filled) as u64;
2614 #[stable(feature = "rust1", since = "1.0.0")]
2615 impl<T: BufRead> BufRead for Take<T> {
2616 fn fill_buf(&mut self) -> Result<&[u8]> {
2617 // Don't call into inner reader at all at EOF because it may still block
2618 if self.limit == 0 {
2622 let buf = self.inner.fill_buf()?;
2623 let cap = cmp::min(buf.len() as u64, self.limit) as usize;
2627 fn consume(&mut self, amt: usize) {
2628 // Don't let callers reset the limit by passing an overlarge value
2629 let amt = cmp::min(amt as u64, self.limit) as usize;
2630 self.limit -= amt as u64;
2631 self.inner.consume(amt);
2635 impl<T> SizeHint for Take<T> {
2637 fn lower_bound(&self) -> usize {
2638 cmp::min(SizeHint::lower_bound(&self.inner) as u64, self.limit) as usize
2642 fn upper_bound(&self) -> Option<usize> {
2643 match SizeHint::upper_bound(&self.inner) {
2644 Some(upper_bound) => Some(cmp::min(upper_bound as u64, self.limit) as usize),
2645 None => self.limit.try_into().ok(),
2650 /// An iterator over `u8` values of a reader.
2652 /// This struct is generally created by calling [`bytes`] on a reader.
2653 /// Please see the documentation of [`bytes`] for more details.
2655 /// [`bytes`]: Read::bytes
2656 #[stable(feature = "rust1", since = "1.0.0")]
2658 pub struct Bytes<R> {
2662 #[stable(feature = "rust1", since = "1.0.0")]
2663 impl<R: Read> Iterator for Bytes<R> {
2664 type Item = Result<u8>;
2666 fn next(&mut self) -> Option<Result<u8>> {
2669 return match self.inner.read(slice::from_mut(&mut byte)) {
2671 Ok(..) => Some(Ok(byte)),
2672 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
2673 Err(e) => Some(Err(e)),
2678 fn size_hint(&self) -> (usize, Option<usize>) {
2679 SizeHint::size_hint(&self.inner)
2684 fn lower_bound(&self) -> usize;
2686 fn upper_bound(&self) -> Option<usize>;
2688 fn size_hint(&self) -> (usize, Option<usize>) {
2689 (self.lower_bound(), self.upper_bound())
2693 impl<T> SizeHint for T {
2695 default fn lower_bound(&self) -> usize {
2700 default fn upper_bound(&self) -> Option<usize> {
2705 impl<T> SizeHint for &mut T {
2707 fn lower_bound(&self) -> usize {
2708 SizeHint::lower_bound(*self)
2712 fn upper_bound(&self) -> Option<usize> {
2713 SizeHint::upper_bound(*self)
2717 impl<T> SizeHint for Box<T> {
2719 fn lower_bound(&self) -> usize {
2720 SizeHint::lower_bound(&**self)
2724 fn upper_bound(&self) -> Option<usize> {
2725 SizeHint::upper_bound(&**self)
2729 impl SizeHint for &[u8] {
2731 fn lower_bound(&self) -> usize {
2736 fn upper_bound(&self) -> Option<usize> {
2741 /// An iterator over the contents of an instance of `BufRead` split on a
2742 /// particular byte.
2744 /// This struct is generally created by calling [`split`] on a `BufRead`.
2745 /// Please see the documentation of [`split`] for more details.
2747 /// [`split`]: BufRead::split
2748 #[stable(feature = "rust1", since = "1.0.0")]
2750 pub struct Split<B> {
2755 #[stable(feature = "rust1", since = "1.0.0")]
2756 impl<B: BufRead> Iterator for Split<B> {
2757 type Item = Result<Vec<u8>>;
2759 fn next(&mut self) -> Option<Result<Vec<u8>>> {
2760 let mut buf = Vec::new();
2761 match self.buf.read_until(self.delim, &mut buf) {
2764 if buf[buf.len() - 1] == self.delim {
2769 Err(e) => Some(Err(e)),
2774 /// An iterator over the lines of an instance of `BufRead`.
2776 /// This struct is generally created by calling [`lines`] on a `BufRead`.
2777 /// Please see the documentation of [`lines`] for more details.
2779 /// [`lines`]: BufRead::lines
2780 #[stable(feature = "rust1", since = "1.0.0")]
2782 pub struct Lines<B> {
2786 #[stable(feature = "rust1", since = "1.0.0")]
2787 impl<B: BufRead> Iterator for Lines<B> {
2788 type Item = Result<String>;
2790 fn next(&mut self) -> Option<Result<String>> {
2791 let mut buf = String::new();
2792 match self.buf.read_line(&mut buf) {
2795 if buf.ends_with('\n') {
2797 if buf.ends_with('\r') {
2803 Err(e) => Some(Err(e)),