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")]
256 use crate::mem::replace;
257 use crate::ops::{Deref, DerefMut};
261 use crate::sys_common::memchr;
263 #[stable(feature = "bufwriter_into_parts", since = "1.56.0")]
264 pub use self::buffered::WriterPanicked;
265 pub(crate) use self::stdio::attempt_print_to_stderr;
266 #[unstable(feature = "internal_output_capture", issue = "none")]
267 #[doc(no_inline, hidden)]
268 pub use self::stdio::set_output_capture;
269 #[unstable(feature = "is_terminal", issue = "98070")]
270 pub use self::stdio::IsTerminal;
271 #[unstable(feature = "print_internals", issue = "none")]
272 pub use self::stdio::{_eprint, _print};
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::{BorrowedBuf, BorrowedCursor};
285 pub(crate) use error::const_io_error;
297 const DEFAULT_BUF_SIZE: usize = crate::sys_common::io::DEFAULT_BUF_SIZE;
299 pub(crate) use stdio::cleanup;
302 buf: &'a mut Vec<u8>,
306 impl Drop for Guard<'_> {
309 self.buf.set_len(self.len);
314 // Several `read_to_string` and `read_line` methods in the standard library will
315 // append data into a `String` buffer, but we need to be pretty careful when
316 // doing this. The implementation will just call `.as_mut_vec()` and then
317 // delegate to a byte-oriented reading method, but we must ensure that when
318 // returning we never leave `buf` in a state such that it contains invalid UTF-8
321 // To this end, we use an RAII guard (to protect against panics) which updates
322 // the length of the string when it is dropped. This guard initially truncates
323 // the string to the prior length and only after we've validated that the
324 // new contents are valid UTF-8 do we allow it to set a longer length.
326 // The unsafety in this function is twofold:
328 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
330 // 2. We're passing a raw buffer to the function `f`, and it is expected that
331 // the function only *appends* bytes to the buffer. We'll get undefined
332 // behavior if existing bytes are overwritten to have non-UTF-8 data.
333 pub(crate) unsafe fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
335 F: FnOnce(&mut Vec<u8>) -> Result<usize>,
337 let mut g = Guard { len: buf.len(), buf: buf.as_mut_vec() };
339 if str::from_utf8(&g.buf[g.len..]).is_err() {
341 Err(error::const_io_error!(
342 ErrorKind::InvalidData,
343 "stream did not contain valid UTF-8"
352 // This uses an adaptive system to extend the vector when it fills. We want to
353 // avoid paying to allocate and zero a huge chunk of memory if the reader only
354 // has 4 bytes while still making large reads if the reader does have a ton
355 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
356 // time is 4,500 times (!) slower than a default reservation size of 32 if the
357 // reader has a very small amount of data to return.
358 pub(crate) fn default_read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
359 let start_len = buf.len();
360 let start_cap = buf.capacity();
362 let mut initialized = 0; // Extra initialized bytes from previous loop iteration
364 if buf.len() == buf.capacity() {
365 buf.reserve(32); // buf is full, need more space
368 let mut read_buf: BorrowedBuf<'_> = buf.spare_capacity_mut().into();
370 // SAFETY: These bytes were initialized but not filled in the previous loop
372 read_buf.set_init(initialized);
375 let mut cursor = read_buf.unfilled();
376 match r.read_buf(cursor.reborrow()) {
378 Err(e) if e.kind() == ErrorKind::Interrupted => continue,
379 Err(e) => return Err(e),
382 if cursor.written() == 0 {
383 return Ok(buf.len() - start_len);
386 // store how much was initialized but not filled
387 initialized = cursor.init_ref().len();
389 // SAFETY: BorrowedBuf's invariants mean this much memory is initialized.
391 let new_len = read_buf.filled().len() + buf.len();
392 buf.set_len(new_len);
395 if buf.len() == buf.capacity() && buf.capacity() == start_cap {
396 // The buffer might be an exact fit. Let's read into a probe buffer
397 // and see if it returns `Ok(0)`. If so, we've avoided an
398 // unnecessary doubling of the capacity. But if not, append the
399 // probe buffer to the primary buffer and let its capacity grow.
400 let mut probe = [0u8; 32];
403 match r.read(&mut probe) {
404 Ok(0) => return Ok(buf.len() - start_len),
406 buf.extend_from_slice(&probe[..n]);
409 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
410 Err(e) => return Err(e),
417 pub(crate) fn default_read_to_string<R: Read + ?Sized>(
421 // Note that we do *not* call `r.read_to_end()` here. We are passing
422 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
423 // method to fill it up. An arbitrary implementation could overwrite the
424 // entire contents of the vector, not just append to it (which is what
425 // we are expecting).
427 // To prevent extraneously checking the UTF-8-ness of the entire buffer
428 // we pass it to our hardcoded `default_read_to_end` implementation which
429 // we know is guaranteed to only read data into the end of the buffer.
430 unsafe { append_to_string(buf, |b| default_read_to_end(r, b)) }
433 pub(crate) fn default_read_vectored<F>(read: F, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
435 F: FnOnce(&mut [u8]) -> Result<usize>,
437 let buf = bufs.iter_mut().find(|b| !b.is_empty()).map_or(&mut [][..], |b| &mut **b);
441 pub(crate) fn default_write_vectored<F>(write: F, bufs: &[IoSlice<'_>]) -> Result<usize>
443 F: FnOnce(&[u8]) -> Result<usize>,
445 let buf = bufs.iter().find(|b| !b.is_empty()).map_or(&[][..], |b| &**b);
449 pub(crate) fn default_read_exact<R: Read + ?Sized>(this: &mut R, mut buf: &mut [u8]) -> Result<()> {
450 while !buf.is_empty() {
451 match this.read(buf) {
457 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
458 Err(e) => return Err(e),
462 Err(error::const_io_error!(ErrorKind::UnexpectedEof, "failed to fill whole buffer"))
468 pub(crate) fn default_read_buf<F>(read: F, mut cursor: BorrowedCursor<'_>) -> Result<()>
470 F: FnOnce(&mut [u8]) -> Result<usize>,
472 let n = read(cursor.ensure_init().init_mut())?;
474 // SAFETY: we initialised using `ensure_init` so there is no uninit data to advance to.
480 /// The `Read` trait allows for reading bytes from a source.
482 /// Implementors of the `Read` trait are called 'readers'.
484 /// Readers are defined by one required method, [`read()`]. Each call to [`read()`]
485 /// will attempt to pull bytes from this source into a provided buffer. A
486 /// number of other methods are implemented in terms of [`read()`], giving
487 /// implementors a number of ways to read bytes while only needing to implement
490 /// Readers are intended to be composable with one another. Many implementors
491 /// throughout [`std::io`] take and provide types which implement the `Read`
494 /// Please note that each call to [`read()`] may involve a system call, and
495 /// therefore, using something that implements [`BufRead`], such as
496 /// [`BufReader`], will be more efficient.
500 /// [`File`]s implement `Read`:
504 /// use std::io::prelude::*;
505 /// use std::fs::File;
507 /// fn main() -> io::Result<()> {
508 /// let mut f = File::open("foo.txt")?;
509 /// let mut buffer = [0; 10];
511 /// // read up to 10 bytes
512 /// f.read(&mut buffer)?;
514 /// let mut buffer = Vec::new();
515 /// // read the whole file
516 /// f.read_to_end(&mut buffer)?;
518 /// // read into a String, so that you don't need to do the conversion.
519 /// let mut buffer = String::new();
520 /// f.read_to_string(&mut buffer)?;
522 /// // and more! See the other methods for more details.
527 /// Read from [`&str`] because [`&[u8]`][prim@slice] implements `Read`:
531 /// use std::io::prelude::*;
533 /// fn main() -> io::Result<()> {
534 /// let mut b = "This string will be read".as_bytes();
535 /// let mut buffer = [0; 10];
537 /// // read up to 10 bytes
538 /// b.read(&mut buffer)?;
540 /// // etc... it works exactly as a File does!
545 /// [`read()`]: Read::read
546 /// [`&str`]: prim@str
547 /// [`std::io`]: self
548 /// [`File`]: crate::fs::File
549 #[stable(feature = "rust1", since = "1.0.0")]
550 #[doc(notable_trait)]
551 #[cfg_attr(not(test), rustc_diagnostic_item = "IoRead")]
553 /// Pull some bytes from this source into the specified buffer, returning
554 /// how many bytes were read.
556 /// This function does not provide any guarantees about whether it blocks
557 /// waiting for data, but if an object needs to block for a read and cannot,
558 /// it will typically signal this via an [`Err`] return value.
560 /// If the return value of this method is [`Ok(n)`], then implementations must
561 /// guarantee that `0 <= n <= buf.len()`. A nonzero `n` value indicates
562 /// that the buffer `buf` has been filled in with `n` bytes of data from this
563 /// source. If `n` is `0`, then it can indicate one of two scenarios:
565 /// 1. This reader has reached its "end of file" and will likely no longer
566 /// be able to produce bytes. Note that this does not mean that the
567 /// reader will *always* no longer be able to produce bytes. As an example,
568 /// on Linux, this method will call the `recv` syscall for a [`TcpStream`],
569 /// where returning zero indicates the connection was shut down correctly. While
570 /// for [`File`], it is possible to reach the end of file and get zero as result,
571 /// but if more data is appended to the file, future calls to `read` will return
573 /// 2. The buffer specified was 0 bytes in length.
575 /// It is not an error if the returned value `n` is smaller than the buffer size,
576 /// even when the reader is not at the end of the stream yet.
577 /// This may happen for example because fewer bytes are actually available right now
578 /// (e. g. being close to end-of-file) or because read() was interrupted by a signal.
580 /// As this trait is safe to implement, callers cannot rely on `n <= buf.len()` for safety.
581 /// Extra care needs to be taken when `unsafe` functions are used to access the read bytes.
582 /// Callers have to ensure that no unchecked out-of-bounds accesses are possible even if
585 /// No guarantees are provided about the contents of `buf` when this
586 /// function is called, so implementations cannot rely on any property of the
587 /// contents of `buf` being true. It is recommended that *implementations*
588 /// only write data to `buf` instead of reading its contents.
590 /// Correspondingly, however, *callers* of this method must not assume any guarantees
591 /// about how the implementation uses `buf`. The trait is safe to implement,
592 /// so it is possible that the code that's supposed to write to the buffer might also read
593 /// from it. It is your responsibility to make sure that `buf` is initialized
594 /// before calling `read`. Calling `read` with an uninitialized `buf` (of the kind one
595 /// obtains via [`MaybeUninit<T>`]) is not safe, and can lead to undefined behavior.
597 /// [`MaybeUninit<T>`]: crate::mem::MaybeUninit
601 /// If this function encounters any form of I/O or other error, an error
602 /// variant will be returned. If an error is returned then it must be
603 /// guaranteed that no bytes were read.
605 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
606 /// operation should be retried if there is nothing else to do.
610 /// [`File`]s implement `Read`:
613 /// [`File`]: crate::fs::File
614 /// [`TcpStream`]: crate::net::TcpStream
618 /// use std::io::prelude::*;
619 /// use std::fs::File;
621 /// fn main() -> io::Result<()> {
622 /// let mut f = File::open("foo.txt")?;
623 /// let mut buffer = [0; 10];
625 /// // read up to 10 bytes
626 /// let n = f.read(&mut buffer[..])?;
628 /// println!("The bytes: {:?}", &buffer[..n]);
632 #[stable(feature = "rust1", since = "1.0.0")]
633 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
635 /// Like `read`, except that it reads into a slice of buffers.
637 /// Data is copied to fill each buffer in order, with the final buffer
638 /// written to possibly being only partially filled. This method must
639 /// behave equivalently to a single call to `read` with concatenated
642 /// The default implementation calls `read` with either the first nonempty
643 /// buffer provided, or an empty one if none exists.
644 #[stable(feature = "iovec", since = "1.36.0")]
645 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
646 default_read_vectored(|b| self.read(b), bufs)
649 /// Determines if this `Read`er has an efficient `read_vectored`
652 /// If a `Read`er does not override the default `read_vectored`
653 /// implementation, code using it may want to avoid the method all together
654 /// and coalesce writes into a single buffer for higher performance.
656 /// The default implementation returns `false`.
657 #[unstable(feature = "can_vector", issue = "69941")]
658 fn is_read_vectored(&self) -> bool {
662 /// Read all bytes until EOF in this source, placing them into `buf`.
664 /// All bytes read from this source will be appended to the specified buffer
665 /// `buf`. This function will continuously call [`read()`] to append more data to
666 /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of
667 /// non-[`ErrorKind::Interrupted`] kind.
669 /// If successful, this function will return the total number of bytes read.
673 /// If this function encounters an error of the kind
674 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
677 /// If any other read error is encountered then this function immediately
678 /// returns. Any bytes which have already been read will be appended to
683 /// [`File`]s implement `Read`:
685 /// [`read()`]: Read::read
687 /// [`File`]: crate::fs::File
691 /// use std::io::prelude::*;
692 /// use std::fs::File;
694 /// fn main() -> io::Result<()> {
695 /// let mut f = File::open("foo.txt")?;
696 /// let mut buffer = Vec::new();
698 /// // read the whole file
699 /// f.read_to_end(&mut buffer)?;
704 /// (See also the [`std::fs::read`] convenience function for reading from a
707 /// [`std::fs::read`]: crate::fs::read
708 #[stable(feature = "rust1", since = "1.0.0")]
709 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
710 default_read_to_end(self, buf)
713 /// Read all bytes until EOF in this source, appending them to `buf`.
715 /// If successful, this function returns the number of bytes which were read
716 /// and appended to `buf`.
720 /// If the data in this stream is *not* valid UTF-8 then an error is
721 /// returned and `buf` is unchanged.
723 /// See [`read_to_end`] for other error semantics.
725 /// [`read_to_end`]: Read::read_to_end
729 /// [`File`]s implement `Read`:
731 /// [`File`]: crate::fs::File
735 /// use std::io::prelude::*;
736 /// use std::fs::File;
738 /// fn main() -> io::Result<()> {
739 /// let mut f = File::open("foo.txt")?;
740 /// let mut buffer = String::new();
742 /// f.read_to_string(&mut buffer)?;
747 /// (See also the [`std::fs::read_to_string`] convenience function for
748 /// reading from a file.)
750 /// [`std::fs::read_to_string`]: crate::fs::read_to_string
751 #[stable(feature = "rust1", since = "1.0.0")]
752 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
753 default_read_to_string(self, buf)
756 /// Read the exact number of bytes required to fill `buf`.
758 /// This function reads as many bytes as necessary to completely fill the
759 /// specified buffer `buf`.
761 /// No guarantees are provided about the contents of `buf` when this
762 /// function is called, so implementations cannot rely on any property of the
763 /// contents of `buf` being true. It is recommended that implementations
764 /// only write data to `buf` instead of reading its contents. The
765 /// documentation on [`read`] has a more detailed explanation on this
770 /// If this function encounters an error of the kind
771 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
774 /// If this function encounters an "end of file" before completely filling
775 /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
776 /// The contents of `buf` are unspecified in this case.
778 /// If any other read error is encountered then this function immediately
779 /// returns. The contents of `buf` are unspecified in this case.
781 /// If this function returns an error, it is unspecified how many bytes it
782 /// has read, but it will never read more than would be necessary to
783 /// completely fill the buffer.
787 /// [`File`]s implement `Read`:
789 /// [`read`]: Read::read
790 /// [`File`]: crate::fs::File
794 /// use std::io::prelude::*;
795 /// use std::fs::File;
797 /// fn main() -> io::Result<()> {
798 /// let mut f = File::open("foo.txt")?;
799 /// let mut buffer = [0; 10];
801 /// // read exactly 10 bytes
802 /// f.read_exact(&mut buffer)?;
806 #[stable(feature = "read_exact", since = "1.6.0")]
807 fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
808 default_read_exact(self, buf)
811 /// Pull some bytes from this source into the specified buffer.
813 /// This is equivalent to the [`read`](Read::read) method, except that it is passed a [`BorrowedCursor`] rather than `[u8]` to allow use
814 /// with uninitialized buffers. The new data will be appended to any existing contents of `buf`.
816 /// The default implementation delegates to `read`.
817 #[unstable(feature = "read_buf", issue = "78485")]
818 fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<()> {
819 default_read_buf(|b| self.read(b), buf)
822 /// Read the exact number of bytes required to fill `cursor`.
824 /// This is equivalent to the [`read_exact`](Read::read_exact) method, except that it is passed a [`BorrowedCursor`] rather than `[u8]` to
825 /// allow use with uninitialized buffers.
826 #[unstable(feature = "read_buf", issue = "78485")]
827 fn read_buf_exact(&mut self, mut cursor: BorrowedCursor<'_>) -> Result<()> {
828 while cursor.capacity() > 0 {
829 let prev_written = cursor.written();
830 match self.read_buf(cursor.reborrow()) {
832 Err(e) if e.kind() == ErrorKind::Interrupted => continue,
833 Err(e) => return Err(e),
836 if cursor.written() == prev_written {
837 return Err(Error::new(ErrorKind::UnexpectedEof, "failed to fill buffer"));
844 /// Creates a "by reference" adaptor for this instance of `Read`.
846 /// The returned adapter also implements `Read` and will simply borrow this
851 /// [`File`]s implement `Read`:
853 /// [`File`]: crate::fs::File
857 /// use std::io::Read;
858 /// use std::fs::File;
860 /// fn main() -> io::Result<()> {
861 /// let mut f = File::open("foo.txt")?;
862 /// let mut buffer = Vec::new();
863 /// let mut other_buffer = Vec::new();
866 /// let reference = f.by_ref();
868 /// // read at most 5 bytes
869 /// reference.take(5).read_to_end(&mut buffer)?;
871 /// } // drop our &mut reference so we can use f again
873 /// // original file still usable, read the rest
874 /// f.read_to_end(&mut other_buffer)?;
878 #[stable(feature = "rust1", since = "1.0.0")]
879 fn by_ref(&mut self) -> &mut Self
886 /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
888 /// The returned type implements [`Iterator`] where the [`Item`] is
889 /// <code>[Result]<[u8], [io::Error]></code>.
890 /// The yielded item is [`Ok`] if a byte was successfully read and [`Err`]
891 /// otherwise. EOF is mapped to returning [`None`] from this iterator.
893 /// The default implementation calls `read` for each byte,
894 /// which can be very inefficient for data that's not in memory,
895 /// such as [`File`]. Consider using a [`BufReader`] in such cases.
899 /// [`File`]s implement `Read`:
901 /// [`Item`]: Iterator::Item
902 /// [`File`]: crate::fs::File "fs::File"
903 /// [Result]: crate::result::Result "Result"
904 /// [io::Error]: self::Error "io::Error"
908 /// use std::io::prelude::*;
909 /// use std::io::BufReader;
910 /// use std::fs::File;
912 /// fn main() -> io::Result<()> {
913 /// let f = BufReader::new(File::open("foo.txt")?);
915 /// for byte in f.bytes() {
916 /// println!("{}", byte.unwrap());
921 #[stable(feature = "rust1", since = "1.0.0")]
922 fn bytes(self) -> Bytes<Self>
926 Bytes { inner: self }
929 /// Creates an adapter which will chain this stream with another.
931 /// The returned `Read` instance will first read all bytes from this object
932 /// until EOF is encountered. Afterwards the output is equivalent to the
933 /// output of `next`.
937 /// [`File`]s implement `Read`:
939 /// [`File`]: crate::fs::File
943 /// use std::io::prelude::*;
944 /// use std::fs::File;
946 /// fn main() -> io::Result<()> {
947 /// let f1 = File::open("foo.txt")?;
948 /// let f2 = File::open("bar.txt")?;
950 /// let mut handle = f1.chain(f2);
951 /// let mut buffer = String::new();
953 /// // read the value into a String. We could use any Read method here,
954 /// // this is just one example.
955 /// handle.read_to_string(&mut buffer)?;
959 #[stable(feature = "rust1", since = "1.0.0")]
960 fn chain<R: Read>(self, next: R) -> Chain<Self, R>
964 Chain { first: self, second: next, done_first: false }
967 /// Creates an adapter which will read at most `limit` bytes from it.
969 /// This function returns a new instance of `Read` which will read at most
970 /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
971 /// read errors will not count towards the number of bytes read and future
972 /// calls to [`read()`] may succeed.
976 /// [`File`]s implement `Read`:
978 /// [`File`]: crate::fs::File
980 /// [`read()`]: Read::read
984 /// use std::io::prelude::*;
985 /// use std::fs::File;
987 /// fn main() -> io::Result<()> {
988 /// let f = File::open("foo.txt")?;
989 /// let mut buffer = [0; 5];
991 /// // read at most five bytes
992 /// let mut handle = f.take(5);
994 /// handle.read(&mut buffer)?;
998 #[stable(feature = "rust1", since = "1.0.0")]
999 fn take(self, limit: u64) -> Take<Self>
1003 Take { inner: self, limit }
1007 /// Read all bytes from a [reader][Read] into a new [`String`].
1009 /// This is a convenience function for [`Read::read_to_string`]. Using this
1010 /// function avoids having to create a variable first and provides more type
1011 /// safety since you can only get the buffer out if there were no errors. (If you
1012 /// use [`Read::read_to_string`] you have to remember to check whether the read
1013 /// succeeded because otherwise your buffer will be empty or only partially full.)
1017 /// The downside of this function's increased ease of use and type safety is
1018 /// that it gives you less control over performance. For example, you can't
1019 /// pre-allocate memory like you can using [`String::with_capacity`] and
1020 /// [`Read::read_to_string`]. Also, you can't re-use the buffer if an error
1021 /// occurs while reading.
1023 /// In many cases, this function's performance will be adequate and the ease of use
1024 /// and type safety tradeoffs will be worth it. However, there are cases where you
1025 /// need more control over performance, and in those cases you should definitely use
1026 /// [`Read::read_to_string`] directly.
1028 /// Note that in some special cases, such as when reading files, this function will
1029 /// pre-allocate memory based on the size of the input it is reading. In those
1030 /// cases, the performance should be as good as if you had used
1031 /// [`Read::read_to_string`] with a manually pre-allocated buffer.
1035 /// This function forces you to handle errors because the output (the `String`)
1036 /// is wrapped in a [`Result`]. See [`Read::read_to_string`] for the errors
1037 /// that can occur. If any error occurs, you will get an [`Err`], so you
1038 /// don't have to worry about your buffer being empty or partially full.
1044 /// fn main() -> io::Result<()> {
1045 /// let stdin = io::read_to_string(io::stdin())?;
1046 /// println!("Stdin was:");
1047 /// println!("{stdin}");
1051 #[stable(feature = "io_read_to_string", since = "1.65.0")]
1052 pub fn read_to_string<R: Read>(mut reader: R) -> Result<String> {
1053 let mut buf = String::new();
1054 reader.read_to_string(&mut buf)?;
1058 /// A buffer type used with `Read::read_vectored`.
1060 /// It is semantically a wrapper around an `&mut [u8]`, but is guaranteed to be
1061 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
1063 #[stable(feature = "iovec", since = "1.36.0")]
1064 #[repr(transparent)]
1065 pub struct IoSliceMut<'a>(sys::io::IoSliceMut<'a>);
1067 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1068 unsafe impl<'a> Send for IoSliceMut<'a> {}
1070 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1071 unsafe impl<'a> Sync for IoSliceMut<'a> {}
1073 #[stable(feature = "iovec", since = "1.36.0")]
1074 impl<'a> fmt::Debug for IoSliceMut<'a> {
1075 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1076 fmt::Debug::fmt(self.0.as_slice(), fmt)
1080 impl<'a> IoSliceMut<'a> {
1081 /// Creates a new `IoSliceMut` wrapping a byte slice.
1085 /// Panics on Windows if the slice is larger than 4GB.
1086 #[stable(feature = "iovec", since = "1.36.0")]
1088 pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> {
1089 IoSliceMut(sys::io::IoSliceMut::new(buf))
1092 /// Advance the internal cursor of the slice.
1094 /// Also see [`IoSliceMut::advance_slices`] to advance the cursors of
1095 /// multiple buffers.
1099 /// Panics when trying to advance beyond the end of the slice.
1104 /// #![feature(io_slice_advance)]
1106 /// use std::io::IoSliceMut;
1107 /// use std::ops::Deref;
1109 /// let mut data = [1; 8];
1110 /// let mut buf = IoSliceMut::new(&mut data);
1112 /// // Mark 3 bytes as read.
1114 /// assert_eq!(buf.deref(), [1; 5].as_ref());
1116 #[unstable(feature = "io_slice_advance", issue = "62726")]
1118 pub fn advance(&mut self, n: usize) {
1122 /// Advance a slice of slices.
1124 /// Shrinks the slice to remove any `IoSliceMut`s that are fully advanced over.
1125 /// If the cursor ends up in the middle of an `IoSliceMut`, it is modified
1126 /// to start at that cursor.
1128 /// For example, if we have a slice of two 8-byte `IoSliceMut`s, and we advance by 10 bytes,
1129 /// the result will only include the second `IoSliceMut`, advanced by 2 bytes.
1133 /// Panics when trying to advance beyond the end of the slices.
1138 /// #![feature(io_slice_advance)]
1140 /// use std::io::IoSliceMut;
1141 /// use std::ops::Deref;
1143 /// let mut buf1 = [1; 8];
1144 /// let mut buf2 = [2; 16];
1145 /// let mut buf3 = [3; 8];
1146 /// let mut bufs = &mut [
1147 /// IoSliceMut::new(&mut buf1),
1148 /// IoSliceMut::new(&mut buf2),
1149 /// IoSliceMut::new(&mut buf3),
1152 /// // Mark 10 bytes as read.
1153 /// IoSliceMut::advance_slices(&mut bufs, 10);
1154 /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1155 /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1157 #[unstable(feature = "io_slice_advance", issue = "62726")]
1159 pub fn advance_slices(bufs: &mut &mut [IoSliceMut<'a>], n: usize) {
1160 // Number of buffers to remove.
1162 // Total length of all the to be removed buffers.
1163 let mut accumulated_len = 0;
1164 for buf in bufs.iter() {
1165 if accumulated_len + buf.len() > n {
1168 accumulated_len += buf.len();
1173 *bufs = &mut replace(bufs, &mut [])[remove..];
1174 if bufs.is_empty() {
1175 assert!(n == accumulated_len, "advancing io slices beyond their length");
1177 bufs[0].advance(n - accumulated_len)
1182 #[stable(feature = "iovec", since = "1.36.0")]
1183 impl<'a> Deref for IoSliceMut<'a> {
1187 fn deref(&self) -> &[u8] {
1192 #[stable(feature = "iovec", since = "1.36.0")]
1193 impl<'a> DerefMut for IoSliceMut<'a> {
1195 fn deref_mut(&mut self) -> &mut [u8] {
1196 self.0.as_mut_slice()
1200 /// A buffer type used with `Write::write_vectored`.
1202 /// It is semantically a wrapper around a `&[u8]`, but is guaranteed to be
1203 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
1205 #[stable(feature = "iovec", since = "1.36.0")]
1206 #[derive(Copy, Clone)]
1207 #[repr(transparent)]
1208 pub struct IoSlice<'a>(sys::io::IoSlice<'a>);
1210 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1211 unsafe impl<'a> Send for IoSlice<'a> {}
1213 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1214 unsafe impl<'a> Sync for IoSlice<'a> {}
1216 #[stable(feature = "iovec", since = "1.36.0")]
1217 impl<'a> fmt::Debug for IoSlice<'a> {
1218 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1219 fmt::Debug::fmt(self.0.as_slice(), fmt)
1223 impl<'a> IoSlice<'a> {
1224 /// Creates a new `IoSlice` wrapping a byte slice.
1228 /// Panics on Windows if the slice is larger than 4GB.
1229 #[stable(feature = "iovec", since = "1.36.0")]
1232 pub fn new(buf: &'a [u8]) -> IoSlice<'a> {
1233 IoSlice(sys::io::IoSlice::new(buf))
1236 /// Advance the internal cursor of the slice.
1238 /// Also see [`IoSlice::advance_slices`] to advance the cursors of multiple
1243 /// Panics when trying to advance beyond the end of the slice.
1248 /// #![feature(io_slice_advance)]
1250 /// use std::io::IoSlice;
1251 /// use std::ops::Deref;
1253 /// let data = [1; 8];
1254 /// let mut buf = IoSlice::new(&data);
1256 /// // Mark 3 bytes as read.
1258 /// assert_eq!(buf.deref(), [1; 5].as_ref());
1260 #[unstable(feature = "io_slice_advance", issue = "62726")]
1262 pub fn advance(&mut self, n: usize) {
1266 /// Advance a slice of slices.
1268 /// Shrinks the slice to remove any `IoSlice`s that are fully advanced over.
1269 /// If the cursor ends up in the middle of an `IoSlice`, it is modified
1270 /// to start at that cursor.
1272 /// For example, if we have a slice of two 8-byte `IoSlice`s, and we advance by 10 bytes,
1273 /// the result will only include the second `IoSlice`, advanced by 2 bytes.
1277 /// Panics when trying to advance beyond the end of the slices.
1282 /// #![feature(io_slice_advance)]
1284 /// use std::io::IoSlice;
1285 /// use std::ops::Deref;
1287 /// let buf1 = [1; 8];
1288 /// let buf2 = [2; 16];
1289 /// let buf3 = [3; 8];
1290 /// let mut bufs = &mut [
1291 /// IoSlice::new(&buf1),
1292 /// IoSlice::new(&buf2),
1293 /// IoSlice::new(&buf3),
1296 /// // Mark 10 bytes as written.
1297 /// IoSlice::advance_slices(&mut bufs, 10);
1298 /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1299 /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1300 #[unstable(feature = "io_slice_advance", issue = "62726")]
1302 pub fn advance_slices(bufs: &mut &mut [IoSlice<'a>], n: usize) {
1303 // Number of buffers to remove.
1305 // Total length of all the to be removed buffers.
1306 let mut accumulated_len = 0;
1307 for buf in bufs.iter() {
1308 if accumulated_len + buf.len() > n {
1311 accumulated_len += buf.len();
1316 *bufs = &mut replace(bufs, &mut [])[remove..];
1317 if bufs.is_empty() {
1318 assert!(n == accumulated_len, "advancing io slices beyond their length");
1320 bufs[0].advance(n - accumulated_len)
1325 #[stable(feature = "iovec", since = "1.36.0")]
1326 impl<'a> Deref for IoSlice<'a> {
1330 fn deref(&self) -> &[u8] {
1335 /// A trait for objects which are byte-oriented sinks.
1337 /// Implementors of the `Write` trait are sometimes called 'writers'.
1339 /// Writers are defined by two required methods, [`write`] and [`flush`]:
1341 /// * The [`write`] method will attempt to write some data into the object,
1342 /// returning how many bytes were successfully written.
1344 /// * The [`flush`] method is useful for adapters and explicit buffers
1345 /// themselves for ensuring that all buffered data has been pushed out to the
1348 /// Writers are intended to be composable with one another. Many implementors
1349 /// throughout [`std::io`] take and provide types which implement the `Write`
1352 /// [`write`]: Write::write
1353 /// [`flush`]: Write::flush
1354 /// [`std::io`]: self
1359 /// use std::io::prelude::*;
1360 /// use std::fs::File;
1362 /// fn main() -> std::io::Result<()> {
1363 /// let data = b"some bytes";
1365 /// let mut pos = 0;
1366 /// let mut buffer = File::create("foo.txt")?;
1368 /// while pos < data.len() {
1369 /// let bytes_written = buffer.write(&data[pos..])?;
1370 /// pos += bytes_written;
1376 /// The trait also provides convenience methods like [`write_all`], which calls
1377 /// `write` in a loop until its entire input has been written.
1379 /// [`write_all`]: Write::write_all
1380 #[stable(feature = "rust1", since = "1.0.0")]
1381 #[doc(notable_trait)]
1382 #[cfg_attr(not(test), rustc_diagnostic_item = "IoWrite")]
1384 /// Write a buffer into this writer, returning how many bytes were written.
1386 /// This function will attempt to write the entire contents of `buf`, but
1387 /// the entire write might not succeed, or the write may also generate an
1388 /// error. A call to `write` represents *at most one* attempt to write to
1389 /// any wrapped object.
1391 /// Calls to `write` are not guaranteed to block waiting for data to be
1392 /// written, and a write which would otherwise block can be indicated through
1393 /// an [`Err`] variant.
1395 /// If the return value is [`Ok(n)`] then it must be guaranteed that
1396 /// `n <= buf.len()`. A return value of `0` typically means that the
1397 /// underlying object is no longer able to accept bytes and will likely not
1398 /// be able to in the future as well, or that the buffer provided is empty.
1402 /// Each call to `write` may generate an I/O error indicating that the
1403 /// operation could not be completed. If an error is returned then no bytes
1404 /// in the buffer were written to this writer.
1406 /// It is **not** considered an error if the entire buffer could not be
1407 /// written to this writer.
1409 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the
1410 /// write operation should be retried if there is nothing else to do.
1415 /// use std::io::prelude::*;
1416 /// use std::fs::File;
1418 /// fn main() -> std::io::Result<()> {
1419 /// let mut buffer = File::create("foo.txt")?;
1421 /// // Writes some prefix of the byte string, not necessarily all of it.
1422 /// buffer.write(b"some bytes")?;
1428 #[stable(feature = "rust1", since = "1.0.0")]
1429 fn write(&mut self, buf: &[u8]) -> Result<usize>;
1431 /// Like [`write`], except that it writes from a slice of buffers.
1433 /// Data is copied from each buffer in order, with the final buffer
1434 /// read from possibly being only partially consumed. This method must
1435 /// behave as a call to [`write`] with the buffers concatenated would.
1437 /// The default implementation calls [`write`] with either the first nonempty
1438 /// buffer provided, or an empty one if none exists.
1443 /// use std::io::IoSlice;
1444 /// use std::io::prelude::*;
1445 /// use std::fs::File;
1447 /// fn main() -> std::io::Result<()> {
1448 /// let data1 = [1; 8];
1449 /// let data2 = [15; 8];
1450 /// let io_slice1 = IoSlice::new(&data1);
1451 /// let io_slice2 = IoSlice::new(&data2);
1453 /// let mut buffer = File::create("foo.txt")?;
1455 /// // Writes some prefix of the byte string, not necessarily all of it.
1456 /// buffer.write_vectored(&[io_slice1, io_slice2])?;
1461 /// [`write`]: Write::write
1462 #[stable(feature = "iovec", since = "1.36.0")]
1463 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize> {
1464 default_write_vectored(|b| self.write(b), bufs)
1467 /// Determines if this `Write`r has an efficient [`write_vectored`]
1470 /// If a `Write`r does not override the default [`write_vectored`]
1471 /// implementation, code using it may want to avoid the method all together
1472 /// and coalesce writes into a single buffer for higher performance.
1474 /// The default implementation returns `false`.
1476 /// [`write_vectored`]: Write::write_vectored
1477 #[unstable(feature = "can_vector", issue = "69941")]
1478 fn is_write_vectored(&self) -> bool {
1482 /// Flush this output stream, ensuring that all intermediately buffered
1483 /// contents reach their destination.
1487 /// It is considered an error if not all bytes could be written due to
1488 /// I/O errors or EOF being reached.
1493 /// use std::io::prelude::*;
1494 /// use std::io::BufWriter;
1495 /// use std::fs::File;
1497 /// fn main() -> std::io::Result<()> {
1498 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
1500 /// buffer.write_all(b"some bytes")?;
1501 /// buffer.flush()?;
1505 #[stable(feature = "rust1", since = "1.0.0")]
1506 fn flush(&mut self) -> Result<()>;
1508 /// Attempts to write an entire buffer into this writer.
1510 /// This method will continuously call [`write`] until there is no more data
1511 /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is
1512 /// returned. This method will not return until the entire buffer has been
1513 /// successfully written or such an error occurs. The first error that is
1514 /// not of [`ErrorKind::Interrupted`] kind generated from this method will be
1517 /// If the buffer contains no data, this will never call [`write`].
1521 /// This function will return the first error of
1522 /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns.
1524 /// [`write`]: Write::write
1529 /// use std::io::prelude::*;
1530 /// use std::fs::File;
1532 /// fn main() -> std::io::Result<()> {
1533 /// let mut buffer = File::create("foo.txt")?;
1535 /// buffer.write_all(b"some bytes")?;
1539 #[stable(feature = "rust1", since = "1.0.0")]
1540 fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
1541 while !buf.is_empty() {
1542 match self.write(buf) {
1544 return Err(error::const_io_error!(
1545 ErrorKind::WriteZero,
1546 "failed to write whole buffer",
1549 Ok(n) => buf = &buf[n..],
1550 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1551 Err(e) => return Err(e),
1557 /// Attempts to write multiple buffers into this writer.
1559 /// This method will continuously call [`write_vectored`] until there is no
1560 /// more data to be written or an error of non-[`ErrorKind::Interrupted`]
1561 /// kind is returned. This method will not return until all buffers have
1562 /// been successfully written or such an error occurs. The first error that
1563 /// is not of [`ErrorKind::Interrupted`] kind generated from this method
1564 /// will be returned.
1566 /// If the buffer contains no data, this will never call [`write_vectored`].
1570 /// Unlike [`write_vectored`], this takes a *mutable* reference to
1571 /// a slice of [`IoSlice`]s, not an immutable one. That's because we need to
1572 /// modify the slice to keep track of the bytes already written.
1574 /// Once this function returns, the contents of `bufs` are unspecified, as
1575 /// this depends on how many calls to [`write_vectored`] were necessary. It is
1576 /// best to understand this function as taking ownership of `bufs` and to
1577 /// not use `bufs` afterwards. The underlying buffers, to which the
1578 /// [`IoSlice`]s point (but not the [`IoSlice`]s themselves), are unchanged and
1581 /// [`write_vectored`]: Write::write_vectored
1586 /// #![feature(write_all_vectored)]
1587 /// # fn main() -> std::io::Result<()> {
1589 /// use std::io::{Write, IoSlice};
1591 /// let mut writer = Vec::new();
1592 /// let bufs = &mut [
1593 /// IoSlice::new(&[1]),
1594 /// IoSlice::new(&[2, 3]),
1595 /// IoSlice::new(&[4, 5, 6]),
1598 /// writer.write_all_vectored(bufs)?;
1599 /// // Note: the contents of `bufs` is now undefined, see the Notes section.
1601 /// assert_eq!(writer, &[1, 2, 3, 4, 5, 6]);
1604 #[unstable(feature = "write_all_vectored", issue = "70436")]
1605 fn write_all_vectored(&mut self, mut bufs: &mut [IoSlice<'_>]) -> Result<()> {
1606 // Guarantee that bufs is empty if it contains no data,
1607 // to avoid calling write_vectored if there is no data to be written.
1608 IoSlice::advance_slices(&mut bufs, 0);
1609 while !bufs.is_empty() {
1610 match self.write_vectored(bufs) {
1612 return Err(error::const_io_error!(
1613 ErrorKind::WriteZero,
1614 "failed to write whole buffer",
1617 Ok(n) => IoSlice::advance_slices(&mut bufs, n),
1618 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1619 Err(e) => return Err(e),
1625 /// Writes a formatted string into this writer, returning any error
1628 /// This method is primarily used to interface with the
1629 /// [`format_args!()`] macro, and it is rare that this should
1630 /// explicitly be called. The [`write!()`] macro should be favored to
1631 /// invoke this method instead.
1633 /// This function internally uses the [`write_all`] method on
1634 /// this trait and hence will continuously write data so long as no errors
1635 /// are received. This also means that partial writes are not indicated in
1638 /// [`write_all`]: Write::write_all
1642 /// This function will return any I/O error reported while formatting.
1647 /// use std::io::prelude::*;
1648 /// use std::fs::File;
1650 /// fn main() -> std::io::Result<()> {
1651 /// let mut buffer = File::create("foo.txt")?;
1654 /// write!(buffer, "{:.*}", 2, 1.234567)?;
1655 /// // turns into this:
1656 /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1660 #[stable(feature = "rust1", since = "1.0.0")]
1661 fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> Result<()> {
1662 // Create a shim which translates a Write to a fmt::Write and saves
1663 // off I/O errors. instead of discarding them
1664 struct Adapter<'a, T: ?Sized + 'a> {
1669 impl<T: Write + ?Sized> fmt::Write for Adapter<'_, T> {
1670 fn write_str(&mut self, s: &str) -> fmt::Result {
1671 match self.inner.write_all(s.as_bytes()) {
1674 self.error = Err(e);
1681 let mut output = Adapter { inner: self, error: Ok(()) };
1682 match fmt::write(&mut output, fmt) {
1685 // check if the error came from the underlying `Write` or not
1686 if output.error.is_err() {
1689 Err(error::const_io_error!(ErrorKind::Uncategorized, "formatter error"))
1695 /// Creates a "by reference" adapter for this instance of `Write`.
1697 /// The returned adapter also implements `Write` and will simply borrow this
1703 /// use std::io::Write;
1704 /// use std::fs::File;
1706 /// fn main() -> std::io::Result<()> {
1707 /// let mut buffer = File::create("foo.txt")?;
1709 /// let reference = buffer.by_ref();
1711 /// // we can use reference just like our original buffer
1712 /// reference.write_all(b"some bytes")?;
1716 #[stable(feature = "rust1", since = "1.0.0")]
1717 fn by_ref(&mut self) -> &mut Self
1725 /// The `Seek` trait provides a cursor which can be moved within a stream of
1728 /// The stream typically has a fixed size, allowing seeking relative to either
1729 /// end or the current offset.
1733 /// [`File`]s implement `Seek`:
1735 /// [`File`]: crate::fs::File
1739 /// use std::io::prelude::*;
1740 /// use std::fs::File;
1741 /// use std::io::SeekFrom;
1743 /// fn main() -> io::Result<()> {
1744 /// let mut f = File::open("foo.txt")?;
1746 /// // move the cursor 42 bytes from the start of the file
1747 /// f.seek(SeekFrom::Start(42))?;
1751 #[stable(feature = "rust1", since = "1.0.0")]
1753 /// Seek to an offset, in bytes, in a stream.
1755 /// A seek beyond the end of a stream is allowed, but behavior is defined
1756 /// by the implementation.
1758 /// If the seek operation completed successfully,
1759 /// this method returns the new position from the start of the stream.
1760 /// That position can be used later with [`SeekFrom::Start`].
1764 /// Seeking can fail, for example because it might involve flushing a buffer.
1766 /// Seeking to a negative offset is considered an error.
1767 #[stable(feature = "rust1", since = "1.0.0")]
1768 fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1770 /// Rewind to the beginning of a stream.
1772 /// This is a convenience method, equivalent to `seek(SeekFrom::Start(0))`.
1776 /// Rewinding can fail, for example because it might involve flushing a buffer.
1781 /// use std::io::{Read, Seek, Write};
1782 /// use std::fs::OpenOptions;
1784 /// let mut f = OpenOptions::new()
1788 /// .open("foo.txt").unwrap();
1790 /// let hello = "Hello!\n";
1791 /// write!(f, "{hello}").unwrap();
1792 /// f.rewind().unwrap();
1794 /// let mut buf = String::new();
1795 /// f.read_to_string(&mut buf).unwrap();
1796 /// assert_eq!(&buf, hello);
1798 #[stable(feature = "seek_rewind", since = "1.55.0")]
1799 fn rewind(&mut self) -> Result<()> {
1800 self.seek(SeekFrom::Start(0))?;
1804 /// Returns the length of this stream (in bytes).
1806 /// This method is implemented using up to three seek operations. If this
1807 /// method returns successfully, the seek position is unchanged (i.e. the
1808 /// position before calling this method is the same as afterwards).
1809 /// However, if this method returns an error, the seek position is
1812 /// If you need to obtain the length of *many* streams and you don't care
1813 /// about the seek position afterwards, you can reduce the number of seek
1814 /// operations by simply calling `seek(SeekFrom::End(0))` and using its
1815 /// return value (it is also the stream length).
1817 /// Note that length of a stream can change over time (for example, when
1818 /// data is appended to a file). So calling this method multiple times does
1819 /// not necessarily return the same length each time.
1824 /// #![feature(seek_stream_len)]
1826 /// io::{self, Seek},
1830 /// fn main() -> io::Result<()> {
1831 /// let mut f = File::open("foo.txt")?;
1833 /// let len = f.stream_len()?;
1834 /// println!("The file is currently {len} bytes long");
1838 #[unstable(feature = "seek_stream_len", issue = "59359")]
1839 fn stream_len(&mut self) -> Result<u64> {
1840 let old_pos = self.stream_position()?;
1841 let len = self.seek(SeekFrom::End(0))?;
1843 // Avoid seeking a third time when we were already at the end of the
1844 // stream. The branch is usually way cheaper than a seek operation.
1846 self.seek(SeekFrom::Start(old_pos))?;
1852 /// Returns the current seek position from the start of the stream.
1854 /// This is equivalent to `self.seek(SeekFrom::Current(0))`.
1860 /// io::{self, BufRead, BufReader, Seek},
1864 /// fn main() -> io::Result<()> {
1865 /// let mut f = BufReader::new(File::open("foo.txt")?);
1867 /// let before = f.stream_position()?;
1868 /// f.read_line(&mut String::new())?;
1869 /// let after = f.stream_position()?;
1871 /// println!("The first line was {} bytes long", after - before);
1875 #[stable(feature = "seek_convenience", since = "1.51.0")]
1876 fn stream_position(&mut self) -> Result<u64> {
1877 self.seek(SeekFrom::Current(0))
1881 /// Enumeration of possible methods to seek within an I/O object.
1883 /// It is used by the [`Seek`] trait.
1884 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1885 #[stable(feature = "rust1", since = "1.0.0")]
1887 /// Sets the offset to the provided number of bytes.
1888 #[stable(feature = "rust1", since = "1.0.0")]
1889 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1891 /// Sets the offset to the size of this object plus the specified number of
1894 /// It is possible to seek beyond the end of an object, but it's an error to
1895 /// seek before byte 0.
1896 #[stable(feature = "rust1", since = "1.0.0")]
1897 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1899 /// Sets the offset to the current position plus the specified number of
1902 /// It is possible to seek beyond the end of an object, but it's an error to
1903 /// seek before byte 0.
1904 #[stable(feature = "rust1", since = "1.0.0")]
1905 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1908 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>) -> Result<usize> {
1911 let (done, used) = {
1912 let available = match r.fill_buf() {
1914 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1915 Err(e) => return Err(e),
1917 match memchr::memchr(delim, available) {
1919 buf.extend_from_slice(&available[..=i]);
1923 buf.extend_from_slice(available);
1924 (false, available.len())
1930 if done || used == 0 {
1936 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1937 /// to perform extra ways of reading.
1939 /// For example, reading line-by-line is inefficient without using a buffer, so
1940 /// if you want to read by line, you'll need `BufRead`, which includes a
1941 /// [`read_line`] method as well as a [`lines`] iterator.
1945 /// A locked standard input implements `BufRead`:
1949 /// use std::io::prelude::*;
1951 /// let stdin = io::stdin();
1952 /// for line in stdin.lock().lines() {
1953 /// println!("{}", line.unwrap());
1957 /// If you have something that implements [`Read`], you can use the [`BufReader`
1958 /// type][`BufReader`] to turn it into a `BufRead`.
1960 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1961 /// [`BufReader`] to the rescue!
1963 /// [`File`]: crate::fs::File
1964 /// [`read_line`]: BufRead::read_line
1965 /// [`lines`]: BufRead::lines
1968 /// use std::io::{self, BufReader};
1969 /// use std::io::prelude::*;
1970 /// use std::fs::File;
1972 /// fn main() -> io::Result<()> {
1973 /// let f = File::open("foo.txt")?;
1974 /// let f = BufReader::new(f);
1976 /// for line in f.lines() {
1977 /// println!("{}", line.unwrap());
1983 #[stable(feature = "rust1", since = "1.0.0")]
1984 pub trait BufRead: Read {
1985 /// Returns the contents of the internal buffer, filling it with more data
1986 /// from the inner reader if it is empty.
1988 /// This function is a lower-level call. It needs to be paired with the
1989 /// [`consume`] method to function properly. When calling this
1990 /// method, none of the contents will be "read" in the sense that later
1991 /// calling `read` may return the same contents. As such, [`consume`] must
1992 /// be called with the number of bytes that are consumed from this buffer to
1993 /// ensure that the bytes are never returned twice.
1995 /// [`consume`]: BufRead::consume
1997 /// An empty buffer returned indicates that the stream has reached EOF.
2001 /// This function will return an I/O error if the underlying reader was
2002 /// read, but returned an error.
2006 /// A locked standard input implements `BufRead`:
2010 /// use std::io::prelude::*;
2012 /// let stdin = io::stdin();
2013 /// let mut stdin = stdin.lock();
2015 /// let buffer = stdin.fill_buf().unwrap();
2017 /// // work with buffer
2018 /// println!("{buffer:?}");
2020 /// // ensure the bytes we worked with aren't returned again later
2021 /// let length = buffer.len();
2022 /// stdin.consume(length);
2024 #[stable(feature = "rust1", since = "1.0.0")]
2025 fn fill_buf(&mut self) -> Result<&[u8]>;
2027 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
2028 /// so they should no longer be returned in calls to `read`.
2030 /// This function is a lower-level call. It needs to be paired with the
2031 /// [`fill_buf`] method to function properly. This function does
2032 /// not perform any I/O, it simply informs this object that some amount of
2033 /// its buffer, returned from [`fill_buf`], has been consumed and should
2034 /// no longer be returned. As such, this function may do odd things if
2035 /// [`fill_buf`] isn't called before calling it.
2037 /// The `amt` must be `<=` the number of bytes in the buffer returned by
2042 /// Since `consume()` is meant to be used with [`fill_buf`],
2043 /// that method's example includes an example of `consume()`.
2045 /// [`fill_buf`]: BufRead::fill_buf
2046 #[stable(feature = "rust1", since = "1.0.0")]
2047 fn consume(&mut self, amt: usize);
2049 /// Check if the underlying `Read` has any data left to be read.
2051 /// This function may fill the buffer to check for data,
2052 /// so this functions returns `Result<bool>`, not `bool`.
2054 /// Default implementation calls `fill_buf` and checks that
2055 /// returned slice is empty (which means that there is no data left,
2056 /// since EOF is reached).
2061 /// #![feature(buf_read_has_data_left)]
2063 /// use std::io::prelude::*;
2065 /// let stdin = io::stdin();
2066 /// let mut stdin = stdin.lock();
2068 /// while stdin.has_data_left().unwrap() {
2069 /// let mut line = String::new();
2070 /// stdin.read_line(&mut line).unwrap();
2071 /// // work with line
2072 /// println!("{line:?}");
2075 #[unstable(feature = "buf_read_has_data_left", reason = "recently added", issue = "86423")]
2076 fn has_data_left(&mut self) -> Result<bool> {
2077 self.fill_buf().map(|b| !b.is_empty())
2080 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
2082 /// This function will read bytes from the underlying stream until the
2083 /// delimiter or EOF is found. Once found, all bytes up to, and including,
2084 /// the delimiter (if found) will be appended to `buf`.
2086 /// If successful, this function will return the total number of bytes read.
2088 /// This function is blocking and should be used carefully: it is possible for
2089 /// an attacker to continuously send bytes without ever sending the delimiter
2094 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
2095 /// will otherwise return any errors returned by [`fill_buf`].
2097 /// If an I/O error is encountered then all bytes read so far will be
2098 /// present in `buf` and its length will have been adjusted appropriately.
2100 /// [`fill_buf`]: BufRead::fill_buf
2104 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2105 /// this example, we use [`Cursor`] to read all the bytes in a byte slice
2106 /// in hyphen delimited segments:
2109 /// use std::io::{self, BufRead};
2111 /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
2112 /// let mut buf = vec![];
2114 /// // cursor is at 'l'
2115 /// let num_bytes = cursor.read_until(b'-', &mut buf)
2116 /// .expect("reading from cursor won't fail");
2117 /// assert_eq!(num_bytes, 6);
2118 /// assert_eq!(buf, b"lorem-");
2121 /// // cursor is at 'i'
2122 /// let num_bytes = cursor.read_until(b'-', &mut buf)
2123 /// .expect("reading from cursor won't fail");
2124 /// assert_eq!(num_bytes, 5);
2125 /// assert_eq!(buf, b"ipsum");
2128 /// // cursor is at EOF
2129 /// let num_bytes = cursor.read_until(b'-', &mut buf)
2130 /// .expect("reading from cursor won't fail");
2131 /// assert_eq!(num_bytes, 0);
2132 /// assert_eq!(buf, b"");
2134 #[stable(feature = "rust1", since = "1.0.0")]
2135 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
2136 read_until(self, byte, buf)
2139 /// Read all bytes until a newline (the `0xA` byte) is reached, and append
2140 /// them to the provided `String` buffer.
2142 /// Previous content of the buffer will be preserved. To avoid appending to
2143 /// the buffer, you need to [`clear`] it first.
2145 /// This function will read bytes from the underlying stream until the
2146 /// newline delimiter (the `0xA` byte) or EOF is found. Once found, all bytes
2147 /// up to, and including, the delimiter (if found) will be appended to
2150 /// If successful, this function will return the total number of bytes read.
2152 /// If this function returns [`Ok(0)`], the stream has reached EOF.
2154 /// This function is blocking and should be used carefully: it is possible for
2155 /// an attacker to continuously send bytes without ever sending a newline
2156 /// or EOF. You can use [`take`] to limit the maximum number of bytes read.
2159 /// [`clear`]: String::clear
2160 /// [`take`]: crate::io::Read::take
2164 /// This function has the same error semantics as [`read_until`] and will
2165 /// also return an error if the read bytes are not valid UTF-8. If an I/O
2166 /// error is encountered then `buf` may contain some bytes already read in
2167 /// the event that all data read so far was valid UTF-8.
2169 /// [`read_until`]: BufRead::read_until
2173 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2174 /// this example, we use [`Cursor`] to read all the lines in a byte slice:
2177 /// use std::io::{self, BufRead};
2179 /// let mut cursor = io::Cursor::new(b"foo\nbar");
2180 /// let mut buf = String::new();
2182 /// // cursor is at 'f'
2183 /// let num_bytes = cursor.read_line(&mut buf)
2184 /// .expect("reading from cursor won't fail");
2185 /// assert_eq!(num_bytes, 4);
2186 /// assert_eq!(buf, "foo\n");
2189 /// // cursor is at 'b'
2190 /// let num_bytes = cursor.read_line(&mut buf)
2191 /// .expect("reading from cursor won't fail");
2192 /// assert_eq!(num_bytes, 3);
2193 /// assert_eq!(buf, "bar");
2196 /// // cursor is at EOF
2197 /// let num_bytes = cursor.read_line(&mut buf)
2198 /// .expect("reading from cursor won't fail");
2199 /// assert_eq!(num_bytes, 0);
2200 /// assert_eq!(buf, "");
2202 #[stable(feature = "rust1", since = "1.0.0")]
2203 fn read_line(&mut self, buf: &mut String) -> Result<usize> {
2204 // Note that we are not calling the `.read_until` method here, but
2205 // rather our hardcoded implementation. For more details as to why, see
2206 // the comments in `read_to_end`.
2207 unsafe { append_to_string(buf, |b| read_until(self, b'\n', b)) }
2210 /// Returns an iterator over the contents of this reader split on the byte
2213 /// The iterator returned from this function will return instances of
2214 /// <code>[io::Result]<[Vec]\<u8>></code>. Each vector returned will *not* have
2215 /// the delimiter byte at the end.
2217 /// This function will yield errors whenever [`read_until`] would have
2218 /// also yielded an error.
2220 /// [io::Result]: self::Result "io::Result"
2221 /// [`read_until`]: BufRead::read_until
2225 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2226 /// this example, we use [`Cursor`] to iterate over all hyphen delimited
2227 /// segments in a byte slice
2230 /// use std::io::{self, BufRead};
2232 /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
2234 /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
2235 /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
2236 /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
2237 /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
2238 /// assert_eq!(split_iter.next(), None);
2240 #[stable(feature = "rust1", since = "1.0.0")]
2241 fn split(self, byte: u8) -> Split<Self>
2245 Split { buf: self, delim: byte }
2248 /// Returns an iterator over the lines of this reader.
2250 /// The iterator returned from this function will yield instances of
2251 /// <code>[io::Result]<[String]></code>. Each string returned will *not* have a newline
2252 /// byte (the `0xA` byte) or `CRLF` (`0xD`, `0xA` bytes) at the end.
2254 /// [io::Result]: self::Result "io::Result"
2258 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2259 /// this example, we use [`Cursor`] to iterate over all the lines in a byte
2263 /// use std::io::{self, BufRead};
2265 /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
2267 /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
2268 /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
2269 /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
2270 /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
2271 /// assert_eq!(lines_iter.next(), None);
2276 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
2277 #[stable(feature = "rust1", since = "1.0.0")]
2278 fn lines(self) -> Lines<Self>
2286 /// Adapter to chain together two readers.
2288 /// This struct is generally created by calling [`chain`] on a reader.
2289 /// Please see the documentation of [`chain`] for more details.
2291 /// [`chain`]: Read::chain
2292 #[stable(feature = "rust1", since = "1.0.0")]
2294 pub struct Chain<T, U> {
2300 impl<T, U> Chain<T, U> {
2301 /// Consumes the `Chain`, returning the wrapped readers.
2307 /// use std::io::prelude::*;
2308 /// use std::fs::File;
2310 /// fn main() -> io::Result<()> {
2311 /// let mut foo_file = File::open("foo.txt")?;
2312 /// let mut bar_file = File::open("bar.txt")?;
2314 /// let chain = foo_file.chain(bar_file);
2315 /// let (foo_file, bar_file) = chain.into_inner();
2319 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2320 pub fn into_inner(self) -> (T, U) {
2321 (self.first, self.second)
2324 /// Gets references to the underlying readers in this `Chain`.
2330 /// use std::io::prelude::*;
2331 /// use std::fs::File;
2333 /// fn main() -> io::Result<()> {
2334 /// let mut foo_file = File::open("foo.txt")?;
2335 /// let mut bar_file = File::open("bar.txt")?;
2337 /// let chain = foo_file.chain(bar_file);
2338 /// let (foo_file, bar_file) = chain.get_ref();
2342 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2343 pub fn get_ref(&self) -> (&T, &U) {
2344 (&self.first, &self.second)
2347 /// Gets mutable references to the underlying readers in this `Chain`.
2349 /// Care should be taken to avoid modifying the internal I/O state of the
2350 /// underlying readers as doing so may corrupt the internal state of this
2357 /// use std::io::prelude::*;
2358 /// use std::fs::File;
2360 /// fn main() -> io::Result<()> {
2361 /// let mut foo_file = File::open("foo.txt")?;
2362 /// let mut bar_file = File::open("bar.txt")?;
2364 /// let mut chain = foo_file.chain(bar_file);
2365 /// let (foo_file, bar_file) = chain.get_mut();
2369 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2370 pub fn get_mut(&mut self) -> (&mut T, &mut U) {
2371 (&mut self.first, &mut self.second)
2375 #[stable(feature = "rust1", since = "1.0.0")]
2376 impl<T: Read, U: Read> Read for Chain<T, U> {
2377 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2378 if !self.done_first {
2379 match self.first.read(buf)? {
2380 0 if !buf.is_empty() => self.done_first = true,
2384 self.second.read(buf)
2387 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
2388 if !self.done_first {
2389 match self.first.read_vectored(bufs)? {
2390 0 if bufs.iter().any(|b| !b.is_empty()) => self.done_first = true,
2394 self.second.read_vectored(bufs)
2398 #[stable(feature = "chain_bufread", since = "1.9.0")]
2399 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
2400 fn fill_buf(&mut self) -> Result<&[u8]> {
2401 if !self.done_first {
2402 match self.first.fill_buf()? {
2403 buf if buf.is_empty() => {
2404 self.done_first = true;
2406 buf => return Ok(buf),
2409 self.second.fill_buf()
2412 fn consume(&mut self, amt: usize) {
2413 if !self.done_first { self.first.consume(amt) } else { self.second.consume(amt) }
2417 impl<T, U> SizeHint for Chain<T, U> {
2419 fn lower_bound(&self) -> usize {
2420 SizeHint::lower_bound(&self.first) + SizeHint::lower_bound(&self.second)
2424 fn upper_bound(&self) -> Option<usize> {
2425 match (SizeHint::upper_bound(&self.first), SizeHint::upper_bound(&self.second)) {
2426 (Some(first), Some(second)) => first.checked_add(second),
2432 /// Reader adapter which limits the bytes read from an underlying reader.
2434 /// This struct is generally created by calling [`take`] on a reader.
2435 /// Please see the documentation of [`take`] for more details.
2437 /// [`take`]: Read::take
2438 #[stable(feature = "rust1", since = "1.0.0")]
2440 pub struct Take<T> {
2446 /// Returns the number of bytes that can be read before this instance will
2451 /// This instance may reach `EOF` after reading fewer bytes than indicated by
2452 /// this method if the underlying [`Read`] instance reaches EOF.
2458 /// use std::io::prelude::*;
2459 /// use std::fs::File;
2461 /// fn main() -> io::Result<()> {
2462 /// let f = File::open("foo.txt")?;
2464 /// // read at most five bytes
2465 /// let handle = f.take(5);
2467 /// println!("limit: {}", handle.limit());
2471 #[stable(feature = "rust1", since = "1.0.0")]
2472 pub fn limit(&self) -> u64 {
2476 /// Sets the number of bytes that can be read before this instance will
2477 /// return EOF. This is the same as constructing a new `Take` instance, so
2478 /// the amount of bytes read and the previous limit value don't matter when
2479 /// calling this method.
2485 /// use std::io::prelude::*;
2486 /// use std::fs::File;
2488 /// fn main() -> io::Result<()> {
2489 /// let f = File::open("foo.txt")?;
2491 /// // read at most five bytes
2492 /// let mut handle = f.take(5);
2493 /// handle.set_limit(10);
2495 /// assert_eq!(handle.limit(), 10);
2499 #[stable(feature = "take_set_limit", since = "1.27.0")]
2500 pub fn set_limit(&mut self, limit: u64) {
2504 /// Consumes the `Take`, returning the wrapped reader.
2510 /// use std::io::prelude::*;
2511 /// use std::fs::File;
2513 /// fn main() -> io::Result<()> {
2514 /// let mut file = File::open("foo.txt")?;
2516 /// let mut buffer = [0; 5];
2517 /// let mut handle = file.take(5);
2518 /// handle.read(&mut buffer)?;
2520 /// let file = handle.into_inner();
2524 #[stable(feature = "io_take_into_inner", since = "1.15.0")]
2525 pub fn into_inner(self) -> T {
2529 /// Gets a reference to the underlying reader.
2535 /// use std::io::prelude::*;
2536 /// use std::fs::File;
2538 /// fn main() -> io::Result<()> {
2539 /// let mut file = File::open("foo.txt")?;
2541 /// let mut buffer = [0; 5];
2542 /// let mut handle = file.take(5);
2543 /// handle.read(&mut buffer)?;
2545 /// let file = handle.get_ref();
2549 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2550 pub fn get_ref(&self) -> &T {
2554 /// Gets a mutable reference to the underlying reader.
2556 /// Care should be taken to avoid modifying the internal I/O state of the
2557 /// underlying reader as doing so may corrupt the internal limit of this
2564 /// use std::io::prelude::*;
2565 /// use std::fs::File;
2567 /// fn main() -> io::Result<()> {
2568 /// let mut file = File::open("foo.txt")?;
2570 /// let mut buffer = [0; 5];
2571 /// let mut handle = file.take(5);
2572 /// handle.read(&mut buffer)?;
2574 /// let file = handle.get_mut();
2578 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2579 pub fn get_mut(&mut self) -> &mut T {
2584 #[stable(feature = "rust1", since = "1.0.0")]
2585 impl<T: Read> Read for Take<T> {
2586 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2587 // Don't call into inner reader at all at EOF because it may still block
2588 if self.limit == 0 {
2592 let max = cmp::min(buf.len() as u64, self.limit) as usize;
2593 let n = self.inner.read(&mut buf[..max])?;
2594 assert!(n as u64 <= self.limit, "number of read bytes exceeds limit");
2595 self.limit -= n as u64;
2599 fn read_buf(&mut self, mut buf: BorrowedCursor<'_>) -> Result<()> {
2600 // Don't call into inner reader at all at EOF because it may still block
2601 if self.limit == 0 {
2605 if self.limit <= buf.capacity() as u64 {
2606 // if we just use an as cast to convert, limit may wrap around on a 32 bit target
2607 let limit = cmp::min(self.limit, usize::MAX as u64) as usize;
2609 let extra_init = cmp::min(limit as usize, buf.init_ref().len());
2611 // SAFETY: no uninit data is written to ibuf
2612 let ibuf = unsafe { &mut buf.as_mut()[..limit] };
2614 let mut sliced_buf: BorrowedBuf<'_> = ibuf.into();
2616 // SAFETY: extra_init bytes of ibuf are known to be initialized
2618 sliced_buf.set_init(extra_init);
2621 let mut cursor = sliced_buf.unfilled();
2622 self.inner.read_buf(cursor.reborrow())?;
2624 let new_init = cursor.init_ref().len();
2625 let filled = sliced_buf.len();
2627 // cursor / sliced_buf / ibuf must drop here
2630 // SAFETY: filled bytes have been filled and therefore initialized
2631 buf.advance(filled);
2632 // SAFETY: new_init bytes of buf's unfilled buffer have been initialized
2633 buf.set_init(new_init);
2636 self.limit -= filled as u64;
2638 let written = buf.written();
2639 self.inner.read_buf(buf.reborrow())?;
2640 self.limit -= (buf.written() - written) as u64;
2647 #[stable(feature = "rust1", since = "1.0.0")]
2648 impl<T: BufRead> BufRead for Take<T> {
2649 fn fill_buf(&mut self) -> Result<&[u8]> {
2650 // Don't call into inner reader at all at EOF because it may still block
2651 if self.limit == 0 {
2655 let buf = self.inner.fill_buf()?;
2656 let cap = cmp::min(buf.len() as u64, self.limit) as usize;
2660 fn consume(&mut self, amt: usize) {
2661 // Don't let callers reset the limit by passing an overlarge value
2662 let amt = cmp::min(amt as u64, self.limit) as usize;
2663 self.limit -= amt as u64;
2664 self.inner.consume(amt);
2668 impl<T> SizeHint for Take<T> {
2670 fn lower_bound(&self) -> usize {
2671 cmp::min(SizeHint::lower_bound(&self.inner) as u64, self.limit) as usize
2675 fn upper_bound(&self) -> Option<usize> {
2676 match SizeHint::upper_bound(&self.inner) {
2677 Some(upper_bound) => Some(cmp::min(upper_bound as u64, self.limit) as usize),
2678 None => self.limit.try_into().ok(),
2683 /// An iterator over `u8` values of a reader.
2685 /// This struct is generally created by calling [`bytes`] on a reader.
2686 /// Please see the documentation of [`bytes`] for more details.
2688 /// [`bytes`]: Read::bytes
2689 #[stable(feature = "rust1", since = "1.0.0")]
2691 pub struct Bytes<R> {
2695 #[stable(feature = "rust1", since = "1.0.0")]
2696 impl<R: Read> Iterator for Bytes<R> {
2697 type Item = Result<u8>;
2699 fn next(&mut self) -> Option<Result<u8>> {
2702 return match self.inner.read(slice::from_mut(&mut byte)) {
2704 Ok(..) => Some(Ok(byte)),
2705 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
2706 Err(e) => Some(Err(e)),
2711 fn size_hint(&self) -> (usize, Option<usize>) {
2712 SizeHint::size_hint(&self.inner)
2717 fn lower_bound(&self) -> usize;
2719 fn upper_bound(&self) -> Option<usize>;
2721 fn size_hint(&self) -> (usize, Option<usize>) {
2722 (self.lower_bound(), self.upper_bound())
2726 impl<T> SizeHint for T {
2728 default fn lower_bound(&self) -> usize {
2733 default fn upper_bound(&self) -> Option<usize> {
2738 impl<T> SizeHint for &mut T {
2740 fn lower_bound(&self) -> usize {
2741 SizeHint::lower_bound(*self)
2745 fn upper_bound(&self) -> Option<usize> {
2746 SizeHint::upper_bound(*self)
2750 impl<T> SizeHint for Box<T> {
2752 fn lower_bound(&self) -> usize {
2753 SizeHint::lower_bound(&**self)
2757 fn upper_bound(&self) -> Option<usize> {
2758 SizeHint::upper_bound(&**self)
2762 impl SizeHint for &[u8] {
2764 fn lower_bound(&self) -> usize {
2769 fn upper_bound(&self) -> Option<usize> {
2774 /// An iterator over the contents of an instance of `BufRead` split on a
2775 /// particular byte.
2777 /// This struct is generally created by calling [`split`] on a `BufRead`.
2778 /// Please see the documentation of [`split`] for more details.
2780 /// [`split`]: BufRead::split
2781 #[stable(feature = "rust1", since = "1.0.0")]
2783 pub struct Split<B> {
2788 #[stable(feature = "rust1", since = "1.0.0")]
2789 impl<B: BufRead> Iterator for Split<B> {
2790 type Item = Result<Vec<u8>>;
2792 fn next(&mut self) -> Option<Result<Vec<u8>>> {
2793 let mut buf = Vec::new();
2794 match self.buf.read_until(self.delim, &mut buf) {
2797 if buf[buf.len() - 1] == self.delim {
2802 Err(e) => Some(Err(e)),
2807 /// An iterator over the lines of an instance of `BufRead`.
2809 /// This struct is generally created by calling [`lines`] on a `BufRead`.
2810 /// Please see the documentation of [`lines`] for more details.
2812 /// [`lines`]: BufRead::lines
2813 #[stable(feature = "rust1", since = "1.0.0")]
2815 pub struct Lines<B> {
2819 #[stable(feature = "rust1", since = "1.0.0")]
2820 impl<B: BufRead> Iterator for Lines<B> {
2821 type Item = Result<String>;
2823 fn next(&mut self) -> Option<Result<String>> {
2824 let mut buf = String::new();
2825 match self.buf.read_line(&mut buf) {
2828 if buf.ends_with('\n') {
2830 if buf.ends_with('\r') {
2836 Err(e) => Some(Err(e)),