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 #[unstable(feature = "raw_os_error_ty", issue = "none")]
266 pub use self::error::RawOsError;
267 pub(crate) use self::stdio::attempt_print_to_stderr;
268 #[unstable(feature = "internal_output_capture", issue = "none")]
269 #[doc(no_inline, hidden)]
270 pub use self::stdio::set_output_capture;
271 #[unstable(feature = "is_terminal", issue = "98070")]
272 pub use self::stdio::IsTerminal;
273 #[unstable(feature = "print_internals", issue = "none")]
274 pub use self::stdio::{_eprint, _print};
275 #[stable(feature = "rust1", since = "1.0.0")]
277 buffered::{BufReader, BufWriter, IntoInnerError, LineWriter},
280 error::{Error, ErrorKind, Result},
281 stdio::{stderr, stdin, stdout, Stderr, StderrLock, Stdin, StdinLock, Stdout, StdoutLock},
282 util::{empty, repeat, sink, Empty, Repeat, Sink},
285 #[unstable(feature = "read_buf", issue = "78485")]
286 pub use self::readbuf::{BorrowedBuf, BorrowedCursor};
287 pub(crate) use error::const_io_error;
299 const DEFAULT_BUF_SIZE: usize = crate::sys_common::io::DEFAULT_BUF_SIZE;
301 pub(crate) use stdio::cleanup;
304 buf: &'a mut Vec<u8>,
308 impl Drop for Guard<'_> {
311 self.buf.set_len(self.len);
316 // Several `read_to_string` and `read_line` methods in the standard library will
317 // append data into a `String` buffer, but we need to be pretty careful when
318 // doing this. The implementation will just call `.as_mut_vec()` and then
319 // delegate to a byte-oriented reading method, but we must ensure that when
320 // returning we never leave `buf` in a state such that it contains invalid UTF-8
323 // To this end, we use an RAII guard (to protect against panics) which updates
324 // the length of the string when it is dropped. This guard initially truncates
325 // the string to the prior length and only after we've validated that the
326 // new contents are valid UTF-8 do we allow it to set a longer length.
328 // The unsafety in this function is twofold:
330 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
332 // 2. We're passing a raw buffer to the function `f`, and it is expected that
333 // the function only *appends* bytes to the buffer. We'll get undefined
334 // behavior if existing bytes are overwritten to have non-UTF-8 data.
335 pub(crate) unsafe fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
337 F: FnOnce(&mut Vec<u8>) -> Result<usize>,
339 let mut g = Guard { len: buf.len(), buf: buf.as_mut_vec() };
341 if str::from_utf8(&g.buf[g.len..]).is_err() {
343 Err(error::const_io_error!(
344 ErrorKind::InvalidData,
345 "stream did not contain valid UTF-8"
354 // This uses an adaptive system to extend the vector when it fills. We want to
355 // avoid paying to allocate and zero a huge chunk of memory if the reader only
356 // has 4 bytes while still making large reads if the reader does have a ton
357 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
358 // time is 4,500 times (!) slower than a default reservation size of 32 if the
359 // reader has a very small amount of data to return.
360 pub(crate) fn default_read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
361 let start_len = buf.len();
362 let start_cap = buf.capacity();
364 let mut initialized = 0; // Extra initialized bytes from previous loop iteration
366 if buf.len() == buf.capacity() {
367 buf.reserve(32); // buf is full, need more space
370 let mut read_buf: BorrowedBuf<'_> = buf.spare_capacity_mut().into();
372 // SAFETY: These bytes were initialized but not filled in the previous loop
374 read_buf.set_init(initialized);
377 let mut cursor = read_buf.unfilled();
378 match r.read_buf(cursor.reborrow()) {
380 Err(e) if e.kind() == ErrorKind::Interrupted => continue,
381 Err(e) => return Err(e),
384 if cursor.written() == 0 {
385 return Ok(buf.len() - start_len);
388 // store how much was initialized but not filled
389 initialized = cursor.init_ref().len();
391 // SAFETY: BorrowedBuf's invariants mean this much memory is initialized.
393 let new_len = read_buf.filled().len() + buf.len();
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::const_io_error!(ErrorKind::UnexpectedEof, "failed to fill whole buffer"))
470 pub(crate) fn default_read_buf<F>(read: F, mut cursor: BorrowedCursor<'_>) -> Result<()>
472 F: FnOnce(&mut [u8]) -> Result<usize>,
474 let n = read(cursor.ensure_init().init_mut())?;
476 // SAFETY: we initialised using `ensure_init` so there is no uninit data to advance to.
482 /// The `Read` trait allows for reading bytes from a source.
484 /// Implementors of the `Read` trait are called 'readers'.
486 /// Readers are defined by one required method, [`read()`]. Each call to [`read()`]
487 /// will attempt to pull bytes from this source into a provided buffer. A
488 /// number of other methods are implemented in terms of [`read()`], giving
489 /// implementors a number of ways to read bytes while only needing to implement
492 /// Readers are intended to be composable with one another. Many implementors
493 /// throughout [`std::io`] take and provide types which implement the `Read`
496 /// Please note that each call to [`read()`] may involve a system call, and
497 /// therefore, using something that implements [`BufRead`], such as
498 /// [`BufReader`], will be more efficient.
502 /// [`File`]s implement `Read`:
506 /// use std::io::prelude::*;
507 /// use std::fs::File;
509 /// fn main() -> io::Result<()> {
510 /// let mut f = File::open("foo.txt")?;
511 /// let mut buffer = [0; 10];
513 /// // read up to 10 bytes
514 /// f.read(&mut buffer)?;
516 /// let mut buffer = Vec::new();
517 /// // read the whole file
518 /// f.read_to_end(&mut buffer)?;
520 /// // read into a String, so that you don't need to do the conversion.
521 /// let mut buffer = String::new();
522 /// f.read_to_string(&mut buffer)?;
524 /// // and more! See the other methods for more details.
529 /// Read from [`&str`] because [`&[u8]`][prim@slice] implements `Read`:
533 /// use std::io::prelude::*;
535 /// fn main() -> io::Result<()> {
536 /// let mut b = "This string will be read".as_bytes();
537 /// let mut buffer = [0; 10];
539 /// // read up to 10 bytes
540 /// b.read(&mut buffer)?;
542 /// // etc... it works exactly as a File does!
547 /// [`read()`]: Read::read
548 /// [`&str`]: prim@str
549 /// [`std::io`]: self
550 /// [`File`]: crate::fs::File
551 #[stable(feature = "rust1", since = "1.0.0")]
552 #[doc(notable_trait)]
553 #[cfg_attr(not(test), rustc_diagnostic_item = "IoRead")]
555 /// Pull some bytes from this source into the specified buffer, returning
556 /// how many bytes were read.
558 /// This function does not provide any guarantees about whether it blocks
559 /// waiting for data, but if an object needs to block for a read and cannot,
560 /// it will typically signal this via an [`Err`] return value.
562 /// If the return value of this method is [`Ok(n)`], then implementations must
563 /// guarantee that `0 <= n <= buf.len()`. A nonzero `n` value indicates
564 /// that the buffer `buf` has been filled in with `n` bytes of data from this
565 /// source. If `n` is `0`, then it can indicate one of two scenarios:
567 /// 1. This reader has reached its "end of file" and will likely no longer
568 /// be able to produce bytes. Note that this does not mean that the
569 /// reader will *always* no longer be able to produce bytes. As an example,
570 /// on Linux, this method will call the `recv` syscall for a [`TcpStream`],
571 /// where returning zero indicates the connection was shut down correctly. While
572 /// for [`File`], it is possible to reach the end of file and get zero as result,
573 /// but if more data is appended to the file, future calls to `read` will return
575 /// 2. The buffer specified was 0 bytes in length.
577 /// It is not an error if the returned value `n` is smaller than the buffer size,
578 /// even when the reader is not at the end of the stream yet.
579 /// This may happen for example because fewer bytes are actually available right now
580 /// (e. g. being close to end-of-file) or because read() was interrupted by a signal.
582 /// As this trait is safe to implement, callers cannot rely on `n <= buf.len()` for safety.
583 /// Extra care needs to be taken when `unsafe` functions are used to access the read bytes.
584 /// Callers have to ensure that no unchecked out-of-bounds accesses are possible even if
587 /// No guarantees are provided about the contents of `buf` when this
588 /// function is called, so implementations cannot rely on any property of the
589 /// contents of `buf` being true. It is recommended that *implementations*
590 /// only write data to `buf` instead of reading its contents.
592 /// Correspondingly, however, *callers* of this method must not assume any guarantees
593 /// about how the implementation uses `buf`. The trait is safe to implement,
594 /// so it is possible that the code that's supposed to write to the buffer might also read
595 /// from it. It is your responsibility to make sure that `buf` is initialized
596 /// before calling `read`. Calling `read` with an uninitialized `buf` (of the kind one
597 /// obtains via [`MaybeUninit<T>`]) is not safe, and can lead to undefined behavior.
599 /// [`MaybeUninit<T>`]: crate::mem::MaybeUninit
603 /// If this function encounters any form of I/O or other error, an error
604 /// variant will be returned. If an error is returned then it must be
605 /// guaranteed that no bytes were read.
607 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
608 /// operation should be retried if there is nothing else to do.
612 /// [`File`]s implement `Read`:
615 /// [`File`]: crate::fs::File
616 /// [`TcpStream`]: crate::net::TcpStream
620 /// use std::io::prelude::*;
621 /// use std::fs::File;
623 /// fn main() -> io::Result<()> {
624 /// let mut f = File::open("foo.txt")?;
625 /// let mut buffer = [0; 10];
627 /// // read up to 10 bytes
628 /// let n = f.read(&mut buffer[..])?;
630 /// println!("The bytes: {:?}", &buffer[..n]);
634 #[stable(feature = "rust1", since = "1.0.0")]
635 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
637 /// Like `read`, except that it reads into a slice of buffers.
639 /// Data is copied to fill each buffer in order, with the final buffer
640 /// written to possibly being only partially filled. This method must
641 /// behave equivalently to a single call to `read` with concatenated
644 /// The default implementation calls `read` with either the first nonempty
645 /// buffer provided, or an empty one if none exists.
646 #[stable(feature = "iovec", since = "1.36.0")]
647 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
648 default_read_vectored(|b| self.read(b), bufs)
651 /// Determines if this `Read`er has an efficient `read_vectored`
654 /// If a `Read`er does not override the default `read_vectored`
655 /// implementation, code using it may want to avoid the method all together
656 /// and coalesce writes into a single buffer for higher performance.
658 /// The default implementation returns `false`.
659 #[unstable(feature = "can_vector", issue = "69941")]
660 fn is_read_vectored(&self) -> bool {
664 /// Read all bytes until EOF in this source, placing them into `buf`.
666 /// All bytes read from this source will be appended to the specified buffer
667 /// `buf`. This function will continuously call [`read()`] to append more data to
668 /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of
669 /// non-[`ErrorKind::Interrupted`] kind.
671 /// If successful, this function will return the total number of bytes read.
675 /// If this function encounters an error of the kind
676 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
679 /// If any other read error is encountered then this function immediately
680 /// returns. Any bytes which have already been read will be appended to
685 /// [`File`]s implement `Read`:
687 /// [`read()`]: Read::read
689 /// [`File`]: crate::fs::File
693 /// use std::io::prelude::*;
694 /// use std::fs::File;
696 /// fn main() -> io::Result<()> {
697 /// let mut f = File::open("foo.txt")?;
698 /// let mut buffer = Vec::new();
700 /// // read the whole file
701 /// f.read_to_end(&mut buffer)?;
706 /// (See also the [`std::fs::read`] convenience function for reading from a
709 /// [`std::fs::read`]: crate::fs::read
710 #[stable(feature = "rust1", since = "1.0.0")]
711 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
712 default_read_to_end(self, buf)
715 /// Read all bytes until EOF in this source, appending them to `buf`.
717 /// If successful, this function returns the number of bytes which were read
718 /// and appended to `buf`.
722 /// If the data in this stream is *not* valid UTF-8 then an error is
723 /// returned and `buf` is unchanged.
725 /// See [`read_to_end`] for other error semantics.
727 /// [`read_to_end`]: Read::read_to_end
731 /// [`File`]s implement `Read`:
733 /// [`File`]: crate::fs::File
737 /// use std::io::prelude::*;
738 /// use std::fs::File;
740 /// fn main() -> io::Result<()> {
741 /// let mut f = File::open("foo.txt")?;
742 /// let mut buffer = String::new();
744 /// f.read_to_string(&mut buffer)?;
749 /// (See also the [`std::fs::read_to_string`] convenience function for
750 /// reading from a file.)
752 /// [`std::fs::read_to_string`]: crate::fs::read_to_string
753 #[stable(feature = "rust1", since = "1.0.0")]
754 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
755 default_read_to_string(self, buf)
758 /// Read the exact number of bytes required to fill `buf`.
760 /// This function reads as many bytes as necessary to completely fill the
761 /// specified buffer `buf`.
763 /// No guarantees are provided about the contents of `buf` when this
764 /// function is called, so implementations cannot rely on any property of the
765 /// contents of `buf` being true. It is recommended that implementations
766 /// only write data to `buf` instead of reading its contents. The
767 /// documentation on [`read`] has a more detailed explanation on this
772 /// If this function encounters an error of the kind
773 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
776 /// If this function encounters an "end of file" before completely filling
777 /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
778 /// The contents of `buf` are unspecified in this case.
780 /// If any other read error is encountered then this function immediately
781 /// returns. The contents of `buf` are unspecified in this case.
783 /// If this function returns an error, it is unspecified how many bytes it
784 /// has read, but it will never read more than would be necessary to
785 /// completely fill the buffer.
789 /// [`File`]s implement `Read`:
791 /// [`read`]: Read::read
792 /// [`File`]: crate::fs::File
796 /// use std::io::prelude::*;
797 /// use std::fs::File;
799 /// fn main() -> io::Result<()> {
800 /// let mut f = File::open("foo.txt")?;
801 /// let mut buffer = [0; 10];
803 /// // read exactly 10 bytes
804 /// f.read_exact(&mut buffer)?;
808 #[stable(feature = "read_exact", since = "1.6.0")]
809 fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
810 default_read_exact(self, buf)
813 /// Pull some bytes from this source into the specified buffer.
815 /// This is equivalent to the [`read`](Read::read) method, except that it is passed a [`BorrowedCursor`] rather than `[u8]` to allow use
816 /// with uninitialized buffers. The new data will be appended to any existing contents of `buf`.
818 /// The default implementation delegates to `read`.
819 #[unstable(feature = "read_buf", issue = "78485")]
820 fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<()> {
821 default_read_buf(|b| self.read(b), buf)
824 /// Read the exact number of bytes required to fill `cursor`.
826 /// This is equivalent to the [`read_exact`](Read::read_exact) method, except that it is passed a [`BorrowedCursor`] rather than `[u8]` to
827 /// allow use with uninitialized buffers.
828 #[unstable(feature = "read_buf", issue = "78485")]
829 fn read_buf_exact(&mut self, mut cursor: BorrowedCursor<'_>) -> Result<()> {
830 while cursor.capacity() > 0 {
831 let prev_written = cursor.written();
832 match self.read_buf(cursor.reborrow()) {
834 Err(e) if e.kind() == ErrorKind::Interrupted => continue,
835 Err(e) => return Err(e),
838 if cursor.written() == prev_written {
839 return Err(Error::new(ErrorKind::UnexpectedEof, "failed to fill buffer"));
846 /// Creates a "by reference" adaptor for this instance of `Read`.
848 /// The returned adapter also implements `Read` and will simply borrow this
853 /// [`File`]s implement `Read`:
855 /// [`File`]: crate::fs::File
859 /// use std::io::Read;
860 /// use std::fs::File;
862 /// fn main() -> io::Result<()> {
863 /// let mut f = File::open("foo.txt")?;
864 /// let mut buffer = Vec::new();
865 /// let mut other_buffer = Vec::new();
868 /// let reference = f.by_ref();
870 /// // read at most 5 bytes
871 /// reference.take(5).read_to_end(&mut buffer)?;
873 /// } // drop our &mut reference so we can use f again
875 /// // original file still usable, read the rest
876 /// f.read_to_end(&mut other_buffer)?;
880 #[stable(feature = "rust1", since = "1.0.0")]
881 fn by_ref(&mut self) -> &mut Self
888 /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
890 /// The returned type implements [`Iterator`] where the [`Item`] is
891 /// <code>[Result]<[u8], [io::Error]></code>.
892 /// The yielded item is [`Ok`] if a byte was successfully read and [`Err`]
893 /// otherwise. EOF is mapped to returning [`None`] from this iterator.
895 /// The default implementation calls `read` for each byte,
896 /// which can be very inefficient for data that's not in memory,
897 /// such as [`File`]. Consider using a [`BufReader`] in such cases.
901 /// [`File`]s implement `Read`:
903 /// [`Item`]: Iterator::Item
904 /// [`File`]: crate::fs::File "fs::File"
905 /// [Result]: crate::result::Result "Result"
906 /// [io::Error]: self::Error "io::Error"
910 /// use std::io::prelude::*;
911 /// use std::io::BufReader;
912 /// use std::fs::File;
914 /// fn main() -> io::Result<()> {
915 /// let f = BufReader::new(File::open("foo.txt")?);
917 /// for byte in f.bytes() {
918 /// println!("{}", byte.unwrap());
923 #[stable(feature = "rust1", since = "1.0.0")]
924 fn bytes(self) -> Bytes<Self>
928 Bytes { inner: self }
931 /// Creates an adapter which will chain this stream with another.
933 /// The returned `Read` instance will first read all bytes from this object
934 /// until EOF is encountered. Afterwards the output is equivalent to the
935 /// output of `next`.
939 /// [`File`]s implement `Read`:
941 /// [`File`]: crate::fs::File
945 /// use std::io::prelude::*;
946 /// use std::fs::File;
948 /// fn main() -> io::Result<()> {
949 /// let f1 = File::open("foo.txt")?;
950 /// let f2 = File::open("bar.txt")?;
952 /// let mut handle = f1.chain(f2);
953 /// let mut buffer = String::new();
955 /// // read the value into a String. We could use any Read method here,
956 /// // this is just one example.
957 /// handle.read_to_string(&mut buffer)?;
961 #[stable(feature = "rust1", since = "1.0.0")]
962 fn chain<R: Read>(self, next: R) -> Chain<Self, R>
966 Chain { first: self, second: next, done_first: false }
969 /// Creates an adapter which will read at most `limit` bytes from it.
971 /// This function returns a new instance of `Read` which will read at most
972 /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
973 /// read errors will not count towards the number of bytes read and future
974 /// calls to [`read()`] may succeed.
978 /// [`File`]s implement `Read`:
980 /// [`File`]: crate::fs::File
982 /// [`read()`]: Read::read
986 /// use std::io::prelude::*;
987 /// use std::fs::File;
989 /// fn main() -> io::Result<()> {
990 /// let f = File::open("foo.txt")?;
991 /// let mut buffer = [0; 5];
993 /// // read at most five bytes
994 /// let mut handle = f.take(5);
996 /// handle.read(&mut buffer)?;
1000 #[stable(feature = "rust1", since = "1.0.0")]
1001 fn take(self, limit: u64) -> Take<Self>
1005 Take { inner: self, limit }
1009 /// Read all bytes from a [reader][Read] into a new [`String`].
1011 /// This is a convenience function for [`Read::read_to_string`]. Using this
1012 /// function avoids having to create a variable first and provides more type
1013 /// safety since you can only get the buffer out if there were no errors. (If you
1014 /// use [`Read::read_to_string`] you have to remember to check whether the read
1015 /// succeeded because otherwise your buffer will be empty or only partially full.)
1019 /// The downside of this function's increased ease of use and type safety is
1020 /// that it gives you less control over performance. For example, you can't
1021 /// pre-allocate memory like you can using [`String::with_capacity`] and
1022 /// [`Read::read_to_string`]. Also, you can't re-use the buffer if an error
1023 /// occurs while reading.
1025 /// In many cases, this function's performance will be adequate and the ease of use
1026 /// and type safety tradeoffs will be worth it. However, there are cases where you
1027 /// need more control over performance, and in those cases you should definitely use
1028 /// [`Read::read_to_string`] directly.
1030 /// Note that in some special cases, such as when reading files, this function will
1031 /// pre-allocate memory based on the size of the input it is reading. In those
1032 /// cases, the performance should be as good as if you had used
1033 /// [`Read::read_to_string`] with a manually pre-allocated buffer.
1037 /// This function forces you to handle errors because the output (the `String`)
1038 /// is wrapped in a [`Result`]. See [`Read::read_to_string`] for the errors
1039 /// that can occur. If any error occurs, you will get an [`Err`], so you
1040 /// don't have to worry about your buffer being empty or partially full.
1046 /// fn main() -> io::Result<()> {
1047 /// let stdin = io::read_to_string(io::stdin())?;
1048 /// println!("Stdin was:");
1049 /// println!("{stdin}");
1053 #[stable(feature = "io_read_to_string", since = "1.65.0")]
1054 pub fn read_to_string<R: Read>(mut reader: R) -> Result<String> {
1055 let mut buf = String::new();
1056 reader.read_to_string(&mut buf)?;
1060 /// A buffer type used with `Read::read_vectored`.
1062 /// It is semantically a wrapper around an `&mut [u8]`, but is guaranteed to be
1063 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
1065 #[stable(feature = "iovec", since = "1.36.0")]
1066 #[repr(transparent)]
1067 pub struct IoSliceMut<'a>(sys::io::IoSliceMut<'a>);
1069 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1070 unsafe impl<'a> Send for IoSliceMut<'a> {}
1072 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1073 unsafe impl<'a> Sync for IoSliceMut<'a> {}
1075 #[stable(feature = "iovec", since = "1.36.0")]
1076 impl<'a> fmt::Debug for IoSliceMut<'a> {
1077 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1078 fmt::Debug::fmt(self.0.as_slice(), fmt)
1082 impl<'a> IoSliceMut<'a> {
1083 /// Creates a new `IoSliceMut` wrapping a byte slice.
1087 /// Panics on Windows if the slice is larger than 4GB.
1088 #[stable(feature = "iovec", since = "1.36.0")]
1090 pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> {
1091 IoSliceMut(sys::io::IoSliceMut::new(buf))
1094 /// Advance the internal cursor of the slice.
1096 /// Also see [`IoSliceMut::advance_slices`] to advance the cursors of
1097 /// multiple buffers.
1101 /// Panics when trying to advance beyond the end of the slice.
1106 /// #![feature(io_slice_advance)]
1108 /// use std::io::IoSliceMut;
1109 /// use std::ops::Deref;
1111 /// let mut data = [1; 8];
1112 /// let mut buf = IoSliceMut::new(&mut data);
1114 /// // Mark 3 bytes as read.
1116 /// assert_eq!(buf.deref(), [1; 5].as_ref());
1118 #[unstable(feature = "io_slice_advance", issue = "62726")]
1120 pub fn advance(&mut self, n: usize) {
1124 /// Advance a slice of slices.
1126 /// Shrinks the slice to remove any `IoSliceMut`s that are fully advanced over.
1127 /// If the cursor ends up in the middle of an `IoSliceMut`, it is modified
1128 /// to start at that cursor.
1130 /// For example, if we have a slice of two 8-byte `IoSliceMut`s, and we advance by 10 bytes,
1131 /// the result will only include the second `IoSliceMut`, advanced by 2 bytes.
1135 /// Panics when trying to advance beyond the end of the slices.
1140 /// #![feature(io_slice_advance)]
1142 /// use std::io::IoSliceMut;
1143 /// use std::ops::Deref;
1145 /// let mut buf1 = [1; 8];
1146 /// let mut buf2 = [2; 16];
1147 /// let mut buf3 = [3; 8];
1148 /// let mut bufs = &mut [
1149 /// IoSliceMut::new(&mut buf1),
1150 /// IoSliceMut::new(&mut buf2),
1151 /// IoSliceMut::new(&mut buf3),
1154 /// // Mark 10 bytes as read.
1155 /// IoSliceMut::advance_slices(&mut bufs, 10);
1156 /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1157 /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1159 #[unstable(feature = "io_slice_advance", issue = "62726")]
1161 pub fn advance_slices(bufs: &mut &mut [IoSliceMut<'a>], n: usize) {
1162 // Number of buffers to remove.
1164 // Total length of all the to be removed buffers.
1165 let mut accumulated_len = 0;
1166 for buf in bufs.iter() {
1167 if accumulated_len + buf.len() > n {
1170 accumulated_len += buf.len();
1175 *bufs = &mut replace(bufs, &mut [])[remove..];
1176 if bufs.is_empty() {
1177 assert!(n == accumulated_len, "advancing io slices beyond their length");
1179 bufs[0].advance(n - accumulated_len)
1184 #[stable(feature = "iovec", since = "1.36.0")]
1185 impl<'a> Deref for IoSliceMut<'a> {
1189 fn deref(&self) -> &[u8] {
1194 #[stable(feature = "iovec", since = "1.36.0")]
1195 impl<'a> DerefMut for IoSliceMut<'a> {
1197 fn deref_mut(&mut self) -> &mut [u8] {
1198 self.0.as_mut_slice()
1202 /// A buffer type used with `Write::write_vectored`.
1204 /// It is semantically a wrapper around a `&[u8]`, but is guaranteed to be
1205 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
1207 #[stable(feature = "iovec", since = "1.36.0")]
1208 #[derive(Copy, Clone)]
1209 #[repr(transparent)]
1210 pub struct IoSlice<'a>(sys::io::IoSlice<'a>);
1212 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1213 unsafe impl<'a> Send for IoSlice<'a> {}
1215 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1216 unsafe impl<'a> Sync for IoSlice<'a> {}
1218 #[stable(feature = "iovec", since = "1.36.0")]
1219 impl<'a> fmt::Debug for IoSlice<'a> {
1220 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1221 fmt::Debug::fmt(self.0.as_slice(), fmt)
1225 impl<'a> IoSlice<'a> {
1226 /// Creates a new `IoSlice` wrapping a byte slice.
1230 /// Panics on Windows if the slice is larger than 4GB.
1231 #[stable(feature = "iovec", since = "1.36.0")]
1234 pub fn new(buf: &'a [u8]) -> IoSlice<'a> {
1235 IoSlice(sys::io::IoSlice::new(buf))
1238 /// Advance the internal cursor of the slice.
1240 /// Also see [`IoSlice::advance_slices`] to advance the cursors of multiple
1245 /// Panics when trying to advance beyond the end of the slice.
1250 /// #![feature(io_slice_advance)]
1252 /// use std::io::IoSlice;
1253 /// use std::ops::Deref;
1255 /// let data = [1; 8];
1256 /// let mut buf = IoSlice::new(&data);
1258 /// // Mark 3 bytes as read.
1260 /// assert_eq!(buf.deref(), [1; 5].as_ref());
1262 #[unstable(feature = "io_slice_advance", issue = "62726")]
1264 pub fn advance(&mut self, n: usize) {
1268 /// Advance a slice of slices.
1270 /// Shrinks the slice to remove any `IoSlice`s that are fully advanced over.
1271 /// If the cursor ends up in the middle of an `IoSlice`, it is modified
1272 /// to start at that cursor.
1274 /// For example, if we have a slice of two 8-byte `IoSlice`s, and we advance by 10 bytes,
1275 /// the result will only include the second `IoSlice`, advanced by 2 bytes.
1279 /// Panics when trying to advance beyond the end of the slices.
1284 /// #![feature(io_slice_advance)]
1286 /// use std::io::IoSlice;
1287 /// use std::ops::Deref;
1289 /// let buf1 = [1; 8];
1290 /// let buf2 = [2; 16];
1291 /// let buf3 = [3; 8];
1292 /// let mut bufs = &mut [
1293 /// IoSlice::new(&buf1),
1294 /// IoSlice::new(&buf2),
1295 /// IoSlice::new(&buf3),
1298 /// // Mark 10 bytes as written.
1299 /// IoSlice::advance_slices(&mut bufs, 10);
1300 /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1301 /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1302 #[unstable(feature = "io_slice_advance", issue = "62726")]
1304 pub fn advance_slices(bufs: &mut &mut [IoSlice<'a>], n: usize) {
1305 // Number of buffers to remove.
1307 // Total length of all the to be removed buffers.
1308 let mut accumulated_len = 0;
1309 for buf in bufs.iter() {
1310 if accumulated_len + buf.len() > n {
1313 accumulated_len += buf.len();
1318 *bufs = &mut replace(bufs, &mut [])[remove..];
1319 if bufs.is_empty() {
1320 assert!(n == accumulated_len, "advancing io slices beyond their length");
1322 bufs[0].advance(n - accumulated_len)
1327 #[stable(feature = "iovec", since = "1.36.0")]
1328 impl<'a> Deref for IoSlice<'a> {
1332 fn deref(&self) -> &[u8] {
1337 /// A trait for objects which are byte-oriented sinks.
1339 /// Implementors of the `Write` trait are sometimes called 'writers'.
1341 /// Writers are defined by two required methods, [`write`] and [`flush`]:
1343 /// * The [`write`] method will attempt to write some data into the object,
1344 /// returning how many bytes were successfully written.
1346 /// * The [`flush`] method is useful for adapters and explicit buffers
1347 /// themselves for ensuring that all buffered data has been pushed out to the
1350 /// Writers are intended to be composable with one another. Many implementors
1351 /// throughout [`std::io`] take and provide types which implement the `Write`
1354 /// [`write`]: Write::write
1355 /// [`flush`]: Write::flush
1356 /// [`std::io`]: self
1361 /// use std::io::prelude::*;
1362 /// use std::fs::File;
1364 /// fn main() -> std::io::Result<()> {
1365 /// let data = b"some bytes";
1367 /// let mut pos = 0;
1368 /// let mut buffer = File::create("foo.txt")?;
1370 /// while pos < data.len() {
1371 /// let bytes_written = buffer.write(&data[pos..])?;
1372 /// pos += bytes_written;
1378 /// The trait also provides convenience methods like [`write_all`], which calls
1379 /// `write` in a loop until its entire input has been written.
1381 /// [`write_all`]: Write::write_all
1382 #[stable(feature = "rust1", since = "1.0.0")]
1383 #[doc(notable_trait)]
1384 #[cfg_attr(not(test), rustc_diagnostic_item = "IoWrite")]
1386 /// Write a buffer into this writer, returning how many bytes were written.
1388 /// This function will attempt to write the entire contents of `buf`, but
1389 /// the entire write might not succeed, or the write may also generate an
1390 /// error. A call to `write` represents *at most one* attempt to write to
1391 /// any wrapped object.
1393 /// Calls to `write` are not guaranteed to block waiting for data to be
1394 /// written, and a write which would otherwise block can be indicated through
1395 /// an [`Err`] variant.
1397 /// If the return value is [`Ok(n)`] then it must be guaranteed that
1398 /// `n <= buf.len()`. A return value of `0` typically means that the
1399 /// underlying object is no longer able to accept bytes and will likely not
1400 /// be able to in the future as well, or that the buffer provided is empty.
1404 /// Each call to `write` may generate an I/O error indicating that the
1405 /// operation could not be completed. If an error is returned then no bytes
1406 /// in the buffer were written to this writer.
1408 /// It is **not** considered an error if the entire buffer could not be
1409 /// written to this writer.
1411 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the
1412 /// write operation should be retried if there is nothing else to do.
1417 /// use std::io::prelude::*;
1418 /// use std::fs::File;
1420 /// fn main() -> std::io::Result<()> {
1421 /// let mut buffer = File::create("foo.txt")?;
1423 /// // Writes some prefix of the byte string, not necessarily all of it.
1424 /// buffer.write(b"some bytes")?;
1430 #[stable(feature = "rust1", since = "1.0.0")]
1431 fn write(&mut self, buf: &[u8]) -> Result<usize>;
1433 /// Like [`write`], except that it writes from a slice of buffers.
1435 /// Data is copied from each buffer in order, with the final buffer
1436 /// read from possibly being only partially consumed. This method must
1437 /// behave as a call to [`write`] with the buffers concatenated would.
1439 /// The default implementation calls [`write`] with either the first nonempty
1440 /// buffer provided, or an empty one if none exists.
1445 /// use std::io::IoSlice;
1446 /// use std::io::prelude::*;
1447 /// use std::fs::File;
1449 /// fn main() -> std::io::Result<()> {
1450 /// let data1 = [1; 8];
1451 /// let data2 = [15; 8];
1452 /// let io_slice1 = IoSlice::new(&data1);
1453 /// let io_slice2 = IoSlice::new(&data2);
1455 /// let mut buffer = File::create("foo.txt")?;
1457 /// // Writes some prefix of the byte string, not necessarily all of it.
1458 /// buffer.write_vectored(&[io_slice1, io_slice2])?;
1463 /// [`write`]: Write::write
1464 #[stable(feature = "iovec", since = "1.36.0")]
1465 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize> {
1466 default_write_vectored(|b| self.write(b), bufs)
1469 /// Determines if this `Write`r has an efficient [`write_vectored`]
1472 /// If a `Write`r does not override the default [`write_vectored`]
1473 /// implementation, code using it may want to avoid the method all together
1474 /// and coalesce writes into a single buffer for higher performance.
1476 /// The default implementation returns `false`.
1478 /// [`write_vectored`]: Write::write_vectored
1479 #[unstable(feature = "can_vector", issue = "69941")]
1480 fn is_write_vectored(&self) -> bool {
1484 /// Flush this output stream, ensuring that all intermediately buffered
1485 /// contents reach their destination.
1489 /// It is considered an error if not all bytes could be written due to
1490 /// I/O errors or EOF being reached.
1495 /// use std::io::prelude::*;
1496 /// use std::io::BufWriter;
1497 /// use std::fs::File;
1499 /// fn main() -> std::io::Result<()> {
1500 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
1502 /// buffer.write_all(b"some bytes")?;
1503 /// buffer.flush()?;
1507 #[stable(feature = "rust1", since = "1.0.0")]
1508 fn flush(&mut self) -> Result<()>;
1510 /// Attempts to write an entire buffer into this writer.
1512 /// This method will continuously call [`write`] until there is no more data
1513 /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is
1514 /// returned. This method will not return until the entire buffer has been
1515 /// successfully written or such an error occurs. The first error that is
1516 /// not of [`ErrorKind::Interrupted`] kind generated from this method will be
1519 /// If the buffer contains no data, this will never call [`write`].
1523 /// This function will return the first error of
1524 /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns.
1526 /// [`write`]: Write::write
1531 /// use std::io::prelude::*;
1532 /// use std::fs::File;
1534 /// fn main() -> std::io::Result<()> {
1535 /// let mut buffer = File::create("foo.txt")?;
1537 /// buffer.write_all(b"some bytes")?;
1541 #[stable(feature = "rust1", since = "1.0.0")]
1542 fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
1543 while !buf.is_empty() {
1544 match self.write(buf) {
1546 return Err(error::const_io_error!(
1547 ErrorKind::WriteZero,
1548 "failed to write whole buffer",
1551 Ok(n) => buf = &buf[n..],
1552 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1553 Err(e) => return Err(e),
1559 /// Attempts to write multiple buffers into this writer.
1561 /// This method will continuously call [`write_vectored`] until there is no
1562 /// more data to be written or an error of non-[`ErrorKind::Interrupted`]
1563 /// kind is returned. This method will not return until all buffers have
1564 /// been successfully written or such an error occurs. The first error that
1565 /// is not of [`ErrorKind::Interrupted`] kind generated from this method
1566 /// will be returned.
1568 /// If the buffer contains no data, this will never call [`write_vectored`].
1572 /// Unlike [`write_vectored`], this takes a *mutable* reference to
1573 /// a slice of [`IoSlice`]s, not an immutable one. That's because we need to
1574 /// modify the slice to keep track of the bytes already written.
1576 /// Once this function returns, the contents of `bufs` are unspecified, as
1577 /// this depends on how many calls to [`write_vectored`] were necessary. It is
1578 /// best to understand this function as taking ownership of `bufs` and to
1579 /// not use `bufs` afterwards. The underlying buffers, to which the
1580 /// [`IoSlice`]s point (but not the [`IoSlice`]s themselves), are unchanged and
1583 /// [`write_vectored`]: Write::write_vectored
1588 /// #![feature(write_all_vectored)]
1589 /// # fn main() -> std::io::Result<()> {
1591 /// use std::io::{Write, IoSlice};
1593 /// let mut writer = Vec::new();
1594 /// let bufs = &mut [
1595 /// IoSlice::new(&[1]),
1596 /// IoSlice::new(&[2, 3]),
1597 /// IoSlice::new(&[4, 5, 6]),
1600 /// writer.write_all_vectored(bufs)?;
1601 /// // Note: the contents of `bufs` is now undefined, see the Notes section.
1603 /// assert_eq!(writer, &[1, 2, 3, 4, 5, 6]);
1606 #[unstable(feature = "write_all_vectored", issue = "70436")]
1607 fn write_all_vectored(&mut self, mut bufs: &mut [IoSlice<'_>]) -> Result<()> {
1608 // Guarantee that bufs is empty if it contains no data,
1609 // to avoid calling write_vectored if there is no data to be written.
1610 IoSlice::advance_slices(&mut bufs, 0);
1611 while !bufs.is_empty() {
1612 match self.write_vectored(bufs) {
1614 return Err(error::const_io_error!(
1615 ErrorKind::WriteZero,
1616 "failed to write whole buffer",
1619 Ok(n) => IoSlice::advance_slices(&mut bufs, n),
1620 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1621 Err(e) => return Err(e),
1627 /// Writes a formatted string into this writer, returning any error
1630 /// This method is primarily used to interface with the
1631 /// [`format_args!()`] macro, and it is rare that this should
1632 /// explicitly be called. The [`write!()`] macro should be favored to
1633 /// invoke this method instead.
1635 /// This function internally uses the [`write_all`] method on
1636 /// this trait and hence will continuously write data so long as no errors
1637 /// are received. This also means that partial writes are not indicated in
1640 /// [`write_all`]: Write::write_all
1644 /// This function will return any I/O error reported while formatting.
1649 /// use std::io::prelude::*;
1650 /// use std::fs::File;
1652 /// fn main() -> std::io::Result<()> {
1653 /// let mut buffer = File::create("foo.txt")?;
1656 /// write!(buffer, "{:.*}", 2, 1.234567)?;
1657 /// // turns into this:
1658 /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1662 #[stable(feature = "rust1", since = "1.0.0")]
1663 fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> Result<()> {
1664 // Create a shim which translates a Write to a fmt::Write and saves
1665 // off I/O errors. instead of discarding them
1666 struct Adapter<'a, T: ?Sized + 'a> {
1671 impl<T: Write + ?Sized> fmt::Write for Adapter<'_, T> {
1672 fn write_str(&mut self, s: &str) -> fmt::Result {
1673 match self.inner.write_all(s.as_bytes()) {
1676 self.error = Err(e);
1683 let mut output = Adapter { inner: self, error: Ok(()) };
1684 match fmt::write(&mut output, fmt) {
1687 // check if the error came from the underlying `Write` or not
1688 if output.error.is_err() {
1691 Err(error::const_io_error!(ErrorKind::Uncategorized, "formatter error"))
1697 /// Creates a "by reference" adapter for this instance of `Write`.
1699 /// The returned adapter also implements `Write` and will simply borrow this
1705 /// use std::io::Write;
1706 /// use std::fs::File;
1708 /// fn main() -> std::io::Result<()> {
1709 /// let mut buffer = File::create("foo.txt")?;
1711 /// let reference = buffer.by_ref();
1713 /// // we can use reference just like our original buffer
1714 /// reference.write_all(b"some bytes")?;
1718 #[stable(feature = "rust1", since = "1.0.0")]
1719 fn by_ref(&mut self) -> &mut Self
1727 /// The `Seek` trait provides a cursor which can be moved within a stream of
1730 /// The stream typically has a fixed size, allowing seeking relative to either
1731 /// end or the current offset.
1735 /// [`File`]s implement `Seek`:
1737 /// [`File`]: crate::fs::File
1741 /// use std::io::prelude::*;
1742 /// use std::fs::File;
1743 /// use std::io::SeekFrom;
1745 /// fn main() -> io::Result<()> {
1746 /// let mut f = File::open("foo.txt")?;
1748 /// // move the cursor 42 bytes from the start of the file
1749 /// f.seek(SeekFrom::Start(42))?;
1753 #[stable(feature = "rust1", since = "1.0.0")]
1755 /// Seek to an offset, in bytes, in a stream.
1757 /// A seek beyond the end of a stream is allowed, but behavior is defined
1758 /// by the implementation.
1760 /// If the seek operation completed successfully,
1761 /// this method returns the new position from the start of the stream.
1762 /// That position can be used later with [`SeekFrom::Start`].
1766 /// Seeking can fail, for example because it might involve flushing a buffer.
1768 /// Seeking to a negative offset is considered an error.
1769 #[stable(feature = "rust1", since = "1.0.0")]
1770 fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1772 /// Rewind to the beginning of a stream.
1774 /// This is a convenience method, equivalent to `seek(SeekFrom::Start(0))`.
1778 /// Rewinding can fail, for example because it might involve flushing a buffer.
1783 /// use std::io::{Read, Seek, Write};
1784 /// use std::fs::OpenOptions;
1786 /// let mut f = OpenOptions::new()
1790 /// .open("foo.txt").unwrap();
1792 /// let hello = "Hello!\n";
1793 /// write!(f, "{hello}").unwrap();
1794 /// f.rewind().unwrap();
1796 /// let mut buf = String::new();
1797 /// f.read_to_string(&mut buf).unwrap();
1798 /// assert_eq!(&buf, hello);
1800 #[stable(feature = "seek_rewind", since = "1.55.0")]
1801 fn rewind(&mut self) -> Result<()> {
1802 self.seek(SeekFrom::Start(0))?;
1806 /// Returns the length of this stream (in bytes).
1808 /// This method is implemented using up to three seek operations. If this
1809 /// method returns successfully, the seek position is unchanged (i.e. the
1810 /// position before calling this method is the same as afterwards).
1811 /// However, if this method returns an error, the seek position is
1814 /// If you need to obtain the length of *many* streams and you don't care
1815 /// about the seek position afterwards, you can reduce the number of seek
1816 /// operations by simply calling `seek(SeekFrom::End(0))` and using its
1817 /// return value (it is also the stream length).
1819 /// Note that length of a stream can change over time (for example, when
1820 /// data is appended to a file). So calling this method multiple times does
1821 /// not necessarily return the same length each time.
1826 /// #![feature(seek_stream_len)]
1828 /// io::{self, Seek},
1832 /// fn main() -> io::Result<()> {
1833 /// let mut f = File::open("foo.txt")?;
1835 /// let len = f.stream_len()?;
1836 /// println!("The file is currently {len} bytes long");
1840 #[unstable(feature = "seek_stream_len", issue = "59359")]
1841 fn stream_len(&mut self) -> Result<u64> {
1842 let old_pos = self.stream_position()?;
1843 let len = self.seek(SeekFrom::End(0))?;
1845 // Avoid seeking a third time when we were already at the end of the
1846 // stream. The branch is usually way cheaper than a seek operation.
1848 self.seek(SeekFrom::Start(old_pos))?;
1854 /// Returns the current seek position from the start of the stream.
1856 /// This is equivalent to `self.seek(SeekFrom::Current(0))`.
1862 /// io::{self, BufRead, BufReader, Seek},
1866 /// fn main() -> io::Result<()> {
1867 /// let mut f = BufReader::new(File::open("foo.txt")?);
1869 /// let before = f.stream_position()?;
1870 /// f.read_line(&mut String::new())?;
1871 /// let after = f.stream_position()?;
1873 /// println!("The first line was {} bytes long", after - before);
1877 #[stable(feature = "seek_convenience", since = "1.51.0")]
1878 fn stream_position(&mut self) -> Result<u64> {
1879 self.seek(SeekFrom::Current(0))
1883 /// Enumeration of possible methods to seek within an I/O object.
1885 /// It is used by the [`Seek`] trait.
1886 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1887 #[stable(feature = "rust1", since = "1.0.0")]
1889 /// Sets the offset to the provided number of bytes.
1890 #[stable(feature = "rust1", since = "1.0.0")]
1891 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1893 /// Sets the offset to the size of this object plus the specified number of
1896 /// It is possible to seek beyond the end of an object, but it's an error to
1897 /// seek before byte 0.
1898 #[stable(feature = "rust1", since = "1.0.0")]
1899 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1901 /// Sets the offset to the current position plus the specified number of
1904 /// It is possible to seek beyond the end of an object, but it's an error to
1905 /// seek before byte 0.
1906 #[stable(feature = "rust1", since = "1.0.0")]
1907 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1910 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>) -> Result<usize> {
1913 let (done, used) = {
1914 let available = match r.fill_buf() {
1916 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1917 Err(e) => return Err(e),
1919 match memchr::memchr(delim, available) {
1921 buf.extend_from_slice(&available[..=i]);
1925 buf.extend_from_slice(available);
1926 (false, available.len())
1932 if done || used == 0 {
1938 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1939 /// to perform extra ways of reading.
1941 /// For example, reading line-by-line is inefficient without using a buffer, so
1942 /// if you want to read by line, you'll need `BufRead`, which includes a
1943 /// [`read_line`] method as well as a [`lines`] iterator.
1947 /// A locked standard input implements `BufRead`:
1951 /// use std::io::prelude::*;
1953 /// let stdin = io::stdin();
1954 /// for line in stdin.lock().lines() {
1955 /// println!("{}", line.unwrap());
1959 /// If you have something that implements [`Read`], you can use the [`BufReader`
1960 /// type][`BufReader`] to turn it into a `BufRead`.
1962 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1963 /// [`BufReader`] to the rescue!
1965 /// [`File`]: crate::fs::File
1966 /// [`read_line`]: BufRead::read_line
1967 /// [`lines`]: BufRead::lines
1970 /// use std::io::{self, BufReader};
1971 /// use std::io::prelude::*;
1972 /// use std::fs::File;
1974 /// fn main() -> io::Result<()> {
1975 /// let f = File::open("foo.txt")?;
1976 /// let f = BufReader::new(f);
1978 /// for line in f.lines() {
1979 /// println!("{}", line.unwrap());
1985 #[stable(feature = "rust1", since = "1.0.0")]
1986 pub trait BufRead: Read {
1987 /// Returns the contents of the internal buffer, filling it with more data
1988 /// from the inner reader if it is empty.
1990 /// This function is a lower-level call. It needs to be paired with the
1991 /// [`consume`] method to function properly. When calling this
1992 /// method, none of the contents will be "read" in the sense that later
1993 /// calling `read` may return the same contents. As such, [`consume`] must
1994 /// be called with the number of bytes that are consumed from this buffer to
1995 /// ensure that the bytes are never returned twice.
1997 /// [`consume`]: BufRead::consume
1999 /// An empty buffer returned indicates that the stream has reached EOF.
2003 /// This function will return an I/O error if the underlying reader was
2004 /// read, but returned an error.
2008 /// A locked standard input implements `BufRead`:
2012 /// use std::io::prelude::*;
2014 /// let stdin = io::stdin();
2015 /// let mut stdin = stdin.lock();
2017 /// let buffer = stdin.fill_buf().unwrap();
2019 /// // work with buffer
2020 /// println!("{buffer:?}");
2022 /// // ensure the bytes we worked with aren't returned again later
2023 /// let length = buffer.len();
2024 /// stdin.consume(length);
2026 #[stable(feature = "rust1", since = "1.0.0")]
2027 fn fill_buf(&mut self) -> Result<&[u8]>;
2029 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
2030 /// so they should no longer be returned in calls to `read`.
2032 /// This function is a lower-level call. It needs to be paired with the
2033 /// [`fill_buf`] method to function properly. This function does
2034 /// not perform any I/O, it simply informs this object that some amount of
2035 /// its buffer, returned from [`fill_buf`], has been consumed and should
2036 /// no longer be returned. As such, this function may do odd things if
2037 /// [`fill_buf`] isn't called before calling it.
2039 /// The `amt` must be `<=` the number of bytes in the buffer returned by
2044 /// Since `consume()` is meant to be used with [`fill_buf`],
2045 /// that method's example includes an example of `consume()`.
2047 /// [`fill_buf`]: BufRead::fill_buf
2048 #[stable(feature = "rust1", since = "1.0.0")]
2049 fn consume(&mut self, amt: usize);
2051 /// Check if the underlying `Read` has any data left to be read.
2053 /// This function may fill the buffer to check for data,
2054 /// so this functions returns `Result<bool>`, not `bool`.
2056 /// Default implementation calls `fill_buf` and checks that
2057 /// returned slice is empty (which means that there is no data left,
2058 /// since EOF is reached).
2063 /// #![feature(buf_read_has_data_left)]
2065 /// use std::io::prelude::*;
2067 /// let stdin = io::stdin();
2068 /// let mut stdin = stdin.lock();
2070 /// while stdin.has_data_left().unwrap() {
2071 /// let mut line = String::new();
2072 /// stdin.read_line(&mut line).unwrap();
2073 /// // work with line
2074 /// println!("{line:?}");
2077 #[unstable(feature = "buf_read_has_data_left", reason = "recently added", issue = "86423")]
2078 fn has_data_left(&mut self) -> Result<bool> {
2079 self.fill_buf().map(|b| !b.is_empty())
2082 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
2084 /// This function will read bytes from the underlying stream until the
2085 /// delimiter or EOF is found. Once found, all bytes up to, and including,
2086 /// the delimiter (if found) will be appended to `buf`.
2088 /// If successful, this function will return the total number of bytes read.
2090 /// This function is blocking and should be used carefully: it is possible for
2091 /// an attacker to continuously send bytes without ever sending the delimiter
2096 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
2097 /// will otherwise return any errors returned by [`fill_buf`].
2099 /// If an I/O error is encountered then all bytes read so far will be
2100 /// present in `buf` and its length will have been adjusted appropriately.
2102 /// [`fill_buf`]: BufRead::fill_buf
2106 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2107 /// this example, we use [`Cursor`] to read all the bytes in a byte slice
2108 /// in hyphen delimited segments:
2111 /// use std::io::{self, BufRead};
2113 /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
2114 /// let mut buf = vec![];
2116 /// // cursor is at 'l'
2117 /// let num_bytes = cursor.read_until(b'-', &mut buf)
2118 /// .expect("reading from cursor won't fail");
2119 /// assert_eq!(num_bytes, 6);
2120 /// assert_eq!(buf, b"lorem-");
2123 /// // cursor is at 'i'
2124 /// let num_bytes = cursor.read_until(b'-', &mut buf)
2125 /// .expect("reading from cursor won't fail");
2126 /// assert_eq!(num_bytes, 5);
2127 /// assert_eq!(buf, b"ipsum");
2130 /// // cursor is at EOF
2131 /// let num_bytes = cursor.read_until(b'-', &mut buf)
2132 /// .expect("reading from cursor won't fail");
2133 /// assert_eq!(num_bytes, 0);
2134 /// assert_eq!(buf, b"");
2136 #[stable(feature = "rust1", since = "1.0.0")]
2137 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
2138 read_until(self, byte, buf)
2141 /// Read all bytes until a newline (the `0xA` byte) is reached, and append
2142 /// them to the provided `String` buffer.
2144 /// Previous content of the buffer will be preserved. To avoid appending to
2145 /// the buffer, you need to [`clear`] it first.
2147 /// This function will read bytes from the underlying stream until the
2148 /// newline delimiter (the `0xA` byte) or EOF is found. Once found, all bytes
2149 /// up to, and including, the delimiter (if found) will be appended to
2152 /// If successful, this function will return the total number of bytes read.
2154 /// If this function returns [`Ok(0)`], the stream has reached EOF.
2156 /// This function is blocking and should be used carefully: it is possible for
2157 /// an attacker to continuously send bytes without ever sending a newline
2158 /// or EOF. You can use [`take`] to limit the maximum number of bytes read.
2161 /// [`clear`]: String::clear
2162 /// [`take`]: crate::io::Read::take
2166 /// This function has the same error semantics as [`read_until`] and will
2167 /// also return an error if the read bytes are not valid UTF-8. If an I/O
2168 /// error is encountered then `buf` may contain some bytes already read in
2169 /// the event that all data read so far was valid UTF-8.
2171 /// [`read_until`]: BufRead::read_until
2175 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2176 /// this example, we use [`Cursor`] to read all the lines in a byte slice:
2179 /// use std::io::{self, BufRead};
2181 /// let mut cursor = io::Cursor::new(b"foo\nbar");
2182 /// let mut buf = String::new();
2184 /// // cursor is at 'f'
2185 /// let num_bytes = cursor.read_line(&mut buf)
2186 /// .expect("reading from cursor won't fail");
2187 /// assert_eq!(num_bytes, 4);
2188 /// assert_eq!(buf, "foo\n");
2191 /// // cursor is at 'b'
2192 /// let num_bytes = cursor.read_line(&mut buf)
2193 /// .expect("reading from cursor won't fail");
2194 /// assert_eq!(num_bytes, 3);
2195 /// assert_eq!(buf, "bar");
2198 /// // cursor is at EOF
2199 /// let num_bytes = cursor.read_line(&mut buf)
2200 /// .expect("reading from cursor won't fail");
2201 /// assert_eq!(num_bytes, 0);
2202 /// assert_eq!(buf, "");
2204 #[stable(feature = "rust1", since = "1.0.0")]
2205 fn read_line(&mut self, buf: &mut String) -> Result<usize> {
2206 // Note that we are not calling the `.read_until` method here, but
2207 // rather our hardcoded implementation. For more details as to why, see
2208 // the comments in `read_to_end`.
2209 unsafe { append_to_string(buf, |b| read_until(self, b'\n', b)) }
2212 /// Returns an iterator over the contents of this reader split on the byte
2215 /// The iterator returned from this function will return instances of
2216 /// <code>[io::Result]<[Vec]\<u8>></code>. Each vector returned will *not* have
2217 /// the delimiter byte at the end.
2219 /// This function will yield errors whenever [`read_until`] would have
2220 /// also yielded an error.
2222 /// [io::Result]: self::Result "io::Result"
2223 /// [`read_until`]: BufRead::read_until
2227 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2228 /// this example, we use [`Cursor`] to iterate over all hyphen delimited
2229 /// segments in a byte slice
2232 /// use std::io::{self, BufRead};
2234 /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
2236 /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
2237 /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
2238 /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
2239 /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
2240 /// assert_eq!(split_iter.next(), None);
2242 #[stable(feature = "rust1", since = "1.0.0")]
2243 fn split(self, byte: u8) -> Split<Self>
2247 Split { buf: self, delim: byte }
2250 /// Returns an iterator over the lines of this reader.
2252 /// The iterator returned from this function will yield instances of
2253 /// <code>[io::Result]<[String]></code>. Each string returned will *not* have a newline
2254 /// byte (the `0xA` byte) or `CRLF` (`0xD`, `0xA` bytes) at the end.
2256 /// [io::Result]: self::Result "io::Result"
2260 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2261 /// this example, we use [`Cursor`] to iterate over all the lines in a byte
2265 /// use std::io::{self, BufRead};
2267 /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
2269 /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
2270 /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
2271 /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
2272 /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
2273 /// assert_eq!(lines_iter.next(), None);
2278 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
2279 #[stable(feature = "rust1", since = "1.0.0")]
2280 fn lines(self) -> Lines<Self>
2288 /// Adapter to chain together two readers.
2290 /// This struct is generally created by calling [`chain`] on a reader.
2291 /// Please see the documentation of [`chain`] for more details.
2293 /// [`chain`]: Read::chain
2294 #[stable(feature = "rust1", since = "1.0.0")]
2296 pub struct Chain<T, U> {
2302 impl<T, U> Chain<T, U> {
2303 /// Consumes the `Chain`, returning the wrapped readers.
2309 /// use std::io::prelude::*;
2310 /// use std::fs::File;
2312 /// fn main() -> io::Result<()> {
2313 /// let mut foo_file = File::open("foo.txt")?;
2314 /// let mut bar_file = File::open("bar.txt")?;
2316 /// let chain = foo_file.chain(bar_file);
2317 /// let (foo_file, bar_file) = chain.into_inner();
2321 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2322 pub fn into_inner(self) -> (T, U) {
2323 (self.first, self.second)
2326 /// Gets references to the underlying readers in this `Chain`.
2332 /// use std::io::prelude::*;
2333 /// use std::fs::File;
2335 /// fn main() -> io::Result<()> {
2336 /// let mut foo_file = File::open("foo.txt")?;
2337 /// let mut bar_file = File::open("bar.txt")?;
2339 /// let chain = foo_file.chain(bar_file);
2340 /// let (foo_file, bar_file) = chain.get_ref();
2344 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2345 pub fn get_ref(&self) -> (&T, &U) {
2346 (&self.first, &self.second)
2349 /// Gets mutable references to the underlying readers in this `Chain`.
2351 /// Care should be taken to avoid modifying the internal I/O state of the
2352 /// underlying readers as doing so may corrupt the internal state of this
2359 /// use std::io::prelude::*;
2360 /// use std::fs::File;
2362 /// fn main() -> io::Result<()> {
2363 /// let mut foo_file = File::open("foo.txt")?;
2364 /// let mut bar_file = File::open("bar.txt")?;
2366 /// let mut chain = foo_file.chain(bar_file);
2367 /// let (foo_file, bar_file) = chain.get_mut();
2371 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2372 pub fn get_mut(&mut self) -> (&mut T, &mut U) {
2373 (&mut self.first, &mut self.second)
2377 #[stable(feature = "rust1", since = "1.0.0")]
2378 impl<T: Read, U: Read> Read for Chain<T, U> {
2379 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2380 if !self.done_first {
2381 match self.first.read(buf)? {
2382 0 if !buf.is_empty() => self.done_first = true,
2386 self.second.read(buf)
2389 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
2390 if !self.done_first {
2391 match self.first.read_vectored(bufs)? {
2392 0 if bufs.iter().any(|b| !b.is_empty()) => self.done_first = true,
2396 self.second.read_vectored(bufs)
2400 #[stable(feature = "chain_bufread", since = "1.9.0")]
2401 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
2402 fn fill_buf(&mut self) -> Result<&[u8]> {
2403 if !self.done_first {
2404 match self.first.fill_buf()? {
2405 buf if buf.is_empty() => {
2406 self.done_first = true;
2408 buf => return Ok(buf),
2411 self.second.fill_buf()
2414 fn consume(&mut self, amt: usize) {
2415 if !self.done_first { self.first.consume(amt) } else { self.second.consume(amt) }
2419 impl<T, U> SizeHint for Chain<T, U> {
2421 fn lower_bound(&self) -> usize {
2422 SizeHint::lower_bound(&self.first) + SizeHint::lower_bound(&self.second)
2426 fn upper_bound(&self) -> Option<usize> {
2427 match (SizeHint::upper_bound(&self.first), SizeHint::upper_bound(&self.second)) {
2428 (Some(first), Some(second)) => first.checked_add(second),
2434 /// Reader adapter which limits the bytes read from an underlying reader.
2436 /// This struct is generally created by calling [`take`] on a reader.
2437 /// Please see the documentation of [`take`] for more details.
2439 /// [`take`]: Read::take
2440 #[stable(feature = "rust1", since = "1.0.0")]
2442 pub struct Take<T> {
2448 /// Returns the number of bytes that can be read before this instance will
2453 /// This instance may reach `EOF` after reading fewer bytes than indicated by
2454 /// this method if the underlying [`Read`] instance reaches EOF.
2460 /// use std::io::prelude::*;
2461 /// use std::fs::File;
2463 /// fn main() -> io::Result<()> {
2464 /// let f = File::open("foo.txt")?;
2466 /// // read at most five bytes
2467 /// let handle = f.take(5);
2469 /// println!("limit: {}", handle.limit());
2473 #[stable(feature = "rust1", since = "1.0.0")]
2474 pub fn limit(&self) -> u64 {
2478 /// Sets the number of bytes that can be read before this instance will
2479 /// return EOF. This is the same as constructing a new `Take` instance, so
2480 /// the amount of bytes read and the previous limit value don't matter when
2481 /// calling this method.
2487 /// use std::io::prelude::*;
2488 /// use std::fs::File;
2490 /// fn main() -> io::Result<()> {
2491 /// let f = File::open("foo.txt")?;
2493 /// // read at most five bytes
2494 /// let mut handle = f.take(5);
2495 /// handle.set_limit(10);
2497 /// assert_eq!(handle.limit(), 10);
2501 #[stable(feature = "take_set_limit", since = "1.27.0")]
2502 pub fn set_limit(&mut self, limit: u64) {
2506 /// Consumes the `Take`, returning the wrapped reader.
2512 /// use std::io::prelude::*;
2513 /// use std::fs::File;
2515 /// fn main() -> io::Result<()> {
2516 /// let mut file = File::open("foo.txt")?;
2518 /// let mut buffer = [0; 5];
2519 /// let mut handle = file.take(5);
2520 /// handle.read(&mut buffer)?;
2522 /// let file = handle.into_inner();
2526 #[stable(feature = "io_take_into_inner", since = "1.15.0")]
2527 pub fn into_inner(self) -> T {
2531 /// Gets a reference to the underlying reader.
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_ref();
2551 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2552 pub fn get_ref(&self) -> &T {
2556 /// Gets a mutable reference to the underlying reader.
2558 /// Care should be taken to avoid modifying the internal I/O state of the
2559 /// underlying reader as doing so may corrupt the internal limit of this
2566 /// use std::io::prelude::*;
2567 /// use std::fs::File;
2569 /// fn main() -> io::Result<()> {
2570 /// let mut file = File::open("foo.txt")?;
2572 /// let mut buffer = [0; 5];
2573 /// let mut handle = file.take(5);
2574 /// handle.read(&mut buffer)?;
2576 /// let file = handle.get_mut();
2580 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2581 pub fn get_mut(&mut self) -> &mut T {
2586 #[stable(feature = "rust1", since = "1.0.0")]
2587 impl<T: Read> Read for Take<T> {
2588 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2589 // Don't call into inner reader at all at EOF because it may still block
2590 if self.limit == 0 {
2594 let max = cmp::min(buf.len() as u64, self.limit) as usize;
2595 let n = self.inner.read(&mut buf[..max])?;
2596 assert!(n as u64 <= self.limit, "number of read bytes exceeds limit");
2597 self.limit -= n as u64;
2601 fn read_buf(&mut self, mut buf: BorrowedCursor<'_>) -> Result<()> {
2602 // Don't call into inner reader at all at EOF because it may still block
2603 if self.limit == 0 {
2607 if self.limit <= buf.capacity() as u64 {
2608 // if we just use an as cast to convert, limit may wrap around on a 32 bit target
2609 let limit = cmp::min(self.limit, usize::MAX as u64) as usize;
2611 let extra_init = cmp::min(limit as usize, buf.init_ref().len());
2613 // SAFETY: no uninit data is written to ibuf
2614 let ibuf = unsafe { &mut buf.as_mut()[..limit] };
2616 let mut sliced_buf: BorrowedBuf<'_> = ibuf.into();
2618 // SAFETY: extra_init bytes of ibuf are known to be initialized
2620 sliced_buf.set_init(extra_init);
2623 let mut cursor = sliced_buf.unfilled();
2624 self.inner.read_buf(cursor.reborrow())?;
2626 let new_init = cursor.init_ref().len();
2627 let filled = sliced_buf.len();
2629 // cursor / sliced_buf / ibuf must drop here
2632 // SAFETY: filled bytes have been filled and therefore initialized
2633 buf.advance(filled);
2634 // SAFETY: new_init bytes of buf's unfilled buffer have been initialized
2635 buf.set_init(new_init);
2638 self.limit -= filled as u64;
2640 let written = buf.written();
2641 self.inner.read_buf(buf.reborrow())?;
2642 self.limit -= (buf.written() - written) as u64;
2649 #[stable(feature = "rust1", since = "1.0.0")]
2650 impl<T: BufRead> BufRead for Take<T> {
2651 fn fill_buf(&mut self) -> Result<&[u8]> {
2652 // Don't call into inner reader at all at EOF because it may still block
2653 if self.limit == 0 {
2657 let buf = self.inner.fill_buf()?;
2658 let cap = cmp::min(buf.len() as u64, self.limit) as usize;
2662 fn consume(&mut self, amt: usize) {
2663 // Don't let callers reset the limit by passing an overlarge value
2664 let amt = cmp::min(amt as u64, self.limit) as usize;
2665 self.limit -= amt as u64;
2666 self.inner.consume(amt);
2670 impl<T> SizeHint for Take<T> {
2672 fn lower_bound(&self) -> usize {
2673 cmp::min(SizeHint::lower_bound(&self.inner) as u64, self.limit) as usize
2677 fn upper_bound(&self) -> Option<usize> {
2678 match SizeHint::upper_bound(&self.inner) {
2679 Some(upper_bound) => Some(cmp::min(upper_bound as u64, self.limit) as usize),
2680 None => self.limit.try_into().ok(),
2685 /// An iterator over `u8` values of a reader.
2687 /// This struct is generally created by calling [`bytes`] on a reader.
2688 /// Please see the documentation of [`bytes`] for more details.
2690 /// [`bytes`]: Read::bytes
2691 #[stable(feature = "rust1", since = "1.0.0")]
2693 pub struct Bytes<R> {
2697 #[stable(feature = "rust1", since = "1.0.0")]
2698 impl<R: Read> Iterator for Bytes<R> {
2699 type Item = Result<u8>;
2701 fn next(&mut self) -> Option<Result<u8>> {
2704 return match self.inner.read(slice::from_mut(&mut byte)) {
2706 Ok(..) => Some(Ok(byte)),
2707 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
2708 Err(e) => Some(Err(e)),
2713 fn size_hint(&self) -> (usize, Option<usize>) {
2714 SizeHint::size_hint(&self.inner)
2719 fn lower_bound(&self) -> usize;
2721 fn upper_bound(&self) -> Option<usize>;
2723 fn size_hint(&self) -> (usize, Option<usize>) {
2724 (self.lower_bound(), self.upper_bound())
2728 impl<T> SizeHint for T {
2730 default fn lower_bound(&self) -> usize {
2735 default fn upper_bound(&self) -> Option<usize> {
2740 impl<T> SizeHint for &mut T {
2742 fn lower_bound(&self) -> usize {
2743 SizeHint::lower_bound(*self)
2747 fn upper_bound(&self) -> Option<usize> {
2748 SizeHint::upper_bound(*self)
2752 impl<T> SizeHint for Box<T> {
2754 fn lower_bound(&self) -> usize {
2755 SizeHint::lower_bound(&**self)
2759 fn upper_bound(&self) -> Option<usize> {
2760 SizeHint::upper_bound(&**self)
2764 impl SizeHint for &[u8] {
2766 fn lower_bound(&self) -> usize {
2771 fn upper_bound(&self) -> Option<usize> {
2776 /// An iterator over the contents of an instance of `BufRead` split on a
2777 /// particular byte.
2779 /// This struct is generally created by calling [`split`] on a `BufRead`.
2780 /// Please see the documentation of [`split`] for more details.
2782 /// [`split`]: BufRead::split
2783 #[stable(feature = "rust1", since = "1.0.0")]
2785 pub struct Split<B> {
2790 #[stable(feature = "rust1", since = "1.0.0")]
2791 impl<B: BufRead> Iterator for Split<B> {
2792 type Item = Result<Vec<u8>>;
2794 fn next(&mut self) -> Option<Result<Vec<u8>>> {
2795 let mut buf = Vec::new();
2796 match self.buf.read_until(self.delim, &mut buf) {
2799 if buf[buf.len() - 1] == self.delim {
2804 Err(e) => Some(Err(e)),
2809 /// An iterator over the lines of an instance of `BufRead`.
2811 /// This struct is generally created by calling [`lines`] on a `BufRead`.
2812 /// Please see the documentation of [`lines`] for more details.
2814 /// [`lines`]: BufRead::lines
2815 #[stable(feature = "rust1", since = "1.0.0")]
2817 pub struct Lines<B> {
2821 #[stable(feature = "rust1", since = "1.0.0")]
2822 impl<B: BufRead> Iterator for Lines<B> {
2823 type Item = Result<String>;
2825 fn next(&mut self) -> Option<Result<String>> {
2826 let mut buf = String::new();
2827 match self.buf.read_line(&mut buf) {
2830 if buf.ends_with('\n') {
2832 if buf.ends_with('\r') {
2838 Err(e) => Some(Err(e)),