1 //! Traits, helpers, and type definitions for core I/O functionality.
3 //! The `std::io` module contains a number of common things you'll need
4 //! when doing input and output. The most core part of this module is
5 //! the [`Read`] and [`Write`] traits, which provide the
6 //! most general interface for reading and writing input and output.
10 //! Because they are traits, [`Read`] and [`Write`] are implemented by a number
11 //! of other types, and you can implement them for your types too. As such,
12 //! you'll see a few different types of I/O throughout the documentation in
13 //! this module: [`File`]s, [`TcpStream`]s, and sometimes even [`Vec<T>`]s. For
14 //! example, [`Read`] adds a [`read`][`Read::read`] method, which we can use on
19 //! use std::io::prelude::*;
20 //! use std::fs::File;
22 //! fn main() -> io::Result<()> {
23 //! let mut f = File::open("foo.txt")?;
24 //! let mut buffer = [0; 10];
26 //! // read up to 10 bytes
27 //! let n = f.read(&mut buffer)?;
29 //! println!("The bytes: {:?}", &buffer[..n]);
34 //! [`Read`] and [`Write`] are so important, implementors of the two traits have a
35 //! nickname: readers and writers. So you'll sometimes see 'a reader' instead
36 //! of 'a type that implements the [`Read`] trait'. Much easier!
38 //! ## Seek and BufRead
40 //! Beyond that, there are two important traits that are provided: [`Seek`]
41 //! and [`BufRead`]. Both of these build on top of a reader to control
42 //! how the reading happens. [`Seek`] lets you control where the next byte is
47 //! use std::io::prelude::*;
48 //! use std::io::SeekFrom;
49 //! use std::fs::File;
51 //! fn main() -> io::Result<()> {
52 //! let mut f = File::open("foo.txt")?;
53 //! let mut buffer = [0; 10];
55 //! // skip to the last 10 bytes of the file
56 //! f.seek(SeekFrom::End(-10))?;
58 //! // read up to 10 bytes
59 //! let n = f.read(&mut buffer)?;
61 //! println!("The bytes: {:?}", &buffer[..n]);
66 //! [`BufRead`] uses an internal buffer to provide a number of other ways to read, but
67 //! to show it off, we'll need to talk about buffers in general. Keep reading!
69 //! ## BufReader and BufWriter
71 //! Byte-based interfaces are unwieldy and can be inefficient, as we'd need to be
72 //! making near-constant calls to the operating system. To help with this,
73 //! `std::io` comes with two structs, [`BufReader`] and [`BufWriter`], which wrap
74 //! readers and writers. The wrapper uses a buffer, reducing the number of
75 //! calls and providing nicer methods for accessing exactly what you want.
77 //! For example, [`BufReader`] works with the [`BufRead`] trait to add extra
78 //! methods to any reader:
82 //! use std::io::prelude::*;
83 //! use std::io::BufReader;
84 //! use std::fs::File;
86 //! fn main() -> io::Result<()> {
87 //! let f = File::open("foo.txt")?;
88 //! let mut reader = BufReader::new(f);
89 //! let mut buffer = String::new();
91 //! // read a line into buffer
92 //! reader.read_line(&mut buffer)?;
94 //! println!("{}", buffer);
99 //! [`BufWriter`] doesn't add any new ways of writing; it just buffers every call
100 //! to [`write`][`Write::write`]:
104 //! use std::io::prelude::*;
105 //! use std::io::BufWriter;
106 //! use std::fs::File;
108 //! fn main() -> io::Result<()> {
109 //! let f = File::create("foo.txt")?;
111 //! let mut writer = BufWriter::new(f);
113 //! // write a byte to the buffer
114 //! writer.write(&[42])?;
116 //! } // the buffer is flushed once writer goes out of scope
122 //! ## Standard input and output
124 //! A very common source of input is standard input:
129 //! fn main() -> io::Result<()> {
130 //! let mut input = String::new();
132 //! io::stdin().read_line(&mut input)?;
134 //! println!("You typed: {}", input.trim());
139 //! Note that you cannot use the [`?` operator] in functions that do not return
140 //! a [`Result<T, E>`][`Result`]. Instead, you can call [`.unwrap()`]
141 //! or `match` on the return value to catch any possible errors:
146 //! let mut input = String::new();
148 //! io::stdin().read_line(&mut input).unwrap();
151 //! And a very common source of output is standard output:
155 //! use std::io::prelude::*;
157 //! fn main() -> io::Result<()> {
158 //! io::stdout().write(&[42])?;
163 //! Of course, using [`io::stdout`] directly is less common than something like
166 //! ## Iterator types
168 //! A large number of the structures provided by `std::io` are for various
169 //! ways of iterating over I/O. For example, [`Lines`] is used to split over
174 //! use std::io::prelude::*;
175 //! use std::io::BufReader;
176 //! use std::fs::File;
178 //! fn main() -> io::Result<()> {
179 //! let f = File::open("foo.txt")?;
180 //! let reader = BufReader::new(f);
182 //! for line in reader.lines() {
183 //! println!("{}", line?);
191 //! There are a number of [functions][functions-list] that offer access to various
192 //! features. For example, we can use three of these functions to copy everything
193 //! from standard input to standard output:
198 //! fn main() -> io::Result<()> {
199 //! io::copy(&mut io::stdin(), &mut io::stdout())?;
204 //! [functions-list]: #functions-1
208 //! Last, but certainly not least, is [`io::Result`]. This type is used
209 //! as the return type of many `std::io` functions that can cause an error, and
210 //! can be returned from your own functions as well. Many of the examples in this
211 //! module use the [`?` operator]:
216 //! fn read_input() -> io::Result<()> {
217 //! let mut input = String::new();
219 //! io::stdin().read_line(&mut input)?;
221 //! println!("You typed: {}", input.trim());
227 //! The return type of `read_input()`, [`io::Result<()>`][`io::Result`], is a very
228 //! common type for functions which don't have a 'real' return value, but do want to
229 //! return errors if they happen. In this case, the only purpose of this function is
230 //! to read the line and print it, so we use `()`.
232 //! ## Platform-specific behavior
234 //! Many I/O functions throughout the standard library are documented to indicate
235 //! what various library or syscalls they are delegated to. This is done to help
236 //! applications both understand what's happening under the hood as well as investigate
237 //! any possibly unclear semantics. Note, however, that this is informative, not a binding
238 //! contract. The implementation of many of these functions are subject to change over
239 //! time and may call fewer or more syscalls/library functions.
241 //! [`File`]: crate::fs::File
242 //! [`TcpStream`]: crate::net::TcpStream
243 //! [`io::stdout`]: stdout
244 //! [`io::Result`]: self::Result
245 //! [`?` operator]: ../../book/appendix-02-operators.html
246 //! [`Result`]: crate::result::Result
247 //! [`.unwrap()`]: crate::result::Result::unwrap
249 #![stable(feature = "rust1", since = "1.0.0")]
255 use crate::convert::TryInto;
257 use crate::mem::replace;
258 use crate::ops::{Deref, DerefMut};
263 use crate::sys_common::memchr;
265 #[stable(feature = "rust1", since = "1.0.0")]
266 pub use self::buffered::IntoInnerError;
267 #[stable(feature = "rust1", since = "1.0.0")]
268 pub use self::buffered::{BufReader, BufWriter, LineWriter};
269 #[stable(feature = "rust1", since = "1.0.0")]
270 pub use self::copy::copy;
271 #[stable(feature = "rust1", since = "1.0.0")]
272 pub use self::cursor::Cursor;
273 #[stable(feature = "rust1", since = "1.0.0")]
274 pub use self::error::{Error, ErrorKind, Result};
275 #[unstable(feature = "internal_output_capture", issue = "none")]
276 #[doc(no_inline, hidden)]
277 pub use self::stdio::set_output_capture;
278 #[stable(feature = "rust1", since = "1.0.0")]
279 pub use self::stdio::{stderr, stdin, stdout, Stderr, Stdin, Stdout};
280 #[stable(feature = "rust1", since = "1.0.0")]
281 pub use self::stdio::{StderrLock, StdinLock, StdoutLock};
282 #[unstable(feature = "print_internals", issue = "none")]
283 pub use self::stdio::{_eprint, _print};
284 #[stable(feature = "rust1", since = "1.0.0")]
285 pub use self::util::{empty, repeat, sink, Empty, Repeat, Sink};
296 const DEFAULT_BUF_SIZE: usize = crate::sys_common::io::DEFAULT_BUF_SIZE;
298 pub(crate) fn cleanup() {
303 buf: &'a mut Vec<u8>,
307 impl Drop for Guard<'_> {
310 self.buf.set_len(self.len);
315 // A few methods below (read_to_string, read_line) will append data into a
316 // `String` buffer, but we need to be pretty careful when doing this. The
317 // implementation will just call `.as_mut_vec()` and then delegate to a
318 // byte-oriented reading method, but we must ensure that when returning we never
319 // leave `buf` in a state such that it contains invalid UTF-8 in its bounds.
321 // To this end, we use an RAII guard (to protect against panics) which updates
322 // the length of the string when it is dropped. This guard initially truncates
323 // the string to the prior length and only after we've validated that the
324 // new contents are valid UTF-8 do we allow it to set a longer length.
326 // The unsafety in this function is twofold:
328 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
330 // 2. We're passing a raw buffer to the function `f`, and it is expected that
331 // the function only *appends* bytes to the buffer. We'll get undefined
332 // behavior if existing bytes are overwritten to have non-UTF-8 data.
333 fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
335 F: FnOnce(&mut Vec<u8>) -> Result<usize>,
338 let mut g = Guard { len: buf.len(), buf: buf.as_mut_vec() };
340 if str::from_utf8(&g.buf[g.len..]).is_err() {
342 Err(Error::new_const(ErrorKind::InvalidData, &"stream did not contain valid UTF-8"))
351 // This uses an adaptive system to extend the vector when it fills. We want to
352 // avoid paying to allocate and zero a huge chunk of memory if the reader only
353 // has 4 bytes while still making large reads if the reader does have a ton
354 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
355 // time is 4,500 times (!) slower than a default reservation size of 32 if the
356 // reader has a very small amount of data to return.
358 // Because we're extending the buffer with uninitialized data for trusted
359 // readers, we need to make sure to truncate that if any of this panics.
360 fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
361 read_to_end_with_reservation(r, buf, |_| 32)
364 fn read_to_end_with_reservation<R, F>(
367 mut reservation_size: F,
371 F: FnMut(&R) -> usize,
373 let start_len = buf.len();
374 let mut g = Guard { len: buf.len(), buf };
376 if g.len == g.buf.len() {
378 // FIXME(danielhenrymantilla): #42788
380 // - This creates a (mut) reference to a slice of
381 // _uninitialized_ integers, which is **undefined behavior**
383 // - Only the standard library gets to soundly "ignore" this,
384 // based on its privileged knowledge of unstable rustc
386 g.buf.reserve(reservation_size(r));
387 let capacity = g.buf.capacity();
388 g.buf.set_len(capacity);
389 r.initializer().initialize(&mut g.buf[g.len..]);
393 let buf = &mut g.buf[g.len..];
395 Ok(0) => return Ok(g.len - start_len),
397 // We can't allow bogus values from read. If it is too large, the returned vec could have its length
398 // set past its capacity, or if it overflows the vec could be shortened which could create an invalid
399 // string if this is called via read_to_string.
400 assert!(n <= buf.len());
403 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
404 Err(e) => return Err(e),
409 pub(crate) fn default_read_vectored<F>(read: F, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
411 F: FnOnce(&mut [u8]) -> Result<usize>,
413 let buf = bufs.iter_mut().find(|b| !b.is_empty()).map_or(&mut [][..], |b| &mut **b);
417 pub(crate) fn default_write_vectored<F>(write: F, bufs: &[IoSlice<'_>]) -> Result<usize>
419 F: FnOnce(&[u8]) -> Result<usize>,
421 let buf = bufs.iter().find(|b| !b.is_empty()).map_or(&[][..], |b| &**b);
425 pub(crate) fn default_read_exact<R: Read + ?Sized>(this: &mut R, mut buf: &mut [u8]) -> Result<()> {
426 while !buf.is_empty() {
427 match this.read(buf) {
433 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
434 Err(e) => return Err(e),
438 Err(Error::new_const(ErrorKind::UnexpectedEof, &"failed to fill whole buffer"))
444 /// The `Read` trait allows for reading bytes from a source.
446 /// Implementors of the `Read` trait are called 'readers'.
448 /// Readers are defined by one required method, [`read()`]. Each call to [`read()`]
449 /// will attempt to pull bytes from this source into a provided buffer. A
450 /// number of other methods are implemented in terms of [`read()`], giving
451 /// implementors a number of ways to read bytes while only needing to implement
454 /// Readers are intended to be composable with one another. Many implementors
455 /// throughout [`std::io`] take and provide types which implement the `Read`
458 /// Please note that each call to [`read()`] may involve a system call, and
459 /// therefore, using something that implements [`BufRead`], such as
460 /// [`BufReader`], will be more efficient.
464 /// [`File`]s implement `Read`:
468 /// use std::io::prelude::*;
469 /// use std::fs::File;
471 /// fn main() -> io::Result<()> {
472 /// let mut f = File::open("foo.txt")?;
473 /// let mut buffer = [0; 10];
475 /// // read up to 10 bytes
476 /// f.read(&mut buffer)?;
478 /// let mut buffer = Vec::new();
479 /// // read the whole file
480 /// f.read_to_end(&mut buffer)?;
482 /// // read into a String, so that you don't need to do the conversion.
483 /// let mut buffer = String::new();
484 /// f.read_to_string(&mut buffer)?;
486 /// // and more! See the other methods for more details.
491 /// Read from [`&str`] because [`&[u8]`][prim@slice] implements `Read`:
495 /// use std::io::prelude::*;
497 /// fn main() -> io::Result<()> {
498 /// let mut b = "This string will be read".as_bytes();
499 /// let mut buffer = [0; 10];
501 /// // read up to 10 bytes
502 /// b.read(&mut buffer)?;
504 /// // etc... it works exactly as a File does!
509 /// [`read()`]: Read::read
510 /// [`&str`]: prim@str
511 /// [`std::io`]: self
512 /// [`File`]: crate::fs::File
513 #[stable(feature = "rust1", since = "1.0.0")]
514 #[doc(notable_trait)]
516 /// Pull some bytes from this source into the specified buffer, returning
517 /// how many bytes were read.
519 /// This function does not provide any guarantees about whether it blocks
520 /// waiting for data, but if an object needs to block for a read and cannot,
521 /// it will typically signal this via an [`Err`] return value.
523 /// If the return value of this method is [`Ok(n)`], then implementations must
524 /// guarantee that `0 <= n <= buf.len()`. A nonzero `n` value indicates
525 /// that the buffer `buf` has been filled in with `n` bytes of data from this
526 /// source. If `n` is `0`, then it can indicate one of two scenarios:
528 /// 1. This reader has reached its "end of file" and will likely no longer
529 /// be able to produce bytes. Note that this does not mean that the
530 /// reader will *always* no longer be able to produce bytes. As an example,
531 /// on Linux, this method will call the `recv` syscall for a [`TcpStream`],
532 /// where returning zero indicates the connection was shut down correctly. While
533 /// for [`File`], it is possible to reach the end of file and get zero as result,
534 /// but if more data is appended to the file, future calls to `read` will return
536 /// 2. The buffer specified was 0 bytes in length.
538 /// It is not an error if the returned value `n` is smaller than the buffer size,
539 /// even when the reader is not at the end of the stream yet.
540 /// This may happen for example because fewer bytes are actually available right now
541 /// (e. g. being close to end-of-file) or because read() was interrupted by a signal.
543 /// As this trait is safe to implement, callers cannot rely on `n <= buf.len()` for safety.
544 /// Extra care needs to be taken when `unsafe` functions are used to access the read bytes.
545 /// Callers have to ensure that no unchecked out-of-bounds accesses are possible even if
548 /// No guarantees are provided about the contents of `buf` when this
549 /// function is called, implementations cannot rely on any property of the
550 /// contents of `buf` being true. It is recommended that *implementations*
551 /// only write data to `buf` instead of reading its contents.
553 /// Correspondingly, however, *callers* of this method may not assume any guarantees
554 /// about how the implementation uses `buf`. The trait is safe to implement,
555 /// so it is possible that the code that's supposed to write to the buffer might also read
556 /// from it. It is your responsibility to make sure that `buf` is initialized
557 /// before calling `read`. Calling `read` with an uninitialized `buf` (of the kind one
558 /// obtains via [`MaybeUninit<T>`]) is not safe, and can lead to undefined behavior.
560 /// [`MaybeUninit<T>`]: crate::mem::MaybeUninit
564 /// If this function encounters any form of I/O or other error, an error
565 /// variant will be returned. If an error is returned then it must be
566 /// guaranteed that no bytes were read.
568 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
569 /// operation should be retried if there is nothing else to do.
573 /// [`File`]s implement `Read`:
576 /// [`File`]: crate::fs::File
577 /// [`TcpStream`]: crate::net::TcpStream
581 /// use std::io::prelude::*;
582 /// use std::fs::File;
584 /// fn main() -> io::Result<()> {
585 /// let mut f = File::open("foo.txt")?;
586 /// let mut buffer = [0; 10];
588 /// // read up to 10 bytes
589 /// let n = f.read(&mut buffer[..])?;
591 /// println!("The bytes: {:?}", &buffer[..n]);
595 #[stable(feature = "rust1", since = "1.0.0")]
596 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
598 /// Like `read`, except that it reads into a slice of buffers.
600 /// Data is copied to fill each buffer in order, with the final buffer
601 /// written to possibly being only partially filled. This method must
602 /// behave equivalently to a single call to `read` with concatenated
605 /// The default implementation calls `read` with either the first nonempty
606 /// buffer provided, or an empty one if none exists.
607 #[stable(feature = "iovec", since = "1.36.0")]
608 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
609 default_read_vectored(|b| self.read(b), bufs)
612 /// Determines if this `Read`er has an efficient `read_vectored`
615 /// If a `Read`er does not override the default `read_vectored`
616 /// implementation, code using it may want to avoid the method all together
617 /// and coalesce writes into a single buffer for higher performance.
619 /// The default implementation returns `false`.
620 #[unstable(feature = "can_vector", issue = "69941")]
621 fn is_read_vectored(&self) -> bool {
625 /// Determines if this `Read`er can work with buffers of uninitialized
628 /// The default implementation returns an initializer which will zero
631 /// If a `Read`er guarantees that it can work properly with uninitialized
632 /// memory, it should call [`Initializer::nop()`]. See the documentation for
633 /// [`Initializer`] for details.
635 /// The behavior of this method must be independent of the state of the
636 /// `Read`er - the method only takes `&self` so that it can be used through
641 /// This method is unsafe because a `Read`er could otherwise return a
642 /// non-zeroing `Initializer` from another `Read` type without an `unsafe`
644 #[unstable(feature = "read_initializer", issue = "42788")]
646 unsafe fn initializer(&self) -> Initializer {
647 Initializer::zeroing()
650 /// Read all bytes until EOF in this source, placing them into `buf`.
652 /// All bytes read from this source will be appended to the specified buffer
653 /// `buf`. This function will continuously call [`read()`] to append more data to
654 /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of
655 /// non-[`ErrorKind::Interrupted`] kind.
657 /// If successful, this function will return the total number of bytes read.
661 /// If this function encounters an error of the kind
662 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
665 /// If any other read error is encountered then this function immediately
666 /// returns. Any bytes which have already been read will be appended to
671 /// [`File`]s implement `Read`:
673 /// [`read()`]: Read::read
675 /// [`File`]: crate::fs::File
679 /// use std::io::prelude::*;
680 /// use std::fs::File;
682 /// fn main() -> io::Result<()> {
683 /// let mut f = File::open("foo.txt")?;
684 /// let mut buffer = Vec::new();
686 /// // read the whole file
687 /// f.read_to_end(&mut buffer)?;
692 /// (See also the [`std::fs::read`] convenience function for reading from a
695 /// [`std::fs::read`]: crate::fs::read
696 #[stable(feature = "rust1", since = "1.0.0")]
697 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
698 read_to_end(self, buf)
701 /// Read all bytes until EOF in this source, appending them to `buf`.
703 /// If successful, this function returns the number of bytes which were read
704 /// and appended to `buf`.
708 /// If the data in this stream is *not* valid UTF-8 then an error is
709 /// returned and `buf` is unchanged.
711 /// See [`read_to_end`] for other error semantics.
713 /// [`read_to_end`]: Read::read_to_end
717 /// [`File`]s implement `Read`:
719 /// [`File`]: crate::fs::File
723 /// use std::io::prelude::*;
724 /// use std::fs::File;
726 /// fn main() -> io::Result<()> {
727 /// let mut f = File::open("foo.txt")?;
728 /// let mut buffer = String::new();
730 /// f.read_to_string(&mut buffer)?;
735 /// (See also the [`std::fs::read_to_string`] convenience function for
736 /// reading from a file.)
738 /// [`std::fs::read_to_string`]: crate::fs::read_to_string
739 #[stable(feature = "rust1", since = "1.0.0")]
740 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
741 // Note that we do *not* call `.read_to_end()` here. We are passing
742 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
743 // method to fill it up. An arbitrary implementation could overwrite the
744 // entire contents of the vector, not just append to it (which is what
745 // we are expecting).
747 // To prevent extraneously checking the UTF-8-ness of the entire buffer
748 // we pass it to our hardcoded `read_to_end` implementation which we
749 // know is guaranteed to only read data into the end of the buffer.
750 append_to_string(buf, |b| read_to_end(self, b))
753 /// Read the exact number of bytes required to fill `buf`.
755 /// This function reads as many bytes as necessary to completely fill the
756 /// specified buffer `buf`.
758 /// No guarantees are provided about the contents of `buf` when this
759 /// function is called, implementations cannot rely on any property of the
760 /// contents of `buf` being true. It is recommended that implementations
761 /// only write data to `buf` instead of reading its contents. The
762 /// documentation on [`read`] has a more detailed explanation on this
767 /// If this function encounters an error of the kind
768 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
771 /// If this function encounters an "end of file" before completely filling
772 /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
773 /// The contents of `buf` are unspecified in this case.
775 /// If any other read error is encountered then this function immediately
776 /// returns. The contents of `buf` are unspecified in this case.
778 /// If this function returns an error, it is unspecified how many bytes it
779 /// has read, but it will never read more than would be necessary to
780 /// completely fill the buffer.
784 /// [`File`]s implement `Read`:
786 /// [`read`]: Read::read
787 /// [`File`]: crate::fs::File
791 /// use std::io::prelude::*;
792 /// use std::fs::File;
794 /// fn main() -> io::Result<()> {
795 /// let mut f = File::open("foo.txt")?;
796 /// let mut buffer = [0; 10];
798 /// // read exactly 10 bytes
799 /// f.read_exact(&mut buffer)?;
803 #[stable(feature = "read_exact", since = "1.6.0")]
804 fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
805 default_read_exact(self, buf)
808 /// Creates a "by reference" adaptor for this instance of `Read`.
810 /// The returned adaptor also implements `Read` and will simply borrow this
815 /// [`File`]s implement `Read`:
817 /// [`File`]: crate::fs::File
821 /// use std::io::Read;
822 /// use std::fs::File;
824 /// fn main() -> io::Result<()> {
825 /// let mut f = File::open("foo.txt")?;
826 /// let mut buffer = Vec::new();
827 /// let mut other_buffer = Vec::new();
830 /// let reference = f.by_ref();
832 /// // read at most 5 bytes
833 /// reference.take(5).read_to_end(&mut buffer)?;
835 /// } // drop our &mut reference so we can use f again
837 /// // original file still usable, read the rest
838 /// f.read_to_end(&mut other_buffer)?;
842 #[stable(feature = "rust1", since = "1.0.0")]
843 fn by_ref(&mut self) -> &mut Self
850 /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
852 /// The returned type implements [`Iterator`] where the `Item` is
853 /// [`Result`]`<`[`u8`]`, `[`io::Error`]`>`.
854 /// The yielded item is [`Ok`] if a byte was successfully read and [`Err`]
855 /// otherwise. EOF is mapped to returning [`None`] from this iterator.
859 /// [`File`]s implement `Read`:
861 /// [`File`]: crate::fs::File
862 /// [`Result`]: crate::result::Result
863 /// [`io::Error`]: self::Error
867 /// use std::io::prelude::*;
868 /// use std::fs::File;
870 /// fn main() -> io::Result<()> {
871 /// let mut f = File::open("foo.txt")?;
873 /// for byte in f.bytes() {
874 /// println!("{}", byte.unwrap());
879 #[stable(feature = "rust1", since = "1.0.0")]
880 fn bytes(self) -> Bytes<Self>
884 Bytes { inner: self }
887 /// Creates an adaptor which will chain this stream with another.
889 /// The returned `Read` instance will first read all bytes from this object
890 /// until EOF is encountered. Afterwards the output is equivalent to the
891 /// output of `next`.
895 /// [`File`]s implement `Read`:
897 /// [`File`]: crate::fs::File
901 /// use std::io::prelude::*;
902 /// use std::fs::File;
904 /// fn main() -> io::Result<()> {
905 /// let mut f1 = File::open("foo.txt")?;
906 /// let mut f2 = File::open("bar.txt")?;
908 /// let mut handle = f1.chain(f2);
909 /// let mut buffer = String::new();
911 /// // read the value into a String. We could use any Read method here,
912 /// // this is just one example.
913 /// handle.read_to_string(&mut buffer)?;
917 #[stable(feature = "rust1", since = "1.0.0")]
918 fn chain<R: Read>(self, next: R) -> Chain<Self, R>
922 Chain { first: self, second: next, done_first: false }
925 /// Creates an adaptor which will read at most `limit` bytes from it.
927 /// This function returns a new instance of `Read` which will read at most
928 /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
929 /// read errors will not count towards the number of bytes read and future
930 /// calls to [`read()`] may succeed.
934 /// [`File`]s implement `Read`:
936 /// [`File`]: crate::fs::File
938 /// [`read()`]: Read::read
942 /// use std::io::prelude::*;
943 /// use std::fs::File;
945 /// fn main() -> io::Result<()> {
946 /// let mut f = File::open("foo.txt")?;
947 /// let mut buffer = [0; 5];
949 /// // read at most five bytes
950 /// let mut handle = f.take(5);
952 /// handle.read(&mut buffer)?;
956 #[stable(feature = "rust1", since = "1.0.0")]
957 fn take(self, limit: u64) -> Take<Self>
961 Take { inner: self, limit }
965 /// Read all bytes from a [reader][Read] into a new [`String`].
967 /// This is a convenience function for [`Read::read_to_string`]. Using this
968 /// function avoids having to create a variable first and provides more type
969 /// safety since you can only get the buffer out if there were no errors. (If you
970 /// use [`Read::read_to_string`] you have to remember to check whether the read
971 /// succeeded because otherwise your buffer will be empty or only partially full.)
975 /// The downside of this function's increased ease of use and type safety is
976 /// that it gives you less control over performance. For example, you can't
977 /// pre-allocate memory like you can using [`String::with_capacity`] and
978 /// [`Read::read_to_string`]. Also, you can't re-use the buffer if an error
979 /// occurs while reading.
981 /// In many cases, this function's performance will be adequate and the ease of use
982 /// and type safety tradeoffs will be worth it. However, there are cases where you
983 /// need more control over performance, and in those cases you should definitely use
984 /// [`Read::read_to_string`] directly.
988 /// This function forces you to handle errors because the output (the `String`)
989 /// is wrapped in a [`Result`]. See [`Read::read_to_string`] for the errors
990 /// that can occur. If any error occurs, you will get an [`Err`], so you
991 /// don't have to worry about your buffer being empty or partially full.
996 /// #![feature(io_read_to_string)]
999 /// fn main() -> io::Result<()> {
1000 /// let stdin = io::read_to_string(&mut io::stdin())?;
1001 /// println!("Stdin was:");
1002 /// println!("{}", stdin);
1006 #[unstable(feature = "io_read_to_string", issue = "80218")]
1007 pub fn read_to_string<R: Read>(reader: &mut R) -> Result<String> {
1008 let mut buf = String::new();
1009 reader.read_to_string(&mut buf)?;
1013 /// A buffer type used with `Read::read_vectored`.
1015 /// It is semantically a wrapper around an `&mut [u8]`, but is guaranteed to be
1016 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
1018 #[stable(feature = "iovec", since = "1.36.0")]
1019 #[repr(transparent)]
1020 pub struct IoSliceMut<'a>(sys::io::IoSliceMut<'a>);
1022 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1023 unsafe impl<'a> Send for IoSliceMut<'a> {}
1025 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1026 unsafe impl<'a> Sync for IoSliceMut<'a> {}
1028 #[stable(feature = "iovec", since = "1.36.0")]
1029 impl<'a> fmt::Debug for IoSliceMut<'a> {
1030 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1031 fmt::Debug::fmt(self.0.as_slice(), fmt)
1035 impl<'a> IoSliceMut<'a> {
1036 /// Creates a new `IoSliceMut` wrapping a byte slice.
1040 /// Panics on Windows if the slice is larger than 4GB.
1041 #[stable(feature = "iovec", since = "1.36.0")]
1043 pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> {
1044 IoSliceMut(sys::io::IoSliceMut::new(buf))
1047 /// Advance the internal cursor of the slice.
1049 /// Also see [`IoSliceMut::advance_slices`] to advance the cursors of
1050 /// multiple buffers.
1055 /// #![feature(io_slice_advance)]
1057 /// use std::io::IoSliceMut;
1058 /// use std::ops::Deref;
1060 /// let mut data = [1; 8];
1061 /// let mut buf = IoSliceMut::new(&mut data);
1063 /// // Mark 3 bytes as read.
1065 /// assert_eq!(buf.deref(), [1; 5].as_ref());
1067 #[unstable(feature = "io_slice_advance", issue = "62726")]
1069 pub fn advance(&mut self, n: usize) {
1073 /// Advance the internal cursor of the slices.
1077 /// Elements in the slice may be modified if the cursor is not advanced to
1078 /// the end of the slice. For example if we have a slice of buffers with 2
1079 /// `IoSliceMut`s, both of length 8, and we advance the cursor by 10 bytes
1080 /// the first `IoSliceMut` will be untouched however the second will be
1081 /// modified to remove the first 2 bytes (10 - 8).
1086 /// #![feature(io_slice_advance)]
1088 /// use std::io::IoSliceMut;
1089 /// use std::ops::Deref;
1091 /// let mut buf1 = [1; 8];
1092 /// let mut buf2 = [2; 16];
1093 /// let mut buf3 = [3; 8];
1094 /// let mut bufs = &mut [
1095 /// IoSliceMut::new(&mut buf1),
1096 /// IoSliceMut::new(&mut buf2),
1097 /// IoSliceMut::new(&mut buf3),
1100 /// // Mark 10 bytes as read.
1101 /// IoSliceMut::advance_slices(&mut bufs, 10);
1102 /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1103 /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1105 #[unstable(feature = "io_slice_advance", issue = "62726")]
1107 pub fn advance_slices(bufs: &mut &mut [IoSliceMut<'a>], n: usize) {
1108 // Number of buffers to remove.
1110 // Total length of all the to be removed buffers.
1111 let mut accumulated_len = 0;
1112 for buf in bufs.iter() {
1113 if accumulated_len + buf.len() > n {
1116 accumulated_len += buf.len();
1121 *bufs = &mut replace(bufs, &mut [])[remove..];
1122 if !bufs.is_empty() {
1123 bufs[0].advance(n - accumulated_len)
1128 #[stable(feature = "iovec", since = "1.36.0")]
1129 impl<'a> Deref for IoSliceMut<'a> {
1133 fn deref(&self) -> &[u8] {
1138 #[stable(feature = "iovec", since = "1.36.0")]
1139 impl<'a> DerefMut for IoSliceMut<'a> {
1141 fn deref_mut(&mut self) -> &mut [u8] {
1142 self.0.as_mut_slice()
1146 /// A buffer type used with `Write::write_vectored`.
1148 /// It is semantically a wrapper around an `&[u8]`, but is guaranteed to be
1149 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
1151 #[stable(feature = "iovec", since = "1.36.0")]
1152 #[derive(Copy, Clone)]
1153 #[repr(transparent)]
1154 pub struct IoSlice<'a>(sys::io::IoSlice<'a>);
1156 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1157 unsafe impl<'a> Send for IoSlice<'a> {}
1159 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1160 unsafe impl<'a> Sync for IoSlice<'a> {}
1162 #[stable(feature = "iovec", since = "1.36.0")]
1163 impl<'a> fmt::Debug for IoSlice<'a> {
1164 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1165 fmt::Debug::fmt(self.0.as_slice(), fmt)
1169 impl<'a> IoSlice<'a> {
1170 /// Creates a new `IoSlice` wrapping a byte slice.
1174 /// Panics on Windows if the slice is larger than 4GB.
1175 #[stable(feature = "iovec", since = "1.36.0")]
1177 pub fn new(buf: &'a [u8]) -> IoSlice<'a> {
1178 IoSlice(sys::io::IoSlice::new(buf))
1181 /// Advance the internal cursor of the slice.
1183 /// Also see [`IoSlice::advance_slices`] to advance the cursors of multiple
1189 /// #![feature(io_slice_advance)]
1191 /// use std::io::IoSlice;
1192 /// use std::ops::Deref;
1194 /// let mut data = [1; 8];
1195 /// let mut buf = IoSlice::new(&mut data);
1197 /// // Mark 3 bytes as read.
1199 /// assert_eq!(buf.deref(), [1; 5].as_ref());
1201 #[unstable(feature = "io_slice_advance", issue = "62726")]
1203 pub fn advance(&mut self, n: usize) {
1207 /// Advance the internal cursor of the slices.
1211 /// Elements in the slice may be modified if the cursor is not advanced to
1212 /// the end of the slice. For example if we have a slice of buffers with 2
1213 /// `IoSlice`s, both of length 8, and we advance the cursor by 10 bytes the
1214 /// first `IoSlice` will be untouched however the second will be modified to
1215 /// remove the first 2 bytes (10 - 8).
1220 /// #![feature(io_slice_advance)]
1222 /// use std::io::IoSlice;
1223 /// use std::ops::Deref;
1225 /// let buf1 = [1; 8];
1226 /// let buf2 = [2; 16];
1227 /// let buf3 = [3; 8];
1228 /// let mut bufs = &mut [
1229 /// IoSlice::new(&buf1),
1230 /// IoSlice::new(&buf2),
1231 /// IoSlice::new(&buf3),
1234 /// // Mark 10 bytes as written.
1235 /// IoSlice::advance_slices(&mut bufs, 10);
1236 /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1237 /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1238 #[unstable(feature = "io_slice_advance", issue = "62726")]
1240 pub fn advance_slices(bufs: &mut &mut [IoSlice<'a>], n: usize) {
1241 // Number of buffers to remove.
1243 // Total length of all the to be removed buffers.
1244 let mut accumulated_len = 0;
1245 for buf in bufs.iter() {
1246 if accumulated_len + buf.len() > n {
1249 accumulated_len += buf.len();
1254 *bufs = &mut replace(bufs, &mut [])[remove..];
1255 if !bufs.is_empty() {
1256 bufs[0].advance(n - accumulated_len)
1261 #[stable(feature = "iovec", since = "1.36.0")]
1262 impl<'a> Deref for IoSlice<'a> {
1266 fn deref(&self) -> &[u8] {
1271 /// A type used to conditionally initialize buffers passed to `Read` methods.
1272 #[unstable(feature = "read_initializer", issue = "42788")]
1274 pub struct Initializer(bool);
1277 /// Returns a new `Initializer` which will zero out buffers.
1278 #[unstable(feature = "read_initializer", issue = "42788")]
1280 pub fn zeroing() -> Initializer {
1284 /// Returns a new `Initializer` which will not zero out buffers.
1288 /// This may only be called by `Read`ers which guarantee that they will not
1289 /// read from buffers passed to `Read` methods, and that the return value of
1290 /// the method accurately reflects the number of bytes that have been
1291 /// written to the head of the buffer.
1292 #[unstable(feature = "read_initializer", issue = "42788")]
1294 pub unsafe fn nop() -> Initializer {
1298 /// Indicates if a buffer should be initialized.
1299 #[unstable(feature = "read_initializer", issue = "42788")]
1301 pub fn should_initialize(&self) -> bool {
1305 /// Initializes a buffer if necessary.
1306 #[unstable(feature = "read_initializer", issue = "42788")]
1308 pub fn initialize(&self, buf: &mut [u8]) {
1309 if self.should_initialize() {
1310 unsafe { ptr::write_bytes(buf.as_mut_ptr(), 0, buf.len()) }
1315 /// A trait for objects which are byte-oriented sinks.
1317 /// Implementors of the `Write` trait are sometimes called 'writers'.
1319 /// Writers are defined by two required methods, [`write`] and [`flush`]:
1321 /// * The [`write`] method will attempt to write some data into the object,
1322 /// returning how many bytes were successfully written.
1324 /// * The [`flush`] method is useful for adaptors and explicit buffers
1325 /// themselves for ensuring that all buffered data has been pushed out to the
1328 /// Writers are intended to be composable with one another. Many implementors
1329 /// throughout [`std::io`] take and provide types which implement the `Write`
1332 /// [`write`]: Write::write
1333 /// [`flush`]: Write::flush
1334 /// [`std::io`]: self
1339 /// use std::io::prelude::*;
1340 /// use std::fs::File;
1342 /// fn main() -> std::io::Result<()> {
1343 /// let data = b"some bytes";
1345 /// let mut pos = 0;
1346 /// let mut buffer = File::create("foo.txt")?;
1348 /// while pos < data.len() {
1349 /// let bytes_written = buffer.write(&data[pos..])?;
1350 /// pos += bytes_written;
1356 /// The trait also provides convenience methods like [`write_all`], which calls
1357 /// `write` in a loop until its entire input has been written.
1359 /// [`write_all`]: Write::write_all
1360 #[stable(feature = "rust1", since = "1.0.0")]
1361 #[doc(notable_trait)]
1363 /// Write a buffer into this writer, returning how many bytes were written.
1365 /// This function will attempt to write the entire contents of `buf`, but
1366 /// the entire write may not succeed, or the write may also generate an
1367 /// error. A call to `write` represents *at most one* attempt to write to
1368 /// any wrapped object.
1370 /// Calls to `write` are not guaranteed to block waiting for data to be
1371 /// written, and a write which would otherwise block can be indicated through
1372 /// an [`Err`] variant.
1374 /// If the return value is [`Ok(n)`] then it must be guaranteed that
1375 /// `n <= buf.len()`. A return value of `0` typically means that the
1376 /// underlying object is no longer able to accept bytes and will likely not
1377 /// be able to in the future as well, or that the buffer provided is empty.
1381 /// Each call to `write` may generate an I/O error indicating that the
1382 /// operation could not be completed. If an error is returned then no bytes
1383 /// in the buffer were written to this writer.
1385 /// It is **not** considered an error if the entire buffer could not be
1386 /// written to this writer.
1388 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the
1389 /// write operation should be retried if there is nothing else to do.
1394 /// use std::io::prelude::*;
1395 /// use std::fs::File;
1397 /// fn main() -> std::io::Result<()> {
1398 /// let mut buffer = File::create("foo.txt")?;
1400 /// // Writes some prefix of the byte string, not necessarily all of it.
1401 /// buffer.write(b"some bytes")?;
1407 #[stable(feature = "rust1", since = "1.0.0")]
1408 fn write(&mut self, buf: &[u8]) -> Result<usize>;
1410 /// Like [`write`], except that it writes from a slice of buffers.
1412 /// Data is copied from each buffer in order, with the final buffer
1413 /// read from possibly being only partially consumed. This method must
1414 /// behave as a call to [`write`] with the buffers concatenated would.
1416 /// The default implementation calls [`write`] with either the first nonempty
1417 /// buffer provided, or an empty one if none exists.
1419 /// [`write`]: Write::write
1420 #[stable(feature = "iovec", since = "1.36.0")]
1421 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize> {
1422 default_write_vectored(|b| self.write(b), bufs)
1425 /// Determines if this `Write`r has an efficient [`write_vectored`]
1428 /// If a `Write`r does not override the default [`write_vectored`]
1429 /// implementation, code using it may want to avoid the method all together
1430 /// and coalesce writes into a single buffer for higher performance.
1432 /// The default implementation returns `false`.
1434 /// [`write_vectored`]: Write::write_vectored
1435 #[unstable(feature = "can_vector", issue = "69941")]
1436 fn is_write_vectored(&self) -> bool {
1440 /// Flush this output stream, ensuring that all intermediately buffered
1441 /// contents reach their destination.
1445 /// It is considered an error if not all bytes could be written due to
1446 /// I/O errors or EOF being reached.
1451 /// use std::io::prelude::*;
1452 /// use std::io::BufWriter;
1453 /// use std::fs::File;
1455 /// fn main() -> std::io::Result<()> {
1456 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
1458 /// buffer.write_all(b"some bytes")?;
1459 /// buffer.flush()?;
1463 #[stable(feature = "rust1", since = "1.0.0")]
1464 fn flush(&mut self) -> Result<()>;
1466 /// Attempts to write an entire buffer into this writer.
1468 /// This method will continuously call [`write`] until there is no more data
1469 /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is
1470 /// returned. This method will not return until the entire buffer has been
1471 /// successfully written or such an error occurs. The first error that is
1472 /// not of [`ErrorKind::Interrupted`] kind generated from this method will be
1475 /// If the buffer contains no data, this will never call [`write`].
1479 /// This function will return the first error of
1480 /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns.
1482 /// [`write`]: Write::write
1487 /// use std::io::prelude::*;
1488 /// use std::fs::File;
1490 /// fn main() -> std::io::Result<()> {
1491 /// let mut buffer = File::create("foo.txt")?;
1493 /// buffer.write_all(b"some bytes")?;
1497 #[stable(feature = "rust1", since = "1.0.0")]
1498 fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
1499 while !buf.is_empty() {
1500 match self.write(buf) {
1502 return Err(Error::new_const(
1503 ErrorKind::WriteZero,
1504 &"failed to write whole buffer",
1507 Ok(n) => buf = &buf[n..],
1508 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1509 Err(e) => return Err(e),
1515 /// Attempts to write multiple buffers into this writer.
1517 /// This method will continuously call [`write_vectored`] until there is no
1518 /// more data to be written or an error of non-[`ErrorKind::Interrupted`]
1519 /// kind is returned. This method will not return until all buffers have
1520 /// been successfully written or such an error occurs. The first error that
1521 /// is not of [`ErrorKind::Interrupted`] kind generated from this method
1522 /// will be returned.
1524 /// If the buffer contains no data, this will never call [`write_vectored`].
1528 /// Unlike [`write_vectored`], this takes a *mutable* reference to
1529 /// a slice of [`IoSlice`]s, not an immutable one. That's because we need to
1530 /// modify the slice to keep track of the bytes already written.
1532 /// Once this function returns, the contents of `bufs` are unspecified, as
1533 /// this depends on how many calls to [`write_vectored`] were necessary. It is
1534 /// best to understand this function as taking ownership of `bufs` and to
1535 /// not use `bufs` afterwards. The underlying buffers, to which the
1536 /// [`IoSlice`]s point (but not the [`IoSlice`]s themselves), are unchanged and
1539 /// [`write_vectored`]: Write::write_vectored
1544 /// #![feature(write_all_vectored)]
1545 /// # fn main() -> std::io::Result<()> {
1547 /// use std::io::{Write, IoSlice};
1549 /// let mut writer = Vec::new();
1550 /// let bufs = &mut [
1551 /// IoSlice::new(&[1]),
1552 /// IoSlice::new(&[2, 3]),
1553 /// IoSlice::new(&[4, 5, 6]),
1556 /// writer.write_all_vectored(bufs)?;
1557 /// // Note: the contents of `bufs` is now undefined, see the Notes section.
1559 /// assert_eq!(writer, &[1, 2, 3, 4, 5, 6]);
1562 #[unstable(feature = "write_all_vectored", issue = "70436")]
1563 fn write_all_vectored(&mut self, mut bufs: &mut [IoSlice<'_>]) -> Result<()> {
1564 // Guarantee that bufs is empty if it contains no data,
1565 // to avoid calling write_vectored if there is no data to be written.
1566 IoSlice::advance_slices(&mut bufs, 0);
1567 while !bufs.is_empty() {
1568 match self.write_vectored(bufs) {
1570 return Err(Error::new_const(
1571 ErrorKind::WriteZero,
1572 &"failed to write whole buffer",
1575 Ok(n) => IoSlice::advance_slices(&mut bufs, n),
1576 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1577 Err(e) => return Err(e),
1583 /// Writes a formatted string into this writer, returning any error
1586 /// This method is primarily used to interface with the
1587 /// [`format_args!()`] macro, but it is rare that this should
1588 /// explicitly be called. The [`write!()`] macro should be favored to
1589 /// invoke this method instead.
1591 /// This function internally uses the [`write_all`] method on
1592 /// this trait and hence will continuously write data so long as no errors
1593 /// are received. This also means that partial writes are not indicated in
1596 /// [`write_all`]: Write::write_all
1600 /// This function will return any I/O error reported while formatting.
1605 /// use std::io::prelude::*;
1606 /// use std::fs::File;
1608 /// fn main() -> std::io::Result<()> {
1609 /// let mut buffer = File::create("foo.txt")?;
1612 /// write!(buffer, "{:.*}", 2, 1.234567)?;
1613 /// // turns into this:
1614 /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1618 #[stable(feature = "rust1", since = "1.0.0")]
1619 fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> Result<()> {
1620 // Create a shim which translates a Write to a fmt::Write and saves
1621 // off I/O errors. instead of discarding them
1622 struct Adaptor<'a, T: ?Sized + 'a> {
1627 impl<T: Write + ?Sized> fmt::Write for Adaptor<'_, T> {
1628 fn write_str(&mut self, s: &str) -> fmt::Result {
1629 match self.inner.write_all(s.as_bytes()) {
1632 self.error = Err(e);
1639 let mut output = Adaptor { inner: self, error: Ok(()) };
1640 match fmt::write(&mut output, fmt) {
1643 // check if the error came from the underlying `Write` or not
1644 if output.error.is_err() {
1647 Err(Error::new_const(ErrorKind::Other, &"formatter error"))
1653 /// Creates a "by reference" adaptor for this instance of `Write`.
1655 /// The returned adaptor also implements `Write` and will simply borrow this
1661 /// use std::io::Write;
1662 /// use std::fs::File;
1664 /// fn main() -> std::io::Result<()> {
1665 /// let mut buffer = File::create("foo.txt")?;
1667 /// let reference = buffer.by_ref();
1669 /// // we can use reference just like our original buffer
1670 /// reference.write_all(b"some bytes")?;
1674 #[stable(feature = "rust1", since = "1.0.0")]
1675 fn by_ref(&mut self) -> &mut Self
1683 /// The `Seek` trait provides a cursor which can be moved within a stream of
1686 /// The stream typically has a fixed size, allowing seeking relative to either
1687 /// end or the current offset.
1691 /// [`File`]s implement `Seek`:
1693 /// [`File`]: crate::fs::File
1697 /// use std::io::prelude::*;
1698 /// use std::fs::File;
1699 /// use std::io::SeekFrom;
1701 /// fn main() -> io::Result<()> {
1702 /// let mut f = File::open("foo.txt")?;
1704 /// // move the cursor 42 bytes from the start of the file
1705 /// f.seek(SeekFrom::Start(42))?;
1709 #[stable(feature = "rust1", since = "1.0.0")]
1711 /// Seek to an offset, in bytes, in a stream.
1713 /// A seek beyond the end of a stream is allowed, but behavior is defined
1714 /// by the implementation.
1716 /// If the seek operation completed successfully,
1717 /// this method returns the new position from the start of the stream.
1718 /// That position can be used later with [`SeekFrom::Start`].
1722 /// Seeking can fail, for example because it might involve flushing a buffer.
1724 /// Seeking to a negative offset is considered an error.
1725 #[stable(feature = "rust1", since = "1.0.0")]
1726 fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1728 /// Rewind to the beginning of a stream.
1730 /// This is a convenience method, equivalent to `seek(SeekFrom::Start(0))`.
1734 /// Rewinding can fail, for example because it might involve flushing a buffer.
1739 /// #![feature(seek_rewind)]
1740 /// use std::io::{Read, Seek, Write};
1741 /// use std::fs::OpenOptions;
1743 /// let mut f = OpenOptions::new()
1747 /// .open("foo.txt").unwrap();
1749 /// let hello = "Hello!\n";
1750 /// write!(f, "{}", hello).unwrap();
1751 /// f.rewind().unwrap();
1753 /// let mut buf = String::new();
1754 /// f.read_to_string(&mut buf).unwrap();
1755 /// assert_eq!(&buf, hello);
1757 #[unstable(feature = "seek_rewind", issue = "85149")]
1758 fn rewind(&mut self) -> Result<()> {
1759 self.seek(SeekFrom::Start(0))?;
1763 /// Returns the length of this stream (in bytes).
1765 /// This method is implemented using up to three seek operations. If this
1766 /// method returns successfully, the seek position is unchanged (i.e. the
1767 /// position before calling this method is the same as afterwards).
1768 /// However, if this method returns an error, the seek position is
1771 /// If you need to obtain the length of *many* streams and you don't care
1772 /// about the seek position afterwards, you can reduce the number of seek
1773 /// operations by simply calling `seek(SeekFrom::End(0))` and using its
1774 /// return value (it is also the stream length).
1776 /// Note that length of a stream can change over time (for example, when
1777 /// data is appended to a file). So calling this method multiple times does
1778 /// not necessarily return the same length each time.
1783 /// #![feature(seek_stream_len)]
1785 /// io::{self, Seek},
1789 /// fn main() -> io::Result<()> {
1790 /// let mut f = File::open("foo.txt")?;
1792 /// let len = f.stream_len()?;
1793 /// println!("The file is currently {} bytes long", len);
1797 #[unstable(feature = "seek_stream_len", issue = "59359")]
1798 fn stream_len(&mut self) -> Result<u64> {
1799 let old_pos = self.stream_position()?;
1800 let len = self.seek(SeekFrom::End(0))?;
1802 // Avoid seeking a third time when we were already at the end of the
1803 // stream. The branch is usually way cheaper than a seek operation.
1805 self.seek(SeekFrom::Start(old_pos))?;
1811 /// Returns the current seek position from the start of the stream.
1813 /// This is equivalent to `self.seek(SeekFrom::Current(0))`.
1819 /// io::{self, BufRead, BufReader, Seek},
1823 /// fn main() -> io::Result<()> {
1824 /// let mut f = BufReader::new(File::open("foo.txt")?);
1826 /// let before = f.stream_position()?;
1827 /// f.read_line(&mut String::new())?;
1828 /// let after = f.stream_position()?;
1830 /// println!("The first line was {} bytes long", after - before);
1834 #[stable(feature = "seek_convenience", since = "1.51.0")]
1835 fn stream_position(&mut self) -> Result<u64> {
1836 self.seek(SeekFrom::Current(0))
1840 /// Enumeration of possible methods to seek within an I/O object.
1842 /// It is used by the [`Seek`] trait.
1843 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1844 #[stable(feature = "rust1", since = "1.0.0")]
1846 /// Sets the offset to the provided number of bytes.
1847 #[stable(feature = "rust1", since = "1.0.0")]
1848 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1850 /// Sets the offset to the size of this object plus the specified number of
1853 /// It is possible to seek beyond the end of an object, but it's an error to
1854 /// seek before byte 0.
1855 #[stable(feature = "rust1", since = "1.0.0")]
1856 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1858 /// Sets the offset to the current position plus the specified number of
1861 /// It is possible to seek beyond the end of an object, but it's an error to
1862 /// seek before byte 0.
1863 #[stable(feature = "rust1", since = "1.0.0")]
1864 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1867 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>) -> Result<usize> {
1870 let (done, used) = {
1871 let available = match r.fill_buf() {
1873 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1874 Err(e) => return Err(e),
1876 match memchr::memchr(delim, available) {
1878 buf.extend_from_slice(&available[..=i]);
1882 buf.extend_from_slice(available);
1883 (false, available.len())
1889 if done || used == 0 {
1895 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1896 /// to perform extra ways of reading.
1898 /// For example, reading line-by-line is inefficient without using a buffer, so
1899 /// if you want to read by line, you'll need `BufRead`, which includes a
1900 /// [`read_line`] method as well as a [`lines`] iterator.
1904 /// A locked standard input implements `BufRead`:
1908 /// use std::io::prelude::*;
1910 /// let stdin = io::stdin();
1911 /// for line in stdin.lock().lines() {
1912 /// println!("{}", line.unwrap());
1916 /// If you have something that implements [`Read`], you can use the [`BufReader`
1917 /// type][`BufReader`] to turn it into a `BufRead`.
1919 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1920 /// [`BufReader`] to the rescue!
1922 /// [`File`]: crate::fs::File
1923 /// [`read_line`]: BufRead::read_line
1924 /// [`lines`]: BufRead::lines
1927 /// use std::io::{self, BufReader};
1928 /// use std::io::prelude::*;
1929 /// use std::fs::File;
1931 /// fn main() -> io::Result<()> {
1932 /// let f = File::open("foo.txt")?;
1933 /// let f = BufReader::new(f);
1935 /// for line in f.lines() {
1936 /// println!("{}", line.unwrap());
1942 #[stable(feature = "rust1", since = "1.0.0")]
1943 pub trait BufRead: Read {
1944 /// Returns the contents of the internal buffer, filling it with more data
1945 /// from the inner reader if it is empty.
1947 /// This function is a lower-level call. It needs to be paired with the
1948 /// [`consume`] method to function properly. When calling this
1949 /// method, none of the contents will be "read" in the sense that later
1950 /// calling `read` may return the same contents. As such, [`consume`] must
1951 /// be called with the number of bytes that are consumed from this buffer to
1952 /// ensure that the bytes are never returned twice.
1954 /// [`consume`]: BufRead::consume
1956 /// An empty buffer returned indicates that the stream has reached EOF.
1960 /// This function will return an I/O error if the underlying reader was
1961 /// read, but returned an error.
1965 /// A locked standard input implements `BufRead`:
1969 /// use std::io::prelude::*;
1971 /// let stdin = io::stdin();
1972 /// let mut stdin = stdin.lock();
1974 /// let buffer = stdin.fill_buf().unwrap();
1976 /// // work with buffer
1977 /// println!("{:?}", buffer);
1979 /// // ensure the bytes we worked with aren't returned again later
1980 /// let length = buffer.len();
1981 /// stdin.consume(length);
1983 #[stable(feature = "rust1", since = "1.0.0")]
1984 fn fill_buf(&mut self) -> Result<&[u8]>;
1986 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1987 /// so they should no longer be returned in calls to `read`.
1989 /// This function is a lower-level call. It needs to be paired with the
1990 /// [`fill_buf`] method to function properly. This function does
1991 /// not perform any I/O, it simply informs this object that some amount of
1992 /// its buffer, returned from [`fill_buf`], has been consumed and should
1993 /// no longer be returned. As such, this function may do odd things if
1994 /// [`fill_buf`] isn't called before calling it.
1996 /// The `amt` must be `<=` the number of bytes in the buffer returned by
2001 /// Since `consume()` is meant to be used with [`fill_buf`],
2002 /// that method's example includes an example of `consume()`.
2004 /// [`fill_buf`]: BufRead::fill_buf
2005 #[stable(feature = "rust1", since = "1.0.0")]
2006 fn consume(&mut self, amt: usize);
2008 /// Check if the underlying `Read` has any data left to be read.
2010 /// This function may fill the buffer to check for data,
2011 /// so this functions returns `Result<bool>`, not `bool`.
2013 /// Default implementation calls `fill_buf` and checks that
2014 /// returned slice is empty (which means that there is no data left,
2015 /// since EOF is reached).
2020 /// #![feature(buf_read_has_data_left)]
2022 /// use std::io::prelude::*;
2024 /// let stdin = io::stdin();
2025 /// let mut stdin = stdin.lock();
2027 /// while stdin.has_data_left().unwrap() {
2028 /// let mut line = String::new();
2029 /// stdin.read_line(&mut line).unwrap();
2030 /// // work with line
2031 /// println!("{:?}", line);
2034 #[unstable(feature = "buf_read_has_data_left", reason = "recently added", issue = "86423")]
2035 fn has_data_left(&mut self) -> Result<bool> {
2036 self.fill_buf().map(|b| !b.is_empty())
2039 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
2041 /// This function will read bytes from the underlying stream until the
2042 /// delimiter or EOF is found. Once found, all bytes up to, and including,
2043 /// the delimiter (if found) will be appended to `buf`.
2045 /// If successful, this function will return the total number of bytes read.
2047 /// This function is blocking and should be used carefully: it is possible for
2048 /// an attacker to continuously send bytes without ever sending the delimiter
2053 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
2054 /// will otherwise return any errors returned by [`fill_buf`].
2056 /// If an I/O error is encountered then all bytes read so far will be
2057 /// present in `buf` and its length will have been adjusted appropriately.
2059 /// [`fill_buf`]: BufRead::fill_buf
2063 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2064 /// this example, we use [`Cursor`] to read all the bytes in a byte slice
2065 /// in hyphen delimited segments:
2068 /// use std::io::{self, BufRead};
2070 /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
2071 /// let mut buf = vec![];
2073 /// // cursor is at 'l'
2074 /// let num_bytes = cursor.read_until(b'-', &mut buf)
2075 /// .expect("reading from cursor won't fail");
2076 /// assert_eq!(num_bytes, 6);
2077 /// assert_eq!(buf, b"lorem-");
2080 /// // cursor is at 'i'
2081 /// let num_bytes = cursor.read_until(b'-', &mut buf)
2082 /// .expect("reading from cursor won't fail");
2083 /// assert_eq!(num_bytes, 5);
2084 /// assert_eq!(buf, b"ipsum");
2087 /// // cursor is at EOF
2088 /// let num_bytes = cursor.read_until(b'-', &mut buf)
2089 /// .expect("reading from cursor won't fail");
2090 /// assert_eq!(num_bytes, 0);
2091 /// assert_eq!(buf, b"");
2093 #[stable(feature = "rust1", since = "1.0.0")]
2094 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
2095 read_until(self, byte, buf)
2098 /// Read all bytes until a newline (the `0xA` byte) is reached, and append
2099 /// them to the provided buffer.
2101 /// This function will read bytes from the underlying stream until the
2102 /// newline delimiter (the `0xA` byte) or EOF is found. Once found, all bytes
2103 /// up to, and including, the delimiter (if found) will be appended to
2106 /// If successful, this function will return the total number of bytes read.
2108 /// If this function returns [`Ok(0)`], the stream has reached EOF.
2110 /// This function is blocking and should be used carefully: it is possible for
2111 /// an attacker to continuously send bytes without ever sending a newline
2118 /// This function has the same error semantics as [`read_until`] and will
2119 /// also return an error if the read bytes are not valid UTF-8. If an I/O
2120 /// error is encountered then `buf` may contain some bytes already read in
2121 /// the event that all data read so far was valid UTF-8.
2123 /// [`read_until`]: BufRead::read_until
2127 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2128 /// this example, we use [`Cursor`] to read all the lines in a byte slice:
2131 /// use std::io::{self, BufRead};
2133 /// let mut cursor = io::Cursor::new(b"foo\nbar");
2134 /// let mut buf = String::new();
2136 /// // cursor is at 'f'
2137 /// let num_bytes = cursor.read_line(&mut buf)
2138 /// .expect("reading from cursor won't fail");
2139 /// assert_eq!(num_bytes, 4);
2140 /// assert_eq!(buf, "foo\n");
2143 /// // cursor is at 'b'
2144 /// let num_bytes = cursor.read_line(&mut buf)
2145 /// .expect("reading from cursor won't fail");
2146 /// assert_eq!(num_bytes, 3);
2147 /// assert_eq!(buf, "bar");
2150 /// // cursor is at EOF
2151 /// let num_bytes = cursor.read_line(&mut buf)
2152 /// .expect("reading from cursor won't fail");
2153 /// assert_eq!(num_bytes, 0);
2154 /// assert_eq!(buf, "");
2156 #[stable(feature = "rust1", since = "1.0.0")]
2157 fn read_line(&mut self, buf: &mut String) -> Result<usize> {
2158 // Note that we are not calling the `.read_until` method here, but
2159 // rather our hardcoded implementation. For more details as to why, see
2160 // the comments in `read_to_end`.
2161 append_to_string(buf, |b| read_until(self, b'\n', b))
2164 /// Returns an iterator over the contents of this reader split on the byte
2167 /// The iterator returned from this function will return instances of
2168 /// [`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
2169 /// the delimiter byte at the end.
2171 /// This function will yield errors whenever [`read_until`] would have
2172 /// also yielded an error.
2174 /// [`io::Result`]: self::Result
2175 /// [`read_until`]: BufRead::read_until
2179 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2180 /// this example, we use [`Cursor`] to iterate over all hyphen delimited
2181 /// segments in a byte slice
2184 /// use std::io::{self, BufRead};
2186 /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
2188 /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
2189 /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
2190 /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
2191 /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
2192 /// assert_eq!(split_iter.next(), None);
2194 #[stable(feature = "rust1", since = "1.0.0")]
2195 fn split(self, byte: u8) -> Split<Self>
2199 Split { buf: self, delim: byte }
2202 /// Returns an iterator over the lines of this reader.
2204 /// The iterator returned from this function will yield instances of
2205 /// [`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline
2206 /// byte (the `0xA` byte) or `CRLF` (`0xD`, `0xA` bytes) at the end.
2208 /// [`io::Result`]: self::Result
2212 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2213 /// this example, we use [`Cursor`] to iterate over all the lines in a byte
2217 /// use std::io::{self, BufRead};
2219 /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
2221 /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
2222 /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
2223 /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
2224 /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
2225 /// assert_eq!(lines_iter.next(), None);
2230 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
2231 #[stable(feature = "rust1", since = "1.0.0")]
2232 fn lines(self) -> Lines<Self>
2240 /// Adaptor to chain together two readers.
2242 /// This struct is generally created by calling [`chain`] on a reader.
2243 /// Please see the documentation of [`chain`] for more details.
2245 /// [`chain`]: Read::chain
2246 #[stable(feature = "rust1", since = "1.0.0")]
2248 pub struct Chain<T, U> {
2254 impl<T, U> Chain<T, U> {
2255 /// Consumes the `Chain`, returning the wrapped readers.
2261 /// use std::io::prelude::*;
2262 /// use std::fs::File;
2264 /// fn main() -> io::Result<()> {
2265 /// let mut foo_file = File::open("foo.txt")?;
2266 /// let mut bar_file = File::open("bar.txt")?;
2268 /// let chain = foo_file.chain(bar_file);
2269 /// let (foo_file, bar_file) = chain.into_inner();
2273 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2274 pub fn into_inner(self) -> (T, U) {
2275 (self.first, self.second)
2278 /// Gets references to the underlying readers in this `Chain`.
2284 /// use std::io::prelude::*;
2285 /// use std::fs::File;
2287 /// fn main() -> io::Result<()> {
2288 /// let mut foo_file = File::open("foo.txt")?;
2289 /// let mut bar_file = File::open("bar.txt")?;
2291 /// let chain = foo_file.chain(bar_file);
2292 /// let (foo_file, bar_file) = chain.get_ref();
2296 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2297 pub fn get_ref(&self) -> (&T, &U) {
2298 (&self.first, &self.second)
2301 /// Gets mutable references to the underlying readers in this `Chain`.
2303 /// Care should be taken to avoid modifying the internal I/O state of the
2304 /// underlying readers as doing so may corrupt the internal state of this
2311 /// use std::io::prelude::*;
2312 /// use std::fs::File;
2314 /// fn main() -> io::Result<()> {
2315 /// let mut foo_file = File::open("foo.txt")?;
2316 /// let mut bar_file = File::open("bar.txt")?;
2318 /// let mut chain = foo_file.chain(bar_file);
2319 /// let (foo_file, bar_file) = chain.get_mut();
2323 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2324 pub fn get_mut(&mut self) -> (&mut T, &mut U) {
2325 (&mut self.first, &mut self.second)
2329 #[stable(feature = "rust1", since = "1.0.0")]
2330 impl<T: Read, U: Read> Read for Chain<T, U> {
2331 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2332 if !self.done_first {
2333 match self.first.read(buf)? {
2334 0 if !buf.is_empty() => self.done_first = true,
2338 self.second.read(buf)
2341 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
2342 if !self.done_first {
2343 match self.first.read_vectored(bufs)? {
2344 0 if bufs.iter().any(|b| !b.is_empty()) => self.done_first = true,
2348 self.second.read_vectored(bufs)
2351 unsafe fn initializer(&self) -> Initializer {
2352 let initializer = self.first.initializer();
2353 if initializer.should_initialize() { initializer } else { self.second.initializer() }
2357 #[stable(feature = "chain_bufread", since = "1.9.0")]
2358 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
2359 fn fill_buf(&mut self) -> Result<&[u8]> {
2360 if !self.done_first {
2361 match self.first.fill_buf()? {
2362 buf if buf.is_empty() => {
2363 self.done_first = true;
2365 buf => return Ok(buf),
2368 self.second.fill_buf()
2371 fn consume(&mut self, amt: usize) {
2372 if !self.done_first { self.first.consume(amt) } else { self.second.consume(amt) }
2376 impl<T, U> SizeHint for Chain<T, U> {
2378 fn lower_bound(&self) -> usize {
2379 SizeHint::lower_bound(&self.first) + SizeHint::lower_bound(&self.second)
2383 fn upper_bound(&self) -> Option<usize> {
2384 match (SizeHint::upper_bound(&self.first), SizeHint::upper_bound(&self.second)) {
2385 (Some(first), Some(second)) => first.checked_add(second),
2391 /// Reader adaptor which limits the bytes read from an underlying reader.
2393 /// This struct is generally created by calling [`take`] on a reader.
2394 /// Please see the documentation of [`take`] for more details.
2396 /// [`take`]: Read::take
2397 #[stable(feature = "rust1", since = "1.0.0")]
2399 pub struct Take<T> {
2405 /// Returns the number of bytes that can be read before this instance will
2410 /// This instance may reach `EOF` after reading fewer bytes than indicated by
2411 /// this method if the underlying [`Read`] instance reaches EOF.
2417 /// use std::io::prelude::*;
2418 /// use std::fs::File;
2420 /// fn main() -> io::Result<()> {
2421 /// let f = File::open("foo.txt")?;
2423 /// // read at most five bytes
2424 /// let handle = f.take(5);
2426 /// println!("limit: {}", handle.limit());
2430 #[stable(feature = "rust1", since = "1.0.0")]
2431 pub fn limit(&self) -> u64 {
2435 /// Sets the number of bytes that can be read before this instance will
2436 /// return EOF. This is the same as constructing a new `Take` instance, so
2437 /// the amount of bytes read and the previous limit value don't matter when
2438 /// calling this method.
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 mut handle = f.take(5);
2452 /// handle.set_limit(10);
2454 /// assert_eq!(handle.limit(), 10);
2458 #[stable(feature = "take_set_limit", since = "1.27.0")]
2459 pub fn set_limit(&mut self, limit: u64) {
2463 /// Consumes the `Take`, returning the wrapped reader.
2469 /// use std::io::prelude::*;
2470 /// use std::fs::File;
2472 /// fn main() -> io::Result<()> {
2473 /// let mut file = File::open("foo.txt")?;
2475 /// let mut buffer = [0; 5];
2476 /// let mut handle = file.take(5);
2477 /// handle.read(&mut buffer)?;
2479 /// let file = handle.into_inner();
2483 #[stable(feature = "io_take_into_inner", since = "1.15.0")]
2484 pub fn into_inner(self) -> T {
2488 /// Gets a reference to the underlying reader.
2494 /// use std::io::prelude::*;
2495 /// use std::fs::File;
2497 /// fn main() -> io::Result<()> {
2498 /// let mut file = File::open("foo.txt")?;
2500 /// let mut buffer = [0; 5];
2501 /// let mut handle = file.take(5);
2502 /// handle.read(&mut buffer)?;
2504 /// let file = handle.get_ref();
2508 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2509 pub fn get_ref(&self) -> &T {
2513 /// Gets a mutable reference to the underlying reader.
2515 /// Care should be taken to avoid modifying the internal I/O state of the
2516 /// underlying reader as doing so may corrupt the internal limit of this
2523 /// use std::io::prelude::*;
2524 /// use std::fs::File;
2526 /// fn main() -> io::Result<()> {
2527 /// let mut file = File::open("foo.txt")?;
2529 /// let mut buffer = [0; 5];
2530 /// let mut handle = file.take(5);
2531 /// handle.read(&mut buffer)?;
2533 /// let file = handle.get_mut();
2537 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2538 pub fn get_mut(&mut self) -> &mut T {
2543 #[stable(feature = "rust1", since = "1.0.0")]
2544 impl<T: Read> Read for Take<T> {
2545 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2546 // Don't call into inner reader at all at EOF because it may still block
2547 if self.limit == 0 {
2551 let max = cmp::min(buf.len() as u64, self.limit) as usize;
2552 let n = self.inner.read(&mut buf[..max])?;
2553 self.limit -= n as u64;
2557 unsafe fn initializer(&self) -> Initializer {
2558 self.inner.initializer()
2561 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
2562 // Pass in a reservation_size closure that respects the current value
2563 // of limit for each read. If we hit the read limit, this prevents the
2564 // final zero-byte read from allocating again.
2565 read_to_end_with_reservation(self, buf, |self_| cmp::min(self_.limit, 32) as usize)
2569 #[stable(feature = "rust1", since = "1.0.0")]
2570 impl<T: BufRead> BufRead for Take<T> {
2571 fn fill_buf(&mut self) -> Result<&[u8]> {
2572 // Don't call into inner reader at all at EOF because it may still block
2573 if self.limit == 0 {
2577 let buf = self.inner.fill_buf()?;
2578 let cap = cmp::min(buf.len() as u64, self.limit) as usize;
2582 fn consume(&mut self, amt: usize) {
2583 // Don't let callers reset the limit by passing an overlarge value
2584 let amt = cmp::min(amt as u64, self.limit) as usize;
2585 self.limit -= amt as u64;
2586 self.inner.consume(amt);
2590 impl<T> SizeHint for Take<T> {
2592 fn lower_bound(&self) -> usize {
2593 cmp::min(SizeHint::lower_bound(&self.inner) as u64, self.limit) as usize
2597 fn upper_bound(&self) -> Option<usize> {
2598 match SizeHint::upper_bound(&self.inner) {
2599 Some(upper_bound) => Some(cmp::min(upper_bound as u64, self.limit) as usize),
2600 None => self.limit.try_into().ok(),
2605 /// An iterator over `u8` values of a reader.
2607 /// This struct is generally created by calling [`bytes`] on a reader.
2608 /// Please see the documentation of [`bytes`] for more details.
2610 /// [`bytes`]: Read::bytes
2611 #[stable(feature = "rust1", since = "1.0.0")]
2613 pub struct Bytes<R> {
2617 #[stable(feature = "rust1", since = "1.0.0")]
2618 impl<R: Read> Iterator for Bytes<R> {
2619 type Item = Result<u8>;
2621 fn next(&mut self) -> Option<Result<u8>> {
2624 return match self.inner.read(slice::from_mut(&mut byte)) {
2626 Ok(..) => Some(Ok(byte)),
2627 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
2628 Err(e) => Some(Err(e)),
2633 fn size_hint(&self) -> (usize, Option<usize>) {
2634 SizeHint::size_hint(&self.inner)
2639 fn lower_bound(&self) -> usize;
2641 fn upper_bound(&self) -> Option<usize>;
2643 fn size_hint(&self) -> (usize, Option<usize>) {
2644 (self.lower_bound(), self.upper_bound())
2648 impl<T> SizeHint for T {
2650 default fn lower_bound(&self) -> usize {
2655 default fn upper_bound(&self) -> Option<usize> {
2660 impl<T> SizeHint for &mut T {
2662 fn lower_bound(&self) -> usize {
2663 SizeHint::lower_bound(*self)
2667 fn upper_bound(&self) -> Option<usize> {
2668 SizeHint::upper_bound(*self)
2672 impl<T> SizeHint for Box<T> {
2674 fn lower_bound(&self) -> usize {
2675 SizeHint::lower_bound(&**self)
2679 fn upper_bound(&self) -> Option<usize> {
2680 SizeHint::upper_bound(&**self)
2684 impl SizeHint for &[u8] {
2686 fn lower_bound(&self) -> usize {
2691 fn upper_bound(&self) -> Option<usize> {
2696 /// An iterator over the contents of an instance of `BufRead` split on a
2697 /// particular byte.
2699 /// This struct is generally created by calling [`split`] on a `BufRead`.
2700 /// Please see the documentation of [`split`] for more details.
2702 /// [`split`]: BufRead::split
2703 #[stable(feature = "rust1", since = "1.0.0")]
2705 pub struct Split<B> {
2710 #[stable(feature = "rust1", since = "1.0.0")]
2711 impl<B: BufRead> Iterator for Split<B> {
2712 type Item = Result<Vec<u8>>;
2714 fn next(&mut self) -> Option<Result<Vec<u8>>> {
2715 let mut buf = Vec::new();
2716 match self.buf.read_until(self.delim, &mut buf) {
2719 if buf[buf.len() - 1] == self.delim {
2724 Err(e) => Some(Err(e)),
2729 /// An iterator over the lines of an instance of `BufRead`.
2731 /// This struct is generally created by calling [`lines`] on a `BufRead`.
2732 /// Please see the documentation of [`lines`] for more details.
2734 /// [`lines`]: BufRead::lines
2735 #[stable(feature = "rust1", since = "1.0.0")]
2737 pub struct Lines<B> {
2741 #[stable(feature = "rust1", since = "1.0.0")]
2742 impl<B: BufRead> Iterator for Lines<B> {
2743 type Item = Result<String>;
2745 fn next(&mut self) -> Option<Result<String>> {
2746 let mut buf = String::new();
2747 match self.buf.read_line(&mut buf) {
2750 if buf.ends_with('\n') {
2752 if buf.ends_with('\r') {
2758 Err(e) => Some(Err(e)),