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 //! [`Read`]: trait.Read.html
242 //! [`Write`]: trait.Write.html
243 //! [`Seek`]: trait.Seek.html
244 //! [`BufRead`]: trait.BufRead.html
245 //! [`File`]: ../fs/struct.File.html
246 //! [`TcpStream`]: ../net/struct.TcpStream.html
247 //! [`Vec<T>`]: ../vec/struct.Vec.html
248 //! [`BufReader`]: struct.BufReader.html
249 //! [`BufWriter`]: struct.BufWriter.html
250 //! [`Write::write`]: trait.Write.html#tymethod.write
251 //! [`io::stdout`]: fn.stdout.html
252 //! [`println!`]: ../macro.println.html
253 //! [`Lines`]: struct.Lines.html
254 //! [`io::Result`]: type.Result.html
255 //! [`?` operator]: ../../book/appendix-02-operators.html
256 //! [`Read::read`]: trait.Read.html#tymethod.read
257 //! [`Result`]: ../result/enum.Result.html
258 //! [`.unwrap()`]: ../result/enum.Result.html#method.unwrap
259 // ignore-tidy-filelength
261 #![stable(feature = "rust1", since = "1.0.0")]
267 use crate::ops::{Deref, DerefMut};
273 #[stable(feature = "rust1", since = "1.0.0")]
274 pub use self::buffered::IntoInnerError;
275 #[stable(feature = "rust1", since = "1.0.0")]
276 pub use self::buffered::{BufReader, BufWriter, LineWriter};
277 #[stable(feature = "rust1", since = "1.0.0")]
278 pub use self::cursor::Cursor;
279 #[stable(feature = "rust1", since = "1.0.0")]
280 pub use self::error::{Error, ErrorKind, Result};
281 #[stable(feature = "rust1", since = "1.0.0")]
282 pub use self::stdio::{stderr, stdin, stdout, Stderr, Stdin, Stdout};
283 #[stable(feature = "rust1", since = "1.0.0")]
284 pub use self::stdio::{StderrLock, StdinLock, StdoutLock};
285 #[unstable(feature = "print_internals", issue = "none")]
286 pub use self::stdio::{_eprint, _print};
287 #[unstable(feature = "libstd_io_internals", issue = "42788")]
288 #[doc(no_inline, hidden)]
289 pub use self::stdio::{set_panic, set_print};
290 #[stable(feature = "rust1", since = "1.0.0")]
291 pub use self::util::{copy, empty, repeat, sink, Empty, Repeat, Sink};
302 const DEFAULT_BUF_SIZE: usize = crate::sys_common::io::DEFAULT_BUF_SIZE;
305 buf: &'a mut Vec<u8>,
309 impl Drop for Guard<'_> {
312 self.buf.set_len(self.len);
317 // A few methods below (read_to_string, read_line) will append data into a
318 // `String` buffer, but we need to be pretty careful when doing this. The
319 // implementation will just call `.as_mut_vec()` and then delegate to a
320 // byte-oriented reading method, but we must ensure that when returning we never
321 // leave `buf` in a state such that it contains invalid UTF-8 in its bounds.
323 // To this end, we use an RAII guard (to protect against panics) which updates
324 // the length of the string when it is dropped. This guard initially truncates
325 // the string to the prior length and only after we've validated that the
326 // new contents are valid UTF-8 do we allow it to set a longer length.
328 // The unsafety in this function is twofold:
330 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
332 // 2. We're passing a raw buffer to the function `f`, and it is expected that
333 // the function only *appends* bytes to the buffer. We'll get undefined
334 // behavior if existing bytes are overwritten to have non-UTF-8 data.
335 fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
337 F: FnOnce(&mut Vec<u8>) -> Result<usize>,
340 let mut g = Guard { len: buf.len(), buf: buf.as_mut_vec() };
342 if str::from_utf8(&g.buf[g.len..]).is_err() {
344 Err(Error::new(ErrorKind::InvalidData, "stream did not contain valid UTF-8"))
353 // This uses an adaptive system to extend the vector when it fills. We want to
354 // avoid paying to allocate and zero a huge chunk of memory if the reader only
355 // has 4 bytes while still making large reads if the reader does have a ton
356 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
357 // time is 4,500 times (!) slower than a default reservation size of 32 if the
358 // reader has a very small amount of data to return.
360 // Because we're extending the buffer with uninitialized data for trusted
361 // readers, we need to make sure to truncate that if any of this panics.
362 fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
363 read_to_end_with_reservation(r, buf, |_| 32)
366 fn read_to_end_with_reservation<R, F>(
369 mut reservation_size: F,
373 F: FnMut(&R) -> usize,
375 let start_len = buf.len();
376 let mut g = Guard { len: buf.len(), buf };
379 if g.len == g.buf.len() {
381 // FIXME(danielhenrymantilla): #42788
383 // - This creates a (mut) reference to a slice of
384 // _uninitialized_ integers, which is **undefined behavior**
386 // - Only the standard library gets to soundly "ignore" this,
387 // based on its privileged knowledge of unstable rustc
389 g.buf.reserve(reservation_size(r));
390 let capacity = g.buf.capacity();
391 g.buf.set_len(capacity);
392 r.initializer().initialize(&mut g.buf[g.len..]);
396 match r.read(&mut g.buf[g.len..]) {
398 ret = Ok(g.len - start_len);
402 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
413 pub(crate) fn default_read_vectored<F>(read: F, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
415 F: FnOnce(&mut [u8]) -> Result<usize>,
417 let buf = bufs.iter_mut().find(|b| !b.is_empty()).map_or(&mut [][..], |b| &mut **b);
421 pub(crate) fn default_write_vectored<F>(write: F, bufs: &[IoSlice<'_>]) -> Result<usize>
423 F: FnOnce(&[u8]) -> Result<usize>,
425 let buf = bufs.iter().find(|b| !b.is_empty()).map_or(&[][..], |b| &**b);
429 /// The `Read` trait allows for reading bytes from a source.
431 /// Implementors of the `Read` trait are called 'readers'.
433 /// Readers are defined by one required method, [`read()`]. Each call to [`read()`]
434 /// will attempt to pull bytes from this source into a provided buffer. A
435 /// number of other methods are implemented in terms of [`read()`], giving
436 /// implementors a number of ways to read bytes while only needing to implement
439 /// Readers are intended to be composable with one another. Many implementors
440 /// throughout [`std::io`] take and provide types which implement the `Read`
443 /// Please note that each call to [`read()`] may involve a system call, and
444 /// therefore, using something that implements [`BufRead`], such as
445 /// [`BufReader`], will be more efficient.
449 /// [`File`]s implement `Read`:
453 /// use std::io::prelude::*;
454 /// use std::fs::File;
456 /// fn main() -> io::Result<()> {
457 /// let mut f = File::open("foo.txt")?;
458 /// let mut buffer = [0; 10];
460 /// // read up to 10 bytes
461 /// f.read(&mut buffer)?;
463 /// let mut buffer = Vec::new();
464 /// // read the whole file
465 /// f.read_to_end(&mut buffer)?;
467 /// // read into a String, so that you don't need to do the conversion.
468 /// let mut buffer = String::new();
469 /// f.read_to_string(&mut buffer)?;
471 /// // and more! See the other methods for more details.
476 /// Read from [`&str`] because [`&[u8]`][slice] implements `Read`:
480 /// use std::io::prelude::*;
482 /// fn main() -> io::Result<()> {
483 /// let mut b = "This string will be read".as_bytes();
484 /// let mut buffer = [0; 10];
486 /// // read up to 10 bytes
487 /// b.read(&mut buffer)?;
489 /// // etc... it works exactly as a File does!
494 /// [`read()`]: trait.Read.html#tymethod.read
495 /// [`std::io`]: ../../std/io/index.html
496 /// [`File`]: ../fs/struct.File.html
497 /// [`BufRead`]: trait.BufRead.html
498 /// [`BufReader`]: struct.BufReader.html
499 /// [`&str`]: ../../std/primitive.str.html
500 /// [slice]: ../../std/primitive.slice.html
501 #[stable(feature = "rust1", since = "1.0.0")]
504 /// Pull some bytes from this source into the specified buffer, returning
505 /// how many bytes were read.
507 /// This function does not provide any guarantees about whether it blocks
508 /// waiting for data, but if an object needs to block for a read and cannot,
509 /// it will typically signal this via an [`Err`] return value.
511 /// If the return value of this method is [`Ok(n)`], then it must be
512 /// guaranteed that `0 <= n <= buf.len()`. A nonzero `n` value indicates
513 /// that the buffer `buf` has been filled in with `n` bytes of data from this
514 /// source. If `n` is `0`, then it can indicate one of two scenarios:
516 /// 1. This reader has reached its "end of file" and will likely no longer
517 /// be able to produce bytes. Note that this does not mean that the
518 /// reader will *always* no longer be able to produce bytes.
519 /// 2. The buffer specified was 0 bytes in length.
521 /// It is not an error if the returned value `n` is smaller than the buffer size,
522 /// even when the reader is not at the end of the stream yet.
523 /// This may happen for example because fewer bytes are actually available right now
524 /// (e. g. being close to end-of-file) or because read() was interrupted by a signal.
526 /// No guarantees are provided about the contents of `buf` when this
527 /// function is called, implementations cannot rely on any property of the
528 /// contents of `buf` being true. It is recommended that *implementations*
529 /// only write data to `buf` instead of reading its contents.
531 /// Correspondingly, however, *callers* of this method may not assume any guarantees
532 /// about how the implementation uses `buf`. The trait is safe to implement,
533 /// so it is possible that the code that's supposed to write to the buffer might also read
534 /// from it. It is your responsibility to make sure that `buf` is initialized
535 /// before calling `read`. Calling `read` with an uninitialized `buf` (of the kind one
536 /// obtains via [`MaybeUninit<T>`]) is not safe, and can lead to undefined behavior.
538 /// [`MaybeUninit<T>`]: ../mem/union.MaybeUninit.html
542 /// If this function encounters any form of I/O or other error, an error
543 /// variant will be returned. If an error is returned then it must be
544 /// guaranteed that no bytes were read.
546 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
547 /// operation should be retried if there is nothing else to do.
551 /// [`File`]s implement `Read`:
553 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
554 /// [`Ok(n)`]: ../../std/result/enum.Result.html#variant.Ok
555 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
556 /// [`File`]: ../fs/struct.File.html
560 /// use std::io::prelude::*;
561 /// use std::fs::File;
563 /// fn main() -> io::Result<()> {
564 /// let mut f = File::open("foo.txt")?;
565 /// let mut buffer = [0; 10];
567 /// // read up to 10 bytes
568 /// let n = f.read(&mut buffer[..])?;
570 /// println!("The bytes: {:?}", &buffer[..n]);
574 #[stable(feature = "rust1", since = "1.0.0")]
575 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
577 /// Like `read`, except that it reads into a slice of buffers.
579 /// Data is copied to fill each buffer in order, with the final buffer
580 /// written to possibly being only partially filled. This method must
581 /// behave equivalently to a single call to `read` with concatenated
584 /// The default implementation calls `read` with either the first nonempty
585 /// buffer provided, or an empty one if none exists.
586 #[stable(feature = "iovec", since = "1.36.0")]
587 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
588 default_read_vectored(|b| self.read(b), bufs)
591 /// Determines if this `Read`er has an efficient `read_vectored`
594 /// If a `Read`er does not override the default `read_vectored`
595 /// implementation, code using it may want to avoid the method all together
596 /// and coalesce writes into a single buffer for higher performance.
598 /// The default implementation returns `false`.
599 #[unstable(feature = "can_vector", issue = "69941")]
600 fn is_read_vectored(&self) -> bool {
604 /// Determines if this `Read`er can work with buffers of uninitialized
607 /// The default implementation returns an initializer which will zero
610 /// If a `Read`er guarantees that it can work properly with uninitialized
611 /// memory, it should call [`Initializer::nop()`]. See the documentation for
612 /// [`Initializer`] for details.
614 /// The behavior of this method must be independent of the state of the
615 /// `Read`er - the method only takes `&self` so that it can be used through
620 /// This method is unsafe because a `Read`er could otherwise return a
621 /// non-zeroing `Initializer` from another `Read` type without an `unsafe`
624 /// [`Initializer::nop()`]: ../../std/io/struct.Initializer.html#method.nop
625 /// [`Initializer`]: ../../std/io/struct.Initializer.html
626 #[unstable(feature = "read_initializer", issue = "42788")]
628 unsafe fn initializer(&self) -> Initializer {
629 Initializer::zeroing()
632 /// Read all bytes until EOF in this source, placing them into `buf`.
634 /// All bytes read from this source will be appended to the specified buffer
635 /// `buf`. This function will continuously call [`read()`] to append more data to
636 /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of
637 /// non-[`ErrorKind::Interrupted`] kind.
639 /// If successful, this function will return the total number of bytes read.
643 /// If this function encounters an error of the kind
644 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
647 /// If any other read error is encountered then this function immediately
648 /// returns. Any bytes which have already been read will be appended to
653 /// [`File`]s implement `Read`:
655 /// [`read()`]: trait.Read.html#tymethod.read
656 /// [`Ok(0)`]: ../../std/result/enum.Result.html#variant.Ok
657 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
658 /// [`File`]: ../fs/struct.File.html
662 /// use std::io::prelude::*;
663 /// use std::fs::File;
665 /// fn main() -> io::Result<()> {
666 /// let mut f = File::open("foo.txt")?;
667 /// let mut buffer = Vec::new();
669 /// // read the whole file
670 /// f.read_to_end(&mut buffer)?;
675 /// (See also the [`std::fs::read`] convenience function for reading from a
678 /// [`std::fs::read`]: ../fs/fn.read.html
679 #[stable(feature = "rust1", since = "1.0.0")]
680 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
681 read_to_end(self, buf)
684 /// Read all bytes until EOF in this source, appending them to `buf`.
686 /// If successful, this function returns the number of bytes which were read
687 /// and appended to `buf`.
691 /// If the data in this stream is *not* valid UTF-8 then an error is
692 /// returned and `buf` is unchanged.
694 /// See [`read_to_end`][readtoend] for other error semantics.
696 /// [readtoend]: #method.read_to_end
700 /// [`File`][file]s implement `Read`:
702 /// [file]: ../fs/struct.File.html
706 /// use std::io::prelude::*;
707 /// use std::fs::File;
709 /// fn main() -> io::Result<()> {
710 /// let mut f = File::open("foo.txt")?;
711 /// let mut buffer = String::new();
713 /// f.read_to_string(&mut buffer)?;
718 /// (See also the [`std::fs::read_to_string`] convenience function for
719 /// reading from a file.)
721 /// [`std::fs::read_to_string`]: ../fs/fn.read_to_string.html
722 #[stable(feature = "rust1", since = "1.0.0")]
723 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
724 // Note that we do *not* call `.read_to_end()` here. We are passing
725 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
726 // method to fill it up. An arbitrary implementation could overwrite the
727 // entire contents of the vector, not just append to it (which is what
728 // we are expecting).
730 // To prevent extraneously checking the UTF-8-ness of the entire buffer
731 // we pass it to our hardcoded `read_to_end` implementation which we
732 // know is guaranteed to only read data into the end of the buffer.
733 append_to_string(buf, |b| read_to_end(self, b))
736 /// Read the exact number of bytes required to fill `buf`.
738 /// This function reads as many bytes as necessary to completely fill the
739 /// specified buffer `buf`.
741 /// No guarantees are provided about the contents of `buf` when this
742 /// function is called, implementations cannot rely on any property of the
743 /// contents of `buf` being true. It is recommended that implementations
744 /// only write data to `buf` instead of reading its contents.
748 /// If this function encounters an error of the kind
749 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
752 /// If this function encounters an "end of file" before completely filling
753 /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
754 /// The contents of `buf` are unspecified in this case.
756 /// If any other read error is encountered then this function immediately
757 /// returns. The contents of `buf` are unspecified in this case.
759 /// If this function returns an error, it is unspecified how many bytes it
760 /// has read, but it will never read more than would be necessary to
761 /// completely fill the buffer.
765 /// [`File`]s implement `Read`:
767 /// [`File`]: ../fs/struct.File.html
768 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
769 /// [`ErrorKind::UnexpectedEof`]: ../../std/io/enum.ErrorKind.html#variant.UnexpectedEof
773 /// use std::io::prelude::*;
774 /// use std::fs::File;
776 /// fn main() -> io::Result<()> {
777 /// let mut f = File::open("foo.txt")?;
778 /// let mut buffer = [0; 10];
780 /// // read exactly 10 bytes
781 /// f.read_exact(&mut buffer)?;
785 #[stable(feature = "read_exact", since = "1.6.0")]
786 fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
787 while !buf.is_empty() {
788 match self.read(buf) {
794 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
795 Err(e) => return Err(e),
799 Err(Error::new(ErrorKind::UnexpectedEof, "failed to fill whole buffer"))
805 /// Creates a "by reference" adaptor for this instance of `Read`.
807 /// The returned adaptor also implements `Read` and will simply borrow this
812 /// [`File`][file]s implement `Read`:
814 /// [file]: ../fs/struct.File.html
818 /// use std::io::Read;
819 /// use std::fs::File;
821 /// fn main() -> io::Result<()> {
822 /// let mut f = File::open("foo.txt")?;
823 /// let mut buffer = Vec::new();
824 /// let mut other_buffer = Vec::new();
827 /// let reference = f.by_ref();
829 /// // read at most 5 bytes
830 /// reference.take(5).read_to_end(&mut buffer)?;
832 /// } // drop our &mut reference so we can use f again
834 /// // original file still usable, read the rest
835 /// f.read_to_end(&mut other_buffer)?;
839 #[stable(feature = "rust1", since = "1.0.0")]
840 fn by_ref(&mut self) -> &mut Self
847 /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
849 /// The returned type implements [`Iterator`] where the `Item` is
850 /// [`Result`]`<`[`u8`]`, `[`io::Error`]`>`.
851 /// The yielded item is [`Ok`] if a byte was successfully read and [`Err`]
852 /// otherwise. EOF is mapped to returning [`None`] from this iterator.
856 /// [`File`][file]s implement `Read`:
858 /// [file]: ../fs/struct.File.html
859 /// [`Iterator`]: ../../std/iter/trait.Iterator.html
860 /// [`Result`]: ../../std/result/enum.Result.html
861 /// [`io::Error`]: ../../std/io/struct.Error.html
862 /// [`u8`]: ../../std/primitive.u8.html
863 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
864 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
865 /// [`None`]: ../../std/option/enum.Option.html#variant.None
869 /// use std::io::prelude::*;
870 /// use std::fs::File;
872 /// fn main() -> io::Result<()> {
873 /// let mut f = File::open("foo.txt")?;
875 /// for byte in f.bytes() {
876 /// println!("{}", byte.unwrap());
881 #[stable(feature = "rust1", since = "1.0.0")]
882 fn bytes(self) -> Bytes<Self>
886 Bytes { inner: self }
889 /// Creates an adaptor which will chain this stream with another.
891 /// The returned `Read` instance will first read all bytes from this object
892 /// until EOF is encountered. Afterwards the output is equivalent to the
893 /// output of `next`.
897 /// [`File`][file]s implement `Read`:
899 /// [file]: ../fs/struct.File.html
903 /// use std::io::prelude::*;
904 /// use std::fs::File;
906 /// fn main() -> io::Result<()> {
907 /// let mut f1 = File::open("foo.txt")?;
908 /// let mut f2 = File::open("bar.txt")?;
910 /// let mut handle = f1.chain(f2);
911 /// let mut buffer = String::new();
913 /// // read the value into a String. We could use any Read method here,
914 /// // this is just one example.
915 /// handle.read_to_string(&mut buffer)?;
919 #[stable(feature = "rust1", since = "1.0.0")]
920 fn chain<R: Read>(self, next: R) -> Chain<Self, R>
924 Chain { first: self, second: next, done_first: false }
927 /// Creates an adaptor which will read at most `limit` bytes from it.
929 /// This function returns a new instance of `Read` which will read at most
930 /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
931 /// read errors will not count towards the number of bytes read and future
932 /// calls to [`read()`] may succeed.
936 /// [`File`]s implement `Read`:
938 /// [`File`]: ../fs/struct.File.html
939 /// [`Ok(0)`]: ../../std/result/enum.Result.html#variant.Ok
940 /// [`read()`]: trait.Read.html#tymethod.read
944 /// use std::io::prelude::*;
945 /// use std::fs::File;
947 /// fn main() -> io::Result<()> {
948 /// let mut f = File::open("foo.txt")?;
949 /// let mut buffer = [0; 5];
951 /// // read at most five bytes
952 /// let mut handle = f.take(5);
954 /// handle.read(&mut buffer)?;
958 #[stable(feature = "rust1", since = "1.0.0")]
959 fn take(self, limit: u64) -> Take<Self>
963 Take { inner: self, limit }
967 /// A buffer type used with `Read::read_vectored`.
969 /// It is semantically a wrapper around an `&mut [u8]`, but is guaranteed to be
970 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
972 #[stable(feature = "iovec", since = "1.36.0")]
974 pub struct IoSliceMut<'a>(sys::io::IoSliceMut<'a>);
976 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
977 unsafe impl<'a> Send for IoSliceMut<'a> {}
979 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
980 unsafe impl<'a> Sync for IoSliceMut<'a> {}
982 #[stable(feature = "iovec", since = "1.36.0")]
983 impl<'a> fmt::Debug for IoSliceMut<'a> {
984 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
985 fmt::Debug::fmt(self.0.as_slice(), fmt)
989 impl<'a> IoSliceMut<'a> {
990 /// Creates a new `IoSliceMut` wrapping a byte slice.
994 /// Panics on Windows if the slice is larger than 4GB.
995 #[stable(feature = "iovec", since = "1.36.0")]
997 pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> {
998 IoSliceMut(sys::io::IoSliceMut::new(buf))
1001 /// Advance the internal cursor of the slice.
1005 /// Elements in the slice may be modified if the cursor is not advanced to
1006 /// the end of the slice. For example if we have a slice of buffers with 2
1007 /// `IoSliceMut`s, both of length 8, and we advance the cursor by 10 bytes
1008 /// the first `IoSliceMut` will be untouched however the second will be
1009 /// modified to remove the first 2 bytes (10 - 8).
1014 /// #![feature(io_slice_advance)]
1016 /// use std::io::IoSliceMut;
1017 /// use std::ops::Deref;
1019 /// let mut buf1 = [1; 8];
1020 /// let mut buf2 = [2; 16];
1021 /// let mut buf3 = [3; 8];
1022 /// let mut bufs = &mut [
1023 /// IoSliceMut::new(&mut buf1),
1024 /// IoSliceMut::new(&mut buf2),
1025 /// IoSliceMut::new(&mut buf3),
1028 /// // Mark 10 bytes as read.
1029 /// bufs = IoSliceMut::advance(bufs, 10);
1030 /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1031 /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1033 #[unstable(feature = "io_slice_advance", issue = "62726")]
1035 pub fn advance<'b>(bufs: &'b mut [IoSliceMut<'a>], n: usize) -> &'b mut [IoSliceMut<'a>] {
1036 // Number of buffers to remove.
1038 // Total length of all the to be removed buffers.
1039 let mut accumulated_len = 0;
1040 for buf in bufs.iter() {
1041 if accumulated_len + buf.len() > n {
1044 accumulated_len += buf.len();
1049 let bufs = &mut bufs[remove..];
1050 if !bufs.is_empty() {
1051 bufs[0].0.advance(n - accumulated_len)
1057 #[stable(feature = "iovec", since = "1.36.0")]
1058 impl<'a> Deref for IoSliceMut<'a> {
1062 fn deref(&self) -> &[u8] {
1067 #[stable(feature = "iovec", since = "1.36.0")]
1068 impl<'a> DerefMut for IoSliceMut<'a> {
1070 fn deref_mut(&mut self) -> &mut [u8] {
1071 self.0.as_mut_slice()
1075 /// A buffer type used with `Write::write_vectored`.
1077 /// It is semantically a wrapper around an `&[u8]`, but is guaranteed to be
1078 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
1080 #[stable(feature = "iovec", since = "1.36.0")]
1081 #[derive(Copy, Clone)]
1082 #[repr(transparent)]
1083 pub struct IoSlice<'a>(sys::io::IoSlice<'a>);
1085 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1086 unsafe impl<'a> Send for IoSlice<'a> {}
1088 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1089 unsafe impl<'a> Sync for IoSlice<'a> {}
1091 #[stable(feature = "iovec", since = "1.36.0")]
1092 impl<'a> fmt::Debug for IoSlice<'a> {
1093 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1094 fmt::Debug::fmt(self.0.as_slice(), fmt)
1098 impl<'a> IoSlice<'a> {
1099 /// Creates a new `IoSlice` wrapping a byte slice.
1103 /// Panics on Windows if the slice is larger than 4GB.
1104 #[stable(feature = "iovec", since = "1.36.0")]
1106 pub fn new(buf: &'a [u8]) -> IoSlice<'a> {
1107 IoSlice(sys::io::IoSlice::new(buf))
1110 /// Advance the internal cursor of the slice.
1114 /// Elements in the slice may be modified if the cursor is not advanced to
1115 /// the end of the slice. For example if we have a slice of buffers with 2
1116 /// `IoSlice`s, both of length 8, and we advance the cursor by 10 bytes the
1117 /// first `IoSlice` will be untouched however the second will be modified to
1118 /// remove the first 2 bytes (10 - 8).
1123 /// #![feature(io_slice_advance)]
1125 /// use std::io::IoSlice;
1126 /// use std::ops::Deref;
1128 /// let buf1 = [1; 8];
1129 /// let buf2 = [2; 16];
1130 /// let buf3 = [3; 8];
1131 /// let mut bufs = &mut [
1132 /// IoSlice::new(&buf1),
1133 /// IoSlice::new(&buf2),
1134 /// IoSlice::new(&buf3),
1137 /// // Mark 10 bytes as written.
1138 /// bufs = IoSlice::advance(bufs, 10);
1139 /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1140 /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1141 #[unstable(feature = "io_slice_advance", issue = "62726")]
1143 pub fn advance<'b>(bufs: &'b mut [IoSlice<'a>], n: usize) -> &'b mut [IoSlice<'a>] {
1144 // Number of buffers to remove.
1146 // Total length of all the to be removed buffers.
1147 let mut accumulated_len = 0;
1148 for buf in bufs.iter() {
1149 if accumulated_len + buf.len() > n {
1152 accumulated_len += buf.len();
1157 let bufs = &mut bufs[remove..];
1158 if !bufs.is_empty() {
1159 bufs[0].0.advance(n - accumulated_len)
1165 #[stable(feature = "iovec", since = "1.36.0")]
1166 impl<'a> Deref for IoSlice<'a> {
1170 fn deref(&self) -> &[u8] {
1175 /// A type used to conditionally initialize buffers passed to `Read` methods.
1176 #[unstable(feature = "read_initializer", issue = "42788")]
1178 pub struct Initializer(bool);
1181 /// Returns a new `Initializer` which will zero out buffers.
1182 #[unstable(feature = "read_initializer", issue = "42788")]
1184 pub fn zeroing() -> Initializer {
1188 /// Returns a new `Initializer` which will not zero out buffers.
1192 /// This may only be called by `Read`ers which guarantee that they will not
1193 /// read from buffers passed to `Read` methods, and that the return value of
1194 /// the method accurately reflects the number of bytes that have been
1195 /// written to the head of the buffer.
1196 #[unstable(feature = "read_initializer", issue = "42788")]
1198 pub unsafe fn nop() -> Initializer {
1202 /// Indicates if a buffer should be initialized.
1203 #[unstable(feature = "read_initializer", issue = "42788")]
1205 pub fn should_initialize(&self) -> bool {
1209 /// Initializes a buffer if necessary.
1210 #[unstable(feature = "read_initializer", issue = "42788")]
1212 pub fn initialize(&self, buf: &mut [u8]) {
1213 if self.should_initialize() {
1214 unsafe { ptr::write_bytes(buf.as_mut_ptr(), 0, buf.len()) }
1219 /// A trait for objects which are byte-oriented sinks.
1221 /// Implementors of the `Write` trait are sometimes called 'writers'.
1223 /// Writers are defined by two required methods, [`write`] and [`flush`]:
1225 /// * The [`write`] method will attempt to write some data into the object,
1226 /// returning how many bytes were successfully written.
1228 /// * The [`flush`] method is useful for adaptors and explicit buffers
1229 /// themselves for ensuring that all buffered data has been pushed out to the
1232 /// Writers are intended to be composable with one another. Many implementors
1233 /// throughout [`std::io`] take and provide types which implement the `Write`
1236 /// [`write`]: #tymethod.write
1237 /// [`flush`]: #tymethod.flush
1238 /// [`std::io`]: index.html
1243 /// use std::io::prelude::*;
1244 /// use std::fs::File;
1246 /// fn main() -> std::io::Result<()> {
1247 /// let data = b"some bytes";
1249 /// let mut pos = 0;
1250 /// let mut buffer = File::create("foo.txt")?;
1252 /// while pos < data.len() {
1253 /// let bytes_written = buffer.write(&data[pos..])?;
1254 /// pos += bytes_written;
1260 /// The trait also provides convenience methods like [`write_all`], which calls
1261 /// `write` in a loop until its entire input has been written.
1263 /// [`write_all`]: #method.write_all
1264 #[stable(feature = "rust1", since = "1.0.0")]
1267 /// Write a buffer into this writer, returning how many bytes were written.
1269 /// This function will attempt to write the entire contents of `buf`, but
1270 /// the entire write may not succeed, or the write may also generate an
1271 /// error. A call to `write` represents *at most one* attempt to write to
1272 /// any wrapped object.
1274 /// Calls to `write` are not guaranteed to block waiting for data to be
1275 /// written, and a write which would otherwise block can be indicated through
1276 /// an [`Err`] variant.
1278 /// If the return value is [`Ok(n)`] then it must be guaranteed that
1279 /// `n <= buf.len()`. A return value of `0` typically means that the
1280 /// underlying object is no longer able to accept bytes and will likely not
1281 /// be able to in the future as well, or that the buffer provided is empty.
1285 /// Each call to `write` may generate an I/O error indicating that the
1286 /// operation could not be completed. If an error is returned then no bytes
1287 /// in the buffer were written to this writer.
1289 /// It is **not** considered an error if the entire buffer could not be
1290 /// written to this writer.
1292 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the
1293 /// write operation should be retried if there is nothing else to do.
1295 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
1296 /// [`Ok(n)`]: ../../std/result/enum.Result.html#variant.Ok
1297 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
1302 /// use std::io::prelude::*;
1303 /// use std::fs::File;
1305 /// fn main() -> std::io::Result<()> {
1306 /// let mut buffer = File::create("foo.txt")?;
1308 /// // Writes some prefix of the byte string, not necessarily all of it.
1309 /// buffer.write(b"some bytes")?;
1313 #[stable(feature = "rust1", since = "1.0.0")]
1314 fn write(&mut self, buf: &[u8]) -> Result<usize>;
1316 /// Like `write`, except that it writes from a slice of buffers.
1318 /// Data is copied from each buffer in order, with the final buffer
1319 /// read from possibly being only partially consumed. This method must
1320 /// behave as a call to `write` with the buffers concatenated would.
1322 /// The default implementation calls `write` with either the first nonempty
1323 /// buffer provided, or an empty one if none exists.
1324 #[stable(feature = "iovec", since = "1.36.0")]
1325 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize> {
1326 default_write_vectored(|b| self.write(b), bufs)
1329 /// Determines if this `Write`er has an efficient `write_vectored`
1332 /// If a `Write`er does not override the default `write_vectored`
1333 /// implementation, code using it may want to avoid the method all together
1334 /// and coalesce writes into a single buffer for higher performance.
1336 /// The default implementation returns `false`.
1337 #[unstable(feature = "can_vector", issue = "69941")]
1338 fn is_write_vectored(&self) -> bool {
1342 /// Flush this output stream, ensuring that all intermediately buffered
1343 /// contents reach their destination.
1347 /// It is considered an error if not all bytes could be written due to
1348 /// I/O errors or EOF being reached.
1353 /// use std::io::prelude::*;
1354 /// use std::io::BufWriter;
1355 /// use std::fs::File;
1357 /// fn main() -> std::io::Result<()> {
1358 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
1360 /// buffer.write_all(b"some bytes")?;
1361 /// buffer.flush()?;
1365 #[stable(feature = "rust1", since = "1.0.0")]
1366 fn flush(&mut self) -> Result<()>;
1368 /// Attempts to write an entire buffer into this writer.
1370 /// This method will continuously call [`write`] until there is no more data
1371 /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is
1372 /// returned. This method will not return until the entire buffer has been
1373 /// successfully written or such an error occurs. The first error that is
1374 /// not of [`ErrorKind::Interrupted`] kind generated from this method will be
1377 /// If the buffer contains no data, this will never call [`write`].
1381 /// This function will return the first error of
1382 /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns.
1384 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
1385 /// [`write`]: #tymethod.write
1390 /// use std::io::prelude::*;
1391 /// use std::fs::File;
1393 /// fn main() -> std::io::Result<()> {
1394 /// let mut buffer = File::create("foo.txt")?;
1396 /// buffer.write_all(b"some bytes")?;
1400 #[stable(feature = "rust1", since = "1.0.0")]
1401 fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
1402 while !buf.is_empty() {
1403 match self.write(buf) {
1405 return Err(Error::new(ErrorKind::WriteZero, "failed to write whole buffer"));
1407 Ok(n) => buf = &buf[n..],
1408 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1409 Err(e) => return Err(e),
1415 /// Attempts to write multiple buffers into this writer.
1417 /// This method will continuously call [`write_vectored`] until there is no
1418 /// more data to be written or an error of non-[`ErrorKind::Interrupted`]
1419 /// kind is returned. This method will not return until all buffers have
1420 /// been successfully written or such an error occurs. The first error that
1421 /// is not of [`ErrorKind::Interrupted`] kind generated from this method
1422 /// will be returned.
1424 /// If the buffer contains no data, this will never call [`write_vectored`].
1426 /// [`write_vectored`]: #method.write_vectored
1427 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
1432 /// Unlike `io::Write::write_vectored`, this takes a *mutable* reference to
1433 /// a slice of `IoSlice`s, not an immutable one. That's because we need to
1434 /// modify the slice to keep track of the bytes already written.
1436 /// Once this function returns, the contents of `bufs` are unspecified, as
1437 /// this depends on how many calls to `write_vectored` were necessary. It is
1438 /// best to understand this function as taking ownership of `bufs` and to
1439 /// not use `bufs` afterwards. The underlying buffers, to which the
1440 /// `IoSlice`s point (but not the `IoSlice`s themselves), are unchanged and
1446 /// #![feature(write_all_vectored)]
1447 /// # fn main() -> std::io::Result<()> {
1449 /// use std::io::{Write, IoSlice};
1451 /// let mut writer = Vec::new();
1452 /// let bufs = &mut [
1453 /// IoSlice::new(&[1]),
1454 /// IoSlice::new(&[2, 3]),
1455 /// IoSlice::new(&[4, 5, 6]),
1458 /// writer.write_all_vectored(bufs)?;
1459 /// // Note: the contents of `bufs` is now undefined, see the Notes section.
1461 /// assert_eq!(writer, &[1, 2, 3, 4, 5, 6]);
1464 #[unstable(feature = "write_all_vectored", issue = "70436")]
1465 fn write_all_vectored(&mut self, mut bufs: &mut [IoSlice<'_>]) -> Result<()> {
1466 while !bufs.is_empty() {
1467 match self.write_vectored(bufs) {
1469 return Err(Error::new(ErrorKind::WriteZero, "failed to write whole buffer"));
1471 Ok(n) => bufs = IoSlice::advance(mem::take(&mut bufs), n),
1472 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1473 Err(e) => return Err(e),
1479 /// Writes a formatted string into this writer, returning any error
1482 /// This method is primarily used to interface with the
1483 /// [`format_args!`][formatargs] macro, but it is rare that this should
1484 /// explicitly be called. The [`write!`][write] macro should be favored to
1485 /// invoke this method instead.
1487 /// [formatargs]: ../macro.format_args.html
1488 /// [write]: ../macro.write.html
1490 /// This function internally uses the [`write_all`][writeall] method on
1491 /// this trait and hence will continuously write data so long as no errors
1492 /// are received. This also means that partial writes are not indicated in
1495 /// [writeall]: #method.write_all
1499 /// This function will return any I/O error reported while formatting.
1504 /// use std::io::prelude::*;
1505 /// use std::fs::File;
1507 /// fn main() -> std::io::Result<()> {
1508 /// let mut buffer = File::create("foo.txt")?;
1511 /// write!(buffer, "{:.*}", 2, 1.234567)?;
1512 /// // turns into this:
1513 /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1517 #[stable(feature = "rust1", since = "1.0.0")]
1518 fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> Result<()> {
1519 // Create a shim which translates a Write to a fmt::Write and saves
1520 // off I/O errors. instead of discarding them
1521 struct Adaptor<'a, T: ?Sized + 'a> {
1526 impl<T: Write + ?Sized> fmt::Write for Adaptor<'_, T> {
1527 fn write_str(&mut self, s: &str) -> fmt::Result {
1528 match self.inner.write_all(s.as_bytes()) {
1531 self.error = Err(e);
1538 let mut output = Adaptor { inner: self, error: Ok(()) };
1539 match fmt::write(&mut output, fmt) {
1542 // check if the error came from the underlying `Write` or not
1543 if output.error.is_err() {
1546 Err(Error::new(ErrorKind::Other, "formatter error"))
1552 /// Creates a "by reference" adaptor for this instance of `Write`.
1554 /// The returned adaptor also implements `Write` and will simply borrow this
1560 /// use std::io::Write;
1561 /// use std::fs::File;
1563 /// fn main() -> std::io::Result<()> {
1564 /// let mut buffer = File::create("foo.txt")?;
1566 /// let reference = buffer.by_ref();
1568 /// // we can use reference just like our original buffer
1569 /// reference.write_all(b"some bytes")?;
1573 #[stable(feature = "rust1", since = "1.0.0")]
1574 fn by_ref(&mut self) -> &mut Self
1582 /// The `Seek` trait provides a cursor which can be moved within a stream of
1585 /// The stream typically has a fixed size, allowing seeking relative to either
1586 /// end or the current offset.
1590 /// [`File`][file]s implement `Seek`:
1592 /// [file]: ../fs/struct.File.html
1596 /// use std::io::prelude::*;
1597 /// use std::fs::File;
1598 /// use std::io::SeekFrom;
1600 /// fn main() -> io::Result<()> {
1601 /// let mut f = File::open("foo.txt")?;
1603 /// // move the cursor 42 bytes from the start of the file
1604 /// f.seek(SeekFrom::Start(42))?;
1608 #[stable(feature = "rust1", since = "1.0.0")]
1610 /// Seek to an offset, in bytes, in a stream.
1612 /// A seek beyond the end of a stream is allowed, but behavior is defined
1613 /// by the implementation.
1615 /// If the seek operation completed successfully,
1616 /// this method returns the new position from the start of the stream.
1617 /// That position can be used later with [`SeekFrom::Start`].
1621 /// Seeking to a negative offset is considered an error.
1623 /// [`SeekFrom::Start`]: enum.SeekFrom.html#variant.Start
1624 #[stable(feature = "rust1", since = "1.0.0")]
1625 fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1627 /// Returns the length of this stream (in bytes).
1629 /// This method is implemented using up to three seek operations. If this
1630 /// method returns successfully, the seek position is unchanged (i.e. the
1631 /// position before calling this method is the same as afterwards).
1632 /// However, if this method returns an error, the seek position is
1635 /// If you need to obtain the length of *many* streams and you don't care
1636 /// about the seek position afterwards, you can reduce the number of seek
1637 /// operations by simply calling `seek(SeekFrom::End(0))` and using its
1638 /// return value (it is also the stream length).
1640 /// Note that length of a stream can change over time (for example, when
1641 /// data is appended to a file). So calling this method multiple times does
1642 /// not necessarily return the same length each time.
1648 /// #![feature(seek_convenience)]
1650 /// io::{self, Seek},
1654 /// fn main() -> io::Result<()> {
1655 /// let mut f = File::open("foo.txt")?;
1657 /// let len = f.stream_len()?;
1658 /// println!("The file is currently {} bytes long", len);
1662 #[unstable(feature = "seek_convenience", issue = "59359")]
1663 fn stream_len(&mut self) -> Result<u64> {
1664 let old_pos = self.stream_position()?;
1665 let len = self.seek(SeekFrom::End(0))?;
1667 // Avoid seeking a third time when we were already at the end of the
1668 // stream. The branch is usually way cheaper than a seek operation.
1670 self.seek(SeekFrom::Start(old_pos))?;
1676 /// Returns the current seek position from the start of the stream.
1678 /// This is equivalent to `self.seek(SeekFrom::Current(0))`.
1684 /// #![feature(seek_convenience)]
1686 /// io::{self, BufRead, BufReader, Seek},
1690 /// fn main() -> io::Result<()> {
1691 /// let mut f = BufReader::new(File::open("foo.txt")?);
1693 /// let before = f.stream_position()?;
1694 /// f.read_line(&mut String::new())?;
1695 /// let after = f.stream_position()?;
1697 /// println!("The first line was {} bytes long", after - before);
1701 #[unstable(feature = "seek_convenience", issue = "59359")]
1702 fn stream_position(&mut self) -> Result<u64> {
1703 self.seek(SeekFrom::Current(0))
1707 /// Enumeration of possible methods to seek within an I/O object.
1709 /// It is used by the [`Seek`] trait.
1711 /// [`Seek`]: trait.Seek.html
1712 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1713 #[stable(feature = "rust1", since = "1.0.0")]
1715 /// Sets the offset to the provided number of bytes.
1716 #[stable(feature = "rust1", since = "1.0.0")]
1717 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1719 /// Sets the offset to the size of this object plus the specified number of
1722 /// It is possible to seek beyond the end of an object, but it's an error to
1723 /// seek before byte 0.
1724 #[stable(feature = "rust1", since = "1.0.0")]
1725 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1727 /// Sets the offset to the current position plus the specified number of
1730 /// It is possible to seek beyond the end of an object, but it's an error to
1731 /// seek before byte 0.
1732 #[stable(feature = "rust1", since = "1.0.0")]
1733 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1736 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>) -> Result<usize> {
1739 let (done, used) = {
1740 let available = match r.fill_buf() {
1742 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1743 Err(e) => return Err(e),
1745 match memchr::memchr(delim, available) {
1747 buf.extend_from_slice(&available[..=i]);
1751 buf.extend_from_slice(available);
1752 (false, available.len())
1758 if done || used == 0 {
1764 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1765 /// to perform extra ways of reading.
1767 /// For example, reading line-by-line is inefficient without using a buffer, so
1768 /// if you want to read by line, you'll need `BufRead`, which includes a
1769 /// [`read_line`] method as well as a [`lines`] iterator.
1773 /// A locked standard input implements `BufRead`:
1777 /// use std::io::prelude::*;
1779 /// let stdin = io::stdin();
1780 /// for line in stdin.lock().lines() {
1781 /// println!("{}", line.unwrap());
1785 /// If you have something that implements [`Read`], you can use the [`BufReader`
1786 /// type][`BufReader`] to turn it into a `BufRead`.
1788 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1789 /// [`BufReader`] to the rescue!
1791 /// [`BufReader`]: struct.BufReader.html
1792 /// [`File`]: ../fs/struct.File.html
1793 /// [`read_line`]: #method.read_line
1794 /// [`lines`]: #method.lines
1795 /// [`Read`]: trait.Read.html
1798 /// use std::io::{self, BufReader};
1799 /// use std::io::prelude::*;
1800 /// use std::fs::File;
1802 /// fn main() -> io::Result<()> {
1803 /// let f = File::open("foo.txt")?;
1804 /// let f = BufReader::new(f);
1806 /// for line in f.lines() {
1807 /// println!("{}", line.unwrap());
1814 #[stable(feature = "rust1", since = "1.0.0")]
1815 pub trait BufRead: Read {
1816 /// Returns the contents of the internal buffer, filling it with more data
1817 /// from the inner reader if it is empty.
1819 /// This function is a lower-level call. It needs to be paired with the
1820 /// [`consume`] method to function properly. When calling this
1821 /// method, none of the contents will be "read" in the sense that later
1822 /// calling `read` may return the same contents. As such, [`consume`] must
1823 /// be called with the number of bytes that are consumed from this buffer to
1824 /// ensure that the bytes are never returned twice.
1826 /// [`consume`]: #tymethod.consume
1828 /// An empty buffer returned indicates that the stream has reached EOF.
1832 /// This function will return an I/O error if the underlying reader was
1833 /// read, but returned an error.
1837 /// A locked standard input implements `BufRead`:
1841 /// use std::io::prelude::*;
1843 /// let stdin = io::stdin();
1844 /// let mut stdin = stdin.lock();
1846 /// let buffer = stdin.fill_buf().unwrap();
1848 /// // work with buffer
1849 /// println!("{:?}", buffer);
1851 /// // ensure the bytes we worked with aren't returned again later
1852 /// let length = buffer.len();
1853 /// stdin.consume(length);
1855 #[stable(feature = "rust1", since = "1.0.0")]
1856 fn fill_buf(&mut self) -> Result<&[u8]>;
1858 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1859 /// so they should no longer be returned in calls to `read`.
1861 /// This function is a lower-level call. It needs to be paired with the
1862 /// [`fill_buf`] method to function properly. This function does
1863 /// not perform any I/O, it simply informs this object that some amount of
1864 /// its buffer, returned from [`fill_buf`], has been consumed and should
1865 /// no longer be returned. As such, this function may do odd things if
1866 /// [`fill_buf`] isn't called before calling it.
1868 /// The `amt` must be `<=` the number of bytes in the buffer returned by
1873 /// Since `consume()` is meant to be used with [`fill_buf`],
1874 /// that method's example includes an example of `consume()`.
1876 /// [`fill_buf`]: #tymethod.fill_buf
1877 #[stable(feature = "rust1", since = "1.0.0")]
1878 fn consume(&mut self, amt: usize);
1880 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
1882 /// This function will read bytes from the underlying stream until the
1883 /// delimiter or EOF is found. Once found, all bytes up to, and including,
1884 /// the delimiter (if found) will be appended to `buf`.
1886 /// If successful, this function will return the total number of bytes read.
1888 /// This function is blocking and should be used carefully: it is possible for
1889 /// an attacker to continuously send bytes without ever sending the delimiter
1894 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1895 /// will otherwise return any errors returned by [`fill_buf`].
1897 /// If an I/O error is encountered then all bytes read so far will be
1898 /// present in `buf` and its length will have been adjusted appropriately.
1900 /// [`fill_buf`]: #tymethod.fill_buf
1901 /// [`ErrorKind::Interrupted`]: enum.ErrorKind.html#variant.Interrupted
1905 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1906 /// this example, we use [`Cursor`] to read all the bytes in a byte slice
1907 /// in hyphen delimited segments:
1909 /// [`Cursor`]: struct.Cursor.html
1912 /// use std::io::{self, BufRead};
1914 /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
1915 /// let mut buf = vec![];
1917 /// // cursor is at 'l'
1918 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1919 /// .expect("reading from cursor won't fail");
1920 /// assert_eq!(num_bytes, 6);
1921 /// assert_eq!(buf, b"lorem-");
1924 /// // cursor is at 'i'
1925 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1926 /// .expect("reading from cursor won't fail");
1927 /// assert_eq!(num_bytes, 5);
1928 /// assert_eq!(buf, b"ipsum");
1931 /// // cursor is at EOF
1932 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1933 /// .expect("reading from cursor won't fail");
1934 /// assert_eq!(num_bytes, 0);
1935 /// assert_eq!(buf, b"");
1937 #[stable(feature = "rust1", since = "1.0.0")]
1938 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
1939 read_until(self, byte, buf)
1942 /// Read all bytes until a newline (the 0xA byte) is reached, and append
1943 /// them to the provided buffer.
1945 /// This function will read bytes from the underlying stream until the
1946 /// newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes
1947 /// up to, and including, the delimiter (if found) will be appended to
1950 /// If successful, this function will return the total number of bytes read.
1952 /// If this function returns `Ok(0)`, the stream has reached EOF.
1954 /// This function is blocking and should be used carefully: it is possible for
1955 /// an attacker to continuously send bytes without ever sending a newline
1960 /// This function has the same error semantics as [`read_until`] and will
1961 /// also return an error if the read bytes are not valid UTF-8. If an I/O
1962 /// error is encountered then `buf` may contain some bytes already read in
1963 /// the event that all data read so far was valid UTF-8.
1965 /// [`read_until`]: #method.read_until
1969 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1970 /// this example, we use [`Cursor`] to read all the lines in a byte slice:
1972 /// [`Cursor`]: struct.Cursor.html
1975 /// use std::io::{self, BufRead};
1977 /// let mut cursor = io::Cursor::new(b"foo\nbar");
1978 /// let mut buf = String::new();
1980 /// // cursor is at 'f'
1981 /// let num_bytes = cursor.read_line(&mut buf)
1982 /// .expect("reading from cursor won't fail");
1983 /// assert_eq!(num_bytes, 4);
1984 /// assert_eq!(buf, "foo\n");
1987 /// // cursor is at 'b'
1988 /// let num_bytes = cursor.read_line(&mut buf)
1989 /// .expect("reading from cursor won't fail");
1990 /// assert_eq!(num_bytes, 3);
1991 /// assert_eq!(buf, "bar");
1994 /// // cursor is at EOF
1995 /// let num_bytes = cursor.read_line(&mut buf)
1996 /// .expect("reading from cursor won't fail");
1997 /// assert_eq!(num_bytes, 0);
1998 /// assert_eq!(buf, "");
2000 #[stable(feature = "rust1", since = "1.0.0")]
2001 fn read_line(&mut self, buf: &mut String) -> Result<usize> {
2002 // Note that we are not calling the `.read_until` method here, but
2003 // rather our hardcoded implementation. For more details as to why, see
2004 // the comments in `read_to_end`.
2005 append_to_string(buf, |b| read_until(self, b'\n', b))
2008 /// Returns an iterator over the contents of this reader split on the byte
2011 /// The iterator returned from this function will return instances of
2012 /// [`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
2013 /// the delimiter byte at the end.
2015 /// This function will yield errors whenever [`read_until`] would have
2016 /// also yielded an error.
2018 /// [`io::Result`]: type.Result.html
2019 /// [`Vec<u8>`]: ../vec/struct.Vec.html
2020 /// [`read_until`]: #method.read_until
2024 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2025 /// this example, we use [`Cursor`] to iterate over all hyphen delimited
2026 /// segments in a byte slice
2028 /// [`Cursor`]: struct.Cursor.html
2031 /// use std::io::{self, BufRead};
2033 /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
2035 /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
2036 /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
2037 /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
2038 /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
2039 /// assert_eq!(split_iter.next(), None);
2041 #[stable(feature = "rust1", since = "1.0.0")]
2042 fn split(self, byte: u8) -> Split<Self>
2046 Split { buf: self, delim: byte }
2049 /// Returns an iterator over the lines of this reader.
2051 /// The iterator returned from this function will yield instances of
2052 /// [`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline
2053 /// byte (the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.
2055 /// [`io::Result`]: type.Result.html
2056 /// [`String`]: ../string/struct.String.html
2060 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2061 /// this example, we use [`Cursor`] to iterate over all the lines in a byte
2064 /// [`Cursor`]: struct.Cursor.html
2067 /// use std::io::{self, BufRead};
2069 /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
2071 /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
2072 /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
2073 /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
2074 /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
2075 /// assert_eq!(lines_iter.next(), None);
2080 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
2082 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
2083 #[stable(feature = "rust1", since = "1.0.0")]
2084 fn lines(self) -> Lines<Self>
2092 /// Adaptor to chain together two readers.
2094 /// This struct is generally created by calling [`chain`] on a reader.
2095 /// Please see the documentation of [`chain`] for more details.
2097 /// [`chain`]: trait.Read.html#method.chain
2098 #[stable(feature = "rust1", since = "1.0.0")]
2099 pub struct Chain<T, U> {
2105 impl<T, U> Chain<T, U> {
2106 /// Consumes the `Chain`, returning the wrapped readers.
2112 /// use std::io::prelude::*;
2113 /// use std::fs::File;
2115 /// fn main() -> io::Result<()> {
2116 /// let mut foo_file = File::open("foo.txt")?;
2117 /// let mut bar_file = File::open("bar.txt")?;
2119 /// let chain = foo_file.chain(bar_file);
2120 /// let (foo_file, bar_file) = chain.into_inner();
2124 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2125 pub fn into_inner(self) -> (T, U) {
2126 (self.first, self.second)
2129 /// Gets references to the underlying readers in this `Chain`.
2135 /// use std::io::prelude::*;
2136 /// use std::fs::File;
2138 /// fn main() -> io::Result<()> {
2139 /// let mut foo_file = File::open("foo.txt")?;
2140 /// let mut bar_file = File::open("bar.txt")?;
2142 /// let chain = foo_file.chain(bar_file);
2143 /// let (foo_file, bar_file) = chain.get_ref();
2147 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2148 pub fn get_ref(&self) -> (&T, &U) {
2149 (&self.first, &self.second)
2152 /// Gets mutable references to the underlying readers in this `Chain`.
2154 /// Care should be taken to avoid modifying the internal I/O state of the
2155 /// underlying readers as doing so may corrupt the internal state of this
2162 /// use std::io::prelude::*;
2163 /// use std::fs::File;
2165 /// fn main() -> io::Result<()> {
2166 /// let mut foo_file = File::open("foo.txt")?;
2167 /// let mut bar_file = File::open("bar.txt")?;
2169 /// let mut chain = foo_file.chain(bar_file);
2170 /// let (foo_file, bar_file) = chain.get_mut();
2174 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2175 pub fn get_mut(&mut self) -> (&mut T, &mut U) {
2176 (&mut self.first, &mut self.second)
2180 #[stable(feature = "std_debug", since = "1.16.0")]
2181 impl<T: fmt::Debug, U: fmt::Debug> fmt::Debug for Chain<T, U> {
2182 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2183 f.debug_struct("Chain").field("t", &self.first).field("u", &self.second).finish()
2187 #[stable(feature = "rust1", since = "1.0.0")]
2188 impl<T: Read, U: Read> Read for Chain<T, U> {
2189 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2190 if !self.done_first {
2191 match self.first.read(buf)? {
2192 0 if !buf.is_empty() => self.done_first = true,
2196 self.second.read(buf)
2199 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
2200 if !self.done_first {
2201 match self.first.read_vectored(bufs)? {
2202 0 if bufs.iter().any(|b| !b.is_empty()) => self.done_first = true,
2206 self.second.read_vectored(bufs)
2209 unsafe fn initializer(&self) -> Initializer {
2210 let initializer = self.first.initializer();
2211 if initializer.should_initialize() { initializer } else { self.second.initializer() }
2215 #[stable(feature = "chain_bufread", since = "1.9.0")]
2216 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
2217 fn fill_buf(&mut self) -> Result<&[u8]> {
2218 if !self.done_first {
2219 match self.first.fill_buf()? {
2220 buf if buf.is_empty() => {
2221 self.done_first = true;
2223 buf => return Ok(buf),
2226 self.second.fill_buf()
2229 fn consume(&mut self, amt: usize) {
2230 if !self.done_first { self.first.consume(amt) } else { self.second.consume(amt) }
2234 /// Reader adaptor which limits the bytes read from an underlying reader.
2236 /// This struct is generally created by calling [`take`] on a reader.
2237 /// Please see the documentation of [`take`] for more details.
2239 /// [`take`]: trait.Read.html#method.take
2240 #[stable(feature = "rust1", since = "1.0.0")]
2242 pub struct Take<T> {
2248 /// Returns the number of bytes that can be read before this instance will
2253 /// This instance may reach `EOF` after reading fewer bytes than indicated by
2254 /// this method if the underlying [`Read`] instance reaches EOF.
2256 /// [`Read`]: ../../std/io/trait.Read.html
2262 /// use std::io::prelude::*;
2263 /// use std::fs::File;
2265 /// fn main() -> io::Result<()> {
2266 /// let f = File::open("foo.txt")?;
2268 /// // read at most five bytes
2269 /// let handle = f.take(5);
2271 /// println!("limit: {}", handle.limit());
2275 #[stable(feature = "rust1", since = "1.0.0")]
2276 pub fn limit(&self) -> u64 {
2280 /// Sets the number of bytes that can be read before this instance will
2281 /// return EOF. This is the same as constructing a new `Take` instance, so
2282 /// the amount of bytes read and the previous limit value don't matter when
2283 /// calling this method.
2289 /// use std::io::prelude::*;
2290 /// use std::fs::File;
2292 /// fn main() -> io::Result<()> {
2293 /// let f = File::open("foo.txt")?;
2295 /// // read at most five bytes
2296 /// let mut handle = f.take(5);
2297 /// handle.set_limit(10);
2299 /// assert_eq!(handle.limit(), 10);
2303 #[stable(feature = "take_set_limit", since = "1.27.0")]
2304 pub fn set_limit(&mut self, limit: u64) {
2308 /// Consumes the `Take`, returning the wrapped reader.
2314 /// use std::io::prelude::*;
2315 /// use std::fs::File;
2317 /// fn main() -> io::Result<()> {
2318 /// let mut file = File::open("foo.txt")?;
2320 /// let mut buffer = [0; 5];
2321 /// let mut handle = file.take(5);
2322 /// handle.read(&mut buffer)?;
2324 /// let file = handle.into_inner();
2328 #[stable(feature = "io_take_into_inner", since = "1.15.0")]
2329 pub fn into_inner(self) -> T {
2333 /// Gets a reference to the underlying reader.
2339 /// use std::io::prelude::*;
2340 /// use std::fs::File;
2342 /// fn main() -> io::Result<()> {
2343 /// let mut file = File::open("foo.txt")?;
2345 /// let mut buffer = [0; 5];
2346 /// let mut handle = file.take(5);
2347 /// handle.read(&mut buffer)?;
2349 /// let file = handle.get_ref();
2353 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2354 pub fn get_ref(&self) -> &T {
2358 /// Gets a mutable reference to the underlying reader.
2360 /// Care should be taken to avoid modifying the internal I/O state of the
2361 /// underlying reader as doing so may corrupt the internal limit of this
2368 /// use std::io::prelude::*;
2369 /// use std::fs::File;
2371 /// fn main() -> io::Result<()> {
2372 /// let mut file = File::open("foo.txt")?;
2374 /// let mut buffer = [0; 5];
2375 /// let mut handle = file.take(5);
2376 /// handle.read(&mut buffer)?;
2378 /// let file = handle.get_mut();
2382 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2383 pub fn get_mut(&mut self) -> &mut T {
2388 #[stable(feature = "rust1", since = "1.0.0")]
2389 impl<T: Read> Read for Take<T> {
2390 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2391 // Don't call into inner reader at all at EOF because it may still block
2392 if self.limit == 0 {
2396 let max = cmp::min(buf.len() as u64, self.limit) as usize;
2397 let n = self.inner.read(&mut buf[..max])?;
2398 self.limit -= n as u64;
2402 unsafe fn initializer(&self) -> Initializer {
2403 self.inner.initializer()
2406 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
2407 // Pass in a reservation_size closure that respects the current value
2408 // of limit for each read. If we hit the read limit, this prevents the
2409 // final zero-byte read from allocating again.
2410 read_to_end_with_reservation(self, buf, |self_| cmp::min(self_.limit, 32) as usize)
2414 #[stable(feature = "rust1", since = "1.0.0")]
2415 impl<T: BufRead> BufRead for Take<T> {
2416 fn fill_buf(&mut self) -> Result<&[u8]> {
2417 // Don't call into inner reader at all at EOF because it may still block
2418 if self.limit == 0 {
2422 let buf = self.inner.fill_buf()?;
2423 let cap = cmp::min(buf.len() as u64, self.limit) as usize;
2427 fn consume(&mut self, amt: usize) {
2428 // Don't let callers reset the limit by passing an overlarge value
2429 let amt = cmp::min(amt as u64, self.limit) as usize;
2430 self.limit -= amt as u64;
2431 self.inner.consume(amt);
2435 /// An iterator over `u8` values of a reader.
2437 /// This struct is generally created by calling [`bytes`] on a reader.
2438 /// Please see the documentation of [`bytes`] for more details.
2440 /// [`bytes`]: trait.Read.html#method.bytes
2441 #[stable(feature = "rust1", since = "1.0.0")]
2443 pub struct Bytes<R> {
2447 #[stable(feature = "rust1", since = "1.0.0")]
2448 impl<R: Read> Iterator for Bytes<R> {
2449 type Item = Result<u8>;
2451 fn next(&mut self) -> Option<Result<u8>> {
2454 return match self.inner.read(slice::from_mut(&mut byte)) {
2456 Ok(..) => Some(Ok(byte)),
2457 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
2458 Err(e) => Some(Err(e)),
2464 /// An iterator over the contents of an instance of `BufRead` split on a
2465 /// particular byte.
2467 /// This struct is generally created by calling [`split`] on a `BufRead`.
2468 /// Please see the documentation of [`split`] for more details.
2470 /// [`split`]: trait.BufRead.html#method.split
2471 #[stable(feature = "rust1", since = "1.0.0")]
2473 pub struct Split<B> {
2478 #[stable(feature = "rust1", since = "1.0.0")]
2479 impl<B: BufRead> Iterator for Split<B> {
2480 type Item = Result<Vec<u8>>;
2482 fn next(&mut self) -> Option<Result<Vec<u8>>> {
2483 let mut buf = Vec::new();
2484 match self.buf.read_until(self.delim, &mut buf) {
2487 if buf[buf.len() - 1] == self.delim {
2492 Err(e) => Some(Err(e)),
2497 /// An iterator over the lines of an instance of `BufRead`.
2499 /// This struct is generally created by calling [`lines`] on a `BufRead`.
2500 /// Please see the documentation of [`lines`] for more details.
2502 /// [`lines`]: trait.BufRead.html#method.lines
2503 #[stable(feature = "rust1", since = "1.0.0")]
2505 pub struct Lines<B> {
2509 #[stable(feature = "rust1", since = "1.0.0")]
2510 impl<B: BufRead> Iterator for Lines<B> {
2511 type Item = Result<String>;
2513 fn next(&mut self) -> Option<Result<String>> {
2514 let mut buf = String::new();
2515 match self.buf.read_line(&mut buf) {
2518 if buf.ends_with('\n') {
2520 if buf.ends_with('\r') {
2526 Err(e) => Some(Err(e)),
2533 use super::{repeat, Cursor, SeekFrom};
2534 use crate::cmp::{self, min};
2535 use crate::io::prelude::*;
2536 use crate::io::{self, IoSlice, IoSliceMut};
2537 use crate::ops::Deref;
2540 #[cfg_attr(target_os = "emscripten", ignore)]
2542 let mut buf = Cursor::new(&b"12"[..]);
2543 let mut v = Vec::new();
2544 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 2);
2545 assert_eq!(v, b"12");
2547 let mut buf = Cursor::new(&b"1233"[..]);
2548 let mut v = Vec::new();
2549 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 3);
2550 assert_eq!(v, b"123");
2552 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 1);
2553 assert_eq!(v, b"3");
2555 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 0);
2561 let buf = Cursor::new(&b"12"[..]);
2562 let mut s = buf.split(b'3');
2563 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2564 assert!(s.next().is_none());
2566 let buf = Cursor::new(&b"1233"[..]);
2567 let mut s = buf.split(b'3');
2568 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2569 assert_eq!(s.next().unwrap().unwrap(), vec![]);
2570 assert!(s.next().is_none());
2575 let mut buf = Cursor::new(&b"12"[..]);
2576 let mut v = String::new();
2577 assert_eq!(buf.read_line(&mut v).unwrap(), 2);
2578 assert_eq!(v, "12");
2580 let mut buf = Cursor::new(&b"12\n\n"[..]);
2581 let mut v = String::new();
2582 assert_eq!(buf.read_line(&mut v).unwrap(), 3);
2583 assert_eq!(v, "12\n");
2585 assert_eq!(buf.read_line(&mut v).unwrap(), 1);
2586 assert_eq!(v, "\n");
2588 assert_eq!(buf.read_line(&mut v).unwrap(), 0);
2594 let buf = Cursor::new(&b"12\r"[..]);
2595 let mut s = buf.lines();
2596 assert_eq!(s.next().unwrap().unwrap(), "12\r".to_string());
2597 assert!(s.next().is_none());
2599 let buf = Cursor::new(&b"12\r\n\n"[..]);
2600 let mut s = buf.lines();
2601 assert_eq!(s.next().unwrap().unwrap(), "12".to_string());
2602 assert_eq!(s.next().unwrap().unwrap(), "".to_string());
2603 assert!(s.next().is_none());
2608 let mut c = Cursor::new(&b""[..]);
2609 let mut v = Vec::new();
2610 assert_eq!(c.read_to_end(&mut v).unwrap(), 0);
2613 let mut c = Cursor::new(&b"1"[..]);
2614 let mut v = Vec::new();
2615 assert_eq!(c.read_to_end(&mut v).unwrap(), 1);
2616 assert_eq!(v, b"1");
2618 let cap = 1024 * 1024;
2619 let data = (0..cap).map(|i| (i / 3) as u8).collect::<Vec<_>>();
2620 let mut v = Vec::new();
2621 let (a, b) = data.split_at(data.len() / 2);
2622 assert_eq!(Cursor::new(a).read_to_end(&mut v).unwrap(), a.len());
2623 assert_eq!(Cursor::new(b).read_to_end(&mut v).unwrap(), b.len());
2624 assert_eq!(v, data);
2628 fn read_to_string() {
2629 let mut c = Cursor::new(&b""[..]);
2630 let mut v = String::new();
2631 assert_eq!(c.read_to_string(&mut v).unwrap(), 0);
2634 let mut c = Cursor::new(&b"1"[..]);
2635 let mut v = String::new();
2636 assert_eq!(c.read_to_string(&mut v).unwrap(), 1);
2639 let mut c = Cursor::new(&b"\xff"[..]);
2640 let mut v = String::new();
2641 assert!(c.read_to_string(&mut v).is_err());
2646 let mut buf = [0; 4];
2648 let mut c = Cursor::new(&b""[..]);
2649 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
2651 let mut c = Cursor::new(&b"123"[..]).chain(Cursor::new(&b"456789"[..]));
2652 c.read_exact(&mut buf).unwrap();
2653 assert_eq!(&buf, b"1234");
2654 c.read_exact(&mut buf).unwrap();
2655 assert_eq!(&buf, b"5678");
2656 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
2660 fn read_exact_slice() {
2661 let mut buf = [0; 4];
2663 let mut c = &b""[..];
2664 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
2666 let mut c = &b"123"[..];
2667 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
2668 // make sure the optimized (early returning) method is being used
2669 assert_eq!(&buf, &[0; 4]);
2671 let mut c = &b"1234"[..];
2672 c.read_exact(&mut buf).unwrap();
2673 assert_eq!(&buf, b"1234");
2675 let mut c = &b"56789"[..];
2676 c.read_exact(&mut buf).unwrap();
2677 assert_eq!(&buf, b"5678");
2678 assert_eq!(c, b"9");
2686 fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
2687 Err(io::Error::new(io::ErrorKind::Other, ""))
2690 impl BufRead for R {
2691 fn fill_buf(&mut self) -> io::Result<&[u8]> {
2692 Err(io::Error::new(io::ErrorKind::Other, ""))
2694 fn consume(&mut self, _amt: usize) {}
2697 let mut buf = [0; 1];
2698 assert_eq!(0, R.take(0).read(&mut buf).unwrap());
2699 assert_eq!(b"", R.take(0).fill_buf().unwrap());
2702 fn cmp_bufread<Br1: BufRead, Br2: BufRead>(mut br1: Br1, mut br2: Br2, exp: &[u8]) {
2703 let mut cat = Vec::new();
2706 let buf1 = br1.fill_buf().unwrap();
2707 let buf2 = br2.fill_buf().unwrap();
2708 let minlen = if buf1.len() < buf2.len() { buf1.len() } else { buf2.len() };
2709 assert_eq!(buf1[..minlen], buf2[..minlen]);
2710 cat.extend_from_slice(&buf1[..minlen]);
2716 br1.consume(consume);
2717 br2.consume(consume);
2719 assert_eq!(br1.fill_buf().unwrap().len(), 0);
2720 assert_eq!(br2.fill_buf().unwrap().len(), 0);
2721 assert_eq!(&cat[..], &exp[..])
2725 fn chain_bufread() {
2726 let testdata = b"ABCDEFGHIJKL";
2728 (&testdata[..3]).chain(&testdata[3..6]).chain(&testdata[6..9]).chain(&testdata[9..]);
2729 let chain2 = (&testdata[..4]).chain(&testdata[4..8]).chain(&testdata[8..]);
2730 cmp_bufread(chain1, chain2, &testdata[..]);
2734 fn chain_zero_length_read_is_not_eof() {
2737 let mut s = String::new();
2738 let mut chain = (&a[..]).chain(&b[..]);
2739 chain.read(&mut []).unwrap();
2740 chain.read_to_string(&mut s).unwrap();
2741 assert_eq!("AB", s);
2745 #[cfg_attr(target_os = "emscripten", ignore)]
2746 fn bench_read_to_end(b: &mut test::Bencher) {
2748 let mut lr = repeat(1).take(10000000);
2749 let mut vec = Vec::with_capacity(1024);
2750 super::read_to_end(&mut lr, &mut vec)
2755 fn seek_len() -> io::Result<()> {
2756 let mut c = Cursor::new(vec![0; 15]);
2757 assert_eq!(c.stream_len()?, 15);
2759 c.seek(SeekFrom::End(0))?;
2760 let old_pos = c.stream_position()?;
2761 assert_eq!(c.stream_len()?, 15);
2762 assert_eq!(c.stream_position()?, old_pos);
2764 c.seek(SeekFrom::Start(7))?;
2765 c.seek(SeekFrom::Current(2))?;
2766 let old_pos = c.stream_position()?;
2767 assert_eq!(c.stream_len()?, 15);
2768 assert_eq!(c.stream_position()?, old_pos);
2774 fn seek_position() -> io::Result<()> {
2775 // All `asserts` are duplicated here to make sure the method does not
2776 // change anything about the seek state.
2777 let mut c = Cursor::new(vec![0; 15]);
2778 assert_eq!(c.stream_position()?, 0);
2779 assert_eq!(c.stream_position()?, 0);
2781 c.seek(SeekFrom::End(0))?;
2782 assert_eq!(c.stream_position()?, 15);
2783 assert_eq!(c.stream_position()?, 15);
2785 c.seek(SeekFrom::Start(7))?;
2786 c.seek(SeekFrom::Current(2))?;
2787 assert_eq!(c.stream_position()?, 9);
2788 assert_eq!(c.stream_position()?, 9);
2790 c.seek(SeekFrom::End(-3))?;
2791 c.seek(SeekFrom::Current(1))?;
2792 c.seek(SeekFrom::Current(-5))?;
2793 assert_eq!(c.stream_position()?, 8);
2794 assert_eq!(c.stream_position()?, 8);
2799 // A simple example reader which uses the default implementation of
2801 struct ExampleSliceReader<'a> {
2805 impl<'a> Read for ExampleSliceReader<'a> {
2806 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
2807 let len = cmp::min(self.slice.len(), buf.len());
2808 buf[..len].copy_from_slice(&self.slice[..len]);
2809 self.slice = &self.slice[len..];
2815 fn test_read_to_end_capacity() -> io::Result<()> {
2816 let input = &b"foo"[..];
2818 // read_to_end() generally needs to over-allocate, both for efficiency
2819 // and so that it can distinguish EOF. Assert that this is the case
2820 // with this simple ExampleSliceReader struct, which uses the default
2821 // implementation of read_to_end. Even though vec1 is allocated with
2822 // exactly enough capacity for the read, read_to_end will allocate more
2824 let mut vec1 = Vec::with_capacity(input.len());
2825 ExampleSliceReader { slice: input }.read_to_end(&mut vec1)?;
2826 assert_eq!(vec1.len(), input.len());
2827 assert!(vec1.capacity() > input.len(), "allocated more");
2829 // However, std::io::Take includes an implementation of read_to_end
2830 // that will not allocate when the limit has already been reached. In
2831 // this case, vec2 never grows.
2832 let mut vec2 = Vec::with_capacity(input.len());
2833 ExampleSliceReader { slice: input }.take(input.len() as u64).read_to_end(&mut vec2)?;
2834 assert_eq!(vec2.len(), input.len());
2835 assert_eq!(vec2.capacity(), input.len(), "did not allocate more");
2841 fn io_slice_mut_advance() {
2842 let mut buf1 = [1; 8];
2843 let mut buf2 = [2; 16];
2844 let mut buf3 = [3; 8];
2845 let mut bufs = &mut [
2846 IoSliceMut::new(&mut buf1),
2847 IoSliceMut::new(&mut buf2),
2848 IoSliceMut::new(&mut buf3),
2851 // Only in a single buffer..
2852 bufs = IoSliceMut::advance(bufs, 1);
2853 assert_eq!(bufs[0].deref(), [1; 7].as_ref());
2854 assert_eq!(bufs[1].deref(), [2; 16].as_ref());
2855 assert_eq!(bufs[2].deref(), [3; 8].as_ref());
2857 // Removing a buffer, leaving others as is.
2858 bufs = IoSliceMut::advance(bufs, 7);
2859 assert_eq!(bufs[0].deref(), [2; 16].as_ref());
2860 assert_eq!(bufs[1].deref(), [3; 8].as_ref());
2862 // Removing a buffer and removing from the next buffer.
2863 bufs = IoSliceMut::advance(bufs, 18);
2864 assert_eq!(bufs[0].deref(), [3; 6].as_ref());
2868 fn io_slice_mut_advance_empty_slice() {
2869 let empty_bufs = &mut [][..];
2871 IoSliceMut::advance(empty_bufs, 1);
2875 fn io_slice_mut_advance_beyond_total_length() {
2876 let mut buf1 = [1; 8];
2877 let mut bufs = &mut [IoSliceMut::new(&mut buf1)][..];
2879 // Going beyond the total length should be ok.
2880 bufs = IoSliceMut::advance(bufs, 9);
2881 assert!(bufs.is_empty());
2885 fn io_slice_advance() {
2889 let mut bufs = &mut [IoSlice::new(&buf1), IoSlice::new(&buf2), IoSlice::new(&buf3)][..];
2891 // Only in a single buffer..
2892 bufs = IoSlice::advance(bufs, 1);
2893 assert_eq!(bufs[0].deref(), [1; 7].as_ref());
2894 assert_eq!(bufs[1].deref(), [2; 16].as_ref());
2895 assert_eq!(bufs[2].deref(), [3; 8].as_ref());
2897 // Removing a buffer, leaving others as is.
2898 bufs = IoSlice::advance(bufs, 7);
2899 assert_eq!(bufs[0].deref(), [2; 16].as_ref());
2900 assert_eq!(bufs[1].deref(), [3; 8].as_ref());
2902 // Removing a buffer and removing from the next buffer.
2903 bufs = IoSlice::advance(bufs, 18);
2904 assert_eq!(bufs[0].deref(), [3; 6].as_ref());
2908 fn io_slice_advance_empty_slice() {
2909 let empty_bufs = &mut [][..];
2911 IoSlice::advance(empty_bufs, 1);
2915 fn io_slice_advance_beyond_total_length() {
2917 let mut bufs = &mut [IoSlice::new(&buf1)][..];
2919 // Going beyond the total length should be ok.
2920 bufs = IoSlice::advance(bufs, 9);
2921 assert!(bufs.is_empty());
2924 /// Create a new writer that reads from at most `n_bufs` and reads
2925 /// `per_call` bytes (in total) per call to write.
2926 fn test_writer(n_bufs: usize, per_call: usize) -> TestWriter {
2927 TestWriter { n_bufs, per_call, written: Vec::new() }
2936 impl Write for TestWriter {
2937 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
2938 self.write_vectored(&[IoSlice::new(buf)])
2941 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
2942 let mut left = self.per_call;
2943 let mut written = 0;
2944 for buf in bufs.iter().take(self.n_bufs) {
2945 let n = min(left, buf.len());
2946 self.written.extend_from_slice(&buf[0..n]);
2953 fn flush(&mut self) -> io::Result<()> {
2959 fn test_writer_read_from_one_buf() {
2960 let mut writer = test_writer(1, 2);
2962 assert_eq!(writer.write(&[]).unwrap(), 0);
2963 assert_eq!(writer.write_vectored(&[]).unwrap(), 0);
2965 // Read at most 2 bytes.
2966 assert_eq!(writer.write(&[1, 1, 1]).unwrap(), 2);
2967 let bufs = &[IoSlice::new(&[2, 2, 2])];
2968 assert_eq!(writer.write_vectored(bufs).unwrap(), 2);
2970 // Only read from first buf.
2971 let bufs = &[IoSlice::new(&[3]), IoSlice::new(&[4, 4])];
2972 assert_eq!(writer.write_vectored(bufs).unwrap(), 1);
2974 assert_eq!(writer.written, &[1, 1, 2, 2, 3]);
2978 fn test_writer_read_from_multiple_bufs() {
2979 let mut writer = test_writer(3, 3);
2981 // Read at most 3 bytes from two buffers.
2982 let bufs = &[IoSlice::new(&[1]), IoSlice::new(&[2, 2, 2])];
2983 assert_eq!(writer.write_vectored(bufs).unwrap(), 3);
2985 // Read at most 3 bytes from three buffers.
2986 let bufs = &[IoSlice::new(&[3]), IoSlice::new(&[4]), IoSlice::new(&[5, 5])];
2987 assert_eq!(writer.write_vectored(bufs).unwrap(), 3);
2989 assert_eq!(writer.written, &[1, 2, 2, 3, 4, 5]);
2993 fn test_write_all_vectored() {
2994 #[rustfmt::skip] // Becomes unreadable otherwise.
2995 let tests: Vec<(_, &'static [u8])> = vec![
2997 (vec![IoSlice::new(&[1])], &[1]),
2998 (vec![IoSlice::new(&[1, 2])], &[1, 2]),
2999 (vec![IoSlice::new(&[1, 2, 3])], &[1, 2, 3]),
3000 (vec![IoSlice::new(&[1, 2, 3, 4])], &[1, 2, 3, 4]),
3001 (vec![IoSlice::new(&[1, 2, 3, 4, 5])], &[1, 2, 3, 4, 5]),
3002 (vec![IoSlice::new(&[1]), IoSlice::new(&[2])], &[1, 2]),
3003 (vec![IoSlice::new(&[1]), IoSlice::new(&[2, 2])], &[1, 2, 2]),
3004 (vec![IoSlice::new(&[1, 1]), IoSlice::new(&[2, 2])], &[1, 1, 2, 2]),
3005 (vec![IoSlice::new(&[1, 1]), IoSlice::new(&[2, 2, 2])], &[1, 1, 2, 2, 2]),
3006 (vec![IoSlice::new(&[1, 1]), IoSlice::new(&[2, 2, 2])], &[1, 1, 2, 2, 2]),
3007 (vec![IoSlice::new(&[1, 1, 1]), IoSlice::new(&[2, 2, 2])], &[1, 1, 1, 2, 2, 2]),
3008 (vec![IoSlice::new(&[1, 1, 1]), IoSlice::new(&[2, 2, 2, 2])], &[1, 1, 1, 2, 2, 2, 2]),
3009 (vec![IoSlice::new(&[1, 1, 1, 1]), IoSlice::new(&[2, 2, 2, 2])], &[1, 1, 1, 1, 2, 2, 2, 2]),
3010 (vec![IoSlice::new(&[1]), IoSlice::new(&[2]), IoSlice::new(&[3])], &[1, 2, 3]),
3011 (vec![IoSlice::new(&[1, 1]), IoSlice::new(&[2, 2]), IoSlice::new(&[3, 3])], &[1, 1, 2, 2, 3, 3]),
3012 (vec![IoSlice::new(&[1]), IoSlice::new(&[2, 2]), IoSlice::new(&[3, 3, 3])], &[1, 2, 2, 3, 3, 3]),
3013 (vec![IoSlice::new(&[1, 1, 1]), IoSlice::new(&[2, 2, 2]), IoSlice::new(&[3, 3, 3])], &[1, 1, 1, 2, 2, 2, 3, 3, 3]),
3016 let writer_configs = &[(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)];
3018 for (n_bufs, per_call) in writer_configs.iter().copied() {
3019 for (mut input, wanted) in tests.clone().into_iter() {
3020 let mut writer = test_writer(n_bufs, per_call);
3021 assert!(writer.write_all_vectored(&mut *input).is_ok());
3022 assert_eq!(&*writer.written, &*wanted);