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 = "rust1", since = "1.0.0")]
265 pub use self::buffered::IntoInnerError;
266 #[stable(feature = "bufwriter_into_parts", since = "1.56.0")]
267 pub use self::buffered::WriterPanicked;
268 #[stable(feature = "rust1", since = "1.0.0")]
269 pub use self::buffered::{BufReader, BufWriter, LineWriter};
270 #[stable(feature = "rust1", since = "1.0.0")]
271 pub use self::copy::copy;
272 #[stable(feature = "rust1", since = "1.0.0")]
273 pub use self::cursor::Cursor;
274 #[stable(feature = "rust1", since = "1.0.0")]
275 pub use self::error::{Error, ErrorKind, Result};
276 #[unstable(feature = "internal_output_capture", issue = "none")]
277 #[doc(no_inline, hidden)]
278 pub use self::stdio::set_output_capture;
279 #[stable(feature = "rust1", since = "1.0.0")]
280 pub use self::stdio::{stderr, stdin, stdout, Stderr, Stdin, Stdout};
281 #[unstable(feature = "stdio_locked", issue = "86845")]
282 pub use self::stdio::{stderr_locked, stdin_locked, stdout_locked};
283 #[stable(feature = "rust1", since = "1.0.0")]
284 pub use self::stdio::{StderrLock, StdinLock, StdoutLock};
285 #[unstable(feature = "print_internals", issue = "none")]
286 pub use self::stdio::{_eprint, _print};
287 #[stable(feature = "rust1", since = "1.0.0")]
288 pub use self::util::{empty, repeat, sink, Empty, Repeat, Sink};
290 #[unstable(feature = "read_buf", issue = "78485")]
291 pub use self::readbuf::ReadBuf;
303 const DEFAULT_BUF_SIZE: usize = crate::sys_common::io::DEFAULT_BUF_SIZE;
305 pub(crate) use stdio::cleanup;
308 buf: &'a mut Vec<u8>,
312 impl Drop for Guard<'_> {
315 self.buf.set_len(self.len);
320 // Several `read_to_string` and `read_line` methods in the standard library will
321 // append data into a `String` buffer, but we need to be pretty careful when
322 // doing this. The implementation will just call `.as_mut_vec()` and then
323 // delegate to a byte-oriented reading method, but we must ensure that when
324 // returning we never leave `buf` in a state such that it contains invalid UTF-8
327 // To this end, we use an RAII guard (to protect against panics) which updates
328 // the length of the string when it is dropped. This guard initially truncates
329 // the string to the prior length and only after we've validated that the
330 // new contents are valid UTF-8 do we allow it to set a longer length.
332 // The unsafety in this function is twofold:
334 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
336 // 2. We're passing a raw buffer to the function `f`, and it is expected that
337 // the function only *appends* bytes to the buffer. We'll get undefined
338 // behavior if existing bytes are overwritten to have non-UTF-8 data.
339 pub(crate) unsafe fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
341 F: FnOnce(&mut Vec<u8>) -> Result<usize>,
343 let mut g = Guard { len: buf.len(), buf: buf.as_mut_vec() };
345 if str::from_utf8(&g.buf[g.len..]).is_err() {
347 Err(Error::new_const(ErrorKind::InvalidData, &"stream did not contain valid UTF-8"))
355 // This uses an adaptive system to extend the vector when it fills. We want to
356 // avoid paying to allocate and zero a huge chunk of memory if the reader only
357 // has 4 bytes while still making large reads if the reader does have a ton
358 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
359 // time is 4,500 times (!) slower than a default reservation size of 32 if the
360 // reader has a very small amount of data to return.
361 pub(crate) fn default_read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
362 let start_len = buf.len();
363 let start_cap = buf.capacity();
365 let mut initialized = 0; // Extra initialized bytes from previous loop iteration
367 if buf.len() == buf.capacity() {
368 buf.reserve(32); // buf is full, need more space
371 let mut read_buf = ReadBuf::uninit(buf.spare_capacity_mut());
373 // SAFETY: These bytes were initialized but not filled in the previous loop
375 read_buf.assume_init(initialized);
378 match r.read_buf(&mut read_buf) {
380 Err(e) if e.kind() == ErrorKind::Interrupted => continue,
381 Err(e) => return Err(e),
384 if read_buf.filled_len() == 0 {
385 return Ok(buf.len() - start_len);
388 // store how much was initialized but not filled
389 initialized = read_buf.initialized_len() - read_buf.filled_len();
390 let new_len = read_buf.filled_len() + buf.len();
392 // SAFETY: ReadBuf's invariants mean this much memory is init
394 buf.set_len(new_len);
397 if buf.len() == buf.capacity() && buf.capacity() == start_cap {
398 // The buffer might be an exact fit. Let's read into a probe buffer
399 // and see if it returns `Ok(0)`. If so, we've avoided an
400 // unnecessary doubling of the capacity. But if not, append the
401 // probe buffer to the primary buffer and let its capacity grow.
402 let mut probe = [0u8; 32];
405 match r.read(&mut probe) {
406 Ok(0) => return Ok(buf.len() - start_len),
408 buf.extend_from_slice(&probe[..n]);
411 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
412 Err(e) => return Err(e),
419 pub(crate) fn default_read_to_string<R: Read + ?Sized>(
423 // Note that we do *not* call `r.read_to_end()` here. We are passing
424 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
425 // method to fill it up. An arbitrary implementation could overwrite the
426 // entire contents of the vector, not just append to it (which is what
427 // we are expecting).
429 // To prevent extraneously checking the UTF-8-ness of the entire buffer
430 // we pass it to our hardcoded `default_read_to_end` implementation which
431 // we know is guaranteed to only read data into the end of the buffer.
432 unsafe { append_to_string(buf, |b| default_read_to_end(r, b)) }
435 pub(crate) fn default_read_vectored<F>(read: F, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
437 F: FnOnce(&mut [u8]) -> Result<usize>,
439 let buf = bufs.iter_mut().find(|b| !b.is_empty()).map_or(&mut [][..], |b| &mut **b);
443 pub(crate) fn default_write_vectored<F>(write: F, bufs: &[IoSlice<'_>]) -> Result<usize>
445 F: FnOnce(&[u8]) -> Result<usize>,
447 let buf = bufs.iter().find(|b| !b.is_empty()).map_or(&[][..], |b| &**b);
451 pub(crate) fn default_read_exact<R: Read + ?Sized>(this: &mut R, mut buf: &mut [u8]) -> Result<()> {
452 while !buf.is_empty() {
453 match this.read(buf) {
459 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
460 Err(e) => return Err(e),
464 Err(Error::new_const(ErrorKind::UnexpectedEof, &"failed to fill whole buffer"))
470 pub(crate) fn default_read_buf<F>(read: F, buf: &mut ReadBuf<'_>) -> Result<()>
472 F: FnOnce(&mut [u8]) -> Result<usize>,
474 let n = read(buf.initialize_unfilled())?;
479 /// The `Read` trait allows for reading bytes from a source.
481 /// Implementors of the `Read` trait are called 'readers'.
483 /// Readers are defined by one required method, [`read()`]. Each call to [`read()`]
484 /// will attempt to pull bytes from this source into a provided buffer. A
485 /// number of other methods are implemented in terms of [`read()`], giving
486 /// implementors a number of ways to read bytes while only needing to implement
489 /// Readers are intended to be composable with one another. Many implementors
490 /// throughout [`std::io`] take and provide types which implement the `Read`
493 /// Please note that each call to [`read()`] may involve a system call, and
494 /// therefore, using something that implements [`BufRead`], such as
495 /// [`BufReader`], will be more efficient.
499 /// [`File`]s implement `Read`:
503 /// use std::io::prelude::*;
504 /// use std::fs::File;
506 /// fn main() -> io::Result<()> {
507 /// let mut f = File::open("foo.txt")?;
508 /// let mut buffer = [0; 10];
510 /// // read up to 10 bytes
511 /// f.read(&mut buffer)?;
513 /// let mut buffer = Vec::new();
514 /// // read the whole file
515 /// f.read_to_end(&mut buffer)?;
517 /// // read into a String, so that you don't need to do the conversion.
518 /// let mut buffer = String::new();
519 /// f.read_to_string(&mut buffer)?;
521 /// // and more! See the other methods for more details.
526 /// Read from [`&str`] because [`&[u8]`][prim@slice] implements `Read`:
530 /// use std::io::prelude::*;
532 /// fn main() -> io::Result<()> {
533 /// let mut b = "This string will be read".as_bytes();
534 /// let mut buffer = [0; 10];
536 /// // read up to 10 bytes
537 /// b.read(&mut buffer)?;
539 /// // etc... it works exactly as a File does!
544 /// [`read()`]: Read::read
545 /// [`&str`]: prim@str
546 /// [`std::io`]: self
547 /// [`File`]: crate::fs::File
548 #[stable(feature = "rust1", since = "1.0.0")]
549 #[doc(notable_trait)]
550 #[cfg_attr(not(test), rustc_diagnostic_item = "IoRead")]
552 /// Pull some bytes from this source into the specified buffer, returning
553 /// how many bytes were read.
555 /// This function does not provide any guarantees about whether it blocks
556 /// waiting for data, but if an object needs to block for a read and cannot,
557 /// it will typically signal this via an [`Err`] return value.
559 /// If the return value of this method is [`Ok(n)`], then implementations must
560 /// guarantee that `0 <= n <= buf.len()`. A nonzero `n` value indicates
561 /// that the buffer `buf` has been filled in with `n` bytes of data from this
562 /// source. If `n` is `0`, then it can indicate one of two scenarios:
564 /// 1. This reader has reached its "end of file" and will likely no longer
565 /// be able to produce bytes. Note that this does not mean that the
566 /// reader will *always* no longer be able to produce bytes. As an example,
567 /// on Linux, this method will call the `recv` syscall for a [`TcpStream`],
568 /// where returning zero indicates the connection was shut down correctly. While
569 /// for [`File`], it is possible to reach the end of file and get zero as result,
570 /// but if more data is appended to the file, future calls to `read` will return
572 /// 2. The buffer specified was 0 bytes in length.
574 /// It is not an error if the returned value `n` is smaller than the buffer size,
575 /// even when the reader is not at the end of the stream yet.
576 /// This may happen for example because fewer bytes are actually available right now
577 /// (e. g. being close to end-of-file) or because read() was interrupted by a signal.
579 /// As this trait is safe to implement, callers cannot rely on `n <= buf.len()` for safety.
580 /// Extra care needs to be taken when `unsafe` functions are used to access the read bytes.
581 /// Callers have to ensure that no unchecked out-of-bounds accesses are possible even if
584 /// No guarantees are provided about the contents of `buf` when this
585 /// function is called, implementations cannot rely on any property of the
586 /// contents of `buf` being true. It is recommended that *implementations*
587 /// only write data to `buf` instead of reading its contents.
589 /// Correspondingly, however, *callers* of this method must not assume any guarantees
590 /// about how the implementation uses `buf`. The trait is safe to implement,
591 /// so it is possible that the code that's supposed to write to the buffer might also read
592 /// from it. It is your responsibility to make sure that `buf` is initialized
593 /// before calling `read`. Calling `read` with an uninitialized `buf` (of the kind one
594 /// obtains via [`MaybeUninit<T>`]) is not safe, and can lead to undefined behavior.
596 /// [`MaybeUninit<T>`]: crate::mem::MaybeUninit
600 /// If this function encounters any form of I/O or other error, an error
601 /// variant will be returned. If an error is returned then it must be
602 /// guaranteed that no bytes were read.
604 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
605 /// operation should be retried if there is nothing else to do.
609 /// [`File`]s implement `Read`:
612 /// [`File`]: crate::fs::File
613 /// [`TcpStream`]: crate::net::TcpStream
617 /// use std::io::prelude::*;
618 /// use std::fs::File;
620 /// fn main() -> io::Result<()> {
621 /// let mut f = File::open("foo.txt")?;
622 /// let mut buffer = [0; 10];
624 /// // read up to 10 bytes
625 /// let n = f.read(&mut buffer[..])?;
627 /// println!("The bytes: {:?}", &buffer[..n]);
631 #[stable(feature = "rust1", since = "1.0.0")]
632 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
634 /// Like `read`, except that it reads into a slice of buffers.
636 /// Data is copied to fill each buffer in order, with the final buffer
637 /// written to possibly being only partially filled. This method must
638 /// behave equivalently to a single call to `read` with concatenated
641 /// The default implementation calls `read` with either the first nonempty
642 /// buffer provided, or an empty one if none exists.
643 #[stable(feature = "iovec", since = "1.36.0")]
644 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
645 default_read_vectored(|b| self.read(b), bufs)
648 /// Determines if this `Read`er has an efficient `read_vectored`
651 /// If a `Read`er does not override the default `read_vectored`
652 /// implementation, code using it may want to avoid the method all together
653 /// and coalesce writes into a single buffer for higher performance.
655 /// The default implementation returns `false`.
656 #[unstable(feature = "can_vector", issue = "69941")]
657 fn is_read_vectored(&self) -> bool {
661 /// Read all bytes until EOF in this source, placing them into `buf`.
663 /// All bytes read from this source will be appended to the specified buffer
664 /// `buf`. This function will continuously call [`read()`] to append more data to
665 /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of
666 /// non-[`ErrorKind::Interrupted`] kind.
668 /// If successful, this function will return the total number of bytes read.
672 /// If this function encounters an error of the kind
673 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
676 /// If any other read error is encountered then this function immediately
677 /// returns. Any bytes which have already been read will be appended to
682 /// [`File`]s implement `Read`:
684 /// [`read()`]: Read::read
686 /// [`File`]: crate::fs::File
690 /// use std::io::prelude::*;
691 /// use std::fs::File;
693 /// fn main() -> io::Result<()> {
694 /// let mut f = File::open("foo.txt")?;
695 /// let mut buffer = Vec::new();
697 /// // read the whole file
698 /// f.read_to_end(&mut buffer)?;
703 /// (See also the [`std::fs::read`] convenience function for reading from a
706 /// [`std::fs::read`]: crate::fs::read
707 #[stable(feature = "rust1", since = "1.0.0")]
708 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
709 default_read_to_end(self, buf)
712 /// Read all bytes until EOF in this source, appending them to `buf`.
714 /// If successful, this function returns the number of bytes which were read
715 /// and appended to `buf`.
719 /// If the data in this stream is *not* valid UTF-8 then an error is
720 /// returned and `buf` is unchanged.
722 /// See [`read_to_end`] for other error semantics.
724 /// [`read_to_end`]: Read::read_to_end
728 /// [`File`]s implement `Read`:
730 /// [`File`]: crate::fs::File
734 /// use std::io::prelude::*;
735 /// use std::fs::File;
737 /// fn main() -> io::Result<()> {
738 /// let mut f = File::open("foo.txt")?;
739 /// let mut buffer = String::new();
741 /// f.read_to_string(&mut buffer)?;
746 /// (See also the [`std::fs::read_to_string`] convenience function for
747 /// reading from a file.)
749 /// [`std::fs::read_to_string`]: crate::fs::read_to_string
750 #[stable(feature = "rust1", since = "1.0.0")]
751 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
752 default_read_to_string(self, buf)
755 /// Read the exact number of bytes required to fill `buf`.
757 /// This function reads as many bytes as necessary to completely fill the
758 /// specified buffer `buf`.
760 /// No guarantees are provided about the contents of `buf` when this
761 /// function is called, implementations cannot rely on any property of the
762 /// contents of `buf` being true. It is recommended that implementations
763 /// only write data to `buf` instead of reading its contents. The
764 /// documentation on [`read`] has a more detailed explanation on this
769 /// If this function encounters an error of the kind
770 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
773 /// If this function encounters an "end of file" before completely filling
774 /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
775 /// The contents of `buf` are unspecified in this case.
777 /// If any other read error is encountered then this function immediately
778 /// returns. The contents of `buf` are unspecified in this case.
780 /// If this function returns an error, it is unspecified how many bytes it
781 /// has read, but it will never read more than would be necessary to
782 /// completely fill the buffer.
786 /// [`File`]s implement `Read`:
788 /// [`read`]: Read::read
789 /// [`File`]: crate::fs::File
793 /// use std::io::prelude::*;
794 /// use std::fs::File;
796 /// fn main() -> io::Result<()> {
797 /// let mut f = File::open("foo.txt")?;
798 /// let mut buffer = [0; 10];
800 /// // read exactly 10 bytes
801 /// f.read_exact(&mut buffer)?;
805 #[stable(feature = "read_exact", since = "1.6.0")]
806 fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
807 default_read_exact(self, buf)
810 /// Pull some bytes from this source into the specified buffer.
812 /// This is equivalent to the [`read`](Read::read) method, except that it is passed a [`ReadBuf`] rather than `[u8]` to allow use
813 /// with uninitialized buffers. The new data will be appended to any existing contents of `buf`.
815 /// The default implementation delegates to `read`.
816 #[unstable(feature = "read_buf", issue = "78485")]
817 fn read_buf(&mut self, buf: &mut ReadBuf<'_>) -> Result<()> {
818 default_read_buf(|b| self.read(b), buf)
821 /// Read the exact number of bytes required to fill `buf`.
823 /// This is equivalent to the [`read_exact`](Read::read_exact) method, except that it is passed a [`ReadBuf`] rather than `[u8]` to
824 /// allow use with uninitialized buffers.
825 #[unstable(feature = "read_buf", issue = "78485")]
826 fn read_buf_exact(&mut self, buf: &mut ReadBuf<'_>) -> Result<()> {
827 while buf.remaining() > 0 {
828 let prev_filled = buf.filled().len();
829 match self.read_buf(buf) {
831 Err(e) if e.kind() == ErrorKind::Interrupted => continue,
832 Err(e) => return Err(e),
835 if buf.filled().len() == prev_filled {
836 return Err(Error::new(ErrorKind::UnexpectedEof, "failed to fill buffer"));
843 /// Creates a "by reference" adaptor for this instance of `Read`.
845 /// The returned adapter also implements `Read` and will simply borrow this
850 /// [`File`]s implement `Read`:
852 /// [`File`]: crate::fs::File
856 /// use std::io::Read;
857 /// use std::fs::File;
859 /// fn main() -> io::Result<()> {
860 /// let mut f = File::open("foo.txt")?;
861 /// let mut buffer = Vec::new();
862 /// let mut other_buffer = Vec::new();
865 /// let reference = f.by_ref();
867 /// // read at most 5 bytes
868 /// reference.take(5).read_to_end(&mut buffer)?;
870 /// } // drop our &mut reference so we can use f again
872 /// // original file still usable, read the rest
873 /// f.read_to_end(&mut other_buffer)?;
877 #[stable(feature = "rust1", since = "1.0.0")]
878 fn by_ref(&mut self) -> &mut Self
885 /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
887 /// The returned type implements [`Iterator`] where the [`Item`] is
888 /// <code>[Result]<[u8], [io::Error]></code>.
889 /// The yielded item is [`Ok`] if a byte was successfully read and [`Err`]
890 /// otherwise. EOF is mapped to returning [`None`] from this iterator.
894 /// [`File`]s implement `Read`:
896 /// [`Item`]: Iterator::Item
897 /// [`File`]: crate::fs::File "fs::File"
898 /// [Result]: crate::result::Result "Result"
899 /// [io::Error]: self::Error "io::Error"
903 /// use std::io::prelude::*;
904 /// use std::fs::File;
906 /// fn main() -> io::Result<()> {
907 /// let mut f = File::open("foo.txt")?;
909 /// for byte in f.bytes() {
910 /// println!("{}", byte.unwrap());
915 #[stable(feature = "rust1", since = "1.0.0")]
916 fn bytes(self) -> Bytes<Self>
920 Bytes { inner: self }
923 /// Creates an adapter which will chain this stream with another.
925 /// The returned `Read` instance will first read all bytes from this object
926 /// until EOF is encountered. Afterwards the output is equivalent to the
927 /// output of `next`.
931 /// [`File`]s implement `Read`:
933 /// [`File`]: crate::fs::File
937 /// use std::io::prelude::*;
938 /// use std::fs::File;
940 /// fn main() -> io::Result<()> {
941 /// let mut f1 = File::open("foo.txt")?;
942 /// let mut f2 = File::open("bar.txt")?;
944 /// let mut handle = f1.chain(f2);
945 /// let mut buffer = String::new();
947 /// // read the value into a String. We could use any Read method here,
948 /// // this is just one example.
949 /// handle.read_to_string(&mut buffer)?;
953 #[stable(feature = "rust1", since = "1.0.0")]
954 fn chain<R: Read>(self, next: R) -> Chain<Self, R>
958 Chain { first: self, second: next, done_first: false }
961 /// Creates an adapter which will read at most `limit` bytes from it.
963 /// This function returns a new instance of `Read` which will read at most
964 /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
965 /// read errors will not count towards the number of bytes read and future
966 /// calls to [`read()`] may succeed.
970 /// [`File`]s implement `Read`:
972 /// [`File`]: crate::fs::File
974 /// [`read()`]: Read::read
978 /// use std::io::prelude::*;
979 /// use std::fs::File;
981 /// fn main() -> io::Result<()> {
982 /// let mut f = File::open("foo.txt")?;
983 /// let mut buffer = [0; 5];
985 /// // read at most five bytes
986 /// let mut handle = f.take(5);
988 /// handle.read(&mut buffer)?;
992 #[stable(feature = "rust1", since = "1.0.0")]
993 fn take(self, limit: u64) -> Take<Self>
997 Take { inner: self, limit }
1001 /// Read all bytes from a [reader][Read] into a new [`String`].
1003 /// This is a convenience function for [`Read::read_to_string`]. Using this
1004 /// function avoids having to create a variable first and provides more type
1005 /// safety since you can only get the buffer out if there were no errors. (If you
1006 /// use [`Read::read_to_string`] you have to remember to check whether the read
1007 /// succeeded because otherwise your buffer will be empty or only partially full.)
1011 /// The downside of this function's increased ease of use and type safety is
1012 /// that it gives you less control over performance. For example, you can't
1013 /// pre-allocate memory like you can using [`String::with_capacity`] and
1014 /// [`Read::read_to_string`]. Also, you can't re-use the buffer if an error
1015 /// occurs while reading.
1017 /// In many cases, this function's performance will be adequate and the ease of use
1018 /// and type safety tradeoffs will be worth it. However, there are cases where you
1019 /// need more control over performance, and in those cases you should definitely use
1020 /// [`Read::read_to_string`] directly.
1022 /// Note that in some special cases, such as when reading files, this function will
1023 /// pre-allocate memory based on the size of the input it is reading. In those
1024 /// cases, the performance should be as good as if you had used
1025 /// [`Read::read_to_string`] with a manually pre-allocated buffer.
1029 /// This function forces you to handle errors because the output (the `String`)
1030 /// is wrapped in a [`Result`]. See [`Read::read_to_string`] for the errors
1031 /// that can occur. If any error occurs, you will get an [`Err`], so you
1032 /// don't have to worry about your buffer being empty or partially full.
1037 /// #![feature(io_read_to_string)]
1040 /// fn main() -> io::Result<()> {
1041 /// let stdin = io::read_to_string(&mut io::stdin())?;
1042 /// println!("Stdin was:");
1043 /// println!("{}", stdin);
1047 #[unstable(feature = "io_read_to_string", issue = "80218")]
1048 pub fn read_to_string<R: Read>(reader: &mut R) -> Result<String> {
1049 let mut buf = String::new();
1050 reader.read_to_string(&mut buf)?;
1054 /// A buffer type used with `Read::read_vectored`.
1056 /// It is semantically a wrapper around an `&mut [u8]`, but is guaranteed to be
1057 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
1059 #[stable(feature = "iovec", since = "1.36.0")]
1060 #[repr(transparent)]
1061 pub struct IoSliceMut<'a>(sys::io::IoSliceMut<'a>);
1063 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1064 unsafe impl<'a> Send for IoSliceMut<'a> {}
1066 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1067 unsafe impl<'a> Sync for IoSliceMut<'a> {}
1069 #[stable(feature = "iovec", since = "1.36.0")]
1070 impl<'a> fmt::Debug for IoSliceMut<'a> {
1071 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1072 fmt::Debug::fmt(self.0.as_slice(), fmt)
1076 impl<'a> IoSliceMut<'a> {
1077 /// Creates a new `IoSliceMut` wrapping a byte slice.
1081 /// Panics on Windows if the slice is larger than 4GB.
1082 #[stable(feature = "iovec", since = "1.36.0")]
1084 pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> {
1085 IoSliceMut(sys::io::IoSliceMut::new(buf))
1088 /// Advance the internal cursor of the slice.
1090 /// Also see [`IoSliceMut::advance_slices`] to advance the cursors of
1091 /// multiple buffers.
1096 /// #![feature(io_slice_advance)]
1098 /// use std::io::IoSliceMut;
1099 /// use std::ops::Deref;
1101 /// let mut data = [1; 8];
1102 /// let mut buf = IoSliceMut::new(&mut data);
1104 /// // Mark 3 bytes as read.
1106 /// assert_eq!(buf.deref(), [1; 5].as_ref());
1108 #[unstable(feature = "io_slice_advance", issue = "62726")]
1110 pub fn advance(&mut self, n: usize) {
1114 /// Advance the internal cursor of the slices.
1118 /// Elements in the slice may be modified if the cursor is not advanced to
1119 /// the end of the slice. For example if we have a slice of buffers with 2
1120 /// `IoSliceMut`s, both of length 8, and we advance the cursor by 10 bytes
1121 /// the first `IoSliceMut` will be untouched however the second will be
1122 /// modified to remove the first 2 bytes (10 - 8).
1127 /// #![feature(io_slice_advance)]
1129 /// use std::io::IoSliceMut;
1130 /// use std::ops::Deref;
1132 /// let mut buf1 = [1; 8];
1133 /// let mut buf2 = [2; 16];
1134 /// let mut buf3 = [3; 8];
1135 /// let mut bufs = &mut [
1136 /// IoSliceMut::new(&mut buf1),
1137 /// IoSliceMut::new(&mut buf2),
1138 /// IoSliceMut::new(&mut buf3),
1141 /// // Mark 10 bytes as read.
1142 /// IoSliceMut::advance_slices(&mut bufs, 10);
1143 /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1144 /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1146 #[unstable(feature = "io_slice_advance", issue = "62726")]
1148 pub fn advance_slices(bufs: &mut &mut [IoSliceMut<'a>], n: usize) {
1149 // Number of buffers to remove.
1151 // Total length of all the to be removed buffers.
1152 let mut accumulated_len = 0;
1153 for buf in bufs.iter() {
1154 if accumulated_len + buf.len() > n {
1157 accumulated_len += buf.len();
1162 *bufs = &mut replace(bufs, &mut [])[remove..];
1163 if !bufs.is_empty() {
1164 bufs[0].advance(n - accumulated_len)
1169 #[stable(feature = "iovec", since = "1.36.0")]
1170 impl<'a> Deref for IoSliceMut<'a> {
1174 fn deref(&self) -> &[u8] {
1179 #[stable(feature = "iovec", since = "1.36.0")]
1180 impl<'a> DerefMut for IoSliceMut<'a> {
1182 fn deref_mut(&mut self) -> &mut [u8] {
1183 self.0.as_mut_slice()
1187 /// A buffer type used with `Write::write_vectored`.
1189 /// It is semantically a wrapper around a `&[u8]`, but is guaranteed to be
1190 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
1192 #[stable(feature = "iovec", since = "1.36.0")]
1193 #[derive(Copy, Clone)]
1194 #[repr(transparent)]
1195 pub struct IoSlice<'a>(sys::io::IoSlice<'a>);
1197 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1198 unsafe impl<'a> Send for IoSlice<'a> {}
1200 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1201 unsafe impl<'a> Sync for IoSlice<'a> {}
1203 #[stable(feature = "iovec", since = "1.36.0")]
1204 impl<'a> fmt::Debug for IoSlice<'a> {
1205 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1206 fmt::Debug::fmt(self.0.as_slice(), fmt)
1210 impl<'a> IoSlice<'a> {
1211 /// Creates a new `IoSlice` wrapping a byte slice.
1215 /// Panics on Windows if the slice is larger than 4GB.
1216 #[stable(feature = "iovec", since = "1.36.0")]
1219 pub fn new(buf: &'a [u8]) -> IoSlice<'a> {
1220 IoSlice(sys::io::IoSlice::new(buf))
1223 /// Advance the internal cursor of the slice.
1225 /// Also see [`IoSlice::advance_slices`] to advance the cursors of multiple
1231 /// #![feature(io_slice_advance)]
1233 /// use std::io::IoSlice;
1234 /// use std::ops::Deref;
1236 /// let mut data = [1; 8];
1237 /// let mut buf = IoSlice::new(&mut data);
1239 /// // Mark 3 bytes as read.
1241 /// assert_eq!(buf.deref(), [1; 5].as_ref());
1243 #[unstable(feature = "io_slice_advance", issue = "62726")]
1245 pub fn advance(&mut self, n: usize) {
1249 /// Advance the internal cursor of the slices.
1253 /// Elements in the slice may be modified if the cursor is not advanced to
1254 /// the end of the slice. For example if we have a slice of buffers with 2
1255 /// `IoSlice`s, both of length 8, and we advance the cursor by 10 bytes the
1256 /// first `IoSlice` will be untouched however the second will be modified to
1257 /// remove the first 2 bytes (10 - 8).
1262 /// #![feature(io_slice_advance)]
1264 /// use std::io::IoSlice;
1265 /// use std::ops::Deref;
1267 /// let buf1 = [1; 8];
1268 /// let buf2 = [2; 16];
1269 /// let buf3 = [3; 8];
1270 /// let mut bufs = &mut [
1271 /// IoSlice::new(&buf1),
1272 /// IoSlice::new(&buf2),
1273 /// IoSlice::new(&buf3),
1276 /// // Mark 10 bytes as written.
1277 /// IoSlice::advance_slices(&mut bufs, 10);
1278 /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1279 /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1280 #[unstable(feature = "io_slice_advance", issue = "62726")]
1282 pub fn advance_slices(bufs: &mut &mut [IoSlice<'a>], n: usize) {
1283 // Number of buffers to remove.
1285 // Total length of all the to be removed buffers.
1286 let mut accumulated_len = 0;
1287 for buf in bufs.iter() {
1288 if accumulated_len + buf.len() > n {
1291 accumulated_len += buf.len();
1296 *bufs = &mut replace(bufs, &mut [])[remove..];
1297 if !bufs.is_empty() {
1298 bufs[0].advance(n - accumulated_len)
1303 #[stable(feature = "iovec", since = "1.36.0")]
1304 impl<'a> Deref for IoSlice<'a> {
1308 fn deref(&self) -> &[u8] {
1313 /// A trait for objects which are byte-oriented sinks.
1315 /// Implementors of the `Write` trait are sometimes called 'writers'.
1317 /// Writers are defined by two required methods, [`write`] and [`flush`]:
1319 /// * The [`write`] method will attempt to write some data into the object,
1320 /// returning how many bytes were successfully written.
1322 /// * The [`flush`] method is useful for adapters and explicit buffers
1323 /// themselves for ensuring that all buffered data has been pushed out to the
1326 /// Writers are intended to be composable with one another. Many implementors
1327 /// throughout [`std::io`] take and provide types which implement the `Write`
1330 /// [`write`]: Write::write
1331 /// [`flush`]: Write::flush
1332 /// [`std::io`]: self
1337 /// use std::io::prelude::*;
1338 /// use std::fs::File;
1340 /// fn main() -> std::io::Result<()> {
1341 /// let data = b"some bytes";
1343 /// let mut pos = 0;
1344 /// let mut buffer = File::create("foo.txt")?;
1346 /// while pos < data.len() {
1347 /// let bytes_written = buffer.write(&data[pos..])?;
1348 /// pos += bytes_written;
1354 /// The trait also provides convenience methods like [`write_all`], which calls
1355 /// `write` in a loop until its entire input has been written.
1357 /// [`write_all`]: Write::write_all
1358 #[stable(feature = "rust1", since = "1.0.0")]
1359 #[doc(notable_trait)]
1360 #[cfg_attr(not(test), rustc_diagnostic_item = "IoWrite")]
1362 /// Write a buffer into this writer, returning how many bytes were written.
1364 /// This function will attempt to write the entire contents of `buf`, but
1365 /// the entire write might not succeed, or the write may also generate an
1366 /// error. A call to `write` represents *at most one* attempt to write to
1367 /// any wrapped object.
1369 /// Calls to `write` are not guaranteed to block waiting for data to be
1370 /// written, and a write which would otherwise block can be indicated through
1371 /// an [`Err`] variant.
1373 /// If the return value is [`Ok(n)`] then it must be guaranteed that
1374 /// `n <= buf.len()`. A return value of `0` typically means that the
1375 /// underlying object is no longer able to accept bytes and will likely not
1376 /// be able to in the future as well, or that the buffer provided is empty.
1380 /// Each call to `write` may generate an I/O error indicating that the
1381 /// operation could not be completed. If an error is returned then no bytes
1382 /// in the buffer were written to this writer.
1384 /// It is **not** considered an error if the entire buffer could not be
1385 /// written to this writer.
1387 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the
1388 /// write operation should be retried if there is nothing else to do.
1393 /// use std::io::prelude::*;
1394 /// use std::fs::File;
1396 /// fn main() -> std::io::Result<()> {
1397 /// let mut buffer = File::create("foo.txt")?;
1399 /// // Writes some prefix of the byte string, not necessarily all of it.
1400 /// buffer.write(b"some bytes")?;
1406 #[stable(feature = "rust1", since = "1.0.0")]
1407 fn write(&mut self, buf: &[u8]) -> Result<usize>;
1409 /// Like [`write`], except that it writes from a slice of buffers.
1411 /// Data is copied from each buffer in order, with the final buffer
1412 /// read from possibly being only partially consumed. This method must
1413 /// behave as a call to [`write`] with the buffers concatenated would.
1415 /// The default implementation calls [`write`] with either the first nonempty
1416 /// buffer provided, or an empty one if none exists.
1421 /// use std::io::IoSlice;
1422 /// use std::io::prelude::*;
1423 /// use std::fs::File;
1425 /// fn main() -> std::io::Result<()> {
1426 /// let mut data1 = [1; 8];
1427 /// let mut data2 = [15; 8];
1428 /// let io_slice1 = IoSlice::new(&mut data1);
1429 /// let io_slice2 = IoSlice::new(&mut data2);
1431 /// let mut buffer = File::create("foo.txt")?;
1433 /// // Writes some prefix of the byte string, not necessarily all of it.
1434 /// buffer.write_vectored(&[io_slice1, io_slice2])?;
1439 /// [`write`]: Write::write
1440 #[stable(feature = "iovec", since = "1.36.0")]
1441 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize> {
1442 default_write_vectored(|b| self.write(b), bufs)
1445 /// Determines if this `Write`r has an efficient [`write_vectored`]
1448 /// If a `Write`r does not override the default [`write_vectored`]
1449 /// implementation, code using it may want to avoid the method all together
1450 /// and coalesce writes into a single buffer for higher performance.
1452 /// The default implementation returns `false`.
1454 /// [`write_vectored`]: Write::write_vectored
1455 #[unstable(feature = "can_vector", issue = "69941")]
1456 fn is_write_vectored(&self) -> bool {
1460 /// Flush this output stream, ensuring that all intermediately buffered
1461 /// contents reach their destination.
1465 /// It is considered an error if not all bytes could be written due to
1466 /// I/O errors or EOF being reached.
1471 /// use std::io::prelude::*;
1472 /// use std::io::BufWriter;
1473 /// use std::fs::File;
1475 /// fn main() -> std::io::Result<()> {
1476 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
1478 /// buffer.write_all(b"some bytes")?;
1479 /// buffer.flush()?;
1483 #[stable(feature = "rust1", since = "1.0.0")]
1484 fn flush(&mut self) -> Result<()>;
1486 /// Attempts to write an entire buffer into this writer.
1488 /// This method will continuously call [`write`] until there is no more data
1489 /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is
1490 /// returned. This method will not return until the entire buffer has been
1491 /// successfully written or such an error occurs. The first error that is
1492 /// not of [`ErrorKind::Interrupted`] kind generated from this method will be
1495 /// If the buffer contains no data, this will never call [`write`].
1499 /// This function will return the first error of
1500 /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns.
1502 /// [`write`]: Write::write
1507 /// use std::io::prelude::*;
1508 /// use std::fs::File;
1510 /// fn main() -> std::io::Result<()> {
1511 /// let mut buffer = File::create("foo.txt")?;
1513 /// buffer.write_all(b"some bytes")?;
1517 #[stable(feature = "rust1", since = "1.0.0")]
1518 fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
1519 while !buf.is_empty() {
1520 match self.write(buf) {
1522 return Err(Error::new_const(
1523 ErrorKind::WriteZero,
1524 &"failed to write whole buffer",
1527 Ok(n) => buf = &buf[n..],
1528 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1529 Err(e) => return Err(e),
1535 /// Attempts to write multiple buffers into this writer.
1537 /// This method will continuously call [`write_vectored`] until there is no
1538 /// more data to be written or an error of non-[`ErrorKind::Interrupted`]
1539 /// kind is returned. This method will not return until all buffers have
1540 /// been successfully written or such an error occurs. The first error that
1541 /// is not of [`ErrorKind::Interrupted`] kind generated from this method
1542 /// will be returned.
1544 /// If the buffer contains no data, this will never call [`write_vectored`].
1548 /// Unlike [`write_vectored`], this takes a *mutable* reference to
1549 /// a slice of [`IoSlice`]s, not an immutable one. That's because we need to
1550 /// modify the slice to keep track of the bytes already written.
1552 /// Once this function returns, the contents of `bufs` are unspecified, as
1553 /// this depends on how many calls to [`write_vectored`] were necessary. It is
1554 /// best to understand this function as taking ownership of `bufs` and to
1555 /// not use `bufs` afterwards. The underlying buffers, to which the
1556 /// [`IoSlice`]s point (but not the [`IoSlice`]s themselves), are unchanged and
1559 /// [`write_vectored`]: Write::write_vectored
1564 /// #![feature(write_all_vectored)]
1565 /// # fn main() -> std::io::Result<()> {
1567 /// use std::io::{Write, IoSlice};
1569 /// let mut writer = Vec::new();
1570 /// let bufs = &mut [
1571 /// IoSlice::new(&[1]),
1572 /// IoSlice::new(&[2, 3]),
1573 /// IoSlice::new(&[4, 5, 6]),
1576 /// writer.write_all_vectored(bufs)?;
1577 /// // Note: the contents of `bufs` is now undefined, see the Notes section.
1579 /// assert_eq!(writer, &[1, 2, 3, 4, 5, 6]);
1582 #[unstable(feature = "write_all_vectored", issue = "70436")]
1583 fn write_all_vectored(&mut self, mut bufs: &mut [IoSlice<'_>]) -> Result<()> {
1584 // Guarantee that bufs is empty if it contains no data,
1585 // to avoid calling write_vectored if there is no data to be written.
1586 IoSlice::advance_slices(&mut bufs, 0);
1587 while !bufs.is_empty() {
1588 match self.write_vectored(bufs) {
1590 return Err(Error::new_const(
1591 ErrorKind::WriteZero,
1592 &"failed to write whole buffer",
1595 Ok(n) => IoSlice::advance_slices(&mut bufs, n),
1596 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1597 Err(e) => return Err(e),
1603 /// Writes a formatted string into this writer, returning any error
1606 /// This method is primarily used to interface with the
1607 /// [`format_args!()`] macro, and it is rare that this should
1608 /// explicitly be called. The [`write!()`] macro should be favored to
1609 /// invoke this method instead.
1611 /// This function internally uses the [`write_all`] method on
1612 /// this trait and hence will continuously write data so long as no errors
1613 /// are received. This also means that partial writes are not indicated in
1616 /// [`write_all`]: Write::write_all
1620 /// This function will return any I/O error reported while formatting.
1625 /// use std::io::prelude::*;
1626 /// use std::fs::File;
1628 /// fn main() -> std::io::Result<()> {
1629 /// let mut buffer = File::create("foo.txt")?;
1632 /// write!(buffer, "{:.*}", 2, 1.234567)?;
1633 /// // turns into this:
1634 /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1638 #[stable(feature = "rust1", since = "1.0.0")]
1639 fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> Result<()> {
1640 // Create a shim which translates a Write to a fmt::Write and saves
1641 // off I/O errors. instead of discarding them
1642 struct Adapter<'a, T: ?Sized + 'a> {
1647 impl<T: Write + ?Sized> fmt::Write for Adapter<'_, T> {
1648 fn write_str(&mut self, s: &str) -> fmt::Result {
1649 match self.inner.write_all(s.as_bytes()) {
1652 self.error = Err(e);
1659 let mut output = Adapter { inner: self, error: Ok(()) };
1660 match fmt::write(&mut output, fmt) {
1663 // check if the error came from the underlying `Write` or not
1664 if output.error.is_err() {
1667 Err(Error::new_const(ErrorKind::Uncategorized, &"formatter error"))
1673 /// Creates a "by reference" adapter for this instance of `Write`.
1675 /// The returned adapter also implements `Write` and will simply borrow this
1681 /// use std::io::Write;
1682 /// use std::fs::File;
1684 /// fn main() -> std::io::Result<()> {
1685 /// let mut buffer = File::create("foo.txt")?;
1687 /// let reference = buffer.by_ref();
1689 /// // we can use reference just like our original buffer
1690 /// reference.write_all(b"some bytes")?;
1694 #[stable(feature = "rust1", since = "1.0.0")]
1695 fn by_ref(&mut self) -> &mut Self
1703 /// The `Seek` trait provides a cursor which can be moved within a stream of
1706 /// The stream typically has a fixed size, allowing seeking relative to either
1707 /// end or the current offset.
1711 /// [`File`]s implement `Seek`:
1713 /// [`File`]: crate::fs::File
1717 /// use std::io::prelude::*;
1718 /// use std::fs::File;
1719 /// use std::io::SeekFrom;
1721 /// fn main() -> io::Result<()> {
1722 /// let mut f = File::open("foo.txt")?;
1724 /// // move the cursor 42 bytes from the start of the file
1725 /// f.seek(SeekFrom::Start(42))?;
1729 #[stable(feature = "rust1", since = "1.0.0")]
1731 /// Seek to an offset, in bytes, in a stream.
1733 /// A seek beyond the end of a stream is allowed, but behavior is defined
1734 /// by the implementation.
1736 /// If the seek operation completed successfully,
1737 /// this method returns the new position from the start of the stream.
1738 /// That position can be used later with [`SeekFrom::Start`].
1742 /// Seeking can fail, for example because it might involve flushing a buffer.
1744 /// Seeking to a negative offset is considered an error.
1745 #[stable(feature = "rust1", since = "1.0.0")]
1746 fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1748 /// Rewind to the beginning of a stream.
1750 /// This is a convenience method, equivalent to `seek(SeekFrom::Start(0))`.
1754 /// Rewinding can fail, for example because it might involve flushing a buffer.
1759 /// use std::io::{Read, Seek, Write};
1760 /// use std::fs::OpenOptions;
1762 /// let mut f = OpenOptions::new()
1766 /// .open("foo.txt").unwrap();
1768 /// let hello = "Hello!\n";
1769 /// write!(f, "{}", hello).unwrap();
1770 /// f.rewind().unwrap();
1772 /// let mut buf = String::new();
1773 /// f.read_to_string(&mut buf).unwrap();
1774 /// assert_eq!(&buf, hello);
1776 #[stable(feature = "seek_rewind", since = "1.55.0")]
1777 fn rewind(&mut self) -> Result<()> {
1778 self.seek(SeekFrom::Start(0))?;
1782 /// Returns the length of this stream (in bytes).
1784 /// This method is implemented using up to three seek operations. If this
1785 /// method returns successfully, the seek position is unchanged (i.e. the
1786 /// position before calling this method is the same as afterwards).
1787 /// However, if this method returns an error, the seek position is
1790 /// If you need to obtain the length of *many* streams and you don't care
1791 /// about the seek position afterwards, you can reduce the number of seek
1792 /// operations by simply calling `seek(SeekFrom::End(0))` and using its
1793 /// return value (it is also the stream length).
1795 /// Note that length of a stream can change over time (for example, when
1796 /// data is appended to a file). So calling this method multiple times does
1797 /// not necessarily return the same length each time.
1802 /// #![feature(seek_stream_len)]
1804 /// io::{self, Seek},
1808 /// fn main() -> io::Result<()> {
1809 /// let mut f = File::open("foo.txt")?;
1811 /// let len = f.stream_len()?;
1812 /// println!("The file is currently {} bytes long", len);
1816 #[unstable(feature = "seek_stream_len", issue = "59359")]
1817 fn stream_len(&mut self) -> Result<u64> {
1818 let old_pos = self.stream_position()?;
1819 let len = self.seek(SeekFrom::End(0))?;
1821 // Avoid seeking a third time when we were already at the end of the
1822 // stream. The branch is usually way cheaper than a seek operation.
1824 self.seek(SeekFrom::Start(old_pos))?;
1830 /// Returns the current seek position from the start of the stream.
1832 /// This is equivalent to `self.seek(SeekFrom::Current(0))`.
1838 /// io::{self, BufRead, BufReader, Seek},
1842 /// fn main() -> io::Result<()> {
1843 /// let mut f = BufReader::new(File::open("foo.txt")?);
1845 /// let before = f.stream_position()?;
1846 /// f.read_line(&mut String::new())?;
1847 /// let after = f.stream_position()?;
1849 /// println!("The first line was {} bytes long", after - before);
1853 #[stable(feature = "seek_convenience", since = "1.51.0")]
1854 fn stream_position(&mut self) -> Result<u64> {
1855 self.seek(SeekFrom::Current(0))
1859 /// Enumeration of possible methods to seek within an I/O object.
1861 /// It is used by the [`Seek`] trait.
1862 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1863 #[stable(feature = "rust1", since = "1.0.0")]
1865 /// Sets the offset to the provided number of bytes.
1866 #[stable(feature = "rust1", since = "1.0.0")]
1867 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1869 /// Sets the offset to the size of this object plus the specified number of
1872 /// It is possible to seek beyond the end of an object, but it's an error to
1873 /// seek before byte 0.
1874 #[stable(feature = "rust1", since = "1.0.0")]
1875 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1877 /// Sets the offset to the current position plus the specified number of
1880 /// It is possible to seek beyond the end of an object, but it's an error to
1881 /// seek before byte 0.
1882 #[stable(feature = "rust1", since = "1.0.0")]
1883 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1886 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>) -> Result<usize> {
1889 let (done, used) = {
1890 let available = match r.fill_buf() {
1892 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1893 Err(e) => return Err(e),
1895 match memchr::memchr(delim, available) {
1897 buf.extend_from_slice(&available[..=i]);
1901 buf.extend_from_slice(available);
1902 (false, available.len())
1908 if done || used == 0 {
1914 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1915 /// to perform extra ways of reading.
1917 /// For example, reading line-by-line is inefficient without using a buffer, so
1918 /// if you want to read by line, you'll need `BufRead`, which includes a
1919 /// [`read_line`] method as well as a [`lines`] iterator.
1923 /// A locked standard input implements `BufRead`:
1927 /// use std::io::prelude::*;
1929 /// let stdin = io::stdin();
1930 /// for line in stdin.lock().lines() {
1931 /// println!("{}", line.unwrap());
1935 /// If you have something that implements [`Read`], you can use the [`BufReader`
1936 /// type][`BufReader`] to turn it into a `BufRead`.
1938 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1939 /// [`BufReader`] to the rescue!
1941 /// [`File`]: crate::fs::File
1942 /// [`read_line`]: BufRead::read_line
1943 /// [`lines`]: BufRead::lines
1946 /// use std::io::{self, BufReader};
1947 /// use std::io::prelude::*;
1948 /// use std::fs::File;
1950 /// fn main() -> io::Result<()> {
1951 /// let f = File::open("foo.txt")?;
1952 /// let f = BufReader::new(f);
1954 /// for line in f.lines() {
1955 /// println!("{}", line.unwrap());
1961 #[stable(feature = "rust1", since = "1.0.0")]
1962 pub trait BufRead: Read {
1963 /// Returns the contents of the internal buffer, filling it with more data
1964 /// from the inner reader if it is empty.
1966 /// This function is a lower-level call. It needs to be paired with the
1967 /// [`consume`] method to function properly. When calling this
1968 /// method, none of the contents will be "read" in the sense that later
1969 /// calling `read` may return the same contents. As such, [`consume`] must
1970 /// be called with the number of bytes that are consumed from this buffer to
1971 /// ensure that the bytes are never returned twice.
1973 /// [`consume`]: BufRead::consume
1975 /// An empty buffer returned indicates that the stream has reached EOF.
1979 /// This function will return an I/O error if the underlying reader was
1980 /// read, but returned an error.
1984 /// A locked standard input implements `BufRead`:
1988 /// use std::io::prelude::*;
1990 /// let stdin = io::stdin();
1991 /// let mut stdin = stdin.lock();
1993 /// let buffer = stdin.fill_buf().unwrap();
1995 /// // work with buffer
1996 /// println!("{:?}", buffer);
1998 /// // ensure the bytes we worked with aren't returned again later
1999 /// let length = buffer.len();
2000 /// stdin.consume(length);
2002 #[stable(feature = "rust1", since = "1.0.0")]
2003 fn fill_buf(&mut self) -> Result<&[u8]>;
2005 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
2006 /// so they should no longer be returned in calls to `read`.
2008 /// This function is a lower-level call. It needs to be paired with the
2009 /// [`fill_buf`] method to function properly. This function does
2010 /// not perform any I/O, it simply informs this object that some amount of
2011 /// its buffer, returned from [`fill_buf`], has been consumed and should
2012 /// no longer be returned. As such, this function may do odd things if
2013 /// [`fill_buf`] isn't called before calling it.
2015 /// The `amt` must be `<=` the number of bytes in the buffer returned by
2020 /// Since `consume()` is meant to be used with [`fill_buf`],
2021 /// that method's example includes an example of `consume()`.
2023 /// [`fill_buf`]: BufRead::fill_buf
2024 #[stable(feature = "rust1", since = "1.0.0")]
2025 fn consume(&mut self, amt: usize);
2027 /// Check if the underlying `Read` has any data left to be read.
2029 /// This function may fill the buffer to check for data,
2030 /// so this functions returns `Result<bool>`, not `bool`.
2032 /// Default implementation calls `fill_buf` and checks that
2033 /// returned slice is empty (which means that there is no data left,
2034 /// since EOF is reached).
2039 /// #![feature(buf_read_has_data_left)]
2041 /// use std::io::prelude::*;
2043 /// let stdin = io::stdin();
2044 /// let mut stdin = stdin.lock();
2046 /// while stdin.has_data_left().unwrap() {
2047 /// let mut line = String::new();
2048 /// stdin.read_line(&mut line).unwrap();
2049 /// // work with line
2050 /// println!("{:?}", line);
2053 #[unstable(feature = "buf_read_has_data_left", reason = "recently added", issue = "86423")]
2054 fn has_data_left(&mut self) -> Result<bool> {
2055 self.fill_buf().map(|b| !b.is_empty())
2058 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
2060 /// This function will read bytes from the underlying stream until the
2061 /// delimiter or EOF is found. Once found, all bytes up to, and including,
2062 /// the delimiter (if found) will be appended to `buf`.
2064 /// If successful, this function will return the total number of bytes read.
2066 /// This function is blocking and should be used carefully: it is possible for
2067 /// an attacker to continuously send bytes without ever sending the delimiter
2072 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
2073 /// will otherwise return any errors returned by [`fill_buf`].
2075 /// If an I/O error is encountered then all bytes read so far will be
2076 /// present in `buf` and its length will have been adjusted appropriately.
2078 /// [`fill_buf`]: BufRead::fill_buf
2082 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2083 /// this example, we use [`Cursor`] to read all the bytes in a byte slice
2084 /// in hyphen delimited segments:
2087 /// use std::io::{self, BufRead};
2089 /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
2090 /// let mut buf = vec![];
2092 /// // cursor is at 'l'
2093 /// let num_bytes = cursor.read_until(b'-', &mut buf)
2094 /// .expect("reading from cursor won't fail");
2095 /// assert_eq!(num_bytes, 6);
2096 /// assert_eq!(buf, b"lorem-");
2099 /// // cursor is at 'i'
2100 /// let num_bytes = cursor.read_until(b'-', &mut buf)
2101 /// .expect("reading from cursor won't fail");
2102 /// assert_eq!(num_bytes, 5);
2103 /// assert_eq!(buf, b"ipsum");
2106 /// // cursor is at EOF
2107 /// let num_bytes = cursor.read_until(b'-', &mut buf)
2108 /// .expect("reading from cursor won't fail");
2109 /// assert_eq!(num_bytes, 0);
2110 /// assert_eq!(buf, b"");
2112 #[stable(feature = "rust1", since = "1.0.0")]
2113 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
2114 read_until(self, byte, buf)
2117 /// Read all bytes until a newline (the `0xA` byte) is reached, and append
2118 /// them to the provided buffer.
2120 /// This function will read bytes from the underlying stream until the
2121 /// newline delimiter (the `0xA` byte) or EOF is found. Once found, all bytes
2122 /// up to, and including, the delimiter (if found) will be appended to
2125 /// If successful, this function will return the total number of bytes read.
2127 /// If this function returns [`Ok(0)`], the stream has reached EOF.
2129 /// This function is blocking and should be used carefully: it is possible for
2130 /// an attacker to continuously send bytes without ever sending a newline
2137 /// This function has the same error semantics as [`read_until`] and will
2138 /// also return an error if the read bytes are not valid UTF-8. If an I/O
2139 /// error is encountered then `buf` may contain some bytes already read in
2140 /// the event that all data read so far was valid UTF-8.
2142 /// [`read_until`]: BufRead::read_until
2146 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2147 /// this example, we use [`Cursor`] to read all the lines in a byte slice:
2150 /// use std::io::{self, BufRead};
2152 /// let mut cursor = io::Cursor::new(b"foo\nbar");
2153 /// let mut buf = String::new();
2155 /// // cursor is at 'f'
2156 /// let num_bytes = cursor.read_line(&mut buf)
2157 /// .expect("reading from cursor won't fail");
2158 /// assert_eq!(num_bytes, 4);
2159 /// assert_eq!(buf, "foo\n");
2162 /// // cursor is at 'b'
2163 /// let num_bytes = cursor.read_line(&mut buf)
2164 /// .expect("reading from cursor won't fail");
2165 /// assert_eq!(num_bytes, 3);
2166 /// assert_eq!(buf, "bar");
2169 /// // cursor is at EOF
2170 /// let num_bytes = cursor.read_line(&mut buf)
2171 /// .expect("reading from cursor won't fail");
2172 /// assert_eq!(num_bytes, 0);
2173 /// assert_eq!(buf, "");
2175 #[stable(feature = "rust1", since = "1.0.0")]
2176 fn read_line(&mut self, buf: &mut String) -> Result<usize> {
2177 // Note that we are not calling the `.read_until` method here, but
2178 // rather our hardcoded implementation. For more details as to why, see
2179 // the comments in `read_to_end`.
2180 unsafe { append_to_string(buf, |b| read_until(self, b'\n', b)) }
2183 /// Returns an iterator over the contents of this reader split on the byte
2186 /// The iterator returned from this function will return instances of
2187 /// <code>[io::Result]<[Vec]\<u8>></code>. Each vector returned will *not* have
2188 /// the delimiter byte at the end.
2190 /// This function will yield errors whenever [`read_until`] would have
2191 /// also yielded an error.
2193 /// [io::Result]: self::Result "io::Result"
2194 /// [`read_until`]: BufRead::read_until
2198 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2199 /// this example, we use [`Cursor`] to iterate over all hyphen delimited
2200 /// segments in a byte slice
2203 /// use std::io::{self, BufRead};
2205 /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
2207 /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
2208 /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
2209 /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
2210 /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
2211 /// assert_eq!(split_iter.next(), None);
2213 #[stable(feature = "rust1", since = "1.0.0")]
2214 fn split(self, byte: u8) -> Split<Self>
2218 Split { buf: self, delim: byte }
2221 /// Returns an iterator over the lines of this reader.
2223 /// The iterator returned from this function will yield instances of
2224 /// <code>[io::Result]<[String]></code>. Each string returned will *not* have a newline
2225 /// byte (the `0xA` byte) or `CRLF` (`0xD`, `0xA` bytes) at the end.
2227 /// [io::Result]: self::Result "io::Result"
2231 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2232 /// this example, we use [`Cursor`] to iterate over all the lines in a byte
2236 /// use std::io::{self, BufRead};
2238 /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
2240 /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
2241 /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
2242 /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
2243 /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
2244 /// assert_eq!(lines_iter.next(), None);
2249 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
2250 #[stable(feature = "rust1", since = "1.0.0")]
2251 fn lines(self) -> Lines<Self>
2259 /// Adapter to chain together two readers.
2261 /// This struct is generally created by calling [`chain`] on a reader.
2262 /// Please see the documentation of [`chain`] for more details.
2264 /// [`chain`]: Read::chain
2265 #[stable(feature = "rust1", since = "1.0.0")]
2267 pub struct Chain<T, U> {
2273 impl<T, U> Chain<T, U> {
2274 /// Consumes the `Chain`, returning the wrapped readers.
2280 /// use std::io::prelude::*;
2281 /// use std::fs::File;
2283 /// fn main() -> io::Result<()> {
2284 /// let mut foo_file = File::open("foo.txt")?;
2285 /// let mut bar_file = File::open("bar.txt")?;
2287 /// let chain = foo_file.chain(bar_file);
2288 /// let (foo_file, bar_file) = chain.into_inner();
2292 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2293 pub fn into_inner(self) -> (T, U) {
2294 (self.first, self.second)
2297 /// Gets references to the underlying readers in this `Chain`.
2303 /// use std::io::prelude::*;
2304 /// use std::fs::File;
2306 /// fn main() -> io::Result<()> {
2307 /// let mut foo_file = File::open("foo.txt")?;
2308 /// let mut bar_file = File::open("bar.txt")?;
2310 /// let chain = foo_file.chain(bar_file);
2311 /// let (foo_file, bar_file) = chain.get_ref();
2315 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2316 pub fn get_ref(&self) -> (&T, &U) {
2317 (&self.first, &self.second)
2320 /// Gets mutable references to the underlying readers in this `Chain`.
2322 /// Care should be taken to avoid modifying the internal I/O state of the
2323 /// underlying readers as doing so may corrupt the internal state of this
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 mut chain = foo_file.chain(bar_file);
2338 /// let (foo_file, bar_file) = chain.get_mut();
2342 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2343 pub fn get_mut(&mut self) -> (&mut T, &mut U) {
2344 (&mut self.first, &mut self.second)
2348 #[stable(feature = "rust1", since = "1.0.0")]
2349 impl<T: Read, U: Read> Read for Chain<T, U> {
2350 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2351 if !self.done_first {
2352 match self.first.read(buf)? {
2353 0 if !buf.is_empty() => self.done_first = true,
2357 self.second.read(buf)
2360 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
2361 if !self.done_first {
2362 match self.first.read_vectored(bufs)? {
2363 0 if bufs.iter().any(|b| !b.is_empty()) => self.done_first = true,
2367 self.second.read_vectored(bufs)
2371 #[stable(feature = "chain_bufread", since = "1.9.0")]
2372 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
2373 fn fill_buf(&mut self) -> Result<&[u8]> {
2374 if !self.done_first {
2375 match self.first.fill_buf()? {
2376 buf if buf.is_empty() => {
2377 self.done_first = true;
2379 buf => return Ok(buf),
2382 self.second.fill_buf()
2385 fn consume(&mut self, amt: usize) {
2386 if !self.done_first { self.first.consume(amt) } else { self.second.consume(amt) }
2390 impl<T, U> SizeHint for Chain<T, U> {
2392 fn lower_bound(&self) -> usize {
2393 SizeHint::lower_bound(&self.first) + SizeHint::lower_bound(&self.second)
2397 fn upper_bound(&self) -> Option<usize> {
2398 match (SizeHint::upper_bound(&self.first), SizeHint::upper_bound(&self.second)) {
2399 (Some(first), Some(second)) => first.checked_add(second),
2405 /// Reader adapter which limits the bytes read from an underlying reader.
2407 /// This struct is generally created by calling [`take`] on a reader.
2408 /// Please see the documentation of [`take`] for more details.
2410 /// [`take`]: Read::take
2411 #[stable(feature = "rust1", since = "1.0.0")]
2413 pub struct Take<T> {
2419 /// Returns the number of bytes that can be read before this instance will
2424 /// This instance may reach `EOF` after reading fewer bytes than indicated by
2425 /// this method if the underlying [`Read`] instance reaches EOF.
2431 /// use std::io::prelude::*;
2432 /// use std::fs::File;
2434 /// fn main() -> io::Result<()> {
2435 /// let f = File::open("foo.txt")?;
2437 /// // read at most five bytes
2438 /// let handle = f.take(5);
2440 /// println!("limit: {}", handle.limit());
2444 #[stable(feature = "rust1", since = "1.0.0")]
2445 pub fn limit(&self) -> u64 {
2449 /// Sets the number of bytes that can be read before this instance will
2450 /// return EOF. This is the same as constructing a new `Take` instance, so
2451 /// the amount of bytes read and the previous limit value don't matter when
2452 /// calling this method.
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 mut handle = f.take(5);
2466 /// handle.set_limit(10);
2468 /// assert_eq!(handle.limit(), 10);
2472 #[stable(feature = "take_set_limit", since = "1.27.0")]
2473 pub fn set_limit(&mut self, limit: u64) {
2477 /// Consumes the `Take`, returning the wrapped reader.
2483 /// use std::io::prelude::*;
2484 /// use std::fs::File;
2486 /// fn main() -> io::Result<()> {
2487 /// let mut file = File::open("foo.txt")?;
2489 /// let mut buffer = [0; 5];
2490 /// let mut handle = file.take(5);
2491 /// handle.read(&mut buffer)?;
2493 /// let file = handle.into_inner();
2497 #[stable(feature = "io_take_into_inner", since = "1.15.0")]
2498 pub fn into_inner(self) -> T {
2502 /// Gets a reference to the underlying reader.
2508 /// use std::io::prelude::*;
2509 /// use std::fs::File;
2511 /// fn main() -> io::Result<()> {
2512 /// let mut file = File::open("foo.txt")?;
2514 /// let mut buffer = [0; 5];
2515 /// let mut handle = file.take(5);
2516 /// handle.read(&mut buffer)?;
2518 /// let file = handle.get_ref();
2522 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2523 pub fn get_ref(&self) -> &T {
2527 /// Gets a mutable reference to the underlying reader.
2529 /// Care should be taken to avoid modifying the internal I/O state of the
2530 /// underlying reader as doing so may corrupt the internal limit of this
2537 /// use std::io::prelude::*;
2538 /// use std::fs::File;
2540 /// fn main() -> io::Result<()> {
2541 /// let mut file = File::open("foo.txt")?;
2543 /// let mut buffer = [0; 5];
2544 /// let mut handle = file.take(5);
2545 /// handle.read(&mut buffer)?;
2547 /// let file = handle.get_mut();
2551 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2552 pub fn get_mut(&mut self) -> &mut T {
2557 #[stable(feature = "rust1", since = "1.0.0")]
2558 impl<T: Read> Read for Take<T> {
2559 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2560 // Don't call into inner reader at all at EOF because it may still block
2561 if self.limit == 0 {
2565 let max = cmp::min(buf.len() as u64, self.limit) as usize;
2566 let n = self.inner.read(&mut buf[..max])?;
2567 self.limit -= n as u64;
2571 fn read_buf(&mut self, buf: &mut ReadBuf<'_>) -> Result<()> {
2572 // Don't call into inner reader at all at EOF because it may still block
2573 if self.limit == 0 {
2577 let prev_filled = buf.filled_len();
2579 if self.limit <= buf.remaining() as u64 {
2580 // if we just use an as cast to convert, limit may wrap around on a 32 bit target
2581 let limit = cmp::min(self.limit, usize::MAX as u64) as usize;
2583 let extra_init = cmp::min(limit as usize, buf.initialized_len() - buf.filled_len());
2585 // SAFETY: no uninit data is written to ibuf
2586 let ibuf = unsafe { &mut buf.unfilled_mut()[..limit] };
2588 let mut sliced_buf = ReadBuf::uninit(ibuf);
2590 // SAFETY: extra_init bytes of ibuf are known to be initialized
2592 sliced_buf.assume_init(extra_init);
2595 self.inner.read_buf(&mut sliced_buf)?;
2597 let new_init = sliced_buf.initialized_len();
2598 let filled = sliced_buf.filled_len();
2600 // sliced_buf / ibuf must drop here
2602 // SAFETY: new_init bytes of buf's unfilled buffer have been initialized
2604 buf.assume_init(new_init);
2607 buf.add_filled(filled);
2609 self.limit -= filled as u64;
2611 self.inner.read_buf(buf)?;
2614 self.limit -= buf.filled_len().saturating_sub(prev_filled) as u64;
2621 #[stable(feature = "rust1", since = "1.0.0")]
2622 impl<T: BufRead> BufRead for Take<T> {
2623 fn fill_buf(&mut self) -> Result<&[u8]> {
2624 // Don't call into inner reader at all at EOF because it may still block
2625 if self.limit == 0 {
2629 let buf = self.inner.fill_buf()?;
2630 let cap = cmp::min(buf.len() as u64, self.limit) as usize;
2634 fn consume(&mut self, amt: usize) {
2635 // Don't let callers reset the limit by passing an overlarge value
2636 let amt = cmp::min(amt as u64, self.limit) as usize;
2637 self.limit -= amt as u64;
2638 self.inner.consume(amt);
2642 impl<T> SizeHint for Take<T> {
2644 fn lower_bound(&self) -> usize {
2645 cmp::min(SizeHint::lower_bound(&self.inner) as u64, self.limit) as usize
2649 fn upper_bound(&self) -> Option<usize> {
2650 match SizeHint::upper_bound(&self.inner) {
2651 Some(upper_bound) => Some(cmp::min(upper_bound as u64, self.limit) as usize),
2652 None => self.limit.try_into().ok(),
2657 /// An iterator over `u8` values of a reader.
2659 /// This struct is generally created by calling [`bytes`] on a reader.
2660 /// Please see the documentation of [`bytes`] for more details.
2662 /// [`bytes`]: Read::bytes
2663 #[stable(feature = "rust1", since = "1.0.0")]
2665 pub struct Bytes<R> {
2669 #[stable(feature = "rust1", since = "1.0.0")]
2670 impl<R: Read> Iterator for Bytes<R> {
2671 type Item = Result<u8>;
2673 fn next(&mut self) -> Option<Result<u8>> {
2676 return match self.inner.read(slice::from_mut(&mut byte)) {
2678 Ok(..) => Some(Ok(byte)),
2679 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
2680 Err(e) => Some(Err(e)),
2685 fn size_hint(&self) -> (usize, Option<usize>) {
2686 SizeHint::size_hint(&self.inner)
2691 fn lower_bound(&self) -> usize;
2693 fn upper_bound(&self) -> Option<usize>;
2695 fn size_hint(&self) -> (usize, Option<usize>) {
2696 (self.lower_bound(), self.upper_bound())
2700 impl<T> SizeHint for T {
2702 default fn lower_bound(&self) -> usize {
2707 default fn upper_bound(&self) -> Option<usize> {
2712 impl<T> SizeHint for &mut T {
2714 fn lower_bound(&self) -> usize {
2715 SizeHint::lower_bound(*self)
2719 fn upper_bound(&self) -> Option<usize> {
2720 SizeHint::upper_bound(*self)
2724 impl<T> SizeHint for Box<T> {
2726 fn lower_bound(&self) -> usize {
2727 SizeHint::lower_bound(&**self)
2731 fn upper_bound(&self) -> Option<usize> {
2732 SizeHint::upper_bound(&**self)
2736 impl SizeHint for &[u8] {
2738 fn lower_bound(&self) -> usize {
2743 fn upper_bound(&self) -> Option<usize> {
2748 /// An iterator over the contents of an instance of `BufRead` split on a
2749 /// particular byte.
2751 /// This struct is generally created by calling [`split`] on a `BufRead`.
2752 /// Please see the documentation of [`split`] for more details.
2754 /// [`split`]: BufRead::split
2755 #[stable(feature = "rust1", since = "1.0.0")]
2757 pub struct Split<B> {
2762 #[stable(feature = "rust1", since = "1.0.0")]
2763 impl<B: BufRead> Iterator for Split<B> {
2764 type Item = Result<Vec<u8>>;
2766 fn next(&mut self) -> Option<Result<Vec<u8>>> {
2767 let mut buf = Vec::new();
2768 match self.buf.read_until(self.delim, &mut buf) {
2771 if buf[buf.len() - 1] == self.delim {
2776 Err(e) => Some(Err(e)),
2781 /// An iterator over the lines of an instance of `BufRead`.
2783 /// This struct is generally created by calling [`lines`] on a `BufRead`.
2784 /// Please see the documentation of [`lines`] for more details.
2786 /// [`lines`]: BufRead::lines
2787 #[stable(feature = "rust1", since = "1.0.0")]
2789 pub struct Lines<B> {
2793 #[stable(feature = "rust1", since = "1.0.0")]
2794 impl<B: BufRead> Iterator for Lines<B> {
2795 type Item = Result<String>;
2797 fn next(&mut self) -> Option<Result<String>> {
2798 let mut buf = String::new();
2799 match self.buf.read_line(&mut buf) {
2802 if buf.ends_with('\n') {
2804 if buf.ends_with('\r') {
2810 Err(e) => Some(Err(e)),