1 //! Traits, helpers, and type definitions for core I/O functionality.
3 //! The `std::io` module contains a number of common things you'll need
4 //! when doing input and output. The most core part of this module is
5 //! the [`Read`] and [`Write`] traits, which provide the
6 //! most general interface for reading and writing input and output.
10 //! Because they are traits, [`Read`] and [`Write`] are implemented by a number
11 //! of other types, and you can implement them for your types too. As such,
12 //! you'll see a few different types of I/O throughout the documentation in
13 //! this module: [`File`]s, [`TcpStream`]s, and sometimes even [`Vec<T>`]s. For
14 //! example, [`Read`] adds a [`read`][`Read::read`] method, which we can use on
19 //! use std::io::prelude::*;
20 //! use std::fs::File;
22 //! fn main() -> io::Result<()> {
23 //! let mut f = File::open("foo.txt")?;
24 //! let mut buffer = [0; 10];
26 //! // read up to 10 bytes
27 //! let n = f.read(&mut buffer)?;
29 //! println!("The bytes: {:?}", &buffer[..n]);
34 //! [`Read`] and [`Write`] are so important, implementors of the two traits have a
35 //! nickname: readers and writers. So you'll sometimes see 'a reader' instead
36 //! of 'a type that implements the [`Read`] trait'. Much easier!
38 //! ## Seek and BufRead
40 //! Beyond that, there are two important traits that are provided: [`Seek`]
41 //! and [`BufRead`]. Both of these build on top of a reader to control
42 //! how the reading happens. [`Seek`] lets you control where the next byte is
47 //! use std::io::prelude::*;
48 //! use std::io::SeekFrom;
49 //! use std::fs::File;
51 //! fn main() -> io::Result<()> {
52 //! let mut f = File::open("foo.txt")?;
53 //! let mut buffer = [0; 10];
55 //! // skip to the last 10 bytes of the file
56 //! f.seek(SeekFrom::End(-10))?;
58 //! // read up to 10 bytes
59 //! let n = f.read(&mut buffer)?;
61 //! println!("The bytes: {:?}", &buffer[..n]);
66 //! [`BufRead`] uses an internal buffer to provide a number of other ways to read, but
67 //! to show it off, we'll need to talk about buffers in general. Keep reading!
69 //! ## BufReader and BufWriter
71 //! Byte-based interfaces are unwieldy and can be inefficient, as we'd need to be
72 //! making near-constant calls to the operating system. To help with this,
73 //! `std::io` comes with two structs, [`BufReader`] and [`BufWriter`], which wrap
74 //! readers and writers. The wrapper uses a buffer, reducing the number of
75 //! calls and providing nicer methods for accessing exactly what you want.
77 //! For example, [`BufReader`] works with the [`BufRead`] trait to add extra
78 //! methods to any reader:
82 //! use std::io::prelude::*;
83 //! use std::io::BufReader;
84 //! use std::fs::File;
86 //! fn main() -> io::Result<()> {
87 //! let f = File::open("foo.txt")?;
88 //! let mut reader = BufReader::new(f);
89 //! let mut buffer = String::new();
91 //! // read a line into buffer
92 //! reader.read_line(&mut buffer)?;
94 //! println!("{buffer}");
99 //! [`BufWriter`] doesn't add any new ways of writing; it just buffers every call
100 //! to [`write`][`Write::write`]:
104 //! use std::io::prelude::*;
105 //! use std::io::BufWriter;
106 //! use std::fs::File;
108 //! fn main() -> io::Result<()> {
109 //! let f = File::create("foo.txt")?;
111 //! let mut writer = BufWriter::new(f);
113 //! // write a byte to the buffer
114 //! writer.write(&[42])?;
116 //! } // the buffer is flushed once writer goes out of scope
122 //! ## Standard input and output
124 //! A very common source of input is standard input:
129 //! fn main() -> io::Result<()> {
130 //! let mut input = String::new();
132 //! io::stdin().read_line(&mut input)?;
134 //! println!("You typed: {}", input.trim());
139 //! Note that you cannot use the [`?` operator] in functions that do not return
140 //! a [`Result<T, E>`][`Result`]. Instead, you can call [`.unwrap()`]
141 //! or `match` on the return value to catch any possible errors:
146 //! let mut input = String::new();
148 //! io::stdin().read_line(&mut input).unwrap();
151 //! And a very common source of output is standard output:
155 //! use std::io::prelude::*;
157 //! fn main() -> io::Result<()> {
158 //! io::stdout().write(&[42])?;
163 //! Of course, using [`io::stdout`] directly is less common than something like
166 //! ## Iterator types
168 //! A large number of the structures provided by `std::io` are for various
169 //! ways of iterating over I/O. For example, [`Lines`] is used to split over
174 //! use std::io::prelude::*;
175 //! use std::io::BufReader;
176 //! use std::fs::File;
178 //! fn main() -> io::Result<()> {
179 //! let f = File::open("foo.txt")?;
180 //! let reader = BufReader::new(f);
182 //! for line in reader.lines() {
183 //! println!("{}", line?);
191 //! There are a number of [functions][functions-list] that offer access to various
192 //! features. For example, we can use three of these functions to copy everything
193 //! from standard input to standard output:
198 //! fn main() -> io::Result<()> {
199 //! io::copy(&mut io::stdin(), &mut io::stdout())?;
204 //! [functions-list]: #functions-1
208 //! Last, but certainly not least, is [`io::Result`]. This type is used
209 //! as the return type of many `std::io` functions that can cause an error, and
210 //! can be returned from your own functions as well. Many of the examples in this
211 //! module use the [`?` operator]:
216 //! fn read_input() -> io::Result<()> {
217 //! let mut input = String::new();
219 //! io::stdin().read_line(&mut input)?;
221 //! println!("You typed: {}", input.trim());
227 //! The return type of `read_input()`, [`io::Result<()>`][`io::Result`], is a very
228 //! common type for functions which don't have a 'real' return value, but do want to
229 //! return errors if they happen. In this case, the only purpose of this function is
230 //! to read the line and print it, so we use `()`.
232 //! ## Platform-specific behavior
234 //! Many I/O functions throughout the standard library are documented to indicate
235 //! what various library or syscalls they are delegated to. This is done to help
236 //! applications both understand what's happening under the hood as well as investigate
237 //! any possibly unclear semantics. Note, however, that this is informative, not a binding
238 //! contract. The implementation of many of these functions are subject to change over
239 //! time and may call fewer or more syscalls/library functions.
241 //! [`File`]: crate::fs::File
242 //! [`TcpStream`]: crate::net::TcpStream
243 //! [`io::stdout`]: stdout
244 //! [`io::Result`]: self::Result
245 //! [`?` operator]: ../../book/appendix-02-operators.html
246 //! [`Result`]: crate::result::Result
247 //! [`.unwrap()`]: crate::result::Result::unwrap
249 #![stable(feature = "rust1", since = "1.0.0")]
255 use crate::convert
::TryInto
;
257 use crate::mem
::replace
;
258 use crate::ops
::{Deref, DerefMut}
;
262 use crate::sys_common
::memchr
;
264 #[stable(feature = "bufwriter_into_parts", since = "1.56.0")]
265 pub use self::buffered
::WriterPanicked
;
266 #[unstable(feature = "internal_output_capture", issue = "none")]
267 #[doc(no_inline, hidden)]
268 pub use self::stdio
::set_output_capture
;
269 #[unstable(feature = "print_internals", issue = "none")]
270 pub use self::stdio
::{_eprint, _print}
;
271 #[stable(feature = "rust1", since = "1.0.0")]
273 buffered
::{BufReader, BufWriter, IntoInnerError, LineWriter}
,
276 error
::{Error, ErrorKind, Result}
,
277 stdio
::{stderr, stdin, stdout, Stderr, StderrLock, Stdin, StdinLock, Stdout, StdoutLock}
,
278 util
::{empty, repeat, sink, Empty, Repeat, Sink}
,
281 #[unstable(feature = "read_buf", issue = "78485")]
282 pub use self::readbuf
::ReadBuf
;
283 pub(crate) use error
::const_io_error
;
295 const DEFAULT_BUF_SIZE
: usize = crate::sys_common
::io
::DEFAULT_BUF_SIZE
;
297 pub(crate) use stdio
::cleanup
;
300 buf
: &'a
mut Vec
<u8>,
304 impl Drop
for Guard
<'_
> {
307 self.buf
.set_len(self.len
);
312 // Several `read_to_string` and `read_line` methods in the standard library will
313 // append data into a `String` buffer, but we need to be pretty careful when
314 // doing this. The implementation will just call `.as_mut_vec()` and then
315 // delegate to a byte-oriented reading method, but we must ensure that when
316 // returning we never leave `buf` in a state such that it contains invalid UTF-8
319 // To this end, we use an RAII guard (to protect against panics) which updates
320 // the length of the string when it is dropped. This guard initially truncates
321 // the string to the prior length and only after we've validated that the
322 // new contents are valid UTF-8 do we allow it to set a longer length.
324 // The unsafety in this function is twofold:
326 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
328 // 2. We're passing a raw buffer to the function `f`, and it is expected that
329 // the function only *appends* bytes to the buffer. We'll get undefined
330 // behavior if existing bytes are overwritten to have non-UTF-8 data.
331 pub(crate) unsafe fn append_to_string
<F
>(buf
: &mut String
, f
: F
) -> Result
<usize>
333 F
: FnOnce(&mut Vec
<u8>) -> Result
<usize>,
335 let mut g
= Guard { len: buf.len(), buf: buf.as_mut_vec() }
;
337 if str::from_utf8(&g
.buf
[g
.len
..]).is_err() {
339 Err(error
::const_io_error
!(
340 ErrorKind
::InvalidData
,
341 "stream did not contain valid UTF-8"
350 // This uses an adaptive system to extend the vector when it fills. We want to
351 // avoid paying to allocate and zero a huge chunk of memory if the reader only
352 // has 4 bytes while still making large reads if the reader does have a ton
353 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
354 // time is 4,500 times (!) slower than a default reservation size of 32 if the
355 // reader has a very small amount of data to return.
356 pub(crate) fn default_read_to_end
<R
: Read
+ ?Sized
>(r
: &mut R
, buf
: &mut Vec
<u8>) -> Result
<usize> {
357 let start_len
= buf
.len();
358 let start_cap
= buf
.capacity();
360 let mut initialized
= 0; // Extra initialized bytes from previous loop iteration
362 if buf
.len() == buf
.capacity() {
363 buf
.reserve(32); // buf is full, need more space
366 let mut read_buf
= ReadBuf
::uninit(buf
.spare_capacity_mut());
368 // SAFETY: These bytes were initialized but not filled in the previous loop
370 read_buf
.assume_init(initialized
);
373 match r
.read_buf(&mut read_buf
) {
375 Err(e
) if e
.kind() == ErrorKind
::Interrupted
=> continue,
376 Err(e
) => return Err(e
),
379 if read_buf
.filled_len() == 0 {
380 return Ok(buf
.len() - start_len
);
383 // store how much was initialized but not filled
384 initialized
= read_buf
.initialized_len() - read_buf
.filled_len();
385 let new_len
= read_buf
.filled_len() + buf
.len();
387 // SAFETY: ReadBuf's invariants mean this much memory is init
389 buf
.set_len(new_len
);
392 if buf
.len() == buf
.capacity() && buf
.capacity() == start_cap
{
393 // The buffer might be an exact fit. Let's read into a probe buffer
394 // and see if it returns `Ok(0)`. If so, we've avoided an
395 // unnecessary doubling of the capacity. But if not, append the
396 // probe buffer to the primary buffer and let its capacity grow.
397 let mut probe
= [0u8; 32];
400 match r
.read(&mut probe
) {
401 Ok(0) => return Ok(buf
.len() - start_len
),
403 buf
.extend_from_slice(&probe
[..n
]);
406 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> continue,
407 Err(e
) => return Err(e
),
414 pub(crate) fn default_read_to_string
<R
: Read
+ ?Sized
>(
418 // Note that we do *not* call `r.read_to_end()` here. We are passing
419 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
420 // method to fill it up. An arbitrary implementation could overwrite the
421 // entire contents of the vector, not just append to it (which is what
422 // we are expecting).
424 // To prevent extraneously checking the UTF-8-ness of the entire buffer
425 // we pass it to our hardcoded `default_read_to_end` implementation which
426 // we know is guaranteed to only read data into the end of the buffer.
427 unsafe { append_to_string(buf, |b| default_read_to_end(r, b)) }
430 pub(crate) fn default_read_vectored
<F
>(read
: F
, bufs
: &mut [IoSliceMut
<'_
>]) -> Result
<usize>
432 F
: FnOnce(&mut [u8]) -> Result
<usize>,
434 let buf
= bufs
.iter_mut().find(|b
| !b
.is_empty()).map_or(&mut [][..], |b
| &mut **b
);
438 pub(crate) fn default_write_vectored
<F
>(write
: F
, bufs
: &[IoSlice
<'_
>]) -> Result
<usize>
440 F
: FnOnce(&[u8]) -> Result
<usize>,
442 let buf
= bufs
.iter().find(|b
| !b
.is_empty()).map_or(&[][..], |b
| &**b
);
446 pub(crate) fn default_read_exact
<R
: Read
+ ?Sized
>(this
: &mut R
, mut buf
: &mut [u8]) -> Result
<()> {
447 while !buf
.is_empty() {
448 match this
.read(buf
) {
454 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> {}
455 Err(e
) => return Err(e
),
459 Err(error
::const_io_error
!(ErrorKind
::UnexpectedEof
, "failed to fill whole buffer"))
465 pub(crate) fn default_read_buf
<F
>(read
: F
, buf
: &mut ReadBuf
<'_
>) -> Result
<()>
467 F
: FnOnce(&mut [u8]) -> Result
<usize>,
469 let n
= read(buf
.initialize_unfilled())?
;
474 /// The `Read` trait allows for reading bytes from a source.
476 /// Implementors of the `Read` trait are called 'readers'.
478 /// Readers are defined by one required method, [`read()`]. Each call to [`read()`]
479 /// will attempt to pull bytes from this source into a provided buffer. A
480 /// number of other methods are implemented in terms of [`read()`], giving
481 /// implementors a number of ways to read bytes while only needing to implement
484 /// Readers are intended to be composable with one another. Many implementors
485 /// throughout [`std::io`] take and provide types which implement the `Read`
488 /// Please note that each call to [`read()`] may involve a system call, and
489 /// therefore, using something that implements [`BufRead`], such as
490 /// [`BufReader`], will be more efficient.
494 /// [`File`]s implement `Read`:
498 /// use std::io::prelude::*;
499 /// use std::fs::File;
501 /// fn main() -> io::Result<()> {
502 /// let mut f = File::open("foo.txt")?;
503 /// let mut buffer = [0; 10];
505 /// // read up to 10 bytes
506 /// f.read(&mut buffer)?;
508 /// let mut buffer = Vec::new();
509 /// // read the whole file
510 /// f.read_to_end(&mut buffer)?;
512 /// // read into a String, so that you don't need to do the conversion.
513 /// let mut buffer = String::new();
514 /// f.read_to_string(&mut buffer)?;
516 /// // and more! See the other methods for more details.
521 /// Read from [`&str`] because [`&[u8]`][prim@slice] implements `Read`:
525 /// use std::io::prelude::*;
527 /// fn main() -> io::Result<()> {
528 /// let mut b = "This string will be read".as_bytes();
529 /// let mut buffer = [0; 10];
531 /// // read up to 10 bytes
532 /// b.read(&mut buffer)?;
534 /// // etc... it works exactly as a File does!
539 /// [`read()`]: Read::read
540 /// [`&str`]: prim@str
541 /// [`std::io`]: self
542 /// [`File`]: crate::fs::File
543 #[stable(feature = "rust1", since = "1.0.0")]
544 #[doc(notable_trait)]
545 #[cfg_attr(not(test), rustc_diagnostic_item = "IoRead")]
547 /// Pull some bytes from this source into the specified buffer, returning
548 /// how many bytes were read.
550 /// This function does not provide any guarantees about whether it blocks
551 /// waiting for data, but if an object needs to block for a read and cannot,
552 /// it will typically signal this via an [`Err`] return value.
554 /// If the return value of this method is [`Ok(n)`], then implementations must
555 /// guarantee that `0 <= n <= buf.len()`. A nonzero `n` value indicates
556 /// that the buffer `buf` has been filled in with `n` bytes of data from this
557 /// source. If `n` is `0`, then it can indicate one of two scenarios:
559 /// 1. This reader has reached its "end of file" and will likely no longer
560 /// be able to produce bytes. Note that this does not mean that the
561 /// reader will *always* no longer be able to produce bytes. As an example,
562 /// on Linux, this method will call the `recv` syscall for a [`TcpStream`],
563 /// where returning zero indicates the connection was shut down correctly. While
564 /// for [`File`], it is possible to reach the end of file and get zero as result,
565 /// but if more data is appended to the file, future calls to `read` will return
567 /// 2. The buffer specified was 0 bytes in length.
569 /// It is not an error if the returned value `n` is smaller than the buffer size,
570 /// even when the reader is not at the end of the stream yet.
571 /// This may happen for example because fewer bytes are actually available right now
572 /// (e. g. being close to end-of-file) or because read() was interrupted by a signal.
574 /// As this trait is safe to implement, callers cannot rely on `n <= buf.len()` for safety.
575 /// Extra care needs to be taken when `unsafe` functions are used to access the read bytes.
576 /// Callers have to ensure that no unchecked out-of-bounds accesses are possible even if
579 /// No guarantees are provided about the contents of `buf` when this
580 /// function is called, implementations cannot rely on any property of the
581 /// contents of `buf` being true. It is recommended that *implementations*
582 /// only write data to `buf` instead of reading its contents.
584 /// Correspondingly, however, *callers* of this method must not assume any guarantees
585 /// about how the implementation uses `buf`. The trait is safe to implement,
586 /// so it is possible that the code that's supposed to write to the buffer might also read
587 /// from it. It is your responsibility to make sure that `buf` is initialized
588 /// before calling `read`. Calling `read` with an uninitialized `buf` (of the kind one
589 /// obtains via [`MaybeUninit<T>`]) is not safe, and can lead to undefined behavior.
591 /// [`MaybeUninit<T>`]: crate::mem::MaybeUninit
595 /// If this function encounters any form of I/O or other error, an error
596 /// variant will be returned. If an error is returned then it must be
597 /// guaranteed that no bytes were read.
599 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
600 /// operation should be retried if there is nothing else to do.
604 /// [`File`]s implement `Read`:
607 /// [`File`]: crate::fs::File
608 /// [`TcpStream`]: crate::net::TcpStream
612 /// use std::io::prelude::*;
613 /// use std::fs::File;
615 /// fn main() -> io::Result<()> {
616 /// let mut f = File::open("foo.txt")?;
617 /// let mut buffer = [0; 10];
619 /// // read up to 10 bytes
620 /// let n = f.read(&mut buffer[..])?;
622 /// println!("The bytes: {:?}", &buffer[..n]);
626 #[stable(feature = "rust1", since = "1.0.0")]
627 fn read(&mut self, buf
: &mut [u8]) -> Result
<usize>;
629 /// Like `read`, except that it reads into a slice of buffers.
631 /// Data is copied to fill each buffer in order, with the final buffer
632 /// written to possibly being only partially filled. This method must
633 /// behave equivalently to a single call to `read` with concatenated
636 /// The default implementation calls `read` with either the first nonempty
637 /// buffer provided, or an empty one if none exists.
638 #[stable(feature = "iovec", since = "1.36.0")]
639 fn read_vectored(&mut self, bufs
: &mut [IoSliceMut
<'_
>]) -> Result
<usize> {
640 default_read_vectored(|b
| self.read(b
), bufs
)
643 /// Determines if this `Read`er has an efficient `read_vectored`
646 /// If a `Read`er does not override the default `read_vectored`
647 /// implementation, code using it may want to avoid the method all together
648 /// and coalesce writes into a single buffer for higher performance.
650 /// The default implementation returns `false`.
651 #[unstable(feature = "can_vector", issue = "69941")]
652 fn is_read_vectored(&self) -> bool
{
656 /// Read all bytes until EOF in this source, placing them into `buf`.
658 /// All bytes read from this source will be appended to the specified buffer
659 /// `buf`. This function will continuously call [`read()`] to append more data to
660 /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of
661 /// non-[`ErrorKind::Interrupted`] kind.
663 /// If successful, this function will return the total number of bytes read.
667 /// If this function encounters an error of the kind
668 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
671 /// If any other read error is encountered then this function immediately
672 /// returns. Any bytes which have already been read will be appended to
677 /// [`File`]s implement `Read`:
679 /// [`read()`]: Read::read
681 /// [`File`]: crate::fs::File
685 /// use std::io::prelude::*;
686 /// use std::fs::File;
688 /// fn main() -> io::Result<()> {
689 /// let mut f = File::open("foo.txt")?;
690 /// let mut buffer = Vec::new();
692 /// // read the whole file
693 /// f.read_to_end(&mut buffer)?;
698 /// (See also the [`std::fs::read`] convenience function for reading from a
701 /// [`std::fs::read`]: crate::fs::read
702 #[stable(feature = "rust1", since = "1.0.0")]
703 fn read_to_end(&mut self, buf
: &mut Vec
<u8>) -> Result
<usize> {
704 default_read_to_end(self, buf
)
707 /// Read all bytes until EOF in this source, appending them to `buf`.
709 /// If successful, this function returns the number of bytes which were read
710 /// and appended to `buf`.
714 /// If the data in this stream is *not* valid UTF-8 then an error is
715 /// returned and `buf` is unchanged.
717 /// See [`read_to_end`] for other error semantics.
719 /// [`read_to_end`]: Read::read_to_end
723 /// [`File`]s implement `Read`:
725 /// [`File`]: crate::fs::File
729 /// use std::io::prelude::*;
730 /// use std::fs::File;
732 /// fn main() -> io::Result<()> {
733 /// let mut f = File::open("foo.txt")?;
734 /// let mut buffer = String::new();
736 /// f.read_to_string(&mut buffer)?;
741 /// (See also the [`std::fs::read_to_string`] convenience function for
742 /// reading from a file.)
744 /// [`std::fs::read_to_string`]: crate::fs::read_to_string
745 #[stable(feature = "rust1", since = "1.0.0")]
746 fn read_to_string(&mut self, buf
: &mut String
) -> Result
<usize> {
747 default_read_to_string(self, buf
)
750 /// Read the exact number of bytes required to fill `buf`.
752 /// This function reads as many bytes as necessary to completely fill the
753 /// specified buffer `buf`.
755 /// No guarantees are provided about the contents of `buf` when this
756 /// function is called, implementations cannot rely on any property of the
757 /// contents of `buf` being true. It is recommended that implementations
758 /// only write data to `buf` instead of reading its contents. The
759 /// documentation on [`read`] has a more detailed explanation on this
764 /// If this function encounters an error of the kind
765 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
768 /// If this function encounters an "end of file" before completely filling
769 /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
770 /// The contents of `buf` are unspecified in this case.
772 /// If any other read error is encountered then this function immediately
773 /// returns. The contents of `buf` are unspecified in this case.
775 /// If this function returns an error, it is unspecified how many bytes it
776 /// has read, but it will never read more than would be necessary to
777 /// completely fill the buffer.
781 /// [`File`]s implement `Read`:
783 /// [`read`]: Read::read
784 /// [`File`]: crate::fs::File
788 /// use std::io::prelude::*;
789 /// use std::fs::File;
791 /// fn main() -> io::Result<()> {
792 /// let mut f = File::open("foo.txt")?;
793 /// let mut buffer = [0; 10];
795 /// // read exactly 10 bytes
796 /// f.read_exact(&mut buffer)?;
800 #[stable(feature = "read_exact", since = "1.6.0")]
801 fn read_exact(&mut self, buf
: &mut [u8]) -> Result
<()> {
802 default_read_exact(self, buf
)
805 /// Pull some bytes from this source into the specified buffer.
807 /// This is equivalent to the [`read`](Read::read) method, except that it is passed a [`ReadBuf`] rather than `[u8]` to allow use
808 /// with uninitialized buffers. The new data will be appended to any existing contents of `buf`.
810 /// The default implementation delegates to `read`.
811 #[unstable(feature = "read_buf", issue = "78485")]
812 fn read_buf(&mut self, buf
: &mut ReadBuf
<'_
>) -> Result
<()> {
813 default_read_buf(|b
| self.read(b
), buf
)
816 /// Read the exact number of bytes required to fill `buf`.
818 /// This is equivalent to the [`read_exact`](Read::read_exact) method, except that it is passed a [`ReadBuf`] rather than `[u8]` to
819 /// allow use with uninitialized buffers.
820 #[unstable(feature = "read_buf", issue = "78485")]
821 fn read_buf_exact(&mut self, buf
: &mut ReadBuf
<'_
>) -> Result
<()> {
822 while buf
.remaining() > 0 {
823 let prev_filled
= buf
.filled().len();
824 match self.read_buf(buf
) {
826 Err(e
) if e
.kind() == ErrorKind
::Interrupted
=> continue,
827 Err(e
) => return Err(e
),
830 if buf
.filled().len() == prev_filled
{
831 return Err(Error
::new(ErrorKind
::UnexpectedEof
, "failed to fill buffer"));
838 /// Creates a "by reference" adaptor for this instance of `Read`.
840 /// The returned adapter also implements `Read` and will simply borrow this
845 /// [`File`]s implement `Read`:
847 /// [`File`]: crate::fs::File
851 /// use std::io::Read;
852 /// use std::fs::File;
854 /// fn main() -> io::Result<()> {
855 /// let mut f = File::open("foo.txt")?;
856 /// let mut buffer = Vec::new();
857 /// let mut other_buffer = Vec::new();
860 /// let reference = f.by_ref();
862 /// // read at most 5 bytes
863 /// reference.take(5).read_to_end(&mut buffer)?;
865 /// } // drop our &mut reference so we can use f again
867 /// // original file still usable, read the rest
868 /// f.read_to_end(&mut other_buffer)?;
872 #[stable(feature = "rust1", since = "1.0.0")]
873 fn by_ref(&mut self) -> &mut Self
880 /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
882 /// The returned type implements [`Iterator`] where the [`Item`] is
883 /// <code>[Result]<[u8], [io::Error]></code>.
884 /// The yielded item is [`Ok`] if a byte was successfully read and [`Err`]
885 /// otherwise. EOF is mapped to returning [`None`] from this iterator.
889 /// [`File`]s implement `Read`:
891 /// [`Item`]: Iterator::Item
892 /// [`File`]: crate::fs::File "fs::File"
893 /// [Result]: crate::result::Result "Result"
894 /// [io::Error]: self::Error "io::Error"
898 /// use std::io::prelude::*;
899 /// use std::fs::File;
901 /// fn main() -> io::Result<()> {
902 /// let mut f = File::open("foo.txt")?;
904 /// for byte in f.bytes() {
905 /// println!("{}", byte.unwrap());
910 #[stable(feature = "rust1", since = "1.0.0")]
911 fn bytes(self) -> Bytes
<Self>
915 Bytes { inner: self }
918 /// Creates an adapter which will chain this stream with another.
920 /// The returned `Read` instance will first read all bytes from this object
921 /// until EOF is encountered. Afterwards the output is equivalent to the
922 /// output of `next`.
926 /// [`File`]s implement `Read`:
928 /// [`File`]: crate::fs::File
932 /// use std::io::prelude::*;
933 /// use std::fs::File;
935 /// fn main() -> io::Result<()> {
936 /// let mut f1 = File::open("foo.txt")?;
937 /// let mut f2 = File::open("bar.txt")?;
939 /// let mut handle = f1.chain(f2);
940 /// let mut buffer = String::new();
942 /// // read the value into a String. We could use any Read method here,
943 /// // this is just one example.
944 /// handle.read_to_string(&mut buffer)?;
948 #[stable(feature = "rust1", since = "1.0.0")]
949 fn chain
<R
: Read
>(self, next
: R
) -> Chain
<Self, R
>
953 Chain { first: self, second: next, done_first: false }
956 /// Creates an adapter which will read at most `limit` bytes from it.
958 /// This function returns a new instance of `Read` which will read at most
959 /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
960 /// read errors will not count towards the number of bytes read and future
961 /// calls to [`read()`] may succeed.
965 /// [`File`]s implement `Read`:
967 /// [`File`]: crate::fs::File
969 /// [`read()`]: Read::read
973 /// use std::io::prelude::*;
974 /// use std::fs::File;
976 /// fn main() -> io::Result<()> {
977 /// let mut f = File::open("foo.txt")?;
978 /// let mut buffer = [0; 5];
980 /// // read at most five bytes
981 /// let mut handle = f.take(5);
983 /// handle.read(&mut buffer)?;
987 #[stable(feature = "rust1", since = "1.0.0")]
988 fn take(self, limit
: u64) -> Take
<Self>
992 Take { inner: self, limit }
996 /// Read all bytes from a [reader][Read] into a new [`String`].
998 /// This is a convenience function for [`Read::read_to_string`]. Using this
999 /// function avoids having to create a variable first and provides more type
1000 /// safety since you can only get the buffer out if there were no errors. (If you
1001 /// use [`Read::read_to_string`] you have to remember to check whether the read
1002 /// succeeded because otherwise your buffer will be empty or only partially full.)
1006 /// The downside of this function's increased ease of use and type safety is
1007 /// that it gives you less control over performance. For example, you can't
1008 /// pre-allocate memory like you can using [`String::with_capacity`] and
1009 /// [`Read::read_to_string`]. Also, you can't re-use the buffer if an error
1010 /// occurs while reading.
1012 /// In many cases, this function's performance will be adequate and the ease of use
1013 /// and type safety tradeoffs will be worth it. However, there are cases where you
1014 /// need more control over performance, and in those cases you should definitely use
1015 /// [`Read::read_to_string`] directly.
1017 /// Note that in some special cases, such as when reading files, this function will
1018 /// pre-allocate memory based on the size of the input it is reading. In those
1019 /// cases, the performance should be as good as if you had used
1020 /// [`Read::read_to_string`] with a manually pre-allocated buffer.
1024 /// This function forces you to handle errors because the output (the `String`)
1025 /// is wrapped in a [`Result`]. See [`Read::read_to_string`] for the errors
1026 /// that can occur. If any error occurs, you will get an [`Err`], so you
1027 /// don't have to worry about your buffer being empty or partially full.
1032 /// #![feature(io_read_to_string)]
1035 /// fn main() -> io::Result<()> {
1036 /// let stdin = io::read_to_string(io::stdin())?;
1037 /// println!("Stdin was:");
1038 /// println!("{stdin}");
1042 #[unstable(feature = "io_read_to_string", issue = "80218")]
1043 pub fn read_to_string
<R
: Read
>(mut reader
: R
) -> Result
<String
> {
1044 let mut buf
= String
::new();
1045 reader
.read_to_string(&mut buf
)?
;
1049 /// A buffer type used with `Read::read_vectored`.
1051 /// It is semantically a wrapper around an `&mut [u8]`, but is guaranteed to be
1052 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
1054 #[stable(feature = "iovec", since = "1.36.0")]
1055 #[repr(transparent)]
1056 pub struct IoSliceMut
<'a
>(sys
::io
::IoSliceMut
<'a
>);
1058 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1059 unsafe impl<'a
> Send
for IoSliceMut
<'a
> {}
1061 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1062 unsafe impl<'a
> Sync
for IoSliceMut
<'a
> {}
1064 #[stable(feature = "iovec", since = "1.36.0")]
1065 impl<'a
> fmt
::Debug
for IoSliceMut
<'a
> {
1066 fn fmt(&self, fmt
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1067 fmt
::Debug
::fmt(self.0.as_slice(), fmt
)
1071 impl<'a
> IoSliceMut
<'a
> {
1072 /// Creates a new `IoSliceMut` wrapping a byte slice.
1076 /// Panics on Windows if the slice is larger than 4GB.
1077 #[stable(feature = "iovec", since = "1.36.0")]
1079 pub fn new(buf
: &'a
mut [u8]) -> IoSliceMut
<'a
> {
1080 IoSliceMut(sys
::io
::IoSliceMut
::new(buf
))
1083 /// Advance the internal cursor of the slice.
1085 /// Also see [`IoSliceMut::advance_slices`] to advance the cursors of
1086 /// multiple buffers.
1091 /// #![feature(io_slice_advance)]
1093 /// use std::io::IoSliceMut;
1094 /// use std::ops::Deref;
1096 /// let mut data = [1; 8];
1097 /// let mut buf = IoSliceMut::new(&mut data);
1099 /// // Mark 3 bytes as read.
1101 /// assert_eq!(buf.deref(), [1; 5].as_ref());
1103 #[unstable(feature = "io_slice_advance", issue = "62726")]
1105 pub fn advance(&mut self, n
: usize) {
1109 /// Advance the internal cursor of the slices.
1113 /// Elements in the slice may be modified if the cursor is not advanced to
1114 /// the end of the slice. For example if we have a slice of buffers with 2
1115 /// `IoSliceMut`s, both of length 8, and we advance the cursor by 10 bytes
1116 /// the first `IoSliceMut` will be untouched however the second will be
1117 /// modified to remove the first 2 bytes (10 - 8).
1122 /// #![feature(io_slice_advance)]
1124 /// use std::io::IoSliceMut;
1125 /// use std::ops::Deref;
1127 /// let mut buf1 = [1; 8];
1128 /// let mut buf2 = [2; 16];
1129 /// let mut buf3 = [3; 8];
1130 /// let mut bufs = &mut [
1131 /// IoSliceMut::new(&mut buf1),
1132 /// IoSliceMut::new(&mut buf2),
1133 /// IoSliceMut::new(&mut buf3),
1136 /// // Mark 10 bytes as read.
1137 /// IoSliceMut::advance_slices(&mut bufs, 10);
1138 /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1139 /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1141 #[unstable(feature = "io_slice_advance", issue = "62726")]
1143 pub fn advance_slices(bufs
: &mut &mut [IoSliceMut
<'a
>], n
: usize) {
1144 // Number of buffers to remove.
1146 // Total length of all the to be removed buffers.
1147 let mut accumulated_len
= 0;
1148 for buf
in bufs
.iter() {
1149 if accumulated_len
+ buf
.len() > n
{
1152 accumulated_len
+= buf
.len();
1157 *bufs
= &mut replace(bufs
, &mut [])[remove
..];
1158 if !bufs
.is_empty() {
1159 bufs
[0].advance(n
- accumulated_len
)
1164 #[stable(feature = "iovec", since = "1.36.0")]
1165 impl<'a
> Deref
for IoSliceMut
<'a
> {
1169 fn deref(&self) -> &[u8] {
1174 #[stable(feature = "iovec", since = "1.36.0")]
1175 impl<'a
> DerefMut
for IoSliceMut
<'a
> {
1177 fn deref_mut(&mut self) -> &mut [u8] {
1178 self.0.as_mut_slice()
1182 /// A buffer type used with `Write::write_vectored`.
1184 /// It is semantically a wrapper around a `&[u8]`, but is guaranteed to be
1185 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
1187 #[stable(feature = "iovec", since = "1.36.0")]
1188 #[derive(Copy, Clone)]
1189 #[repr(transparent)]
1190 pub struct IoSlice
<'a
>(sys
::io
::IoSlice
<'a
>);
1192 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1193 unsafe impl<'a
> Send
for IoSlice
<'a
> {}
1195 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1196 unsafe impl<'a
> Sync
for IoSlice
<'a
> {}
1198 #[stable(feature = "iovec", since = "1.36.0")]
1199 impl<'a
> fmt
::Debug
for IoSlice
<'a
> {
1200 fn fmt(&self, fmt
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1201 fmt
::Debug
::fmt(self.0.as_slice(), fmt
)
1205 impl<'a
> IoSlice
<'a
> {
1206 /// Creates a new `IoSlice` wrapping a byte slice.
1210 /// Panics on Windows if the slice is larger than 4GB.
1211 #[stable(feature = "iovec", since = "1.36.0")]
1214 pub fn new(buf
: &'a
[u8]) -> IoSlice
<'a
> {
1215 IoSlice(sys
::io
::IoSlice
::new(buf
))
1218 /// Advance the internal cursor of the slice.
1220 /// Also see [`IoSlice::advance_slices`] to advance the cursors of multiple
1226 /// #![feature(io_slice_advance)]
1228 /// use std::io::IoSlice;
1229 /// use std::ops::Deref;
1231 /// let mut data = [1; 8];
1232 /// let mut buf = IoSlice::new(&mut data);
1234 /// // Mark 3 bytes as read.
1236 /// assert_eq!(buf.deref(), [1; 5].as_ref());
1238 #[unstable(feature = "io_slice_advance", issue = "62726")]
1240 pub fn advance(&mut self, n
: usize) {
1244 /// Advance the internal cursor of the slices.
1248 /// Elements in the slice may be modified if the cursor is not advanced to
1249 /// the end of the slice. For example if we have a slice of buffers with 2
1250 /// `IoSlice`s, both of length 8, and we advance the cursor by 10 bytes the
1251 /// first `IoSlice` will be untouched however the second will be modified to
1252 /// remove the first 2 bytes (10 - 8).
1257 /// #![feature(io_slice_advance)]
1259 /// use std::io::IoSlice;
1260 /// use std::ops::Deref;
1262 /// let buf1 = [1; 8];
1263 /// let buf2 = [2; 16];
1264 /// let buf3 = [3; 8];
1265 /// let mut bufs = &mut [
1266 /// IoSlice::new(&buf1),
1267 /// IoSlice::new(&buf2),
1268 /// IoSlice::new(&buf3),
1271 /// // Mark 10 bytes as written.
1272 /// IoSlice::advance_slices(&mut bufs, 10);
1273 /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1274 /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1275 #[unstable(feature = "io_slice_advance", issue = "62726")]
1277 pub fn advance_slices(bufs
: &mut &mut [IoSlice
<'a
>], n
: usize) {
1278 // Number of buffers to remove.
1280 // Total length of all the to be removed buffers.
1281 let mut accumulated_len
= 0;
1282 for buf
in bufs
.iter() {
1283 if accumulated_len
+ buf
.len() > n
{
1286 accumulated_len
+= buf
.len();
1291 *bufs
= &mut replace(bufs
, &mut [])[remove
..];
1292 if !bufs
.is_empty() {
1293 bufs
[0].advance(n
- accumulated_len
)
1298 #[stable(feature = "iovec", since = "1.36.0")]
1299 impl<'a
> Deref
for IoSlice
<'a
> {
1303 fn deref(&self) -> &[u8] {
1308 /// A trait for objects which are byte-oriented sinks.
1310 /// Implementors of the `Write` trait are sometimes called 'writers'.
1312 /// Writers are defined by two required methods, [`write`] and [`flush`]:
1314 /// * The [`write`] method will attempt to write some data into the object,
1315 /// returning how many bytes were successfully written.
1317 /// * The [`flush`] method is useful for adapters and explicit buffers
1318 /// themselves for ensuring that all buffered data has been pushed out to the
1321 /// Writers are intended to be composable with one another. Many implementors
1322 /// throughout [`std::io`] take and provide types which implement the `Write`
1325 /// [`write`]: Write::write
1326 /// [`flush`]: Write::flush
1327 /// [`std::io`]: self
1332 /// use std::io::prelude::*;
1333 /// use std::fs::File;
1335 /// fn main() -> std::io::Result<()> {
1336 /// let data = b"some bytes";
1338 /// let mut pos = 0;
1339 /// let mut buffer = File::create("foo.txt")?;
1341 /// while pos < data.len() {
1342 /// let bytes_written = buffer.write(&data[pos..])?;
1343 /// pos += bytes_written;
1349 /// The trait also provides convenience methods like [`write_all`], which calls
1350 /// `write` in a loop until its entire input has been written.
1352 /// [`write_all`]: Write::write_all
1353 #[stable(feature = "rust1", since = "1.0.0")]
1354 #[doc(notable_trait)]
1355 #[cfg_attr(not(test), rustc_diagnostic_item = "IoWrite")]
1357 /// Write a buffer into this writer, returning how many bytes were written.
1359 /// This function will attempt to write the entire contents of `buf`, but
1360 /// the entire write might not succeed, or the write may also generate an
1361 /// error. A call to `write` represents *at most one* attempt to write to
1362 /// any wrapped object.
1364 /// Calls to `write` are not guaranteed to block waiting for data to be
1365 /// written, and a write which would otherwise block can be indicated through
1366 /// an [`Err`] variant.
1368 /// If the return value is [`Ok(n)`] then it must be guaranteed that
1369 /// `n <= buf.len()`. A return value of `0` typically means that the
1370 /// underlying object is no longer able to accept bytes and will likely not
1371 /// be able to in the future as well, or that the buffer provided is empty.
1375 /// Each call to `write` may generate an I/O error indicating that the
1376 /// operation could not be completed. If an error is returned then no bytes
1377 /// in the buffer were written to this writer.
1379 /// It is **not** considered an error if the entire buffer could not be
1380 /// written to this writer.
1382 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the
1383 /// write operation should be retried if there is nothing else to do.
1388 /// use std::io::prelude::*;
1389 /// use std::fs::File;
1391 /// fn main() -> std::io::Result<()> {
1392 /// let mut buffer = File::create("foo.txt")?;
1394 /// // Writes some prefix of the byte string, not necessarily all of it.
1395 /// buffer.write(b"some bytes")?;
1401 #[stable(feature = "rust1", since = "1.0.0")]
1402 fn write(&mut self, buf
: &[u8]) -> Result
<usize>;
1404 /// Like [`write`], except that it writes from a slice of buffers.
1406 /// Data is copied from each buffer in order, with the final buffer
1407 /// read from possibly being only partially consumed. This method must
1408 /// behave as a call to [`write`] with the buffers concatenated would.
1410 /// The default implementation calls [`write`] with either the first nonempty
1411 /// buffer provided, or an empty one if none exists.
1416 /// use std::io::IoSlice;
1417 /// use std::io::prelude::*;
1418 /// use std::fs::File;
1420 /// fn main() -> std::io::Result<()> {
1421 /// let mut data1 = [1; 8];
1422 /// let mut data2 = [15; 8];
1423 /// let io_slice1 = IoSlice::new(&mut data1);
1424 /// let io_slice2 = IoSlice::new(&mut data2);
1426 /// let mut buffer = File::create("foo.txt")?;
1428 /// // Writes some prefix of the byte string, not necessarily all of it.
1429 /// buffer.write_vectored(&[io_slice1, io_slice2])?;
1434 /// [`write`]: Write::write
1435 #[stable(feature = "iovec", since = "1.36.0")]
1436 fn write_vectored(&mut self, bufs
: &[IoSlice
<'_
>]) -> Result
<usize> {
1437 default_write_vectored(|b
| self.write(b
), bufs
)
1440 /// Determines if this `Write`r has an efficient [`write_vectored`]
1443 /// If a `Write`r does not override the default [`write_vectored`]
1444 /// implementation, code using it may want to avoid the method all together
1445 /// and coalesce writes into a single buffer for higher performance.
1447 /// The default implementation returns `false`.
1449 /// [`write_vectored`]: Write::write_vectored
1450 #[unstable(feature = "can_vector", issue = "69941")]
1451 fn is_write_vectored(&self) -> bool
{
1455 /// Flush this output stream, ensuring that all intermediately buffered
1456 /// contents reach their destination.
1460 /// It is considered an error if not all bytes could be written due to
1461 /// I/O errors or EOF being reached.
1466 /// use std::io::prelude::*;
1467 /// use std::io::BufWriter;
1468 /// use std::fs::File;
1470 /// fn main() -> std::io::Result<()> {
1471 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
1473 /// buffer.write_all(b"some bytes")?;
1474 /// buffer.flush()?;
1478 #[stable(feature = "rust1", since = "1.0.0")]
1479 fn flush(&mut self) -> Result
<()>;
1481 /// Attempts to write an entire buffer into this writer.
1483 /// This method will continuously call [`write`] until there is no more data
1484 /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is
1485 /// returned. This method will not return until the entire buffer has been
1486 /// successfully written or such an error occurs. The first error that is
1487 /// not of [`ErrorKind::Interrupted`] kind generated from this method will be
1490 /// If the buffer contains no data, this will never call [`write`].
1494 /// This function will return the first error of
1495 /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns.
1497 /// [`write`]: Write::write
1502 /// use std::io::prelude::*;
1503 /// use std::fs::File;
1505 /// fn main() -> std::io::Result<()> {
1506 /// let mut buffer = File::create("foo.txt")?;
1508 /// buffer.write_all(b"some bytes")?;
1512 #[stable(feature = "rust1", since = "1.0.0")]
1513 fn write_all(&mut self, mut buf
: &[u8]) -> Result
<()> {
1514 while !buf
.is_empty() {
1515 match self.write(buf
) {
1517 return Err(error
::const_io_error
!(
1518 ErrorKind
::WriteZero
,
1519 "failed to write whole buffer",
1522 Ok(n
) => buf
= &buf
[n
..],
1523 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> {}
1524 Err(e
) => return Err(e
),
1530 /// Attempts to write multiple buffers into this writer.
1532 /// This method will continuously call [`write_vectored`] until there is no
1533 /// more data to be written or an error of non-[`ErrorKind::Interrupted`]
1534 /// kind is returned. This method will not return until all buffers have
1535 /// been successfully written or such an error occurs. The first error that
1536 /// is not of [`ErrorKind::Interrupted`] kind generated from this method
1537 /// will be returned.
1539 /// If the buffer contains no data, this will never call [`write_vectored`].
1543 /// Unlike [`write_vectored`], this takes a *mutable* reference to
1544 /// a slice of [`IoSlice`]s, not an immutable one. That's because we need to
1545 /// modify the slice to keep track of the bytes already written.
1547 /// Once this function returns, the contents of `bufs` are unspecified, as
1548 /// this depends on how many calls to [`write_vectored`] were necessary. It is
1549 /// best to understand this function as taking ownership of `bufs` and to
1550 /// not use `bufs` afterwards. The underlying buffers, to which the
1551 /// [`IoSlice`]s point (but not the [`IoSlice`]s themselves), are unchanged and
1554 /// [`write_vectored`]: Write::write_vectored
1559 /// #![feature(write_all_vectored)]
1560 /// # fn main() -> std::io::Result<()> {
1562 /// use std::io::{Write, IoSlice};
1564 /// let mut writer = Vec::new();
1565 /// let bufs = &mut [
1566 /// IoSlice::new(&[1]),
1567 /// IoSlice::new(&[2, 3]),
1568 /// IoSlice::new(&[4, 5, 6]),
1571 /// writer.write_all_vectored(bufs)?;
1572 /// // Note: the contents of `bufs` is now undefined, see the Notes section.
1574 /// assert_eq!(writer, &[1, 2, 3, 4, 5, 6]);
1577 #[unstable(feature = "write_all_vectored", issue = "70436")]
1578 fn write_all_vectored(&mut self, mut bufs
: &mut [IoSlice
<'_
>]) -> Result
<()> {
1579 // Guarantee that bufs is empty if it contains no data,
1580 // to avoid calling write_vectored if there is no data to be written.
1581 IoSlice
::advance_slices(&mut bufs
, 0);
1582 while !bufs
.is_empty() {
1583 match self.write_vectored(bufs
) {
1585 return Err(error
::const_io_error
!(
1586 ErrorKind
::WriteZero
,
1587 "failed to write whole buffer",
1590 Ok(n
) => IoSlice
::advance_slices(&mut bufs
, n
),
1591 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> {}
1592 Err(e
) => return Err(e
),
1598 /// Writes a formatted string into this writer, returning any error
1601 /// This method is primarily used to interface with the
1602 /// [`format_args!()`] macro, and it is rare that this should
1603 /// explicitly be called. The [`write!()`] macro should be favored to
1604 /// invoke this method instead.
1606 /// This function internally uses the [`write_all`] method on
1607 /// this trait and hence will continuously write data so long as no errors
1608 /// are received. This also means that partial writes are not indicated in
1611 /// [`write_all`]: Write::write_all
1615 /// This function will return any I/O error reported while formatting.
1620 /// use std::io::prelude::*;
1621 /// use std::fs::File;
1623 /// fn main() -> std::io::Result<()> {
1624 /// let mut buffer = File::create("foo.txt")?;
1627 /// write!(buffer, "{:.*}", 2, 1.234567)?;
1628 /// // turns into this:
1629 /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1633 #[stable(feature = "rust1", since = "1.0.0")]
1634 fn write_fmt(&mut self, fmt
: fmt
::Arguments
<'_
>) -> Result
<()> {
1635 // Create a shim which translates a Write to a fmt::Write and saves
1636 // off I/O errors. instead of discarding them
1637 struct Adapter
<'a
, T
: ?Sized
+ 'a
> {
1642 impl<T
: Write
+ ?Sized
> fmt
::Write
for Adapter
<'_
, T
> {
1643 fn write_str(&mut self, s
: &str) -> fmt
::Result
{
1644 match self.inner
.write_all(s
.as_bytes()) {
1647 self.error
= Err(e
);
1654 let mut output
= Adapter { inner: self, error: Ok(()) }
;
1655 match fmt
::write(&mut output
, fmt
) {
1658 // check if the error came from the underlying `Write` or not
1659 if output
.error
.is_err() {
1662 Err(error
::const_io_error
!(ErrorKind
::Uncategorized
, "formatter error"))
1668 /// Creates a "by reference" adapter for this instance of `Write`.
1670 /// The returned adapter also implements `Write` and will simply borrow this
1676 /// use std::io::Write;
1677 /// use std::fs::File;
1679 /// fn main() -> std::io::Result<()> {
1680 /// let mut buffer = File::create("foo.txt")?;
1682 /// let reference = buffer.by_ref();
1684 /// // we can use reference just like our original buffer
1685 /// reference.write_all(b"some bytes")?;
1689 #[stable(feature = "rust1", since = "1.0.0")]
1690 fn by_ref(&mut self) -> &mut Self
1698 /// The `Seek` trait provides a cursor which can be moved within a stream of
1701 /// The stream typically has a fixed size, allowing seeking relative to either
1702 /// end or the current offset.
1706 /// [`File`]s implement `Seek`:
1708 /// [`File`]: crate::fs::File
1712 /// use std::io::prelude::*;
1713 /// use std::fs::File;
1714 /// use std::io::SeekFrom;
1716 /// fn main() -> io::Result<()> {
1717 /// let mut f = File::open("foo.txt")?;
1719 /// // move the cursor 42 bytes from the start of the file
1720 /// f.seek(SeekFrom::Start(42))?;
1724 #[stable(feature = "rust1", since = "1.0.0")]
1726 /// Seek to an offset, in bytes, in a stream.
1728 /// A seek beyond the end of a stream is allowed, but behavior is defined
1729 /// by the implementation.
1731 /// If the seek operation completed successfully,
1732 /// this method returns the new position from the start of the stream.
1733 /// That position can be used later with [`SeekFrom::Start`].
1737 /// Seeking can fail, for example because it might involve flushing a buffer.
1739 /// Seeking to a negative offset is considered an error.
1740 #[stable(feature = "rust1", since = "1.0.0")]
1741 fn seek(&mut self, pos
: SeekFrom
) -> Result
<u64>;
1743 /// Rewind to the beginning of a stream.
1745 /// This is a convenience method, equivalent to `seek(SeekFrom::Start(0))`.
1749 /// Rewinding can fail, for example because it might involve flushing a buffer.
1754 /// use std::io::{Read, Seek, Write};
1755 /// use std::fs::OpenOptions;
1757 /// let mut f = OpenOptions::new()
1761 /// .open("foo.txt").unwrap();
1763 /// let hello = "Hello!\n";
1764 /// write!(f, "{hello}").unwrap();
1765 /// f.rewind().unwrap();
1767 /// let mut buf = String::new();
1768 /// f.read_to_string(&mut buf).unwrap();
1769 /// assert_eq!(&buf, hello);
1771 #[stable(feature = "seek_rewind", since = "1.55.0")]
1772 fn rewind(&mut self) -> Result
<()> {
1773 self.seek(SeekFrom
::Start(0))?
;
1777 /// Returns the length of this stream (in bytes).
1779 /// This method is implemented using up to three seek operations. If this
1780 /// method returns successfully, the seek position is unchanged (i.e. the
1781 /// position before calling this method is the same as afterwards).
1782 /// However, if this method returns an error, the seek position is
1785 /// If you need to obtain the length of *many* streams and you don't care
1786 /// about the seek position afterwards, you can reduce the number of seek
1787 /// operations by simply calling `seek(SeekFrom::End(0))` and using its
1788 /// return value (it is also the stream length).
1790 /// Note that length of a stream can change over time (for example, when
1791 /// data is appended to a file). So calling this method multiple times does
1792 /// not necessarily return the same length each time.
1797 /// #![feature(seek_stream_len)]
1799 /// io::{self, Seek},
1803 /// fn main() -> io::Result<()> {
1804 /// let mut f = File::open("foo.txt")?;
1806 /// let len = f.stream_len()?;
1807 /// println!("The file is currently {len} bytes long");
1811 #[unstable(feature = "seek_stream_len", issue = "59359")]
1812 fn stream_len(&mut self) -> Result
<u64> {
1813 let old_pos
= self.stream_position()?
;
1814 let len
= self.seek(SeekFrom
::End(0))?
;
1816 // Avoid seeking a third time when we were already at the end of the
1817 // stream. The branch is usually way cheaper than a seek operation.
1819 self.seek(SeekFrom
::Start(old_pos
))?
;
1825 /// Returns the current seek position from the start of the stream.
1827 /// This is equivalent to `self.seek(SeekFrom::Current(0))`.
1833 /// io::{self, BufRead, BufReader, Seek},
1837 /// fn main() -> io::Result<()> {
1838 /// let mut f = BufReader::new(File::open("foo.txt")?);
1840 /// let before = f.stream_position()?;
1841 /// f.read_line(&mut String::new())?;
1842 /// let after = f.stream_position()?;
1844 /// println!("The first line was {} bytes long", after - before);
1848 #[stable(feature = "seek_convenience", since = "1.51.0")]
1849 fn stream_position(&mut self) -> Result
<u64> {
1850 self.seek(SeekFrom
::Current(0))
1854 /// Enumeration of possible methods to seek within an I/O object.
1856 /// It is used by the [`Seek`] trait.
1857 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1858 #[stable(feature = "rust1", since = "1.0.0")]
1860 /// Sets the offset to the provided number of bytes.
1861 #[stable(feature = "rust1", since = "1.0.0")]
1862 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1864 /// Sets the offset to the size of this object plus the specified number of
1867 /// It is possible to seek beyond the end of an object, but it's an error to
1868 /// seek before byte 0.
1869 #[stable(feature = "rust1", since = "1.0.0")]
1870 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1872 /// Sets the offset to the current position plus the specified number of
1875 /// It is possible to seek beyond the end of an object, but it's an error to
1876 /// seek before byte 0.
1877 #[stable(feature = "rust1", since = "1.0.0")]
1878 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1881 fn read_until
<R
: BufRead
+ ?Sized
>(r
: &mut R
, delim
: u8, buf
: &mut Vec
<u8>) -> Result
<usize> {
1884 let (done
, used
) = {
1885 let available
= match r
.fill_buf() {
1887 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> continue,
1888 Err(e
) => return Err(e
),
1890 match memchr
::memchr(delim
, available
) {
1892 buf
.extend_from_slice(&available
[..=i
]);
1896 buf
.extend_from_slice(available
);
1897 (false, available
.len())
1903 if done
|| used
== 0 {
1909 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1910 /// to perform extra ways of reading.
1912 /// For example, reading line-by-line is inefficient without using a buffer, so
1913 /// if you want to read by line, you'll need `BufRead`, which includes a
1914 /// [`read_line`] method as well as a [`lines`] iterator.
1918 /// A locked standard input implements `BufRead`:
1922 /// use std::io::prelude::*;
1924 /// let stdin = io::stdin();
1925 /// for line in stdin.lock().lines() {
1926 /// println!("{}", line.unwrap());
1930 /// If you have something that implements [`Read`], you can use the [`BufReader`
1931 /// type][`BufReader`] to turn it into a `BufRead`.
1933 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1934 /// [`BufReader`] to the rescue!
1936 /// [`File`]: crate::fs::File
1937 /// [`read_line`]: BufRead::read_line
1938 /// [`lines`]: BufRead::lines
1941 /// use std::io::{self, BufReader};
1942 /// use std::io::prelude::*;
1943 /// use std::fs::File;
1945 /// fn main() -> io::Result<()> {
1946 /// let f = File::open("foo.txt")?;
1947 /// let f = BufReader::new(f);
1949 /// for line in f.lines() {
1950 /// println!("{}", line.unwrap());
1956 #[stable(feature = "rust1", since = "1.0.0")]
1957 pub trait BufRead
: Read
{
1958 /// Returns the contents of the internal buffer, filling it with more data
1959 /// from the inner reader if it is empty.
1961 /// This function is a lower-level call. It needs to be paired with the
1962 /// [`consume`] method to function properly. When calling this
1963 /// method, none of the contents will be "read" in the sense that later
1964 /// calling `read` may return the same contents. As such, [`consume`] must
1965 /// be called with the number of bytes that are consumed from this buffer to
1966 /// ensure that the bytes are never returned twice.
1968 /// [`consume`]: BufRead::consume
1970 /// An empty buffer returned indicates that the stream has reached EOF.
1974 /// This function will return an I/O error if the underlying reader was
1975 /// read, but returned an error.
1979 /// A locked standard input implements `BufRead`:
1983 /// use std::io::prelude::*;
1985 /// let stdin = io::stdin();
1986 /// let mut stdin = stdin.lock();
1988 /// let buffer = stdin.fill_buf().unwrap();
1990 /// // work with buffer
1991 /// println!("{buffer:?}");
1993 /// // ensure the bytes we worked with aren't returned again later
1994 /// let length = buffer.len();
1995 /// stdin.consume(length);
1997 #[stable(feature = "rust1", since = "1.0.0")]
1998 fn fill_buf(&mut self) -> Result
<&[u8]>;
2000 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
2001 /// so they should no longer be returned in calls to `read`.
2003 /// This function is a lower-level call. It needs to be paired with the
2004 /// [`fill_buf`] method to function properly. This function does
2005 /// not perform any I/O, it simply informs this object that some amount of
2006 /// its buffer, returned from [`fill_buf`], has been consumed and should
2007 /// no longer be returned. As such, this function may do odd things if
2008 /// [`fill_buf`] isn't called before calling it.
2010 /// The `amt` must be `<=` the number of bytes in the buffer returned by
2015 /// Since `consume()` is meant to be used with [`fill_buf`],
2016 /// that method's example includes an example of `consume()`.
2018 /// [`fill_buf`]: BufRead::fill_buf
2019 #[stable(feature = "rust1", since = "1.0.0")]
2020 fn consume(&mut self, amt
: usize);
2022 /// Check if the underlying `Read` has any data left to be read.
2024 /// This function may fill the buffer to check for data,
2025 /// so this functions returns `Result<bool>`, not `bool`.
2027 /// Default implementation calls `fill_buf` and checks that
2028 /// returned slice is empty (which means that there is no data left,
2029 /// since EOF is reached).
2034 /// #![feature(buf_read_has_data_left)]
2036 /// use std::io::prelude::*;
2038 /// let stdin = io::stdin();
2039 /// let mut stdin = stdin.lock();
2041 /// while stdin.has_data_left().unwrap() {
2042 /// let mut line = String::new();
2043 /// stdin.read_line(&mut line).unwrap();
2044 /// // work with line
2045 /// println!("{line:?}");
2048 #[unstable(feature = "buf_read_has_data_left", reason = "recently added", issue = "86423")]
2049 fn has_data_left(&mut self) -> Result
<bool
> {
2050 self.fill_buf().map(|b
| !b
.is_empty())
2053 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
2055 /// This function will read bytes from the underlying stream until the
2056 /// delimiter or EOF is found. Once found, all bytes up to, and including,
2057 /// the delimiter (if found) will be appended to `buf`.
2059 /// If successful, this function will return the total number of bytes read.
2061 /// This function is blocking and should be used carefully: it is possible for
2062 /// an attacker to continuously send bytes without ever sending the delimiter
2067 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
2068 /// will otherwise return any errors returned by [`fill_buf`].
2070 /// If an I/O error is encountered then all bytes read so far will be
2071 /// present in `buf` and its length will have been adjusted appropriately.
2073 /// [`fill_buf`]: BufRead::fill_buf
2077 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2078 /// this example, we use [`Cursor`] to read all the bytes in a byte slice
2079 /// in hyphen delimited segments:
2082 /// use std::io::{self, BufRead};
2084 /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
2085 /// let mut buf = vec![];
2087 /// // cursor is at 'l'
2088 /// let num_bytes = cursor.read_until(b'-', &mut buf)
2089 /// .expect("reading from cursor won't fail");
2090 /// assert_eq!(num_bytes, 6);
2091 /// assert_eq!(buf, b"lorem-");
2094 /// // cursor is at 'i'
2095 /// let num_bytes = cursor.read_until(b'-', &mut buf)
2096 /// .expect("reading from cursor won't fail");
2097 /// assert_eq!(num_bytes, 5);
2098 /// assert_eq!(buf, b"ipsum");
2101 /// // cursor is at EOF
2102 /// let num_bytes = cursor.read_until(b'-', &mut buf)
2103 /// .expect("reading from cursor won't fail");
2104 /// assert_eq!(num_bytes, 0);
2105 /// assert_eq!(buf, b"");
2107 #[stable(feature = "rust1", since = "1.0.0")]
2108 fn read_until(&mut self, byte
: u8, buf
: &mut Vec
<u8>) -> Result
<usize> {
2109 read_until(self, byte
, buf
)
2112 /// Read all bytes until a newline (the `0xA` byte) is reached, and append
2113 /// them to the provided buffer. You do not need to clear the buffer before
2116 /// This function will read bytes from the underlying stream until the
2117 /// newline delimiter (the `0xA` byte) or EOF is found. Once found, all bytes
2118 /// up to, and including, the delimiter (if found) will be appended to
2121 /// If successful, this function will return the total number of bytes read.
2123 /// If this function returns [`Ok(0)`], the stream has reached EOF.
2125 /// This function is blocking and should be used carefully: it is possible for
2126 /// an attacker to continuously send bytes without ever sending a newline
2133 /// This function has the same error semantics as [`read_until`] and will
2134 /// also return an error if the read bytes are not valid UTF-8. If an I/O
2135 /// error is encountered then `buf` may contain some bytes already read in
2136 /// the event that all data read so far was valid UTF-8.
2138 /// [`read_until`]: BufRead::read_until
2142 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2143 /// this example, we use [`Cursor`] to read all the lines in a byte slice:
2146 /// use std::io::{self, BufRead};
2148 /// let mut cursor = io::Cursor::new(b"foo\nbar");
2149 /// let mut buf = String::new();
2151 /// // cursor is at 'f'
2152 /// let num_bytes = cursor.read_line(&mut buf)
2153 /// .expect("reading from cursor won't fail");
2154 /// assert_eq!(num_bytes, 4);
2155 /// assert_eq!(buf, "foo\n");
2158 /// // cursor is at 'b'
2159 /// let num_bytes = cursor.read_line(&mut buf)
2160 /// .expect("reading from cursor won't fail");
2161 /// assert_eq!(num_bytes, 3);
2162 /// assert_eq!(buf, "bar");
2165 /// // cursor is at EOF
2166 /// let num_bytes = cursor.read_line(&mut buf)
2167 /// .expect("reading from cursor won't fail");
2168 /// assert_eq!(num_bytes, 0);
2169 /// assert_eq!(buf, "");
2171 #[stable(feature = "rust1", since = "1.0.0")]
2172 fn read_line(&mut self, buf
: &mut String
) -> Result
<usize> {
2173 // Note that we are not calling the `.read_until` method here, but
2174 // rather our hardcoded implementation. For more details as to why, see
2175 // the comments in `read_to_end`.
2176 unsafe { append_to_string(buf, |b| read_until(self, b'\n', b)) }
2179 /// Returns an iterator over the contents of this reader split on the byte
2182 /// The iterator returned from this function will return instances of
2183 /// <code>[io::Result]<[Vec]\<u8>></code>. Each vector returned will *not* have
2184 /// the delimiter byte at the end.
2186 /// This function will yield errors whenever [`read_until`] would have
2187 /// also yielded an error.
2189 /// [io::Result]: self::Result "io::Result"
2190 /// [`read_until`]: BufRead::read_until
2194 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2195 /// this example, we use [`Cursor`] to iterate over all hyphen delimited
2196 /// segments in a byte slice
2199 /// use std::io::{self, BufRead};
2201 /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
2203 /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
2204 /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
2205 /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
2206 /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
2207 /// assert_eq!(split_iter.next(), None);
2209 #[stable(feature = "rust1", since = "1.0.0")]
2210 fn split(self, byte
: u8) -> Split
<Self>
2214 Split { buf: self, delim: byte }
2217 /// Returns an iterator over the lines of this reader.
2219 /// The iterator returned from this function will yield instances of
2220 /// <code>[io::Result]<[String]></code>. Each string returned will *not* have a newline
2221 /// byte (the `0xA` byte) or `CRLF` (`0xD`, `0xA` bytes) at the end.
2223 /// [io::Result]: self::Result "io::Result"
2227 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2228 /// this example, we use [`Cursor`] to iterate over all the lines in a byte
2232 /// use std::io::{self, BufRead};
2234 /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
2236 /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
2237 /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
2238 /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
2239 /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
2240 /// assert_eq!(lines_iter.next(), None);
2245 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
2246 #[stable(feature = "rust1", since = "1.0.0")]
2247 fn lines(self) -> Lines
<Self>
2255 /// Adapter to chain together two readers.
2257 /// This struct is generally created by calling [`chain`] on a reader.
2258 /// Please see the documentation of [`chain`] for more details.
2260 /// [`chain`]: Read::chain
2261 #[stable(feature = "rust1", since = "1.0.0")]
2263 pub struct Chain
<T
, U
> {
2269 impl<T
, U
> Chain
<T
, U
> {
2270 /// Consumes the `Chain`, returning the wrapped readers.
2276 /// use std::io::prelude::*;
2277 /// use std::fs::File;
2279 /// fn main() -> io::Result<()> {
2280 /// let mut foo_file = File::open("foo.txt")?;
2281 /// let mut bar_file = File::open("bar.txt")?;
2283 /// let chain = foo_file.chain(bar_file);
2284 /// let (foo_file, bar_file) = chain.into_inner();
2288 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2289 pub fn into_inner(self) -> (T
, U
) {
2290 (self.first
, self.second
)
2293 /// Gets references to the underlying readers in this `Chain`.
2299 /// use std::io::prelude::*;
2300 /// use std::fs::File;
2302 /// fn main() -> io::Result<()> {
2303 /// let mut foo_file = File::open("foo.txt")?;
2304 /// let mut bar_file = File::open("bar.txt")?;
2306 /// let chain = foo_file.chain(bar_file);
2307 /// let (foo_file, bar_file) = chain.get_ref();
2311 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2312 pub fn get_ref(&self) -> (&T
, &U
) {
2313 (&self.first
, &self.second
)
2316 /// Gets mutable references to the underlying readers in this `Chain`.
2318 /// Care should be taken to avoid modifying the internal I/O state of the
2319 /// underlying readers as doing so may corrupt the internal state of this
2326 /// use std::io::prelude::*;
2327 /// use std::fs::File;
2329 /// fn main() -> io::Result<()> {
2330 /// let mut foo_file = File::open("foo.txt")?;
2331 /// let mut bar_file = File::open("bar.txt")?;
2333 /// let mut chain = foo_file.chain(bar_file);
2334 /// let (foo_file, bar_file) = chain.get_mut();
2338 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2339 pub fn get_mut(&mut self) -> (&mut T
, &mut U
) {
2340 (&mut self.first
, &mut self.second
)
2344 #[stable(feature = "rust1", since = "1.0.0")]
2345 impl<T
: Read
, U
: Read
> Read
for Chain
<T
, U
> {
2346 fn read(&mut self, buf
: &mut [u8]) -> Result
<usize> {
2347 if !self.done_first
{
2348 match self.first
.read(buf
)?
{
2349 0 if !buf
.is_empty() => self.done_first
= true,
2353 self.second
.read(buf
)
2356 fn read_vectored(&mut self, bufs
: &mut [IoSliceMut
<'_
>]) -> Result
<usize> {
2357 if !self.done_first
{
2358 match self.first
.read_vectored(bufs
)?
{
2359 0 if bufs
.iter().any(|b
| !b
.is_empty()) => self.done_first
= true,
2363 self.second
.read_vectored(bufs
)
2367 #[stable(feature = "chain_bufread", since = "1.9.0")]
2368 impl<T
: BufRead
, U
: BufRead
> BufRead
for Chain
<T
, U
> {
2369 fn fill_buf(&mut self) -> Result
<&[u8]> {
2370 if !self.done_first
{
2371 match self.first
.fill_buf()?
{
2372 buf
if buf
.is_empty() => {
2373 self.done_first
= true;
2375 buf
=> return Ok(buf
),
2378 self.second
.fill_buf()
2381 fn consume(&mut self, amt
: usize) {
2382 if !self.done_first { self.first.consume(amt) }
else { self.second.consume(amt) }
2386 impl<T
, U
> SizeHint
for Chain
<T
, U
> {
2388 fn lower_bound(&self) -> usize {
2389 SizeHint
::lower_bound(&self.first
) + SizeHint
::lower_bound(&self.second
)
2393 fn upper_bound(&self) -> Option
<usize> {
2394 match (SizeHint
::upper_bound(&self.first
), SizeHint
::upper_bound(&self.second
)) {
2395 (Some(first
), Some(second
)) => first
.checked_add(second
),
2401 /// Reader adapter which limits the bytes read from an underlying reader.
2403 /// This struct is generally created by calling [`take`] on a reader.
2404 /// Please see the documentation of [`take`] for more details.
2406 /// [`take`]: Read::take
2407 #[stable(feature = "rust1", since = "1.0.0")]
2409 pub struct Take
<T
> {
2415 /// Returns the number of bytes that can be read before this instance will
2420 /// This instance may reach `EOF` after reading fewer bytes than indicated by
2421 /// this method if the underlying [`Read`] instance reaches EOF.
2427 /// use std::io::prelude::*;
2428 /// use std::fs::File;
2430 /// fn main() -> io::Result<()> {
2431 /// let f = File::open("foo.txt")?;
2433 /// // read at most five bytes
2434 /// let handle = f.take(5);
2436 /// println!("limit: {}", handle.limit());
2440 #[stable(feature = "rust1", since = "1.0.0")]
2441 pub fn limit(&self) -> u64 {
2445 /// Sets the number of bytes that can be read before this instance will
2446 /// return EOF. This is the same as constructing a new `Take` instance, so
2447 /// the amount of bytes read and the previous limit value don't matter when
2448 /// calling this method.
2454 /// use std::io::prelude::*;
2455 /// use std::fs::File;
2457 /// fn main() -> io::Result<()> {
2458 /// let f = File::open("foo.txt")?;
2460 /// // read at most five bytes
2461 /// let mut handle = f.take(5);
2462 /// handle.set_limit(10);
2464 /// assert_eq!(handle.limit(), 10);
2468 #[stable(feature = "take_set_limit", since = "1.27.0")]
2469 pub fn set_limit(&mut self, limit
: u64) {
2473 /// Consumes the `Take`, returning the wrapped reader.
2479 /// use std::io::prelude::*;
2480 /// use std::fs::File;
2482 /// fn main() -> io::Result<()> {
2483 /// let mut file = File::open("foo.txt")?;
2485 /// let mut buffer = [0; 5];
2486 /// let mut handle = file.take(5);
2487 /// handle.read(&mut buffer)?;
2489 /// let file = handle.into_inner();
2493 #[stable(feature = "io_take_into_inner", since = "1.15.0")]
2494 pub fn into_inner(self) -> T
{
2498 /// Gets a reference to the underlying reader.
2504 /// use std::io::prelude::*;
2505 /// use std::fs::File;
2507 /// fn main() -> io::Result<()> {
2508 /// let mut file = File::open("foo.txt")?;
2510 /// let mut buffer = [0; 5];
2511 /// let mut handle = file.take(5);
2512 /// handle.read(&mut buffer)?;
2514 /// let file = handle.get_ref();
2518 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2519 pub fn get_ref(&self) -> &T
{
2523 /// Gets a mutable reference to the underlying reader.
2525 /// Care should be taken to avoid modifying the internal I/O state of the
2526 /// underlying reader as doing so may corrupt the internal limit of this
2533 /// use std::io::prelude::*;
2534 /// use std::fs::File;
2536 /// fn main() -> io::Result<()> {
2537 /// let mut file = File::open("foo.txt")?;
2539 /// let mut buffer = [0; 5];
2540 /// let mut handle = file.take(5);
2541 /// handle.read(&mut buffer)?;
2543 /// let file = handle.get_mut();
2547 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2548 pub fn get_mut(&mut self) -> &mut T
{
2553 #[stable(feature = "rust1", since = "1.0.0")]
2554 impl<T
: Read
> Read
for Take
<T
> {
2555 fn read(&mut self, buf
: &mut [u8]) -> Result
<usize> {
2556 // Don't call into inner reader at all at EOF because it may still block
2557 if self.limit
== 0 {
2561 let max
= cmp
::min(buf
.len() as u64, self.limit
) as usize;
2562 let n
= self.inner
.read(&mut buf
[..max
])?
;
2563 self.limit
-= n
as u64;
2567 fn read_buf(&mut self, buf
: &mut ReadBuf
<'_
>) -> Result
<()> {
2568 // Don't call into inner reader at all at EOF because it may still block
2569 if self.limit
== 0 {
2573 let prev_filled
= buf
.filled_len();
2575 if self.limit
<= buf
.remaining() as u64 {
2576 // if we just use an as cast to convert, limit may wrap around on a 32 bit target
2577 let limit
= cmp
::min(self.limit
, usize::MAX
as u64) as usize;
2579 let extra_init
= cmp
::min(limit
as usize, buf
.initialized_len() - buf
.filled_len());
2581 // SAFETY: no uninit data is written to ibuf
2582 let ibuf
= unsafe { &mut buf.unfilled_mut()[..limit] }
;
2584 let mut sliced_buf
= ReadBuf
::uninit(ibuf
);
2586 // SAFETY: extra_init bytes of ibuf are known to be initialized
2588 sliced_buf
.assume_init(extra_init
);
2591 self.inner
.read_buf(&mut sliced_buf
)?
;
2593 let new_init
= sliced_buf
.initialized_len();
2594 let filled
= sliced_buf
.filled_len();
2596 // sliced_buf / ibuf must drop here
2598 // SAFETY: new_init bytes of buf's unfilled buffer have been initialized
2600 buf
.assume_init(new_init
);
2603 buf
.add_filled(filled
);
2605 self.limit
-= filled
as u64;
2607 self.inner
.read_buf(buf
)?
;
2610 self.limit
-= buf
.filled_len().saturating_sub(prev_filled
) as u64;
2617 #[stable(feature = "rust1", since = "1.0.0")]
2618 impl<T
: BufRead
> BufRead
for Take
<T
> {
2619 fn fill_buf(&mut self) -> Result
<&[u8]> {
2620 // Don't call into inner reader at all at EOF because it may still block
2621 if self.limit
== 0 {
2625 let buf
= self.inner
.fill_buf()?
;
2626 let cap
= cmp
::min(buf
.len() as u64, self.limit
) as usize;
2630 fn consume(&mut self, amt
: usize) {
2631 // Don't let callers reset the limit by passing an overlarge value
2632 let amt
= cmp
::min(amt
as u64, self.limit
) as usize;
2633 self.limit
-= amt
as u64;
2634 self.inner
.consume(amt
);
2638 impl<T
> SizeHint
for Take
<T
> {
2640 fn lower_bound(&self) -> usize {
2641 cmp
::min(SizeHint
::lower_bound(&self.inner
) as u64, self.limit
) as usize
2645 fn upper_bound(&self) -> Option
<usize> {
2646 match SizeHint
::upper_bound(&self.inner
) {
2647 Some(upper_bound
) => Some(cmp
::min(upper_bound
as u64, self.limit
) as usize),
2648 None
=> self.limit
.try_into().ok(),
2653 /// An iterator over `u8` values of a reader.
2655 /// This struct is generally created by calling [`bytes`] on a reader.
2656 /// Please see the documentation of [`bytes`] for more details.
2658 /// [`bytes`]: Read::bytes
2659 #[stable(feature = "rust1", since = "1.0.0")]
2661 pub struct Bytes
<R
> {
2665 #[stable(feature = "rust1", since = "1.0.0")]
2666 impl<R
: Read
> Iterator
for Bytes
<R
> {
2667 type Item
= Result
<u8>;
2669 fn next(&mut self) -> Option
<Result
<u8>> {
2672 return match self.inner
.read(slice
::from_mut(&mut byte
)) {
2674 Ok(..) => Some(Ok(byte
)),
2675 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> continue,
2676 Err(e
) => Some(Err(e
)),
2681 fn size_hint(&self) -> (usize, Option
<usize>) {
2682 SizeHint
::size_hint(&self.inner
)
2687 fn lower_bound(&self) -> usize;
2689 fn upper_bound(&self) -> Option
<usize>;
2691 fn size_hint(&self) -> (usize, Option
<usize>) {
2692 (self.lower_bound(), self.upper_bound())
2696 impl<T
> SizeHint
for T
{
2698 default fn lower_bound(&self) -> usize {
2703 default fn upper_bound(&self) -> Option
<usize> {
2708 impl<T
> SizeHint
for &mut T
{
2710 fn lower_bound(&self) -> usize {
2711 SizeHint
::lower_bound(*self)
2715 fn upper_bound(&self) -> Option
<usize> {
2716 SizeHint
::upper_bound(*self)
2720 impl<T
> SizeHint
for Box
<T
> {
2722 fn lower_bound(&self) -> usize {
2723 SizeHint
::lower_bound(&**self)
2727 fn upper_bound(&self) -> Option
<usize> {
2728 SizeHint
::upper_bound(&**self)
2732 impl SizeHint
for &[u8] {
2734 fn lower_bound(&self) -> usize {
2739 fn upper_bound(&self) -> Option
<usize> {
2744 /// An iterator over the contents of an instance of `BufRead` split on a
2745 /// particular byte.
2747 /// This struct is generally created by calling [`split`] on a `BufRead`.
2748 /// Please see the documentation of [`split`] for more details.
2750 /// [`split`]: BufRead::split
2751 #[stable(feature = "rust1", since = "1.0.0")]
2753 pub struct Split
<B
> {
2758 #[stable(feature = "rust1", since = "1.0.0")]
2759 impl<B
: BufRead
> Iterator
for Split
<B
> {
2760 type Item
= Result
<Vec
<u8>>;
2762 fn next(&mut self) -> Option
<Result
<Vec
<u8>>> {
2763 let mut buf
= Vec
::new();
2764 match self.buf
.read_until(self.delim
, &mut buf
) {
2767 if buf
[buf
.len() - 1] == self.delim
{
2772 Err(e
) => Some(Err(e
)),
2777 /// An iterator over the lines of an instance of `BufRead`.
2779 /// This struct is generally created by calling [`lines`] on a `BufRead`.
2780 /// Please see the documentation of [`lines`] for more details.
2782 /// [`lines`]: BufRead::lines
2783 #[stable(feature = "rust1", since = "1.0.0")]
2785 pub struct Lines
<B
> {
2789 #[stable(feature = "rust1", since = "1.0.0")]
2790 impl<B
: BufRead
> Iterator
for Lines
<B
> {
2791 type Item
= Result
<String
>;
2793 fn next(&mut self) -> Option
<Result
<String
>> {
2794 let mut buf
= String
::new();
2795 match self.buf
.read_line(&mut buf
) {
2798 if buf
.ends_with('
\n'
) {
2800 if buf
.ends_with('
\r'
) {
2806 Err(e
) => Some(Err(e
)),