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::ops::{Deref, DerefMut};
261 use crate::sys_common::memchr;
263 #[stable(feature = "rust1", since = "1.0.0")]
264 pub use self::buffered::IntoInnerError;
265 #[stable(feature = "rust1", since = "1.0.0")]
266 pub use self::buffered::{BufReader, BufWriter, LineWriter};
267 #[stable(feature = "rust1", since = "1.0.0")]
268 pub use self::copy::copy;
269 #[stable(feature = "rust1", since = "1.0.0")]
270 pub use self::cursor::Cursor;
271 #[stable(feature = "rust1", since = "1.0.0")]
272 pub use self::error::{Error, ErrorKind, Result};
273 #[unstable(feature = "internal_output_capture", issue = "none")]
274 #[doc(no_inline, hidden)]
275 pub use self::stdio::set_output_capture;
276 #[stable(feature = "rust1", since = "1.0.0")]
277 pub use self::stdio::{stderr, stdin, stdout, Stderr, Stdin, Stdout};
278 #[stable(feature = "rust1", since = "1.0.0")]
279 pub use self::stdio::{StderrLock, StdinLock, StdoutLock};
280 #[unstable(feature = "print_internals", issue = "none")]
281 pub use self::stdio::{_eprint, _print};
282 #[stable(feature = "rust1", since = "1.0.0")]
283 pub use self::util::{empty, repeat, sink, Empty, Repeat, Sink};
294 const DEFAULT_BUF_SIZE: usize = crate::sys_common::io::DEFAULT_BUF_SIZE;
296 pub(crate) fn cleanup() {
301 buf: &'a mut Vec<u8>,
305 impl Drop for Guard<'_> {
308 self.buf.set_len(self.len);
313 // A few methods below (read_to_string, read_line) will append data into a
314 // `String` buffer, but we need to be pretty careful when doing this. The
315 // implementation will just call `.as_mut_vec()` and then delegate to a
316 // byte-oriented reading method, but we must ensure that when returning we never
317 // leave `buf` in a state such that it contains invalid UTF-8 in its bounds.
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 fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
333 F: FnOnce(&mut Vec<u8>) -> Result<usize>,
336 let mut g = Guard { len: buf.len(), buf: buf.as_mut_vec() };
338 if str::from_utf8(&g.buf[g.len..]).is_err() {
340 Err(Error::new_const(ErrorKind::InvalidData, &"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.
356 // Because we're extending the buffer with uninitialized data for trusted
357 // readers, we need to make sure to truncate that if any of this panics.
358 fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
359 read_to_end_with_reservation(r, buf, |_| 32)
362 fn read_to_end_with_reservation<R, F>(
365 mut reservation_size: F,
369 F: FnMut(&R) -> usize,
371 let start_len = buf.len();
372 let mut g = Guard { len: buf.len(), buf };
374 if g.len == g.buf.len() {
376 // FIXME(danielhenrymantilla): #42788
378 // - This creates a (mut) reference to a slice of
379 // _uninitialized_ integers, which is **undefined behavior**
381 // - Only the standard library gets to soundly "ignore" this,
382 // based on its privileged knowledge of unstable rustc
384 g.buf.reserve(reservation_size(r));
385 let capacity = g.buf.capacity();
386 g.buf.set_len(capacity);
387 r.initializer().initialize(&mut g.buf[g.len..]);
391 let buf = &mut g.buf[g.len..];
393 Ok(0) => return Ok(g.len - start_len),
395 // We can't allow bogus values from read. If it is too large, the returned vec could have its length
396 // set past its capacity, or if it overflows the vec could be shortened which could create an invalid
397 // string if this is called via read_to_string.
398 assert!(n <= buf.len());
401 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
402 Err(e) => return Err(e),
407 pub(crate) fn default_read_vectored<F>(read: F, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
409 F: FnOnce(&mut [u8]) -> Result<usize>,
411 let buf = bufs.iter_mut().find(|b| !b.is_empty()).map_or(&mut [][..], |b| &mut **b);
415 pub(crate) fn default_write_vectored<F>(write: F, bufs: &[IoSlice<'_>]) -> Result<usize>
417 F: FnOnce(&[u8]) -> Result<usize>,
419 let buf = bufs.iter().find(|b| !b.is_empty()).map_or(&[][..], |b| &**b);
423 pub(crate) fn default_read_exact<R: Read + ?Sized>(this: &mut R, mut buf: &mut [u8]) -> Result<()> {
424 while !buf.is_empty() {
425 match this.read(buf) {
431 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
432 Err(e) => return Err(e),
436 Err(Error::new_const(ErrorKind::UnexpectedEof, &"failed to fill whole buffer"))
442 /// The `Read` trait allows for reading bytes from a source.
444 /// Implementors of the `Read` trait are called 'readers'.
446 /// Readers are defined by one required method, [`read()`]. Each call to [`read()`]
447 /// will attempt to pull bytes from this source into a provided buffer. A
448 /// number of other methods are implemented in terms of [`read()`], giving
449 /// implementors a number of ways to read bytes while only needing to implement
452 /// Readers are intended to be composable with one another. Many implementors
453 /// throughout [`std::io`] take and provide types which implement the `Read`
456 /// Please note that each call to [`read()`] may involve a system call, and
457 /// therefore, using something that implements [`BufRead`], such as
458 /// [`BufReader`], will be more efficient.
462 /// [`File`]s implement `Read`:
466 /// use std::io::prelude::*;
467 /// use std::fs::File;
469 /// fn main() -> io::Result<()> {
470 /// let mut f = File::open("foo.txt")?;
471 /// let mut buffer = [0; 10];
473 /// // read up to 10 bytes
474 /// f.read(&mut buffer)?;
476 /// let mut buffer = Vec::new();
477 /// // read the whole file
478 /// f.read_to_end(&mut buffer)?;
480 /// // read into a String, so that you don't need to do the conversion.
481 /// let mut buffer = String::new();
482 /// f.read_to_string(&mut buffer)?;
484 /// // and more! See the other methods for more details.
489 /// Read from [`&str`] because [`&[u8]`][prim@slice] implements `Read`:
493 /// use std::io::prelude::*;
495 /// fn main() -> io::Result<()> {
496 /// let mut b = "This string will be read".as_bytes();
497 /// let mut buffer = [0; 10];
499 /// // read up to 10 bytes
500 /// b.read(&mut buffer)?;
502 /// // etc... it works exactly as a File does!
507 /// [`read()`]: Read::read
508 /// [`&str`]: prim@str
509 /// [`std::io`]: self
510 /// [`File`]: crate::fs::File
511 #[stable(feature = "rust1", since = "1.0.0")]
512 #[cfg_attr(bootstrap, doc(spotlight))]
513 #[cfg_attr(not(bootstrap), doc(notable_trait))]
515 /// Pull some bytes from this source into the specified buffer, returning
516 /// how many bytes were read.
518 /// This function does not provide any guarantees about whether it blocks
519 /// waiting for data, but if an object needs to block for a read and cannot,
520 /// it will typically signal this via an [`Err`] return value.
522 /// If the return value of this method is [`Ok(n)`], then implementations must
523 /// guarantee that `0 <= n <= buf.len()`. A nonzero `n` value indicates
524 /// that the buffer `buf` has been filled in with `n` bytes of data from this
525 /// source. If `n` is `0`, then it can indicate one of two scenarios:
527 /// 1. This reader has reached its "end of file" and will likely no longer
528 /// be able to produce bytes. Note that this does not mean that the
529 /// reader will *always* no longer be able to produce bytes. As an example,
530 /// on Linux, this method will call the `recv` syscall for a [`TcpStream`],
531 /// where returning zero indicates the connection was shut down correctly. While
532 /// for [`File`], it is possible to reach the end of file and get zero as result,
533 /// but if more data is appended to the file, future calls to `read` will return
535 /// 2. The buffer specified was 0 bytes in length.
537 /// It is not an error if the returned value `n` is smaller than the buffer size,
538 /// even when the reader is not at the end of the stream yet.
539 /// This may happen for example because fewer bytes are actually available right now
540 /// (e. g. being close to end-of-file) or because read() was interrupted by a signal.
542 /// As this trait is safe to implement, callers cannot rely on `n <= buf.len()` for safety.
543 /// Extra care needs to be taken when `unsafe` functions are used to access the read bytes.
544 /// Callers have to ensure that no unchecked out-of-bounds accesses are possible even if
547 /// No guarantees are provided about the contents of `buf` when this
548 /// function is called, implementations cannot rely on any property of the
549 /// contents of `buf` being true. It is recommended that *implementations*
550 /// only write data to `buf` instead of reading its contents.
552 /// Correspondingly, however, *callers* of this method may not assume any guarantees
553 /// about how the implementation uses `buf`. The trait is safe to implement,
554 /// so it is possible that the code that's supposed to write to the buffer might also read
555 /// from it. It is your responsibility to make sure that `buf` is initialized
556 /// before calling `read`. Calling `read` with an uninitialized `buf` (of the kind one
557 /// obtains via [`MaybeUninit<T>`]) is not safe, and can lead to undefined behavior.
559 /// [`MaybeUninit<T>`]: crate::mem::MaybeUninit
563 /// If this function encounters any form of I/O or other error, an error
564 /// variant will be returned. If an error is returned then it must be
565 /// guaranteed that no bytes were read.
567 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
568 /// operation should be retried if there is nothing else to do.
572 /// [`File`]s implement `Read`:
575 /// [`File`]: crate::fs::File
576 /// [`TcpStream`]: crate::net::TcpStream
580 /// use std::io::prelude::*;
581 /// use std::fs::File;
583 /// fn main() -> io::Result<()> {
584 /// let mut f = File::open("foo.txt")?;
585 /// let mut buffer = [0; 10];
587 /// // read up to 10 bytes
588 /// let n = f.read(&mut buffer[..])?;
590 /// println!("The bytes: {:?}", &buffer[..n]);
594 #[stable(feature = "rust1", since = "1.0.0")]
595 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
597 /// Like `read`, except that it reads into a slice of buffers.
599 /// Data is copied to fill each buffer in order, with the final buffer
600 /// written to possibly being only partially filled. This method must
601 /// behave equivalently to a single call to `read` with concatenated
604 /// The default implementation calls `read` with either the first nonempty
605 /// buffer provided, or an empty one if none exists.
606 #[stable(feature = "iovec", since = "1.36.0")]
607 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
608 default_read_vectored(|b| self.read(b), bufs)
611 /// Determines if this `Read`er has an efficient `read_vectored`
614 /// If a `Read`er does not override the default `read_vectored`
615 /// implementation, code using it may want to avoid the method all together
616 /// and coalesce writes into a single buffer for higher performance.
618 /// The default implementation returns `false`.
619 #[unstable(feature = "can_vector", issue = "69941")]
620 fn is_read_vectored(&self) -> bool {
624 /// Determines if this `Read`er can work with buffers of uninitialized
627 /// The default implementation returns an initializer which will zero
630 /// If a `Read`er guarantees that it can work properly with uninitialized
631 /// memory, it should call [`Initializer::nop()`]. See the documentation for
632 /// [`Initializer`] for details.
634 /// The behavior of this method must be independent of the state of the
635 /// `Read`er - the method only takes `&self` so that it can be used through
640 /// This method is unsafe because a `Read`er could otherwise return a
641 /// non-zeroing `Initializer` from another `Read` type without an `unsafe`
643 #[unstable(feature = "read_initializer", issue = "42788")]
645 unsafe fn initializer(&self) -> Initializer {
646 Initializer::zeroing()
649 /// Read all bytes until EOF in this source, placing them into `buf`.
651 /// All bytes read from this source will be appended to the specified buffer
652 /// `buf`. This function will continuously call [`read()`] to append more data to
653 /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of
654 /// non-[`ErrorKind::Interrupted`] kind.
656 /// If successful, this function will return the total number of bytes read.
660 /// If this function encounters an error of the kind
661 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
664 /// If any other read error is encountered then this function immediately
665 /// returns. Any bytes which have already been read will be appended to
670 /// [`File`]s implement `Read`:
672 /// [`read()`]: Read::read
674 /// [`File`]: crate::fs::File
678 /// use std::io::prelude::*;
679 /// use std::fs::File;
681 /// fn main() -> io::Result<()> {
682 /// let mut f = File::open("foo.txt")?;
683 /// let mut buffer = Vec::new();
685 /// // read the whole file
686 /// f.read_to_end(&mut buffer)?;
691 /// (See also the [`std::fs::read`] convenience function for reading from a
694 /// [`std::fs::read`]: crate::fs::read
695 #[stable(feature = "rust1", since = "1.0.0")]
696 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
697 read_to_end(self, buf)
700 /// Read all bytes until EOF in this source, appending them to `buf`.
702 /// If successful, this function returns the number of bytes which were read
703 /// and appended to `buf`.
707 /// If the data in this stream is *not* valid UTF-8 then an error is
708 /// returned and `buf` is unchanged.
710 /// See [`read_to_end`] for other error semantics.
712 /// [`read_to_end`]: Read::read_to_end
716 /// [`File`]s implement `Read`:
718 /// [`File`]: crate::fs::File
722 /// use std::io::prelude::*;
723 /// use std::fs::File;
725 /// fn main() -> io::Result<()> {
726 /// let mut f = File::open("foo.txt")?;
727 /// let mut buffer = String::new();
729 /// f.read_to_string(&mut buffer)?;
734 /// (See also the [`std::fs::read_to_string`] convenience function for
735 /// reading from a file.)
737 /// [`std::fs::read_to_string`]: crate::fs::read_to_string
738 #[stable(feature = "rust1", since = "1.0.0")]
739 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
740 // Note that we do *not* call `.read_to_end()` here. We are passing
741 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
742 // method to fill it up. An arbitrary implementation could overwrite the
743 // entire contents of the vector, not just append to it (which is what
744 // we are expecting).
746 // To prevent extraneously checking the UTF-8-ness of the entire buffer
747 // we pass it to our hardcoded `read_to_end` implementation which we
748 // know is guaranteed to only read data into the end of the buffer.
749 append_to_string(buf, |b| read_to_end(self, b))
752 /// Read the exact number of bytes required to fill `buf`.
754 /// This function reads as many bytes as necessary to completely fill the
755 /// specified buffer `buf`.
757 /// No guarantees are provided about the contents of `buf` when this
758 /// function is called, implementations cannot rely on any property of the
759 /// contents of `buf` being true. It is recommended that implementations
760 /// only write data to `buf` instead of reading its contents. The
761 /// documentation on [`read`] has a more detailed explanation on this
766 /// If this function encounters an error of the kind
767 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
770 /// If this function encounters an "end of file" before completely filling
771 /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
772 /// The contents of `buf` are unspecified in this case.
774 /// If any other read error is encountered then this function immediately
775 /// returns. The contents of `buf` are unspecified in this case.
777 /// If this function returns an error, it is unspecified how many bytes it
778 /// has read, but it will never read more than would be necessary to
779 /// completely fill the buffer.
783 /// [`File`]s implement `Read`:
785 /// [`read`]: Read::read
786 /// [`File`]: crate::fs::File
790 /// use std::io::prelude::*;
791 /// use std::fs::File;
793 /// fn main() -> io::Result<()> {
794 /// let mut f = File::open("foo.txt")?;
795 /// let mut buffer = [0; 10];
797 /// // read exactly 10 bytes
798 /// f.read_exact(&mut buffer)?;
802 #[stable(feature = "read_exact", since = "1.6.0")]
803 fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
804 default_read_exact(self, buf)
807 /// Creates a "by reference" adaptor for this instance of `Read`.
809 /// The returned adaptor also implements `Read` and will simply borrow this
814 /// [`File`]s implement `Read`:
816 /// [`File`]: crate::fs::File
820 /// use std::io::Read;
821 /// use std::fs::File;
823 /// fn main() -> io::Result<()> {
824 /// let mut f = File::open("foo.txt")?;
825 /// let mut buffer = Vec::new();
826 /// let mut other_buffer = Vec::new();
829 /// let reference = f.by_ref();
831 /// // read at most 5 bytes
832 /// reference.take(5).read_to_end(&mut buffer)?;
834 /// } // drop our &mut reference so we can use f again
836 /// // original file still usable, read the rest
837 /// f.read_to_end(&mut other_buffer)?;
841 #[stable(feature = "rust1", since = "1.0.0")]
842 fn by_ref(&mut self) -> &mut Self
849 /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
851 /// The returned type implements [`Iterator`] where the `Item` is
852 /// [`Result`]`<`[`u8`]`, `[`io::Error`]`>`.
853 /// The yielded item is [`Ok`] if a byte was successfully read and [`Err`]
854 /// otherwise. EOF is mapped to returning [`None`] from this iterator.
858 /// [`File`]s implement `Read`:
860 /// [`File`]: crate::fs::File
861 /// [`Result`]: crate::result::Result
862 /// [`io::Error`]: self::Error
866 /// use std::io::prelude::*;
867 /// use std::fs::File;
869 /// fn main() -> io::Result<()> {
870 /// let mut f = File::open("foo.txt")?;
872 /// for byte in f.bytes() {
873 /// println!("{}", byte.unwrap());
878 #[stable(feature = "rust1", since = "1.0.0")]
879 fn bytes(self) -> Bytes<Self>
883 Bytes { inner: self }
886 /// Creates an adaptor which will chain this stream with another.
888 /// The returned `Read` instance will first read all bytes from this object
889 /// until EOF is encountered. Afterwards the output is equivalent to the
890 /// output of `next`.
894 /// [`File`]s implement `Read`:
896 /// [`File`]: crate::fs::File
900 /// use std::io::prelude::*;
901 /// use std::fs::File;
903 /// fn main() -> io::Result<()> {
904 /// let mut f1 = File::open("foo.txt")?;
905 /// let mut f2 = File::open("bar.txt")?;
907 /// let mut handle = f1.chain(f2);
908 /// let mut buffer = String::new();
910 /// // read the value into a String. We could use any Read method here,
911 /// // this is just one example.
912 /// handle.read_to_string(&mut buffer)?;
916 #[stable(feature = "rust1", since = "1.0.0")]
917 fn chain<R: Read>(self, next: R) -> Chain<Self, R>
921 Chain { first: self, second: next, done_first: false }
924 /// Creates an adaptor which will read at most `limit` bytes from it.
926 /// This function returns a new instance of `Read` which will read at most
927 /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
928 /// read errors will not count towards the number of bytes read and future
929 /// calls to [`read()`] may succeed.
933 /// [`File`]s implement `Read`:
935 /// [`File`]: crate::fs::File
937 /// [`read()`]: Read::read
941 /// use std::io::prelude::*;
942 /// use std::fs::File;
944 /// fn main() -> io::Result<()> {
945 /// let mut f = File::open("foo.txt")?;
946 /// let mut buffer = [0; 5];
948 /// // read at most five bytes
949 /// let mut handle = f.take(5);
951 /// handle.read(&mut buffer)?;
955 #[stable(feature = "rust1", since = "1.0.0")]
956 fn take(self, limit: u64) -> Take<Self>
960 Take { inner: self, limit }
964 /// Read all bytes from a [reader][Read] into a new [`String`].
966 /// This is a convenience function for [`Read::read_to_string`]. Using this
967 /// function avoids having to create a variable first and provides more type
968 /// safety since you can only get the buffer out if there were no errors. (If you
969 /// use [`Read::read_to_string`] you have to remember to check whether the read
970 /// succeeded because otherwise your buffer will be empty or only partially full.)
974 /// The downside of this function's increased ease of use and type safety is
975 /// that it gives you less control over performance. For example, you can't
976 /// pre-allocate memory like you can using [`String::with_capacity`] and
977 /// [`Read::read_to_string`]. Also, you can't re-use the buffer if an error
978 /// occurs while reading.
980 /// In many cases, this function's performance will be adequate and the ease of use
981 /// and type safety tradeoffs will be worth it. However, there are cases where you
982 /// need more control over performance, and in those cases you should definitely use
983 /// [`Read::read_to_string`] directly.
987 /// This function forces you to handle errors because the output (the `String`)
988 /// is wrapped in a [`Result`]. See [`Read::read_to_string`] for the errors
989 /// that can occur. If any error occurs, you will get an [`Err`], so you
990 /// don't have to worry about your buffer being empty or partially full.
995 /// #![feature(io_read_to_string)]
998 /// fn main() -> io::Result<()> {
999 /// let stdin = io::read_to_string(&mut io::stdin())?;
1000 /// println!("Stdin was:");
1001 /// println!("{}", stdin);
1005 #[unstable(feature = "io_read_to_string", issue = "80218")]
1006 pub fn read_to_string<R: Read>(reader: &mut R) -> Result<String> {
1007 let mut buf = String::new();
1008 reader.read_to_string(&mut buf)?;
1012 /// A buffer type used with `Read::read_vectored`.
1014 /// It is semantically a wrapper around an `&mut [u8]`, but is guaranteed to be
1015 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
1017 #[stable(feature = "iovec", since = "1.36.0")]
1018 #[repr(transparent)]
1019 pub struct IoSliceMut<'a>(sys::io::IoSliceMut<'a>);
1021 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1022 unsafe impl<'a> Send for IoSliceMut<'a> {}
1024 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1025 unsafe impl<'a> Sync for IoSliceMut<'a> {}
1027 #[stable(feature = "iovec", since = "1.36.0")]
1028 impl<'a> fmt::Debug for IoSliceMut<'a> {
1029 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1030 fmt::Debug::fmt(self.0.as_slice(), fmt)
1034 impl<'a> IoSliceMut<'a> {
1035 /// Creates a new `IoSliceMut` wrapping a byte slice.
1039 /// Panics on Windows if the slice is larger than 4GB.
1040 #[stable(feature = "iovec", since = "1.36.0")]
1042 pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> {
1043 IoSliceMut(sys::io::IoSliceMut::new(buf))
1046 /// Advance the internal cursor of the slice.
1050 /// Elements in the slice may be modified if the cursor is not advanced to
1051 /// the end of the slice. For example if we have a slice of buffers with 2
1052 /// `IoSliceMut`s, both of length 8, and we advance the cursor by 10 bytes
1053 /// the first `IoSliceMut` will be untouched however the second will be
1054 /// modified to remove the first 2 bytes (10 - 8).
1059 /// #![feature(io_slice_advance)]
1061 /// use std::io::IoSliceMut;
1062 /// use std::ops::Deref;
1064 /// let mut buf1 = [1; 8];
1065 /// let mut buf2 = [2; 16];
1066 /// let mut buf3 = [3; 8];
1067 /// let mut bufs = &mut [
1068 /// IoSliceMut::new(&mut buf1),
1069 /// IoSliceMut::new(&mut buf2),
1070 /// IoSliceMut::new(&mut buf3),
1073 /// // Mark 10 bytes as read.
1074 /// bufs = IoSliceMut::advance(bufs, 10);
1075 /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1076 /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1078 #[unstable(feature = "io_slice_advance", issue = "62726")]
1080 pub fn advance<'b>(bufs: &'b mut [IoSliceMut<'a>], n: usize) -> &'b mut [IoSliceMut<'a>] {
1081 // Number of buffers to remove.
1083 // Total length of all the to be removed buffers.
1084 let mut accumulated_len = 0;
1085 for buf in bufs.iter() {
1086 if accumulated_len + buf.len() > n {
1089 accumulated_len += buf.len();
1094 let bufs = &mut bufs[remove..];
1095 if !bufs.is_empty() {
1096 bufs[0].0.advance(n - accumulated_len)
1102 #[stable(feature = "iovec", since = "1.36.0")]
1103 impl<'a> Deref for IoSliceMut<'a> {
1107 fn deref(&self) -> &[u8] {
1112 #[stable(feature = "iovec", since = "1.36.0")]
1113 impl<'a> DerefMut for IoSliceMut<'a> {
1115 fn deref_mut(&mut self) -> &mut [u8] {
1116 self.0.as_mut_slice()
1120 /// A buffer type used with `Write::write_vectored`.
1122 /// It is semantically a wrapper around an `&[u8]`, but is guaranteed to be
1123 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
1125 #[stable(feature = "iovec", since = "1.36.0")]
1126 #[derive(Copy, Clone)]
1127 #[repr(transparent)]
1128 pub struct IoSlice<'a>(sys::io::IoSlice<'a>);
1130 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1131 unsafe impl<'a> Send for IoSlice<'a> {}
1133 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1134 unsafe impl<'a> Sync for IoSlice<'a> {}
1136 #[stable(feature = "iovec", since = "1.36.0")]
1137 impl<'a> fmt::Debug for IoSlice<'a> {
1138 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1139 fmt::Debug::fmt(self.0.as_slice(), fmt)
1143 impl<'a> IoSlice<'a> {
1144 /// Creates a new `IoSlice` wrapping a byte slice.
1148 /// Panics on Windows if the slice is larger than 4GB.
1149 #[stable(feature = "iovec", since = "1.36.0")]
1151 pub fn new(buf: &'a [u8]) -> IoSlice<'a> {
1152 IoSlice(sys::io::IoSlice::new(buf))
1155 /// Advance the internal cursor of the slice.
1159 /// Elements in the slice may be modified if the cursor is not advanced to
1160 /// the end of the slice. For example if we have a slice of buffers with 2
1161 /// `IoSlice`s, both of length 8, and we advance the cursor by 10 bytes the
1162 /// first `IoSlice` will be untouched however the second will be modified to
1163 /// remove the first 2 bytes (10 - 8).
1168 /// #![feature(io_slice_advance)]
1170 /// use std::io::IoSlice;
1171 /// use std::ops::Deref;
1173 /// let buf1 = [1; 8];
1174 /// let buf2 = [2; 16];
1175 /// let buf3 = [3; 8];
1176 /// let mut bufs = &mut [
1177 /// IoSlice::new(&buf1),
1178 /// IoSlice::new(&buf2),
1179 /// IoSlice::new(&buf3),
1182 /// // Mark 10 bytes as written.
1183 /// bufs = IoSlice::advance(bufs, 10);
1184 /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1185 /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1186 #[unstable(feature = "io_slice_advance", issue = "62726")]
1188 pub fn advance<'b>(bufs: &'b mut [IoSlice<'a>], n: usize) -> &'b mut [IoSlice<'a>] {
1189 // Number of buffers to remove.
1191 // Total length of all the to be removed buffers.
1192 let mut accumulated_len = 0;
1193 for buf in bufs.iter() {
1194 if accumulated_len + buf.len() > n {
1197 accumulated_len += buf.len();
1202 let bufs = &mut bufs[remove..];
1203 if !bufs.is_empty() {
1204 bufs[0].0.advance(n - accumulated_len)
1210 #[stable(feature = "iovec", since = "1.36.0")]
1211 impl<'a> Deref for IoSlice<'a> {
1215 fn deref(&self) -> &[u8] {
1220 /// A type used to conditionally initialize buffers passed to `Read` methods.
1221 #[unstable(feature = "read_initializer", issue = "42788")]
1223 pub struct Initializer(bool);
1226 /// Returns a new `Initializer` which will zero out buffers.
1227 #[unstable(feature = "read_initializer", issue = "42788")]
1229 pub fn zeroing() -> Initializer {
1233 /// Returns a new `Initializer` which will not zero out buffers.
1237 /// This may only be called by `Read`ers which guarantee that they will not
1238 /// read from buffers passed to `Read` methods, and that the return value of
1239 /// the method accurately reflects the number of bytes that have been
1240 /// written to the head of the buffer.
1241 #[unstable(feature = "read_initializer", issue = "42788")]
1243 pub unsafe fn nop() -> Initializer {
1247 /// Indicates if a buffer should be initialized.
1248 #[unstable(feature = "read_initializer", issue = "42788")]
1250 pub fn should_initialize(&self) -> bool {
1254 /// Initializes a buffer if necessary.
1255 #[unstable(feature = "read_initializer", issue = "42788")]
1257 pub fn initialize(&self, buf: &mut [u8]) {
1258 if self.should_initialize() {
1259 unsafe { ptr::write_bytes(buf.as_mut_ptr(), 0, buf.len()) }
1264 /// A trait for objects which are byte-oriented sinks.
1266 /// Implementors of the `Write` trait are sometimes called 'writers'.
1268 /// Writers are defined by two required methods, [`write`] and [`flush`]:
1270 /// * The [`write`] method will attempt to write some data into the object,
1271 /// returning how many bytes were successfully written.
1273 /// * The [`flush`] method is useful for adaptors and explicit buffers
1274 /// themselves for ensuring that all buffered data has been pushed out to the
1277 /// Writers are intended to be composable with one another. Many implementors
1278 /// throughout [`std::io`] take and provide types which implement the `Write`
1281 /// [`write`]: Write::write
1282 /// [`flush`]: Write::flush
1283 /// [`std::io`]: self
1288 /// use std::io::prelude::*;
1289 /// use std::fs::File;
1291 /// fn main() -> std::io::Result<()> {
1292 /// let data = b"some bytes";
1294 /// let mut pos = 0;
1295 /// let mut buffer = File::create("foo.txt")?;
1297 /// while pos < data.len() {
1298 /// let bytes_written = buffer.write(&data[pos..])?;
1299 /// pos += bytes_written;
1305 /// The trait also provides convenience methods like [`write_all`], which calls
1306 /// `write` in a loop until its entire input has been written.
1308 /// [`write_all`]: Write::write_all
1309 #[stable(feature = "rust1", since = "1.0.0")]
1310 #[cfg_attr(bootstrap, doc(spotlight))]
1311 #[cfg_attr(not(bootstrap), doc(notable_trait))]
1313 /// Write a buffer into this writer, returning how many bytes were written.
1315 /// This function will attempt to write the entire contents of `buf`, but
1316 /// the entire write may not succeed, or the write may also generate an
1317 /// error. A call to `write` represents *at most one* attempt to write to
1318 /// any wrapped object.
1320 /// Calls to `write` are not guaranteed to block waiting for data to be
1321 /// written, and a write which would otherwise block can be indicated through
1322 /// an [`Err`] variant.
1324 /// If the return value is [`Ok(n)`] then it must be guaranteed that
1325 /// `n <= buf.len()`. A return value of `0` typically means that the
1326 /// underlying object is no longer able to accept bytes and will likely not
1327 /// be able to in the future as well, or that the buffer provided is empty.
1331 /// Each call to `write` may generate an I/O error indicating that the
1332 /// operation could not be completed. If an error is returned then no bytes
1333 /// in the buffer were written to this writer.
1335 /// It is **not** considered an error if the entire buffer could not be
1336 /// written to this writer.
1338 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the
1339 /// write operation should be retried if there is nothing else to do.
1344 /// use std::io::prelude::*;
1345 /// use std::fs::File;
1347 /// fn main() -> std::io::Result<()> {
1348 /// let mut buffer = File::create("foo.txt")?;
1350 /// // Writes some prefix of the byte string, not necessarily all of it.
1351 /// buffer.write(b"some bytes")?;
1357 #[stable(feature = "rust1", since = "1.0.0")]
1358 fn write(&mut self, buf: &[u8]) -> Result<usize>;
1360 /// Like [`write`], except that it writes from a slice of buffers.
1362 /// Data is copied from each buffer in order, with the final buffer
1363 /// read from possibly being only partially consumed. This method must
1364 /// behave as a call to [`write`] with the buffers concatenated would.
1366 /// The default implementation calls [`write`] with either the first nonempty
1367 /// buffer provided, or an empty one if none exists.
1369 /// [`write`]: Write::write
1370 #[stable(feature = "iovec", since = "1.36.0")]
1371 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize> {
1372 default_write_vectored(|b| self.write(b), bufs)
1375 /// Determines if this `Write`r has an efficient [`write_vectored`]
1378 /// If a `Write`r does not override the default [`write_vectored`]
1379 /// implementation, code using it may want to avoid the method all together
1380 /// and coalesce writes into a single buffer for higher performance.
1382 /// The default implementation returns `false`.
1384 /// [`write_vectored`]: Write::write_vectored
1385 #[unstable(feature = "can_vector", issue = "69941")]
1386 fn is_write_vectored(&self) -> bool {
1390 /// Flush this output stream, ensuring that all intermediately buffered
1391 /// contents reach their destination.
1395 /// It is considered an error if not all bytes could be written due to
1396 /// I/O errors or EOF being reached.
1401 /// use std::io::prelude::*;
1402 /// use std::io::BufWriter;
1403 /// use std::fs::File;
1405 /// fn main() -> std::io::Result<()> {
1406 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
1408 /// buffer.write_all(b"some bytes")?;
1409 /// buffer.flush()?;
1413 #[stable(feature = "rust1", since = "1.0.0")]
1414 fn flush(&mut self) -> Result<()>;
1416 /// Attempts to write an entire buffer into this writer.
1418 /// This method will continuously call [`write`] until there is no more data
1419 /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is
1420 /// returned. This method will not return until the entire buffer has been
1421 /// successfully written or such an error occurs. The first error that is
1422 /// not of [`ErrorKind::Interrupted`] kind generated from this method will be
1425 /// If the buffer contains no data, this will never call [`write`].
1429 /// This function will return the first error of
1430 /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns.
1432 /// [`write`]: Write::write
1437 /// use std::io::prelude::*;
1438 /// use std::fs::File;
1440 /// fn main() -> std::io::Result<()> {
1441 /// let mut buffer = File::create("foo.txt")?;
1443 /// buffer.write_all(b"some bytes")?;
1447 #[stable(feature = "rust1", since = "1.0.0")]
1448 fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
1449 while !buf.is_empty() {
1450 match self.write(buf) {
1452 return Err(Error::new_const(
1453 ErrorKind::WriteZero,
1454 &"failed to write whole buffer",
1457 Ok(n) => buf = &buf[n..],
1458 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1459 Err(e) => return Err(e),
1465 /// Attempts to write multiple buffers into this writer.
1467 /// This method will continuously call [`write_vectored`] until there is no
1468 /// more data to be written or an error of non-[`ErrorKind::Interrupted`]
1469 /// kind is returned. This method will not return until all buffers have
1470 /// been successfully written or such an error occurs. The first error that
1471 /// is not of [`ErrorKind::Interrupted`] kind generated from this method
1472 /// will be returned.
1474 /// If the buffer contains no data, this will never call [`write_vectored`].
1478 /// Unlike [`write_vectored`], this takes a *mutable* reference to
1479 /// a slice of [`IoSlice`]s, not an immutable one. That's because we need to
1480 /// modify the slice to keep track of the bytes already written.
1482 /// Once this function returns, the contents of `bufs` are unspecified, as
1483 /// this depends on how many calls to [`write_vectored`] were necessary. It is
1484 /// best to understand this function as taking ownership of `bufs` and to
1485 /// not use `bufs` afterwards. The underlying buffers, to which the
1486 /// [`IoSlice`]s point (but not the [`IoSlice`]s themselves), are unchanged and
1489 /// [`write_vectored`]: Write::write_vectored
1494 /// #![feature(write_all_vectored)]
1495 /// # fn main() -> std::io::Result<()> {
1497 /// use std::io::{Write, IoSlice};
1499 /// let mut writer = Vec::new();
1500 /// let bufs = &mut [
1501 /// IoSlice::new(&[1]),
1502 /// IoSlice::new(&[2, 3]),
1503 /// IoSlice::new(&[4, 5, 6]),
1506 /// writer.write_all_vectored(bufs)?;
1507 /// // Note: the contents of `bufs` is now undefined, see the Notes section.
1509 /// assert_eq!(writer, &[1, 2, 3, 4, 5, 6]);
1512 #[unstable(feature = "write_all_vectored", issue = "70436")]
1513 fn write_all_vectored(&mut self, mut bufs: &mut [IoSlice<'_>]) -> Result<()> {
1514 // Guarantee that bufs is empty if it contains no data,
1515 // to avoid calling write_vectored if there is no data to be written.
1516 bufs = IoSlice::advance(bufs, 0);
1517 while !bufs.is_empty() {
1518 match self.write_vectored(bufs) {
1520 return Err(Error::new_const(
1521 ErrorKind::WriteZero,
1522 &"failed to write whole buffer",
1525 Ok(n) => bufs = IoSlice::advance(bufs, n),
1526 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1527 Err(e) => return Err(e),
1533 /// Writes a formatted string into this writer, returning any error
1536 /// This method is primarily used to interface with the
1537 /// [`format_args!()`] macro, but it is rare that this should
1538 /// explicitly be called. The [`write!()`] macro should be favored to
1539 /// invoke this method instead.
1541 /// This function internally uses the [`write_all`] method on
1542 /// this trait and hence will continuously write data so long as no errors
1543 /// are received. This also means that partial writes are not indicated in
1546 /// [`write_all`]: Write::write_all
1550 /// This function will return any I/O error reported while formatting.
1555 /// use std::io::prelude::*;
1556 /// use std::fs::File;
1558 /// fn main() -> std::io::Result<()> {
1559 /// let mut buffer = File::create("foo.txt")?;
1562 /// write!(buffer, "{:.*}", 2, 1.234567)?;
1563 /// // turns into this:
1564 /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1568 #[stable(feature = "rust1", since = "1.0.0")]
1569 fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> Result<()> {
1570 // Create a shim which translates a Write to a fmt::Write and saves
1571 // off I/O errors. instead of discarding them
1572 struct Adaptor<'a, T: ?Sized + 'a> {
1577 impl<T: Write + ?Sized> fmt::Write for Adaptor<'_, T> {
1578 fn write_str(&mut self, s: &str) -> fmt::Result {
1579 match self.inner.write_all(s.as_bytes()) {
1582 self.error = Err(e);
1589 let mut output = Adaptor { inner: self, error: Ok(()) };
1590 match fmt::write(&mut output, fmt) {
1593 // check if the error came from the underlying `Write` or not
1594 if output.error.is_err() {
1597 Err(Error::new_const(ErrorKind::Other, &"formatter error"))
1603 /// Creates a "by reference" adaptor for this instance of `Write`.
1605 /// The returned adaptor also implements `Write` and will simply borrow this
1611 /// use std::io::Write;
1612 /// use std::fs::File;
1614 /// fn main() -> std::io::Result<()> {
1615 /// let mut buffer = File::create("foo.txt")?;
1617 /// let reference = buffer.by_ref();
1619 /// // we can use reference just like our original buffer
1620 /// reference.write_all(b"some bytes")?;
1624 #[stable(feature = "rust1", since = "1.0.0")]
1625 fn by_ref(&mut self) -> &mut Self
1633 /// The `Seek` trait provides a cursor which can be moved within a stream of
1636 /// The stream typically has a fixed size, allowing seeking relative to either
1637 /// end or the current offset.
1641 /// [`File`]s implement `Seek`:
1643 /// [`File`]: crate::fs::File
1647 /// use std::io::prelude::*;
1648 /// use std::fs::File;
1649 /// use std::io::SeekFrom;
1651 /// fn main() -> io::Result<()> {
1652 /// let mut f = File::open("foo.txt")?;
1654 /// // move the cursor 42 bytes from the start of the file
1655 /// f.seek(SeekFrom::Start(42))?;
1659 #[stable(feature = "rust1", since = "1.0.0")]
1661 /// Seek to an offset, in bytes, in a stream.
1663 /// A seek beyond the end of a stream is allowed, but behavior is defined
1664 /// by the implementation.
1666 /// If the seek operation completed successfully,
1667 /// this method returns the new position from the start of the stream.
1668 /// That position can be used later with [`SeekFrom::Start`].
1672 /// Seeking can fail, for example because it might involve flushing a buffer.
1674 /// Seeking to a negative offset is considered an error.
1675 #[stable(feature = "rust1", since = "1.0.0")]
1676 fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1678 /// Rewind to the beginning of a stream.
1680 /// This is a convenience method, equivalent to `seek(SeekFrom::Start(0))`.
1684 /// Rewinding can fail, for example because it might involve flushing a buffer.
1689 /// #![feature(seek_rewind)]
1690 /// use std::io::{Read, Seek, Write};
1691 /// use std::fs::OpenOptions;
1693 /// let mut f = OpenOptions::new()
1697 /// .open("foo.txt").unwrap();
1699 /// let hello = "Hello!\n";
1700 /// write!(f, "{}", hello).unwrap();
1701 /// f.rewind().unwrap();
1703 /// let mut buf = String::new();
1704 /// f.read_to_string(&mut buf).unwrap();
1705 /// assert_eq!(&buf, hello);
1707 #[unstable(feature = "seek_rewind", issue = "85149")]
1708 fn rewind(&mut self) -> Result<()> {
1709 self.seek(SeekFrom::Start(0))?;
1713 /// Returns the length of this stream (in bytes).
1715 /// This method is implemented using up to three seek operations. If this
1716 /// method returns successfully, the seek position is unchanged (i.e. the
1717 /// position before calling this method is the same as afterwards).
1718 /// However, if this method returns an error, the seek position is
1721 /// If you need to obtain the length of *many* streams and you don't care
1722 /// about the seek position afterwards, you can reduce the number of seek
1723 /// operations by simply calling `seek(SeekFrom::End(0))` and using its
1724 /// return value (it is also the stream length).
1726 /// Note that length of a stream can change over time (for example, when
1727 /// data is appended to a file). So calling this method multiple times does
1728 /// not necessarily return the same length each time.
1733 /// #![feature(seek_stream_len)]
1735 /// io::{self, Seek},
1739 /// fn main() -> io::Result<()> {
1740 /// let mut f = File::open("foo.txt")?;
1742 /// let len = f.stream_len()?;
1743 /// println!("The file is currently {} bytes long", len);
1747 #[unstable(feature = "seek_stream_len", issue = "59359")]
1748 fn stream_len(&mut self) -> Result<u64> {
1749 let old_pos = self.stream_position()?;
1750 let len = self.seek(SeekFrom::End(0))?;
1752 // Avoid seeking a third time when we were already at the end of the
1753 // stream. The branch is usually way cheaper than a seek operation.
1755 self.seek(SeekFrom::Start(old_pos))?;
1761 /// Returns the current seek position from the start of the stream.
1763 /// This is equivalent to `self.seek(SeekFrom::Current(0))`.
1769 /// io::{self, BufRead, BufReader, Seek},
1773 /// fn main() -> io::Result<()> {
1774 /// let mut f = BufReader::new(File::open("foo.txt")?);
1776 /// let before = f.stream_position()?;
1777 /// f.read_line(&mut String::new())?;
1778 /// let after = f.stream_position()?;
1780 /// println!("The first line was {} bytes long", after - before);
1784 #[stable(feature = "seek_convenience", since = "1.51.0")]
1785 fn stream_position(&mut self) -> Result<u64> {
1786 self.seek(SeekFrom::Current(0))
1790 /// Enumeration of possible methods to seek within an I/O object.
1792 /// It is used by the [`Seek`] trait.
1793 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1794 #[stable(feature = "rust1", since = "1.0.0")]
1796 /// Sets the offset to the provided number of bytes.
1797 #[stable(feature = "rust1", since = "1.0.0")]
1798 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1800 /// Sets the offset to the size of this object plus the specified number of
1803 /// It is possible to seek beyond the end of an object, but it's an error to
1804 /// seek before byte 0.
1805 #[stable(feature = "rust1", since = "1.0.0")]
1806 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1808 /// Sets the offset to the current position plus the specified number of
1811 /// It is possible to seek beyond the end of an object, but it's an error to
1812 /// seek before byte 0.
1813 #[stable(feature = "rust1", since = "1.0.0")]
1814 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1817 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>) -> Result<usize> {
1820 let (done, used) = {
1821 let available = match r.fill_buf() {
1823 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1824 Err(e) => return Err(e),
1826 match memchr::memchr(delim, available) {
1828 buf.extend_from_slice(&available[..=i]);
1832 buf.extend_from_slice(available);
1833 (false, available.len())
1839 if done || used == 0 {
1845 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1846 /// to perform extra ways of reading.
1848 /// For example, reading line-by-line is inefficient without using a buffer, so
1849 /// if you want to read by line, you'll need `BufRead`, which includes a
1850 /// [`read_line`] method as well as a [`lines`] iterator.
1854 /// A locked standard input implements `BufRead`:
1858 /// use std::io::prelude::*;
1860 /// let stdin = io::stdin();
1861 /// for line in stdin.lock().lines() {
1862 /// println!("{}", line.unwrap());
1866 /// If you have something that implements [`Read`], you can use the [`BufReader`
1867 /// type][`BufReader`] to turn it into a `BufRead`.
1869 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1870 /// [`BufReader`] to the rescue!
1872 /// [`File`]: crate::fs::File
1873 /// [`read_line`]: BufRead::read_line
1874 /// [`lines`]: BufRead::lines
1877 /// use std::io::{self, BufReader};
1878 /// use std::io::prelude::*;
1879 /// use std::fs::File;
1881 /// fn main() -> io::Result<()> {
1882 /// let f = File::open("foo.txt")?;
1883 /// let f = BufReader::new(f);
1885 /// for line in f.lines() {
1886 /// println!("{}", line.unwrap());
1892 #[stable(feature = "rust1", since = "1.0.0")]
1893 pub trait BufRead: Read {
1894 /// Returns the contents of the internal buffer, filling it with more data
1895 /// from the inner reader if it is empty.
1897 /// This function is a lower-level call. It needs to be paired with the
1898 /// [`consume`] method to function properly. When calling this
1899 /// method, none of the contents will be "read" in the sense that later
1900 /// calling `read` may return the same contents. As such, [`consume`] must
1901 /// be called with the number of bytes that are consumed from this buffer to
1902 /// ensure that the bytes are never returned twice.
1904 /// [`consume`]: BufRead::consume
1906 /// An empty buffer returned indicates that the stream has reached EOF.
1910 /// This function will return an I/O error if the underlying reader was
1911 /// read, but returned an error.
1915 /// A locked standard input implements `BufRead`:
1919 /// use std::io::prelude::*;
1921 /// let stdin = io::stdin();
1922 /// let mut stdin = stdin.lock();
1924 /// let buffer = stdin.fill_buf().unwrap();
1926 /// // work with buffer
1927 /// println!("{:?}", buffer);
1929 /// // ensure the bytes we worked with aren't returned again later
1930 /// let length = buffer.len();
1931 /// stdin.consume(length);
1933 #[stable(feature = "rust1", since = "1.0.0")]
1934 fn fill_buf(&mut self) -> Result<&[u8]>;
1936 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1937 /// so they should no longer be returned in calls to `read`.
1939 /// This function is a lower-level call. It needs to be paired with the
1940 /// [`fill_buf`] method to function properly. This function does
1941 /// not perform any I/O, it simply informs this object that some amount of
1942 /// its buffer, returned from [`fill_buf`], has been consumed and should
1943 /// no longer be returned. As such, this function may do odd things if
1944 /// [`fill_buf`] isn't called before calling it.
1946 /// The `amt` must be `<=` the number of bytes in the buffer returned by
1951 /// Since `consume()` is meant to be used with [`fill_buf`],
1952 /// that method's example includes an example of `consume()`.
1954 /// [`fill_buf`]: BufRead::fill_buf
1955 #[stable(feature = "rust1", since = "1.0.0")]
1956 fn consume(&mut self, amt: usize);
1958 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
1960 /// This function will read bytes from the underlying stream until the
1961 /// delimiter or EOF is found. Once found, all bytes up to, and including,
1962 /// the delimiter (if found) will be appended to `buf`.
1964 /// If successful, this function will return the total number of bytes read.
1966 /// This function is blocking and should be used carefully: it is possible for
1967 /// an attacker to continuously send bytes without ever sending the delimiter
1972 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1973 /// will otherwise return any errors returned by [`fill_buf`].
1975 /// If an I/O error is encountered then all bytes read so far will be
1976 /// present in `buf` and its length will have been adjusted appropriately.
1978 /// [`fill_buf`]: BufRead::fill_buf
1982 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1983 /// this example, we use [`Cursor`] to read all the bytes in a byte slice
1984 /// in hyphen delimited segments:
1987 /// use std::io::{self, BufRead};
1989 /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
1990 /// let mut buf = vec![];
1992 /// // cursor is at 'l'
1993 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1994 /// .expect("reading from cursor won't fail");
1995 /// assert_eq!(num_bytes, 6);
1996 /// assert_eq!(buf, b"lorem-");
1999 /// // cursor is at 'i'
2000 /// let num_bytes = cursor.read_until(b'-', &mut buf)
2001 /// .expect("reading from cursor won't fail");
2002 /// assert_eq!(num_bytes, 5);
2003 /// assert_eq!(buf, b"ipsum");
2006 /// // cursor is at EOF
2007 /// let num_bytes = cursor.read_until(b'-', &mut buf)
2008 /// .expect("reading from cursor won't fail");
2009 /// assert_eq!(num_bytes, 0);
2010 /// assert_eq!(buf, b"");
2012 #[stable(feature = "rust1", since = "1.0.0")]
2013 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
2014 read_until(self, byte, buf)
2017 /// Read all bytes until a newline (the `0xA` byte) is reached, and append
2018 /// them to the provided buffer.
2020 /// This function will read bytes from the underlying stream until the
2021 /// newline delimiter (the `0xA` byte) or EOF is found. Once found, all bytes
2022 /// up to, and including, the delimiter (if found) will be appended to
2025 /// If successful, this function will return the total number of bytes read.
2027 /// If this function returns [`Ok(0)`], the stream has reached EOF.
2029 /// This function is blocking and should be used carefully: it is possible for
2030 /// an attacker to continuously send bytes without ever sending a newline
2037 /// This function has the same error semantics as [`read_until`] and will
2038 /// also return an error if the read bytes are not valid UTF-8. If an I/O
2039 /// error is encountered then `buf` may contain some bytes already read in
2040 /// the event that all data read so far was valid UTF-8.
2042 /// [`read_until`]: BufRead::read_until
2046 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2047 /// this example, we use [`Cursor`] to read all the lines in a byte slice:
2050 /// use std::io::{self, BufRead};
2052 /// let mut cursor = io::Cursor::new(b"foo\nbar");
2053 /// let mut buf = String::new();
2055 /// // cursor is at 'f'
2056 /// let num_bytes = cursor.read_line(&mut buf)
2057 /// .expect("reading from cursor won't fail");
2058 /// assert_eq!(num_bytes, 4);
2059 /// assert_eq!(buf, "foo\n");
2062 /// // cursor is at 'b'
2063 /// let num_bytes = cursor.read_line(&mut buf)
2064 /// .expect("reading from cursor won't fail");
2065 /// assert_eq!(num_bytes, 3);
2066 /// assert_eq!(buf, "bar");
2069 /// // cursor is at EOF
2070 /// let num_bytes = cursor.read_line(&mut buf)
2071 /// .expect("reading from cursor won't fail");
2072 /// assert_eq!(num_bytes, 0);
2073 /// assert_eq!(buf, "");
2075 #[stable(feature = "rust1", since = "1.0.0")]
2076 fn read_line(&mut self, buf: &mut String) -> Result<usize> {
2077 // Note that we are not calling the `.read_until` method here, but
2078 // rather our hardcoded implementation. For more details as to why, see
2079 // the comments in `read_to_end`.
2080 append_to_string(buf, |b| read_until(self, b'\n', b))
2083 /// Returns an iterator over the contents of this reader split on the byte
2086 /// The iterator returned from this function will return instances of
2087 /// [`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
2088 /// the delimiter byte at the end.
2090 /// This function will yield errors whenever [`read_until`] would have
2091 /// also yielded an error.
2093 /// [`io::Result`]: self::Result
2094 /// [`read_until`]: BufRead::read_until
2098 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2099 /// this example, we use [`Cursor`] to iterate over all hyphen delimited
2100 /// segments in a byte slice
2103 /// use std::io::{self, BufRead};
2105 /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
2107 /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
2108 /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
2109 /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
2110 /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
2111 /// assert_eq!(split_iter.next(), None);
2113 #[stable(feature = "rust1", since = "1.0.0")]
2114 fn split(self, byte: u8) -> Split<Self>
2118 Split { buf: self, delim: byte }
2121 /// Returns an iterator over the lines of this reader.
2123 /// The iterator returned from this function will yield instances of
2124 /// [`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline
2125 /// byte (the `0xA` byte) or `CRLF` (`0xD`, `0xA` bytes) at the end.
2127 /// [`io::Result`]: self::Result
2131 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2132 /// this example, we use [`Cursor`] to iterate over all the lines in a byte
2136 /// use std::io::{self, BufRead};
2138 /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
2140 /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
2141 /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
2142 /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
2143 /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
2144 /// assert_eq!(lines_iter.next(), None);
2149 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
2150 #[stable(feature = "rust1", since = "1.0.0")]
2151 fn lines(self) -> Lines<Self>
2159 /// Adaptor to chain together two readers.
2161 /// This struct is generally created by calling [`chain`] on a reader.
2162 /// Please see the documentation of [`chain`] for more details.
2164 /// [`chain`]: Read::chain
2165 #[stable(feature = "rust1", since = "1.0.0")]
2167 pub struct Chain<T, U> {
2173 impl<T, U> Chain<T, U> {
2174 /// Consumes the `Chain`, returning the wrapped readers.
2180 /// use std::io::prelude::*;
2181 /// use std::fs::File;
2183 /// fn main() -> io::Result<()> {
2184 /// let mut foo_file = File::open("foo.txt")?;
2185 /// let mut bar_file = File::open("bar.txt")?;
2187 /// let chain = foo_file.chain(bar_file);
2188 /// let (foo_file, bar_file) = chain.into_inner();
2192 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2193 pub fn into_inner(self) -> (T, U) {
2194 (self.first, self.second)
2197 /// Gets references to the underlying readers in this `Chain`.
2203 /// use std::io::prelude::*;
2204 /// use std::fs::File;
2206 /// fn main() -> io::Result<()> {
2207 /// let mut foo_file = File::open("foo.txt")?;
2208 /// let mut bar_file = File::open("bar.txt")?;
2210 /// let chain = foo_file.chain(bar_file);
2211 /// let (foo_file, bar_file) = chain.get_ref();
2215 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2216 pub fn get_ref(&self) -> (&T, &U) {
2217 (&self.first, &self.second)
2220 /// Gets mutable references to the underlying readers in this `Chain`.
2222 /// Care should be taken to avoid modifying the internal I/O state of the
2223 /// underlying readers as doing so may corrupt the internal state of this
2230 /// use std::io::prelude::*;
2231 /// use std::fs::File;
2233 /// fn main() -> io::Result<()> {
2234 /// let mut foo_file = File::open("foo.txt")?;
2235 /// let mut bar_file = File::open("bar.txt")?;
2237 /// let mut chain = foo_file.chain(bar_file);
2238 /// let (foo_file, bar_file) = chain.get_mut();
2242 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2243 pub fn get_mut(&mut self) -> (&mut T, &mut U) {
2244 (&mut self.first, &mut self.second)
2248 #[stable(feature = "rust1", since = "1.0.0")]
2249 impl<T: Read, U: Read> Read for Chain<T, U> {
2250 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2251 if !self.done_first {
2252 match self.first.read(buf)? {
2253 0 if !buf.is_empty() => self.done_first = true,
2257 self.second.read(buf)
2260 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
2261 if !self.done_first {
2262 match self.first.read_vectored(bufs)? {
2263 0 if bufs.iter().any(|b| !b.is_empty()) => self.done_first = true,
2267 self.second.read_vectored(bufs)
2270 unsafe fn initializer(&self) -> Initializer {
2271 let initializer = self.first.initializer();
2272 if initializer.should_initialize() { initializer } else { self.second.initializer() }
2276 #[stable(feature = "chain_bufread", since = "1.9.0")]
2277 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
2278 fn fill_buf(&mut self) -> Result<&[u8]> {
2279 if !self.done_first {
2280 match self.first.fill_buf()? {
2281 buf if buf.is_empty() => {
2282 self.done_first = true;
2284 buf => return Ok(buf),
2287 self.second.fill_buf()
2290 fn consume(&mut self, amt: usize) {
2291 if !self.done_first { self.first.consume(amt) } else { self.second.consume(amt) }
2295 impl<T, U> SizeHint for Chain<T, U> {
2296 fn lower_bound(&self) -> usize {
2297 SizeHint::lower_bound(&self.first) + SizeHint::lower_bound(&self.second)
2300 fn upper_bound(&self) -> Option<usize> {
2301 match (SizeHint::upper_bound(&self.first), SizeHint::upper_bound(&self.second)) {
2302 (Some(first), Some(second)) => Some(first + second),
2308 /// Reader adaptor which limits the bytes read from an underlying reader.
2310 /// This struct is generally created by calling [`take`] on a reader.
2311 /// Please see the documentation of [`take`] for more details.
2313 /// [`take`]: Read::take
2314 #[stable(feature = "rust1", since = "1.0.0")]
2316 pub struct Take<T> {
2322 /// Returns the number of bytes that can be read before this instance will
2327 /// This instance may reach `EOF` after reading fewer bytes than indicated by
2328 /// this method if the underlying [`Read`] instance reaches EOF.
2334 /// use std::io::prelude::*;
2335 /// use std::fs::File;
2337 /// fn main() -> io::Result<()> {
2338 /// let f = File::open("foo.txt")?;
2340 /// // read at most five bytes
2341 /// let handle = f.take(5);
2343 /// println!("limit: {}", handle.limit());
2347 #[stable(feature = "rust1", since = "1.0.0")]
2348 pub fn limit(&self) -> u64 {
2352 /// Sets the number of bytes that can be read before this instance will
2353 /// return EOF. This is the same as constructing a new `Take` instance, so
2354 /// the amount of bytes read and the previous limit value don't matter when
2355 /// calling this method.
2361 /// use std::io::prelude::*;
2362 /// use std::fs::File;
2364 /// fn main() -> io::Result<()> {
2365 /// let f = File::open("foo.txt")?;
2367 /// // read at most five bytes
2368 /// let mut handle = f.take(5);
2369 /// handle.set_limit(10);
2371 /// assert_eq!(handle.limit(), 10);
2375 #[stable(feature = "take_set_limit", since = "1.27.0")]
2376 pub fn set_limit(&mut self, limit: u64) {
2380 /// Consumes the `Take`, returning the wrapped reader.
2386 /// use std::io::prelude::*;
2387 /// use std::fs::File;
2389 /// fn main() -> io::Result<()> {
2390 /// let mut file = File::open("foo.txt")?;
2392 /// let mut buffer = [0; 5];
2393 /// let mut handle = file.take(5);
2394 /// handle.read(&mut buffer)?;
2396 /// let file = handle.into_inner();
2400 #[stable(feature = "io_take_into_inner", since = "1.15.0")]
2401 pub fn into_inner(self) -> T {
2405 /// Gets a reference to the underlying reader.
2411 /// use std::io::prelude::*;
2412 /// use std::fs::File;
2414 /// fn main() -> io::Result<()> {
2415 /// let mut file = File::open("foo.txt")?;
2417 /// let mut buffer = [0; 5];
2418 /// let mut handle = file.take(5);
2419 /// handle.read(&mut buffer)?;
2421 /// let file = handle.get_ref();
2425 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2426 pub fn get_ref(&self) -> &T {
2430 /// Gets a mutable reference to the underlying reader.
2432 /// Care should be taken to avoid modifying the internal I/O state of the
2433 /// underlying reader as doing so may corrupt the internal limit of this
2440 /// use std::io::prelude::*;
2441 /// use std::fs::File;
2443 /// fn main() -> io::Result<()> {
2444 /// let mut file = File::open("foo.txt")?;
2446 /// let mut buffer = [0; 5];
2447 /// let mut handle = file.take(5);
2448 /// handle.read(&mut buffer)?;
2450 /// let file = handle.get_mut();
2454 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2455 pub fn get_mut(&mut self) -> &mut T {
2460 #[stable(feature = "rust1", since = "1.0.0")]
2461 impl<T: Read> Read for Take<T> {
2462 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2463 // Don't call into inner reader at all at EOF because it may still block
2464 if self.limit == 0 {
2468 let max = cmp::min(buf.len() as u64, self.limit) as usize;
2469 let n = self.inner.read(&mut buf[..max])?;
2470 self.limit -= n as u64;
2474 unsafe fn initializer(&self) -> Initializer {
2475 self.inner.initializer()
2478 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
2479 // Pass in a reservation_size closure that respects the current value
2480 // of limit for each read. If we hit the read limit, this prevents the
2481 // final zero-byte read from allocating again.
2482 read_to_end_with_reservation(self, buf, |self_| cmp::min(self_.limit, 32) as usize)
2486 #[stable(feature = "rust1", since = "1.0.0")]
2487 impl<T: BufRead> BufRead for Take<T> {
2488 fn fill_buf(&mut self) -> Result<&[u8]> {
2489 // Don't call into inner reader at all at EOF because it may still block
2490 if self.limit == 0 {
2494 let buf = self.inner.fill_buf()?;
2495 let cap = cmp::min(buf.len() as u64, self.limit) as usize;
2499 fn consume(&mut self, amt: usize) {
2500 // Don't let callers reset the limit by passing an overlarge value
2501 let amt = cmp::min(amt as u64, self.limit) as usize;
2502 self.limit -= amt as u64;
2503 self.inner.consume(amt);
2507 /// An iterator over `u8` values of a reader.
2509 /// This struct is generally created by calling [`bytes`] on a reader.
2510 /// Please see the documentation of [`bytes`] for more details.
2512 /// [`bytes`]: Read::bytes
2513 #[stable(feature = "rust1", since = "1.0.0")]
2515 pub struct Bytes<R> {
2519 #[stable(feature = "rust1", since = "1.0.0")]
2520 impl<R: Read> Iterator for Bytes<R> {
2521 type Item = Result<u8>;
2523 fn next(&mut self) -> Option<Result<u8>> {
2526 return match self.inner.read(slice::from_mut(&mut byte)) {
2528 Ok(..) => Some(Ok(byte)),
2529 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
2530 Err(e) => Some(Err(e)),
2535 fn size_hint(&self) -> (usize, Option<usize>) {
2536 SizeHint::size_hint(&self.inner)
2541 fn lower_bound(&self) -> usize;
2543 fn upper_bound(&self) -> Option<usize>;
2545 fn size_hint(&self) -> (usize, Option<usize>) {
2546 (self.lower_bound(), self.upper_bound())
2550 impl<T> SizeHint for T {
2551 default fn lower_bound(&self) -> usize {
2555 default fn upper_bound(&self) -> Option<usize> {
2560 /// An iterator over the contents of an instance of `BufRead` split on a
2561 /// particular byte.
2563 /// This struct is generally created by calling [`split`] on a `BufRead`.
2564 /// Please see the documentation of [`split`] for more details.
2566 /// [`split`]: BufRead::split
2567 #[stable(feature = "rust1", since = "1.0.0")]
2569 pub struct Split<B> {
2574 #[stable(feature = "rust1", since = "1.0.0")]
2575 impl<B: BufRead> Iterator for Split<B> {
2576 type Item = Result<Vec<u8>>;
2578 fn next(&mut self) -> Option<Result<Vec<u8>>> {
2579 let mut buf = Vec::new();
2580 match self.buf.read_until(self.delim, &mut buf) {
2583 if buf[buf.len() - 1] == self.delim {
2588 Err(e) => Some(Err(e)),
2593 /// An iterator over the lines of an instance of `BufRead`.
2595 /// This struct is generally created by calling [`lines`] on a `BufRead`.
2596 /// Please see the documentation of [`lines`] for more details.
2598 /// [`lines`]: BufRead::lines
2599 #[stable(feature = "rust1", since = "1.0.0")]
2601 pub struct Lines<B> {
2605 #[stable(feature = "rust1", since = "1.0.0")]
2606 impl<B: BufRead> Iterator for Lines<B> {
2607 type Item = Result<String>;
2609 fn next(&mut self) -> Option<Result<String>> {
2610 let mut buf = String::new();
2611 match self.buf.read_line(&mut buf) {
2614 if buf.ends_with('\n') {
2616 if buf.ends_with('\r') {
2622 Err(e) => Some(Err(e)),