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 = "internal_output_capture", issue = "none")]
266 #[doc(no_inline, hidden)]
267 pub use self::stdio
::set_output_capture
;
268 #[unstable(feature = "print_internals", issue = "none")]
269 pub use self::stdio
::{_eprint, _print}
;
270 #[stable(feature = "rust1", since = "1.0.0")]
272 buffered
::{BufReader, BufWriter, IntoInnerError, LineWriter}
,
275 error
::{Error, ErrorKind, Result}
,
276 stdio
::{stderr, stdin, stdout, Stderr, StderrLock, Stdin, StdinLock, Stdout, StdoutLock}
,
277 util
::{empty, repeat, sink, Empty, Repeat, Sink}
,
280 #[unstable(feature = "read_buf", issue = "78485")]
281 pub use self::readbuf
::ReadBuf
;
282 pub(crate) use error
::const_io_error
;
294 const DEFAULT_BUF_SIZE
: usize = crate::sys_common
::io
::DEFAULT_BUF_SIZE
;
296 pub(crate) use stdio
::cleanup
;
299 buf
: &'a
mut Vec
<u8>,
303 impl Drop
for Guard
<'_
> {
306 self.buf
.set_len(self.len
);
311 // Several `read_to_string` and `read_line` methods in the standard library will
312 // append data into a `String` buffer, but we need to be pretty careful when
313 // doing this. The implementation will just call `.as_mut_vec()` and then
314 // delegate to a byte-oriented reading method, but we must ensure that when
315 // returning we never leave `buf` in a state such that it contains invalid UTF-8
318 // To this end, we use an RAII guard (to protect against panics) which updates
319 // the length of the string when it is dropped. This guard initially truncates
320 // the string to the prior length and only after we've validated that the
321 // new contents are valid UTF-8 do we allow it to set a longer length.
323 // The unsafety in this function is twofold:
325 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
327 // 2. We're passing a raw buffer to the function `f`, and it is expected that
328 // the function only *appends* bytes to the buffer. We'll get undefined
329 // behavior if existing bytes are overwritten to have non-UTF-8 data.
330 pub(crate) unsafe fn append_to_string
<F
>(buf
: &mut String
, f
: F
) -> Result
<usize>
332 F
: FnOnce(&mut Vec
<u8>) -> Result
<usize>,
334 let mut g
= Guard { len: buf.len(), buf: buf.as_mut_vec() }
;
336 if str::from_utf8(&g
.buf
[g
.len
..]).is_err() {
338 Err(error
::const_io_error
!(
339 ErrorKind
::InvalidData
,
340 "stream did not contain valid UTF-8"
349 // This uses an adaptive system to extend the vector when it fills. We want to
350 // avoid paying to allocate and zero a huge chunk of memory if the reader only
351 // has 4 bytes while still making large reads if the reader does have a ton
352 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
353 // time is 4,500 times (!) slower than a default reservation size of 32 if the
354 // reader has a very small amount of data to return.
355 pub(crate) fn default_read_to_end
<R
: Read
+ ?Sized
>(r
: &mut R
, buf
: &mut Vec
<u8>) -> Result
<usize> {
356 let start_len
= buf
.len();
357 let start_cap
= buf
.capacity();
359 let mut initialized
= 0; // Extra initialized bytes from previous loop iteration
361 if buf
.len() == buf
.capacity() {
362 buf
.reserve(32); // buf is full, need more space
365 let mut read_buf
= ReadBuf
::uninit(buf
.spare_capacity_mut());
367 // SAFETY: These bytes were initialized but not filled in the previous loop
369 read_buf
.assume_init(initialized
);
372 match r
.read_buf(&mut read_buf
) {
374 Err(e
) if e
.kind() == ErrorKind
::Interrupted
=> continue,
375 Err(e
) => return Err(e
),
378 if read_buf
.filled_len() == 0 {
379 return Ok(buf
.len() - start_len
);
382 // store how much was initialized but not filled
383 initialized
= read_buf
.initialized_len() - read_buf
.filled_len();
384 let new_len
= read_buf
.filled_len() + buf
.len();
386 // SAFETY: ReadBuf's invariants mean this much memory is init
388 buf
.set_len(new_len
);
391 if buf
.len() == buf
.capacity() && buf
.capacity() == start_cap
{
392 // The buffer might be an exact fit. Let's read into a probe buffer
393 // and see if it returns `Ok(0)`. If so, we've avoided an
394 // unnecessary doubling of the capacity. But if not, append the
395 // probe buffer to the primary buffer and let its capacity grow.
396 let mut probe
= [0u8; 32];
399 match r
.read(&mut probe
) {
400 Ok(0) => return Ok(buf
.len() - start_len
),
402 buf
.extend_from_slice(&probe
[..n
]);
405 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> continue,
406 Err(e
) => return Err(e
),
413 pub(crate) fn default_read_to_string
<R
: Read
+ ?Sized
>(
417 // Note that we do *not* call `r.read_to_end()` here. We are passing
418 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
419 // method to fill it up. An arbitrary implementation could overwrite the
420 // entire contents of the vector, not just append to it (which is what
421 // we are expecting).
423 // To prevent extraneously checking the UTF-8-ness of the entire buffer
424 // we pass it to our hardcoded `default_read_to_end` implementation which
425 // we know is guaranteed to only read data into the end of the buffer.
426 unsafe { append_to_string(buf, |b| default_read_to_end(r, b)) }
429 pub(crate) fn default_read_vectored
<F
>(read
: F
, bufs
: &mut [IoSliceMut
<'_
>]) -> Result
<usize>
431 F
: FnOnce(&mut [u8]) -> Result
<usize>,
433 let buf
= bufs
.iter_mut().find(|b
| !b
.is_empty()).map_or(&mut [][..], |b
| &mut **b
);
437 pub(crate) fn default_write_vectored
<F
>(write
: F
, bufs
: &[IoSlice
<'_
>]) -> Result
<usize>
439 F
: FnOnce(&[u8]) -> Result
<usize>,
441 let buf
= bufs
.iter().find(|b
| !b
.is_empty()).map_or(&[][..], |b
| &**b
);
445 pub(crate) fn default_read_exact
<R
: Read
+ ?Sized
>(this
: &mut R
, mut buf
: &mut [u8]) -> Result
<()> {
446 while !buf
.is_empty() {
447 match this
.read(buf
) {
453 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> {}
454 Err(e
) => return Err(e
),
458 Err(error
::const_io_error
!(ErrorKind
::UnexpectedEof
, "failed to fill whole buffer"))
464 pub(crate) fn default_read_buf
<F
>(read
: F
, buf
: &mut ReadBuf
<'_
>) -> Result
<()>
466 F
: FnOnce(&mut [u8]) -> Result
<usize>,
468 let n
= read(buf
.initialize_unfilled())?
;
473 /// The `Read` trait allows for reading bytes from a source.
475 /// Implementors of the `Read` trait are called 'readers'.
477 /// Readers are defined by one required method, [`read()`]. Each call to [`read()`]
478 /// will attempt to pull bytes from this source into a provided buffer. A
479 /// number of other methods are implemented in terms of [`read()`], giving
480 /// implementors a number of ways to read bytes while only needing to implement
483 /// Readers are intended to be composable with one another. Many implementors
484 /// throughout [`std::io`] take and provide types which implement the `Read`
487 /// Please note that each call to [`read()`] may involve a system call, and
488 /// therefore, using something that implements [`BufRead`], such as
489 /// [`BufReader`], will be more efficient.
493 /// [`File`]s implement `Read`:
497 /// use std::io::prelude::*;
498 /// use std::fs::File;
500 /// fn main() -> io::Result<()> {
501 /// let mut f = File::open("foo.txt")?;
502 /// let mut buffer = [0; 10];
504 /// // read up to 10 bytes
505 /// f.read(&mut buffer)?;
507 /// let mut buffer = Vec::new();
508 /// // read the whole file
509 /// f.read_to_end(&mut buffer)?;
511 /// // read into a String, so that you don't need to do the conversion.
512 /// let mut buffer = String::new();
513 /// f.read_to_string(&mut buffer)?;
515 /// // and more! See the other methods for more details.
520 /// Read from [`&str`] because [`&[u8]`][prim@slice] implements `Read`:
524 /// use std::io::prelude::*;
526 /// fn main() -> io::Result<()> {
527 /// let mut b = "This string will be read".as_bytes();
528 /// let mut buffer = [0; 10];
530 /// // read up to 10 bytes
531 /// b.read(&mut buffer)?;
533 /// // etc... it works exactly as a File does!
538 /// [`read()`]: Read::read
539 /// [`&str`]: prim@str
540 /// [`std::io`]: self
541 /// [`File`]: crate::fs::File
542 #[stable(feature = "rust1", since = "1.0.0")]
543 #[doc(notable_trait)]
544 #[cfg_attr(not(test), rustc_diagnostic_item = "IoRead")]
546 /// Pull some bytes from this source into the specified buffer, returning
547 /// how many bytes were read.
549 /// This function does not provide any guarantees about whether it blocks
550 /// waiting for data, but if an object needs to block for a read and cannot,
551 /// it will typically signal this via an [`Err`] return value.
553 /// If the return value of this method is [`Ok(n)`], then implementations must
554 /// guarantee that `0 <= n <= buf.len()`. A nonzero `n` value indicates
555 /// that the buffer `buf` has been filled in with `n` bytes of data from this
556 /// source. If `n` is `0`, then it can indicate one of two scenarios:
558 /// 1. This reader has reached its "end of file" and will likely no longer
559 /// be able to produce bytes. Note that this does not mean that the
560 /// reader will *always* no longer be able to produce bytes. As an example,
561 /// on Linux, this method will call the `recv` syscall for a [`TcpStream`],
562 /// where returning zero indicates the connection was shut down correctly. While
563 /// for [`File`], it is possible to reach the end of file and get zero as result,
564 /// but if more data is appended to the file, future calls to `read` will return
566 /// 2. The buffer specified was 0 bytes in length.
568 /// It is not an error if the returned value `n` is smaller than the buffer size,
569 /// even when the reader is not at the end of the stream yet.
570 /// This may happen for example because fewer bytes are actually available right now
571 /// (e. g. being close to end-of-file) or because read() was interrupted by a signal.
573 /// As this trait is safe to implement, callers cannot rely on `n <= buf.len()` for safety.
574 /// Extra care needs to be taken when `unsafe` functions are used to access the read bytes.
575 /// Callers have to ensure that no unchecked out-of-bounds accesses are possible even if
578 /// No guarantees are provided about the contents of `buf` when this
579 /// function is called, implementations cannot rely on any property of the
580 /// contents of `buf` being true. It is recommended that *implementations*
581 /// only write data to `buf` instead of reading its contents.
583 /// Correspondingly, however, *callers* of this method must not assume any guarantees
584 /// about how the implementation uses `buf`. The trait is safe to implement,
585 /// so it is possible that the code that's supposed to write to the buffer might also read
586 /// from it. It is your responsibility to make sure that `buf` is initialized
587 /// before calling `read`. Calling `read` with an uninitialized `buf` (of the kind one
588 /// obtains via [`MaybeUninit<T>`]) is not safe, and can lead to undefined behavior.
590 /// [`MaybeUninit<T>`]: crate::mem::MaybeUninit
594 /// If this function encounters any form of I/O or other error, an error
595 /// variant will be returned. If an error is returned then it must be
596 /// guaranteed that no bytes were read.
598 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
599 /// operation should be retried if there is nothing else to do.
603 /// [`File`]s implement `Read`:
606 /// [`File`]: crate::fs::File
607 /// [`TcpStream`]: crate::net::TcpStream
611 /// use std::io::prelude::*;
612 /// use std::fs::File;
614 /// fn main() -> io::Result<()> {
615 /// let mut f = File::open("foo.txt")?;
616 /// let mut buffer = [0; 10];
618 /// // read up to 10 bytes
619 /// let n = f.read(&mut buffer[..])?;
621 /// println!("The bytes: {:?}", &buffer[..n]);
625 #[stable(feature = "rust1", since = "1.0.0")]
626 fn read(&mut self, buf
: &mut [u8]) -> Result
<usize>;
628 /// Like `read`, except that it reads into a slice of buffers.
630 /// Data is copied to fill each buffer in order, with the final buffer
631 /// written to possibly being only partially filled. This method must
632 /// behave equivalently to a single call to `read` with concatenated
635 /// The default implementation calls `read` with either the first nonempty
636 /// buffer provided, or an empty one if none exists.
637 #[stable(feature = "iovec", since = "1.36.0")]
638 fn read_vectored(&mut self, bufs
: &mut [IoSliceMut
<'_
>]) -> Result
<usize> {
639 default_read_vectored(|b
| self.read(b
), bufs
)
642 /// Determines if this `Read`er has an efficient `read_vectored`
645 /// If a `Read`er does not override the default `read_vectored`
646 /// implementation, code using it may want to avoid the method all together
647 /// and coalesce writes into a single buffer for higher performance.
649 /// The default implementation returns `false`.
650 #[unstable(feature = "can_vector", issue = "69941")]
651 fn is_read_vectored(&self) -> bool
{
655 /// Read all bytes until EOF in this source, placing them into `buf`.
657 /// All bytes read from this source will be appended to the specified buffer
658 /// `buf`. This function will continuously call [`read()`] to append more data to
659 /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of
660 /// non-[`ErrorKind::Interrupted`] kind.
662 /// If successful, this function will return the total number of bytes read.
666 /// If this function encounters an error of the kind
667 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
670 /// If any other read error is encountered then this function immediately
671 /// returns. Any bytes which have already been read will be appended to
676 /// [`File`]s implement `Read`:
678 /// [`read()`]: Read::read
680 /// [`File`]: crate::fs::File
684 /// use std::io::prelude::*;
685 /// use std::fs::File;
687 /// fn main() -> io::Result<()> {
688 /// let mut f = File::open("foo.txt")?;
689 /// let mut buffer = Vec::new();
691 /// // read the whole file
692 /// f.read_to_end(&mut buffer)?;
697 /// (See also the [`std::fs::read`] convenience function for reading from a
700 /// [`std::fs::read`]: crate::fs::read
701 #[stable(feature = "rust1", since = "1.0.0")]
702 fn read_to_end(&mut self, buf
: &mut Vec
<u8>) -> Result
<usize> {
703 default_read_to_end(self, buf
)
706 /// Read all bytes until EOF in this source, appending them to `buf`.
708 /// If successful, this function returns the number of bytes which were read
709 /// and appended to `buf`.
713 /// If the data in this stream is *not* valid UTF-8 then an error is
714 /// returned and `buf` is unchanged.
716 /// See [`read_to_end`] for other error semantics.
718 /// [`read_to_end`]: Read::read_to_end
722 /// [`File`]s implement `Read`:
724 /// [`File`]: crate::fs::File
728 /// use std::io::prelude::*;
729 /// use std::fs::File;
731 /// fn main() -> io::Result<()> {
732 /// let mut f = File::open("foo.txt")?;
733 /// let mut buffer = String::new();
735 /// f.read_to_string(&mut buffer)?;
740 /// (See also the [`std::fs::read_to_string`] convenience function for
741 /// reading from a file.)
743 /// [`std::fs::read_to_string`]: crate::fs::read_to_string
744 #[stable(feature = "rust1", since = "1.0.0")]
745 fn read_to_string(&mut self, buf
: &mut String
) -> Result
<usize> {
746 default_read_to_string(self, buf
)
749 /// Read the exact number of bytes required to fill `buf`.
751 /// This function reads as many bytes as necessary to completely fill the
752 /// specified buffer `buf`.
754 /// No guarantees are provided about the contents of `buf` when this
755 /// function is called, implementations cannot rely on any property of the
756 /// contents of `buf` being true. It is recommended that implementations
757 /// only write data to `buf` instead of reading its contents. The
758 /// documentation on [`read`] has a more detailed explanation on this
763 /// If this function encounters an error of the kind
764 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
767 /// If this function encounters an "end of file" before completely filling
768 /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
769 /// The contents of `buf` are unspecified in this case.
771 /// If any other read error is encountered then this function immediately
772 /// returns. The contents of `buf` are unspecified in this case.
774 /// If this function returns an error, it is unspecified how many bytes it
775 /// has read, but it will never read more than would be necessary to
776 /// completely fill the buffer.
780 /// [`File`]s implement `Read`:
782 /// [`read`]: Read::read
783 /// [`File`]: crate::fs::File
787 /// use std::io::prelude::*;
788 /// use std::fs::File;
790 /// fn main() -> io::Result<()> {
791 /// let mut f = File::open("foo.txt")?;
792 /// let mut buffer = [0; 10];
794 /// // read exactly 10 bytes
795 /// f.read_exact(&mut buffer)?;
799 #[stable(feature = "read_exact", since = "1.6.0")]
800 fn read_exact(&mut self, buf
: &mut [u8]) -> Result
<()> {
801 default_read_exact(self, buf
)
804 /// Pull some bytes from this source into the specified buffer.
806 /// This is equivalent to the [`read`](Read::read) method, except that it is passed a [`ReadBuf`] rather than `[u8]` to allow use
807 /// with uninitialized buffers. The new data will be appended to any existing contents of `buf`.
809 /// The default implementation delegates to `read`.
810 #[unstable(feature = "read_buf", issue = "78485")]
811 fn read_buf(&mut self, buf
: &mut ReadBuf
<'_
>) -> Result
<()> {
812 default_read_buf(|b
| self.read(b
), buf
)
815 /// Read the exact number of bytes required to fill `buf`.
817 /// This is equivalent to the [`read_exact`](Read::read_exact) method, except that it is passed a [`ReadBuf`] rather than `[u8]` to
818 /// allow use with uninitialized buffers.
819 #[unstable(feature = "read_buf", issue = "78485")]
820 fn read_buf_exact(&mut self, buf
: &mut ReadBuf
<'_
>) -> Result
<()> {
821 while buf
.remaining() > 0 {
822 let prev_filled
= buf
.filled().len();
823 match self.read_buf(buf
) {
825 Err(e
) if e
.kind() == ErrorKind
::Interrupted
=> continue,
826 Err(e
) => return Err(e
),
829 if buf
.filled().len() == prev_filled
{
830 return Err(Error
::new(ErrorKind
::UnexpectedEof
, "failed to fill buffer"));
837 /// Creates a "by reference" adaptor for this instance of `Read`.
839 /// The returned adapter also implements `Read` and will simply borrow this
844 /// [`File`]s implement `Read`:
846 /// [`File`]: crate::fs::File
850 /// use std::io::Read;
851 /// use std::fs::File;
853 /// fn main() -> io::Result<()> {
854 /// let mut f = File::open("foo.txt")?;
855 /// let mut buffer = Vec::new();
856 /// let mut other_buffer = Vec::new();
859 /// let reference = f.by_ref();
861 /// // read at most 5 bytes
862 /// reference.take(5).read_to_end(&mut buffer)?;
864 /// } // drop our &mut reference so we can use f again
866 /// // original file still usable, read the rest
867 /// f.read_to_end(&mut other_buffer)?;
871 #[stable(feature = "rust1", since = "1.0.0")]
872 fn by_ref(&mut self) -> &mut Self
879 /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
881 /// The returned type implements [`Iterator`] where the [`Item`] is
882 /// <code>[Result]<[u8], [io::Error]></code>.
883 /// The yielded item is [`Ok`] if a byte was successfully read and [`Err`]
884 /// otherwise. EOF is mapped to returning [`None`] from this iterator.
888 /// [`File`]s implement `Read`:
890 /// [`Item`]: Iterator::Item
891 /// [`File`]: crate::fs::File "fs::File"
892 /// [Result]: crate::result::Result "Result"
893 /// [io::Error]: self::Error "io::Error"
897 /// use std::io::prelude::*;
898 /// use std::fs::File;
900 /// fn main() -> io::Result<()> {
901 /// let mut f = File::open("foo.txt")?;
903 /// for byte in f.bytes() {
904 /// println!("{}", byte.unwrap());
909 #[stable(feature = "rust1", since = "1.0.0")]
910 fn bytes(self) -> Bytes
<Self>
914 Bytes { inner: self }
917 /// Creates an adapter which will chain this stream with another.
919 /// The returned `Read` instance will first read all bytes from this object
920 /// until EOF is encountered. Afterwards the output is equivalent to the
921 /// output of `next`.
925 /// [`File`]s implement `Read`:
927 /// [`File`]: crate::fs::File
931 /// use std::io::prelude::*;
932 /// use std::fs::File;
934 /// fn main() -> io::Result<()> {
935 /// let mut f1 = File::open("foo.txt")?;
936 /// let mut f2 = File::open("bar.txt")?;
938 /// let mut handle = f1.chain(f2);
939 /// let mut buffer = String::new();
941 /// // read the value into a String. We could use any Read method here,
942 /// // this is just one example.
943 /// handle.read_to_string(&mut buffer)?;
947 #[stable(feature = "rust1", since = "1.0.0")]
948 fn chain
<R
: Read
>(self, next
: R
) -> Chain
<Self, R
>
952 Chain { first: self, second: next, done_first: false }
955 /// Creates an adapter which will read at most `limit` bytes from it.
957 /// This function returns a new instance of `Read` which will read at most
958 /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
959 /// read errors will not count towards the number of bytes read and future
960 /// calls to [`read()`] may succeed.
964 /// [`File`]s implement `Read`:
966 /// [`File`]: crate::fs::File
968 /// [`read()`]: Read::read
972 /// use std::io::prelude::*;
973 /// use std::fs::File;
975 /// fn main() -> io::Result<()> {
976 /// let mut f = File::open("foo.txt")?;
977 /// let mut buffer = [0; 5];
979 /// // read at most five bytes
980 /// let mut handle = f.take(5);
982 /// handle.read(&mut buffer)?;
986 #[stable(feature = "rust1", since = "1.0.0")]
987 fn take(self, limit
: u64) -> Take
<Self>
991 Take { inner: self, limit }
995 /// Read all bytes from a [reader][Read] into a new [`String`].
997 /// This is a convenience function for [`Read::read_to_string`]. Using this
998 /// function avoids having to create a variable first and provides more type
999 /// safety since you can only get the buffer out if there were no errors. (If you
1000 /// use [`Read::read_to_string`] you have to remember to check whether the read
1001 /// succeeded because otherwise your buffer will be empty or only partially full.)
1005 /// The downside of this function's increased ease of use and type safety is
1006 /// that it gives you less control over performance. For example, you can't
1007 /// pre-allocate memory like you can using [`String::with_capacity`] and
1008 /// [`Read::read_to_string`]. Also, you can't re-use the buffer if an error
1009 /// occurs while reading.
1011 /// In many cases, this function's performance will be adequate and the ease of use
1012 /// and type safety tradeoffs will be worth it. However, there are cases where you
1013 /// need more control over performance, and in those cases you should definitely use
1014 /// [`Read::read_to_string`] directly.
1016 /// Note that in some special cases, such as when reading files, this function will
1017 /// pre-allocate memory based on the size of the input it is reading. In those
1018 /// cases, the performance should be as good as if you had used
1019 /// [`Read::read_to_string`] with a manually pre-allocated buffer.
1023 /// This function forces you to handle errors because the output (the `String`)
1024 /// is wrapped in a [`Result`]. See [`Read::read_to_string`] for the errors
1025 /// that can occur. If any error occurs, you will get an [`Err`], so you
1026 /// don't have to worry about your buffer being empty or partially full.
1031 /// #![feature(io_read_to_string)]
1034 /// fn main() -> io::Result<()> {
1035 /// let stdin = io::read_to_string(io::stdin())?;
1036 /// println!("Stdin was:");
1037 /// println!("{stdin}");
1041 #[unstable(feature = "io_read_to_string", issue = "80218")]
1042 pub fn read_to_string
<R
: Read
>(mut reader
: R
) -> Result
<String
> {
1043 let mut buf
= String
::new();
1044 reader
.read_to_string(&mut buf
)?
;
1048 /// A buffer type used with `Read::read_vectored`.
1050 /// It is semantically a wrapper around an `&mut [u8]`, but is guaranteed to be
1051 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
1053 #[stable(feature = "iovec", since = "1.36.0")]
1054 #[repr(transparent)]
1055 pub struct IoSliceMut
<'a
>(sys
::io
::IoSliceMut
<'a
>);
1057 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1058 unsafe impl<'a
> Send
for IoSliceMut
<'a
> {}
1060 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1061 unsafe impl<'a
> Sync
for IoSliceMut
<'a
> {}
1063 #[stable(feature = "iovec", since = "1.36.0")]
1064 impl<'a
> fmt
::Debug
for IoSliceMut
<'a
> {
1065 fn fmt(&self, fmt
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1066 fmt
::Debug
::fmt(self.0.as_slice(), fmt
)
1070 impl<'a
> IoSliceMut
<'a
> {
1071 /// Creates a new `IoSliceMut` wrapping a byte slice.
1075 /// Panics on Windows if the slice is larger than 4GB.
1076 #[stable(feature = "iovec", since = "1.36.0")]
1078 pub fn new(buf
: &'a
mut [u8]) -> IoSliceMut
<'a
> {
1079 IoSliceMut(sys
::io
::IoSliceMut
::new(buf
))
1082 /// Advance the internal cursor of the slice.
1084 /// Also see [`IoSliceMut::advance_slices`] to advance the cursors of
1085 /// multiple buffers.
1089 /// Panics when trying to advance beyond the end of the slice.
1094 /// #![feature(io_slice_advance)]
1096 /// use std::io::IoSliceMut;
1097 /// use std::ops::Deref;
1099 /// let mut data = [1; 8];
1100 /// let mut buf = IoSliceMut::new(&mut data);
1102 /// // Mark 3 bytes as read.
1104 /// assert_eq!(buf.deref(), [1; 5].as_ref());
1106 #[unstable(feature = "io_slice_advance", issue = "62726")]
1108 pub fn advance(&mut self, n
: usize) {
1112 /// Advance a slice of slices.
1114 /// Shrinks the slice to remove any `IoSliceMut`s that are fully advanced over.
1115 /// If the cursor ends up in the middle of an `IoSliceMut`, it is modified
1116 /// to start at that cursor.
1118 /// For example, if we have a slice of two 8-byte `IoSliceMut`s, and we advance by 10 bytes,
1119 /// the result will only include the second `IoSliceMut`, advanced by 2 bytes.
1123 /// Panics when trying to advance beyond the end of the slices.
1128 /// #![feature(io_slice_advance)]
1130 /// use std::io::IoSliceMut;
1131 /// use std::ops::Deref;
1133 /// let mut buf1 = [1; 8];
1134 /// let mut buf2 = [2; 16];
1135 /// let mut buf3 = [3; 8];
1136 /// let mut bufs = &mut [
1137 /// IoSliceMut::new(&mut buf1),
1138 /// IoSliceMut::new(&mut buf2),
1139 /// IoSliceMut::new(&mut buf3),
1142 /// // Mark 10 bytes as read.
1143 /// IoSliceMut::advance_slices(&mut bufs, 10);
1144 /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1145 /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1147 #[unstable(feature = "io_slice_advance", issue = "62726")]
1149 pub fn advance_slices(bufs
: &mut &mut [IoSliceMut
<'a
>], n
: usize) {
1150 // Number of buffers to remove.
1152 // Total length of all the to be removed buffers.
1153 let mut accumulated_len
= 0;
1154 for buf
in bufs
.iter() {
1155 if accumulated_len
+ buf
.len() > n
{
1158 accumulated_len
+= buf
.len();
1163 *bufs
= &mut replace(bufs
, &mut [])[remove
..];
1164 if bufs
.is_empty() {
1165 assert
!(n
== accumulated_len
, "advancing io slices beyond their length");
1167 bufs
[0].advance(n
- accumulated_len
)
1172 #[stable(feature = "iovec", since = "1.36.0")]
1173 impl<'a
> Deref
for IoSliceMut
<'a
> {
1177 fn deref(&self) -> &[u8] {
1182 #[stable(feature = "iovec", since = "1.36.0")]
1183 impl<'a
> DerefMut
for IoSliceMut
<'a
> {
1185 fn deref_mut(&mut self) -> &mut [u8] {
1186 self.0.as_mut_slice()
1190 /// A buffer type used with `Write::write_vectored`.
1192 /// It is semantically a wrapper around a `&[u8]`, but is guaranteed to be
1193 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
1195 #[stable(feature = "iovec", since = "1.36.0")]
1196 #[derive(Copy, Clone)]
1197 #[repr(transparent)]
1198 pub struct IoSlice
<'a
>(sys
::io
::IoSlice
<'a
>);
1200 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1201 unsafe impl<'a
> Send
for IoSlice
<'a
> {}
1203 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1204 unsafe impl<'a
> Sync
for IoSlice
<'a
> {}
1206 #[stable(feature = "iovec", since = "1.36.0")]
1207 impl<'a
> fmt
::Debug
for IoSlice
<'a
> {
1208 fn fmt(&self, fmt
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1209 fmt
::Debug
::fmt(self.0.as_slice(), fmt
)
1213 impl<'a
> IoSlice
<'a
> {
1214 /// Creates a new `IoSlice` wrapping a byte slice.
1218 /// Panics on Windows if the slice is larger than 4GB.
1219 #[stable(feature = "iovec", since = "1.36.0")]
1222 pub fn new(buf
: &'a
[u8]) -> IoSlice
<'a
> {
1223 IoSlice(sys
::io
::IoSlice
::new(buf
))
1226 /// Advance the internal cursor of the slice.
1228 /// Also see [`IoSlice::advance_slices`] to advance the cursors of multiple
1233 /// Panics when trying to advance beyond the end of the slice.
1238 /// #![feature(io_slice_advance)]
1240 /// use std::io::IoSlice;
1241 /// use std::ops::Deref;
1243 /// let data = [1; 8];
1244 /// let mut buf = IoSlice::new(&data);
1246 /// // Mark 3 bytes as read.
1248 /// assert_eq!(buf.deref(), [1; 5].as_ref());
1250 #[unstable(feature = "io_slice_advance", issue = "62726")]
1252 pub fn advance(&mut self, n
: usize) {
1256 /// Advance a slice of slices.
1258 /// Shrinks the slice to remove any `IoSlice`s that are fully advanced over.
1259 /// If the cursor ends up in the middle of an `IoSlice`, it is modified
1260 /// to start at that cursor.
1262 /// For example, if we have a slice of two 8-byte `IoSlice`s, and we advance by 10 bytes,
1263 /// the result will only include the second `IoSlice`, advanced by 2 bytes.
1267 /// Panics when trying to advance beyond the end of the slices.
1272 /// #![feature(io_slice_advance)]
1274 /// use std::io::IoSlice;
1275 /// use std::ops::Deref;
1277 /// let buf1 = [1; 8];
1278 /// let buf2 = [2; 16];
1279 /// let buf3 = [3; 8];
1280 /// let mut bufs = &mut [
1281 /// IoSlice::new(&buf1),
1282 /// IoSlice::new(&buf2),
1283 /// IoSlice::new(&buf3),
1286 /// // Mark 10 bytes as written.
1287 /// IoSlice::advance_slices(&mut bufs, 10);
1288 /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1289 /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1290 #[unstable(feature = "io_slice_advance", issue = "62726")]
1292 pub fn advance_slices(bufs
: &mut &mut [IoSlice
<'a
>], n
: usize) {
1293 // Number of buffers to remove.
1295 // Total length of all the to be removed buffers.
1296 let mut accumulated_len
= 0;
1297 for buf
in bufs
.iter() {
1298 if accumulated_len
+ buf
.len() > n
{
1301 accumulated_len
+= buf
.len();
1306 *bufs
= &mut replace(bufs
, &mut [])[remove
..];
1307 if bufs
.is_empty() {
1308 assert
!(n
== accumulated_len
, "advancing io slices beyond their length");
1310 bufs
[0].advance(n
- accumulated_len
)
1315 #[stable(feature = "iovec", since = "1.36.0")]
1316 impl<'a
> Deref
for IoSlice
<'a
> {
1320 fn deref(&self) -> &[u8] {
1325 /// A trait for objects which are byte-oriented sinks.
1327 /// Implementors of the `Write` trait are sometimes called 'writers'.
1329 /// Writers are defined by two required methods, [`write`] and [`flush`]:
1331 /// * The [`write`] method will attempt to write some data into the object,
1332 /// returning how many bytes were successfully written.
1334 /// * The [`flush`] method is useful for adapters and explicit buffers
1335 /// themselves for ensuring that all buffered data has been pushed out to the
1338 /// Writers are intended to be composable with one another. Many implementors
1339 /// throughout [`std::io`] take and provide types which implement the `Write`
1342 /// [`write`]: Write::write
1343 /// [`flush`]: Write::flush
1344 /// [`std::io`]: self
1349 /// use std::io::prelude::*;
1350 /// use std::fs::File;
1352 /// fn main() -> std::io::Result<()> {
1353 /// let data = b"some bytes";
1355 /// let mut pos = 0;
1356 /// let mut buffer = File::create("foo.txt")?;
1358 /// while pos < data.len() {
1359 /// let bytes_written = buffer.write(&data[pos..])?;
1360 /// pos += bytes_written;
1366 /// The trait also provides convenience methods like [`write_all`], which calls
1367 /// `write` in a loop until its entire input has been written.
1369 /// [`write_all`]: Write::write_all
1370 #[stable(feature = "rust1", since = "1.0.0")]
1371 #[doc(notable_trait)]
1372 #[cfg_attr(not(test), rustc_diagnostic_item = "IoWrite")]
1374 /// Write a buffer into this writer, returning how many bytes were written.
1376 /// This function will attempt to write the entire contents of `buf`, but
1377 /// the entire write might not succeed, or the write may also generate an
1378 /// error. A call to `write` represents *at most one* attempt to write to
1379 /// any wrapped object.
1381 /// Calls to `write` are not guaranteed to block waiting for data to be
1382 /// written, and a write which would otherwise block can be indicated through
1383 /// an [`Err`] variant.
1385 /// If the return value is [`Ok(n)`] then it must be guaranteed that
1386 /// `n <= buf.len()`. A return value of `0` typically means that the
1387 /// underlying object is no longer able to accept bytes and will likely not
1388 /// be able to in the future as well, or that the buffer provided is empty.
1392 /// Each call to `write` may generate an I/O error indicating that the
1393 /// operation could not be completed. If an error is returned then no bytes
1394 /// in the buffer were written to this writer.
1396 /// It is **not** considered an error if the entire buffer could not be
1397 /// written to this writer.
1399 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the
1400 /// write operation should be retried if there is nothing else to do.
1405 /// use std::io::prelude::*;
1406 /// use std::fs::File;
1408 /// fn main() -> std::io::Result<()> {
1409 /// let mut buffer = File::create("foo.txt")?;
1411 /// // Writes some prefix of the byte string, not necessarily all of it.
1412 /// buffer.write(b"some bytes")?;
1418 #[stable(feature = "rust1", since = "1.0.0")]
1419 fn write(&mut self, buf
: &[u8]) -> Result
<usize>;
1421 /// Like [`write`], except that it writes from a slice of buffers.
1423 /// Data is copied from each buffer in order, with the final buffer
1424 /// read from possibly being only partially consumed. This method must
1425 /// behave as a call to [`write`] with the buffers concatenated would.
1427 /// The default implementation calls [`write`] with either the first nonempty
1428 /// buffer provided, or an empty one if none exists.
1433 /// use std::io::IoSlice;
1434 /// use std::io::prelude::*;
1435 /// use std::fs::File;
1437 /// fn main() -> std::io::Result<()> {
1438 /// let data1 = [1; 8];
1439 /// let data2 = [15; 8];
1440 /// let io_slice1 = IoSlice::new(&data1);
1441 /// let io_slice2 = IoSlice::new(&data2);
1443 /// let mut buffer = File::create("foo.txt")?;
1445 /// // Writes some prefix of the byte string, not necessarily all of it.
1446 /// buffer.write_vectored(&[io_slice1, io_slice2])?;
1451 /// [`write`]: Write::write
1452 #[stable(feature = "iovec", since = "1.36.0")]
1453 fn write_vectored(&mut self, bufs
: &[IoSlice
<'_
>]) -> Result
<usize> {
1454 default_write_vectored(|b
| self.write(b
), bufs
)
1457 /// Determines if this `Write`r has an efficient [`write_vectored`]
1460 /// If a `Write`r does not override the default [`write_vectored`]
1461 /// implementation, code using it may want to avoid the method all together
1462 /// and coalesce writes into a single buffer for higher performance.
1464 /// The default implementation returns `false`.
1466 /// [`write_vectored`]: Write::write_vectored
1467 #[unstable(feature = "can_vector", issue = "69941")]
1468 fn is_write_vectored(&self) -> bool
{
1472 /// Flush this output stream, ensuring that all intermediately buffered
1473 /// contents reach their destination.
1477 /// It is considered an error if not all bytes could be written due to
1478 /// I/O errors or EOF being reached.
1483 /// use std::io::prelude::*;
1484 /// use std::io::BufWriter;
1485 /// use std::fs::File;
1487 /// fn main() -> std::io::Result<()> {
1488 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
1490 /// buffer.write_all(b"some bytes")?;
1491 /// buffer.flush()?;
1495 #[stable(feature = "rust1", since = "1.0.0")]
1496 fn flush(&mut self) -> Result
<()>;
1498 /// Attempts to write an entire buffer into this writer.
1500 /// This method will continuously call [`write`] until there is no more data
1501 /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is
1502 /// returned. This method will not return until the entire buffer has been
1503 /// successfully written or such an error occurs. The first error that is
1504 /// not of [`ErrorKind::Interrupted`] kind generated from this method will be
1507 /// If the buffer contains no data, this will never call [`write`].
1511 /// This function will return the first error of
1512 /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns.
1514 /// [`write`]: Write::write
1519 /// use std::io::prelude::*;
1520 /// use std::fs::File;
1522 /// fn main() -> std::io::Result<()> {
1523 /// let mut buffer = File::create("foo.txt")?;
1525 /// buffer.write_all(b"some bytes")?;
1529 #[stable(feature = "rust1", since = "1.0.0")]
1530 fn write_all(&mut self, mut buf
: &[u8]) -> Result
<()> {
1531 while !buf
.is_empty() {
1532 match self.write(buf
) {
1534 return Err(error
::const_io_error
!(
1535 ErrorKind
::WriteZero
,
1536 "failed to write whole buffer",
1539 Ok(n
) => buf
= &buf
[n
..],
1540 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> {}
1541 Err(e
) => return Err(e
),
1547 /// Attempts to write multiple buffers into this writer.
1549 /// This method will continuously call [`write_vectored`] until there is no
1550 /// more data to be written or an error of non-[`ErrorKind::Interrupted`]
1551 /// kind is returned. This method will not return until all buffers have
1552 /// been successfully written or such an error occurs. The first error that
1553 /// is not of [`ErrorKind::Interrupted`] kind generated from this method
1554 /// will be returned.
1556 /// If the buffer contains no data, this will never call [`write_vectored`].
1560 /// Unlike [`write_vectored`], this takes a *mutable* reference to
1561 /// a slice of [`IoSlice`]s, not an immutable one. That's because we need to
1562 /// modify the slice to keep track of the bytes already written.
1564 /// Once this function returns, the contents of `bufs` are unspecified, as
1565 /// this depends on how many calls to [`write_vectored`] were necessary. It is
1566 /// best to understand this function as taking ownership of `bufs` and to
1567 /// not use `bufs` afterwards. The underlying buffers, to which the
1568 /// [`IoSlice`]s point (but not the [`IoSlice`]s themselves), are unchanged and
1571 /// [`write_vectored`]: Write::write_vectored
1576 /// #![feature(write_all_vectored)]
1577 /// # fn main() -> std::io::Result<()> {
1579 /// use std::io::{Write, IoSlice};
1581 /// let mut writer = Vec::new();
1582 /// let bufs = &mut [
1583 /// IoSlice::new(&[1]),
1584 /// IoSlice::new(&[2, 3]),
1585 /// IoSlice::new(&[4, 5, 6]),
1588 /// writer.write_all_vectored(bufs)?;
1589 /// // Note: the contents of `bufs` is now undefined, see the Notes section.
1591 /// assert_eq!(writer, &[1, 2, 3, 4, 5, 6]);
1594 #[unstable(feature = "write_all_vectored", issue = "70436")]
1595 fn write_all_vectored(&mut self, mut bufs
: &mut [IoSlice
<'_
>]) -> Result
<()> {
1596 // Guarantee that bufs is empty if it contains no data,
1597 // to avoid calling write_vectored if there is no data to be written.
1598 IoSlice
::advance_slices(&mut bufs
, 0);
1599 while !bufs
.is_empty() {
1600 match self.write_vectored(bufs
) {
1602 return Err(error
::const_io_error
!(
1603 ErrorKind
::WriteZero
,
1604 "failed to write whole buffer",
1607 Ok(n
) => IoSlice
::advance_slices(&mut bufs
, n
),
1608 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> {}
1609 Err(e
) => return Err(e
),
1615 /// Writes a formatted string into this writer, returning any error
1618 /// This method is primarily used to interface with the
1619 /// [`format_args!()`] macro, and it is rare that this should
1620 /// explicitly be called. The [`write!()`] macro should be favored to
1621 /// invoke this method instead.
1623 /// This function internally uses the [`write_all`] method on
1624 /// this trait and hence will continuously write data so long as no errors
1625 /// are received. This also means that partial writes are not indicated in
1628 /// [`write_all`]: Write::write_all
1632 /// This function will return any I/O error reported while formatting.
1637 /// use std::io::prelude::*;
1638 /// use std::fs::File;
1640 /// fn main() -> std::io::Result<()> {
1641 /// let mut buffer = File::create("foo.txt")?;
1644 /// write!(buffer, "{:.*}", 2, 1.234567)?;
1645 /// // turns into this:
1646 /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1650 #[stable(feature = "rust1", since = "1.0.0")]
1651 fn write_fmt(&mut self, fmt
: fmt
::Arguments
<'_
>) -> Result
<()> {
1652 // Create a shim which translates a Write to a fmt::Write and saves
1653 // off I/O errors. instead of discarding them
1654 struct Adapter
<'a
, T
: ?Sized
+ 'a
> {
1659 impl<T
: Write
+ ?Sized
> fmt
::Write
for Adapter
<'_
, T
> {
1660 fn write_str(&mut self, s
: &str) -> fmt
::Result
{
1661 match self.inner
.write_all(s
.as_bytes()) {
1664 self.error
= Err(e
);
1671 let mut output
= Adapter { inner: self, error: Ok(()) }
;
1672 match fmt
::write(&mut output
, fmt
) {
1675 // check if the error came from the underlying `Write` or not
1676 if output
.error
.is_err() {
1679 Err(error
::const_io_error
!(ErrorKind
::Uncategorized
, "formatter error"))
1685 /// Creates a "by reference" adapter for this instance of `Write`.
1687 /// The returned adapter also implements `Write` and will simply borrow this
1693 /// use std::io::Write;
1694 /// use std::fs::File;
1696 /// fn main() -> std::io::Result<()> {
1697 /// let mut buffer = File::create("foo.txt")?;
1699 /// let reference = buffer.by_ref();
1701 /// // we can use reference just like our original buffer
1702 /// reference.write_all(b"some bytes")?;
1706 #[stable(feature = "rust1", since = "1.0.0")]
1707 fn by_ref(&mut self) -> &mut Self
1715 /// The `Seek` trait provides a cursor which can be moved within a stream of
1718 /// The stream typically has a fixed size, allowing seeking relative to either
1719 /// end or the current offset.
1723 /// [`File`]s implement `Seek`:
1725 /// [`File`]: crate::fs::File
1729 /// use std::io::prelude::*;
1730 /// use std::fs::File;
1731 /// use std::io::SeekFrom;
1733 /// fn main() -> io::Result<()> {
1734 /// let mut f = File::open("foo.txt")?;
1736 /// // move the cursor 42 bytes from the start of the file
1737 /// f.seek(SeekFrom::Start(42))?;
1741 #[stable(feature = "rust1", since = "1.0.0")]
1743 /// Seek to an offset, in bytes, in a stream.
1745 /// A seek beyond the end of a stream is allowed, but behavior is defined
1746 /// by the implementation.
1748 /// If the seek operation completed successfully,
1749 /// this method returns the new position from the start of the stream.
1750 /// That position can be used later with [`SeekFrom::Start`].
1754 /// Seeking can fail, for example because it might involve flushing a buffer.
1756 /// Seeking to a negative offset is considered an error.
1757 #[stable(feature = "rust1", since = "1.0.0")]
1758 fn seek(&mut self, pos
: SeekFrom
) -> Result
<u64>;
1760 /// Rewind to the beginning of a stream.
1762 /// This is a convenience method, equivalent to `seek(SeekFrom::Start(0))`.
1766 /// Rewinding can fail, for example because it might involve flushing a buffer.
1771 /// use std::io::{Read, Seek, Write};
1772 /// use std::fs::OpenOptions;
1774 /// let mut f = OpenOptions::new()
1778 /// .open("foo.txt").unwrap();
1780 /// let hello = "Hello!\n";
1781 /// write!(f, "{hello}").unwrap();
1782 /// f.rewind().unwrap();
1784 /// let mut buf = String::new();
1785 /// f.read_to_string(&mut buf).unwrap();
1786 /// assert_eq!(&buf, hello);
1788 #[stable(feature = "seek_rewind", since = "1.55.0")]
1789 fn rewind(&mut self) -> Result
<()> {
1790 self.seek(SeekFrom
::Start(0))?
;
1794 /// Returns the length of this stream (in bytes).
1796 /// This method is implemented using up to three seek operations. If this
1797 /// method returns successfully, the seek position is unchanged (i.e. the
1798 /// position before calling this method is the same as afterwards).
1799 /// However, if this method returns an error, the seek position is
1802 /// If you need to obtain the length of *many* streams and you don't care
1803 /// about the seek position afterwards, you can reduce the number of seek
1804 /// operations by simply calling `seek(SeekFrom::End(0))` and using its
1805 /// return value (it is also the stream length).
1807 /// Note that length of a stream can change over time (for example, when
1808 /// data is appended to a file). So calling this method multiple times does
1809 /// not necessarily return the same length each time.
1814 /// #![feature(seek_stream_len)]
1816 /// io::{self, Seek},
1820 /// fn main() -> io::Result<()> {
1821 /// let mut f = File::open("foo.txt")?;
1823 /// let len = f.stream_len()?;
1824 /// println!("The file is currently {len} bytes long");
1828 #[unstable(feature = "seek_stream_len", issue = "59359")]
1829 fn stream_len(&mut self) -> Result
<u64> {
1830 let old_pos
= self.stream_position()?
;
1831 let len
= self.seek(SeekFrom
::End(0))?
;
1833 // Avoid seeking a third time when we were already at the end of the
1834 // stream. The branch is usually way cheaper than a seek operation.
1836 self.seek(SeekFrom
::Start(old_pos
))?
;
1842 /// Returns the current seek position from the start of the stream.
1844 /// This is equivalent to `self.seek(SeekFrom::Current(0))`.
1850 /// io::{self, BufRead, BufReader, Seek},
1854 /// fn main() -> io::Result<()> {
1855 /// let mut f = BufReader::new(File::open("foo.txt")?);
1857 /// let before = f.stream_position()?;
1858 /// f.read_line(&mut String::new())?;
1859 /// let after = f.stream_position()?;
1861 /// println!("The first line was {} bytes long", after - before);
1865 #[stable(feature = "seek_convenience", since = "1.51.0")]
1866 fn stream_position(&mut self) -> Result
<u64> {
1867 self.seek(SeekFrom
::Current(0))
1871 /// Enumeration of possible methods to seek within an I/O object.
1873 /// It is used by the [`Seek`] trait.
1874 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1875 #[stable(feature = "rust1", since = "1.0.0")]
1877 /// Sets the offset to the provided number of bytes.
1878 #[stable(feature = "rust1", since = "1.0.0")]
1879 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1881 /// Sets the offset to the size of this object plus the specified number of
1884 /// It is possible to seek beyond the end of an object, but it's an error to
1885 /// seek before byte 0.
1886 #[stable(feature = "rust1", since = "1.0.0")]
1887 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1889 /// Sets the offset to the current position plus the specified number of
1892 /// It is possible to seek beyond the end of an object, but it's an error to
1893 /// seek before byte 0.
1894 #[stable(feature = "rust1", since = "1.0.0")]
1895 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1898 fn read_until
<R
: BufRead
+ ?Sized
>(r
: &mut R
, delim
: u8, buf
: &mut Vec
<u8>) -> Result
<usize> {
1901 let (done
, used
) = {
1902 let available
= match r
.fill_buf() {
1904 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> continue,
1905 Err(e
) => return Err(e
),
1907 match memchr
::memchr(delim
, available
) {
1909 buf
.extend_from_slice(&available
[..=i
]);
1913 buf
.extend_from_slice(available
);
1914 (false, available
.len())
1920 if done
|| used
== 0 {
1926 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1927 /// to perform extra ways of reading.
1929 /// For example, reading line-by-line is inefficient without using a buffer, so
1930 /// if you want to read by line, you'll need `BufRead`, which includes a
1931 /// [`read_line`] method as well as a [`lines`] iterator.
1935 /// A locked standard input implements `BufRead`:
1939 /// use std::io::prelude::*;
1941 /// let stdin = io::stdin();
1942 /// for line in stdin.lock().lines() {
1943 /// println!("{}", line.unwrap());
1947 /// If you have something that implements [`Read`], you can use the [`BufReader`
1948 /// type][`BufReader`] to turn it into a `BufRead`.
1950 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1951 /// [`BufReader`] to the rescue!
1953 /// [`File`]: crate::fs::File
1954 /// [`read_line`]: BufRead::read_line
1955 /// [`lines`]: BufRead::lines
1958 /// use std::io::{self, BufReader};
1959 /// use std::io::prelude::*;
1960 /// use std::fs::File;
1962 /// fn main() -> io::Result<()> {
1963 /// let f = File::open("foo.txt")?;
1964 /// let f = BufReader::new(f);
1966 /// for line in f.lines() {
1967 /// println!("{}", line.unwrap());
1973 #[stable(feature = "rust1", since = "1.0.0")]
1974 pub trait BufRead
: Read
{
1975 /// Returns the contents of the internal buffer, filling it with more data
1976 /// from the inner reader if it is empty.
1978 /// This function is a lower-level call. It needs to be paired with the
1979 /// [`consume`] method to function properly. When calling this
1980 /// method, none of the contents will be "read" in the sense that later
1981 /// calling `read` may return the same contents. As such, [`consume`] must
1982 /// be called with the number of bytes that are consumed from this buffer to
1983 /// ensure that the bytes are never returned twice.
1985 /// [`consume`]: BufRead::consume
1987 /// An empty buffer returned indicates that the stream has reached EOF.
1991 /// This function will return an I/O error if the underlying reader was
1992 /// read, but returned an error.
1996 /// A locked standard input implements `BufRead`:
2000 /// use std::io::prelude::*;
2002 /// let stdin = io::stdin();
2003 /// let mut stdin = stdin.lock();
2005 /// let buffer = stdin.fill_buf().unwrap();
2007 /// // work with buffer
2008 /// println!("{buffer:?}");
2010 /// // ensure the bytes we worked with aren't returned again later
2011 /// let length = buffer.len();
2012 /// stdin.consume(length);
2014 #[stable(feature = "rust1", since = "1.0.0")]
2015 fn fill_buf(&mut self) -> Result
<&[u8]>;
2017 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
2018 /// so they should no longer be returned in calls to `read`.
2020 /// This function is a lower-level call. It needs to be paired with the
2021 /// [`fill_buf`] method to function properly. This function does
2022 /// not perform any I/O, it simply informs this object that some amount of
2023 /// its buffer, returned from [`fill_buf`], has been consumed and should
2024 /// no longer be returned. As such, this function may do odd things if
2025 /// [`fill_buf`] isn't called before calling it.
2027 /// The `amt` must be `<=` the number of bytes in the buffer returned by
2032 /// Since `consume()` is meant to be used with [`fill_buf`],
2033 /// that method's example includes an example of `consume()`.
2035 /// [`fill_buf`]: BufRead::fill_buf
2036 #[stable(feature = "rust1", since = "1.0.0")]
2037 fn consume(&mut self, amt
: usize);
2039 /// Check if the underlying `Read` has any data left to be read.
2041 /// This function may fill the buffer to check for data,
2042 /// so this functions returns `Result<bool>`, not `bool`.
2044 /// Default implementation calls `fill_buf` and checks that
2045 /// returned slice is empty (which means that there is no data left,
2046 /// since EOF is reached).
2051 /// #![feature(buf_read_has_data_left)]
2053 /// use std::io::prelude::*;
2055 /// let stdin = io::stdin();
2056 /// let mut stdin = stdin.lock();
2058 /// while stdin.has_data_left().unwrap() {
2059 /// let mut line = String::new();
2060 /// stdin.read_line(&mut line).unwrap();
2061 /// // work with line
2062 /// println!("{line:?}");
2065 #[unstable(feature = "buf_read_has_data_left", reason = "recently added", issue = "86423")]
2066 fn has_data_left(&mut self) -> Result
<bool
> {
2067 self.fill_buf().map(|b
| !b
.is_empty())
2070 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
2072 /// This function will read bytes from the underlying stream until the
2073 /// delimiter or EOF is found. Once found, all bytes up to, and including,
2074 /// the delimiter (if found) will be appended to `buf`.
2076 /// If successful, this function will return the total number of bytes read.
2078 /// This function is blocking and should be used carefully: it is possible for
2079 /// an attacker to continuously send bytes without ever sending the delimiter
2084 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
2085 /// will otherwise return any errors returned by [`fill_buf`].
2087 /// If an I/O error is encountered then all bytes read so far will be
2088 /// present in `buf` and its length will have been adjusted appropriately.
2090 /// [`fill_buf`]: BufRead::fill_buf
2094 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2095 /// this example, we use [`Cursor`] to read all the bytes in a byte slice
2096 /// in hyphen delimited segments:
2099 /// use std::io::{self, BufRead};
2101 /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
2102 /// let mut buf = vec![];
2104 /// // cursor is at 'l'
2105 /// let num_bytes = cursor.read_until(b'-', &mut buf)
2106 /// .expect("reading from cursor won't fail");
2107 /// assert_eq!(num_bytes, 6);
2108 /// assert_eq!(buf, b"lorem-");
2111 /// // cursor is at 'i'
2112 /// let num_bytes = cursor.read_until(b'-', &mut buf)
2113 /// .expect("reading from cursor won't fail");
2114 /// assert_eq!(num_bytes, 5);
2115 /// assert_eq!(buf, b"ipsum");
2118 /// // cursor is at EOF
2119 /// let num_bytes = cursor.read_until(b'-', &mut buf)
2120 /// .expect("reading from cursor won't fail");
2121 /// assert_eq!(num_bytes, 0);
2122 /// assert_eq!(buf, b"");
2124 #[stable(feature = "rust1", since = "1.0.0")]
2125 fn read_until(&mut self, byte
: u8, buf
: &mut Vec
<u8>) -> Result
<usize> {
2126 read_until(self, byte
, buf
)
2129 /// Read all bytes until a newline (the `0xA` byte) is reached, and append
2130 /// them to the provided buffer. You do not need to clear the buffer before
2133 /// This function will read bytes from the underlying stream until the
2134 /// newline delimiter (the `0xA` byte) or EOF is found. Once found, all bytes
2135 /// up to, and including, the delimiter (if found) will be appended to
2138 /// If successful, this function will return the total number of bytes read.
2140 /// If this function returns [`Ok(0)`], the stream has reached EOF.
2142 /// This function is blocking and should be used carefully: it is possible for
2143 /// an attacker to continuously send bytes without ever sending a newline
2150 /// This function has the same error semantics as [`read_until`] and will
2151 /// also return an error if the read bytes are not valid UTF-8. If an I/O
2152 /// error is encountered then `buf` may contain some bytes already read in
2153 /// the event that all data read so far was valid UTF-8.
2155 /// [`read_until`]: BufRead::read_until
2159 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2160 /// this example, we use [`Cursor`] to read all the lines in a byte slice:
2163 /// use std::io::{self, BufRead};
2165 /// let mut cursor = io::Cursor::new(b"foo\nbar");
2166 /// let mut buf = String::new();
2168 /// // cursor is at 'f'
2169 /// let num_bytes = cursor.read_line(&mut buf)
2170 /// .expect("reading from cursor won't fail");
2171 /// assert_eq!(num_bytes, 4);
2172 /// assert_eq!(buf, "foo\n");
2175 /// // cursor is at 'b'
2176 /// let num_bytes = cursor.read_line(&mut buf)
2177 /// .expect("reading from cursor won't fail");
2178 /// assert_eq!(num_bytes, 3);
2179 /// assert_eq!(buf, "bar");
2182 /// // cursor is at EOF
2183 /// let num_bytes = cursor.read_line(&mut buf)
2184 /// .expect("reading from cursor won't fail");
2185 /// assert_eq!(num_bytes, 0);
2186 /// assert_eq!(buf, "");
2188 #[stable(feature = "rust1", since = "1.0.0")]
2189 fn read_line(&mut self, buf
: &mut String
) -> Result
<usize> {
2190 // Note that we are not calling the `.read_until` method here, but
2191 // rather our hardcoded implementation. For more details as to why, see
2192 // the comments in `read_to_end`.
2193 unsafe { append_to_string(buf, |b| read_until(self, b'\n', b)) }
2196 /// Returns an iterator over the contents of this reader split on the byte
2199 /// The iterator returned from this function will return instances of
2200 /// <code>[io::Result]<[Vec]\<u8>></code>. Each vector returned will *not* have
2201 /// the delimiter byte at the end.
2203 /// This function will yield errors whenever [`read_until`] would have
2204 /// also yielded an error.
2206 /// [io::Result]: self::Result "io::Result"
2207 /// [`read_until`]: BufRead::read_until
2211 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2212 /// this example, we use [`Cursor`] to iterate over all hyphen delimited
2213 /// segments in a byte slice
2216 /// use std::io::{self, BufRead};
2218 /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
2220 /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
2221 /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
2222 /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
2223 /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
2224 /// assert_eq!(split_iter.next(), None);
2226 #[stable(feature = "rust1", since = "1.0.0")]
2227 fn split(self, byte
: u8) -> Split
<Self>
2231 Split { buf: self, delim: byte }
2234 /// Returns an iterator over the lines of this reader.
2236 /// The iterator returned from this function will yield instances of
2237 /// <code>[io::Result]<[String]></code>. Each string returned will *not* have a newline
2238 /// byte (the `0xA` byte) or `CRLF` (`0xD`, `0xA` bytes) at the end.
2240 /// [io::Result]: self::Result "io::Result"
2244 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2245 /// this example, we use [`Cursor`] to iterate over all the lines in a byte
2249 /// use std::io::{self, BufRead};
2251 /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
2253 /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
2254 /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
2255 /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
2256 /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
2257 /// assert_eq!(lines_iter.next(), None);
2262 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
2263 #[stable(feature = "rust1", since = "1.0.0")]
2264 fn lines(self) -> Lines
<Self>
2272 /// Adapter to chain together two readers.
2274 /// This struct is generally created by calling [`chain`] on a reader.
2275 /// Please see the documentation of [`chain`] for more details.
2277 /// [`chain`]: Read::chain
2278 #[stable(feature = "rust1", since = "1.0.0")]
2280 pub struct Chain
<T
, U
> {
2286 impl<T
, U
> Chain
<T
, U
> {
2287 /// Consumes the `Chain`, returning the wrapped readers.
2293 /// use std::io::prelude::*;
2294 /// use std::fs::File;
2296 /// fn main() -> io::Result<()> {
2297 /// let mut foo_file = File::open("foo.txt")?;
2298 /// let mut bar_file = File::open("bar.txt")?;
2300 /// let chain = foo_file.chain(bar_file);
2301 /// let (foo_file, bar_file) = chain.into_inner();
2305 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2306 pub fn into_inner(self) -> (T
, U
) {
2307 (self.first
, self.second
)
2310 /// Gets references to the underlying readers in this `Chain`.
2316 /// use std::io::prelude::*;
2317 /// use std::fs::File;
2319 /// fn main() -> io::Result<()> {
2320 /// let mut foo_file = File::open("foo.txt")?;
2321 /// let mut bar_file = File::open("bar.txt")?;
2323 /// let chain = foo_file.chain(bar_file);
2324 /// let (foo_file, bar_file) = chain.get_ref();
2328 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2329 pub fn get_ref(&self) -> (&T
, &U
) {
2330 (&self.first
, &self.second
)
2333 /// Gets mutable references to the underlying readers in this `Chain`.
2335 /// Care should be taken to avoid modifying the internal I/O state of the
2336 /// underlying readers as doing so may corrupt the internal state of this
2343 /// use std::io::prelude::*;
2344 /// use std::fs::File;
2346 /// fn main() -> io::Result<()> {
2347 /// let mut foo_file = File::open("foo.txt")?;
2348 /// let mut bar_file = File::open("bar.txt")?;
2350 /// let mut chain = foo_file.chain(bar_file);
2351 /// let (foo_file, bar_file) = chain.get_mut();
2355 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2356 pub fn get_mut(&mut self) -> (&mut T
, &mut U
) {
2357 (&mut self.first
, &mut self.second
)
2361 #[stable(feature = "rust1", since = "1.0.0")]
2362 impl<T
: Read
, U
: Read
> Read
for Chain
<T
, U
> {
2363 fn read(&mut self, buf
: &mut [u8]) -> Result
<usize> {
2364 if !self.done_first
{
2365 match self.first
.read(buf
)?
{
2366 0 if !buf
.is_empty() => self.done_first
= true,
2370 self.second
.read(buf
)
2373 fn read_vectored(&mut self, bufs
: &mut [IoSliceMut
<'_
>]) -> Result
<usize> {
2374 if !self.done_first
{
2375 match self.first
.read_vectored(bufs
)?
{
2376 0 if bufs
.iter().any(|b
| !b
.is_empty()) => self.done_first
= true,
2380 self.second
.read_vectored(bufs
)
2384 #[stable(feature = "chain_bufread", since = "1.9.0")]
2385 impl<T
: BufRead
, U
: BufRead
> BufRead
for Chain
<T
, U
> {
2386 fn fill_buf(&mut self) -> Result
<&[u8]> {
2387 if !self.done_first
{
2388 match self.first
.fill_buf()?
{
2389 buf
if buf
.is_empty() => {
2390 self.done_first
= true;
2392 buf
=> return Ok(buf
),
2395 self.second
.fill_buf()
2398 fn consume(&mut self, amt
: usize) {
2399 if !self.done_first { self.first.consume(amt) }
else { self.second.consume(amt) }
2403 impl<T
, U
> SizeHint
for Chain
<T
, U
> {
2405 fn lower_bound(&self) -> usize {
2406 SizeHint
::lower_bound(&self.first
) + SizeHint
::lower_bound(&self.second
)
2410 fn upper_bound(&self) -> Option
<usize> {
2411 match (SizeHint
::upper_bound(&self.first
), SizeHint
::upper_bound(&self.second
)) {
2412 (Some(first
), Some(second
)) => first
.checked_add(second
),
2418 /// Reader adapter which limits the bytes read from an underlying reader.
2420 /// This struct is generally created by calling [`take`] on a reader.
2421 /// Please see the documentation of [`take`] for more details.
2423 /// [`take`]: Read::take
2424 #[stable(feature = "rust1", since = "1.0.0")]
2426 pub struct Take
<T
> {
2432 /// Returns the number of bytes that can be read before this instance will
2437 /// This instance may reach `EOF` after reading fewer bytes than indicated by
2438 /// this method if the underlying [`Read`] instance reaches EOF.
2444 /// use std::io::prelude::*;
2445 /// use std::fs::File;
2447 /// fn main() -> io::Result<()> {
2448 /// let f = File::open("foo.txt")?;
2450 /// // read at most five bytes
2451 /// let handle = f.take(5);
2453 /// println!("limit: {}", handle.limit());
2457 #[stable(feature = "rust1", since = "1.0.0")]
2458 pub fn limit(&self) -> u64 {
2462 /// Sets the number of bytes that can be read before this instance will
2463 /// return EOF. This is the same as constructing a new `Take` instance, so
2464 /// the amount of bytes read and the previous limit value don't matter when
2465 /// calling this method.
2471 /// use std::io::prelude::*;
2472 /// use std::fs::File;
2474 /// fn main() -> io::Result<()> {
2475 /// let f = File::open("foo.txt")?;
2477 /// // read at most five bytes
2478 /// let mut handle = f.take(5);
2479 /// handle.set_limit(10);
2481 /// assert_eq!(handle.limit(), 10);
2485 #[stable(feature = "take_set_limit", since = "1.27.0")]
2486 pub fn set_limit(&mut self, limit
: u64) {
2490 /// Consumes the `Take`, returning the wrapped reader.
2496 /// use std::io::prelude::*;
2497 /// use std::fs::File;
2499 /// fn main() -> io::Result<()> {
2500 /// let mut file = File::open("foo.txt")?;
2502 /// let mut buffer = [0; 5];
2503 /// let mut handle = file.take(5);
2504 /// handle.read(&mut buffer)?;
2506 /// let file = handle.into_inner();
2510 #[stable(feature = "io_take_into_inner", since = "1.15.0")]
2511 pub fn into_inner(self) -> T
{
2515 /// Gets a reference to the underlying reader.
2521 /// use std::io::prelude::*;
2522 /// use std::fs::File;
2524 /// fn main() -> io::Result<()> {
2525 /// let mut file = File::open("foo.txt")?;
2527 /// let mut buffer = [0; 5];
2528 /// let mut handle = file.take(5);
2529 /// handle.read(&mut buffer)?;
2531 /// let file = handle.get_ref();
2535 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2536 pub fn get_ref(&self) -> &T
{
2540 /// Gets a mutable reference to the underlying reader.
2542 /// Care should be taken to avoid modifying the internal I/O state of the
2543 /// underlying reader as doing so may corrupt the internal limit of this
2550 /// use std::io::prelude::*;
2551 /// use std::fs::File;
2553 /// fn main() -> io::Result<()> {
2554 /// let mut file = File::open("foo.txt")?;
2556 /// let mut buffer = [0; 5];
2557 /// let mut handle = file.take(5);
2558 /// handle.read(&mut buffer)?;
2560 /// let file = handle.get_mut();
2564 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2565 pub fn get_mut(&mut self) -> &mut T
{
2570 #[stable(feature = "rust1", since = "1.0.0")]
2571 impl<T
: Read
> Read
for Take
<T
> {
2572 fn read(&mut self, buf
: &mut [u8]) -> Result
<usize> {
2573 // Don't call into inner reader at all at EOF because it may still block
2574 if self.limit
== 0 {
2578 let max
= cmp
::min(buf
.len() as u64, self.limit
) as usize;
2579 let n
= self.inner
.read(&mut buf
[..max
])?
;
2580 self.limit
-= n
as u64;
2584 fn read_buf(&mut self, buf
: &mut ReadBuf
<'_
>) -> Result
<()> {
2585 // Don't call into inner reader at all at EOF because it may still block
2586 if self.limit
== 0 {
2590 let prev_filled
= buf
.filled_len();
2592 if self.limit
<= buf
.remaining() as u64 {
2593 // if we just use an as cast to convert, limit may wrap around on a 32 bit target
2594 let limit
= cmp
::min(self.limit
, usize::MAX
as u64) as usize;
2596 let extra_init
= cmp
::min(limit
as usize, buf
.initialized_len() - buf
.filled_len());
2598 // SAFETY: no uninit data is written to ibuf
2599 let ibuf
= unsafe { &mut buf.unfilled_mut()[..limit] }
;
2601 let mut sliced_buf
= ReadBuf
::uninit(ibuf
);
2603 // SAFETY: extra_init bytes of ibuf are known to be initialized
2605 sliced_buf
.assume_init(extra_init
);
2608 self.inner
.read_buf(&mut sliced_buf
)?
;
2610 let new_init
= sliced_buf
.initialized_len();
2611 let filled
= sliced_buf
.filled_len();
2613 // sliced_buf / ibuf must drop here
2615 // SAFETY: new_init bytes of buf's unfilled buffer have been initialized
2617 buf
.assume_init(new_init
);
2620 buf
.add_filled(filled
);
2622 self.limit
-= filled
as u64;
2624 self.inner
.read_buf(buf
)?
;
2627 self.limit
-= buf
.filled_len().saturating_sub(prev_filled
) as u64;
2634 #[stable(feature = "rust1", since = "1.0.0")]
2635 impl<T
: BufRead
> BufRead
for Take
<T
> {
2636 fn fill_buf(&mut self) -> Result
<&[u8]> {
2637 // Don't call into inner reader at all at EOF because it may still block
2638 if self.limit
== 0 {
2642 let buf
= self.inner
.fill_buf()?
;
2643 let cap
= cmp
::min(buf
.len() as u64, self.limit
) as usize;
2647 fn consume(&mut self, amt
: usize) {
2648 // Don't let callers reset the limit by passing an overlarge value
2649 let amt
= cmp
::min(amt
as u64, self.limit
) as usize;
2650 self.limit
-= amt
as u64;
2651 self.inner
.consume(amt
);
2655 impl<T
> SizeHint
for Take
<T
> {
2657 fn lower_bound(&self) -> usize {
2658 cmp
::min(SizeHint
::lower_bound(&self.inner
) as u64, self.limit
) as usize
2662 fn upper_bound(&self) -> Option
<usize> {
2663 match SizeHint
::upper_bound(&self.inner
) {
2664 Some(upper_bound
) => Some(cmp
::min(upper_bound
as u64, self.limit
) as usize),
2665 None
=> self.limit
.try_into().ok(),
2670 /// An iterator over `u8` values of a reader.
2672 /// This struct is generally created by calling [`bytes`] on a reader.
2673 /// Please see the documentation of [`bytes`] for more details.
2675 /// [`bytes`]: Read::bytes
2676 #[stable(feature = "rust1", since = "1.0.0")]
2678 pub struct Bytes
<R
> {
2682 #[stable(feature = "rust1", since = "1.0.0")]
2683 impl<R
: Read
> Iterator
for Bytes
<R
> {
2684 type Item
= Result
<u8>;
2686 fn next(&mut self) -> Option
<Result
<u8>> {
2689 return match self.inner
.read(slice
::from_mut(&mut byte
)) {
2691 Ok(..) => Some(Ok(byte
)),
2692 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> continue,
2693 Err(e
) => Some(Err(e
)),
2698 fn size_hint(&self) -> (usize, Option
<usize>) {
2699 SizeHint
::size_hint(&self.inner
)
2704 fn lower_bound(&self) -> usize;
2706 fn upper_bound(&self) -> Option
<usize>;
2708 fn size_hint(&self) -> (usize, Option
<usize>) {
2709 (self.lower_bound(), self.upper_bound())
2713 impl<T
> SizeHint
for T
{
2715 default fn lower_bound(&self) -> usize {
2720 default fn upper_bound(&self) -> Option
<usize> {
2725 impl<T
> SizeHint
for &mut T
{
2727 fn lower_bound(&self) -> usize {
2728 SizeHint
::lower_bound(*self)
2732 fn upper_bound(&self) -> Option
<usize> {
2733 SizeHint
::upper_bound(*self)
2737 impl<T
> SizeHint
for Box
<T
> {
2739 fn lower_bound(&self) -> usize {
2740 SizeHint
::lower_bound(&**self)
2744 fn upper_bound(&self) -> Option
<usize> {
2745 SizeHint
::upper_bound(&**self)
2749 impl SizeHint
for &[u8] {
2751 fn lower_bound(&self) -> usize {
2756 fn upper_bound(&self) -> Option
<usize> {
2761 /// An iterator over the contents of an instance of `BufRead` split on a
2762 /// particular byte.
2764 /// This struct is generally created by calling [`split`] on a `BufRead`.
2765 /// Please see the documentation of [`split`] for more details.
2767 /// [`split`]: BufRead::split
2768 #[stable(feature = "rust1", since = "1.0.0")]
2770 pub struct Split
<B
> {
2775 #[stable(feature = "rust1", since = "1.0.0")]
2776 impl<B
: BufRead
> Iterator
for Split
<B
> {
2777 type Item
= Result
<Vec
<u8>>;
2779 fn next(&mut self) -> Option
<Result
<Vec
<u8>>> {
2780 let mut buf
= Vec
::new();
2781 match self.buf
.read_until(self.delim
, &mut buf
) {
2784 if buf
[buf
.len() - 1] == self.delim
{
2789 Err(e
) => Some(Err(e
)),
2794 /// An iterator over the lines of an instance of `BufRead`.
2796 /// This struct is generally created by calling [`lines`] on a `BufRead`.
2797 /// Please see the documentation of [`lines`] for more details.
2799 /// [`lines`]: BufRead::lines
2800 #[stable(feature = "rust1", since = "1.0.0")]
2802 pub struct Lines
<B
> {
2806 #[stable(feature = "rust1", since = "1.0.0")]
2807 impl<B
: BufRead
> Iterator
for Lines
<B
> {
2808 type Item
= Result
<String
>;
2810 fn next(&mut self) -> Option
<Result
<String
>> {
2811 let mut buf
= String
::new();
2812 match self.buf
.read_line(&mut buf
) {
2815 if buf
.ends_with('
\n'
) {
2817 if buf
.ends_with('
\r'
) {
2823 Err(e
) => Some(Err(e
)),