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 //! f.read(&mut buffer)?;
29 //! println!("The bytes: {:?}", buffer);
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 //! f.read(&mut buffer)?;
61 //! println!("The bytes: {:?}", buffer);
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
260 #![stable(feature = "rust1", since = "1.0.0")]
267 use crate::ops::{Deref, DerefMut};
271 #[stable(feature = "rust1", since = "1.0.0")]
272 pub use self::buffered::{BufReader, BufWriter, LineWriter};
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::cursor::Cursor;
277 #[stable(feature = "rust1", since = "1.0.0")]
278 pub use self::error::{Result, Error, ErrorKind};
279 #[stable(feature = "rust1", since = "1.0.0")]
280 pub use self::util::{copy, sink, Sink, empty, Empty, repeat, Repeat};
281 #[stable(feature = "rust1", since = "1.0.0")]
282 pub use self::stdio::{stdin, stdout, stderr, Stdin, Stdout, Stderr};
283 #[stable(feature = "rust1", since = "1.0.0")]
284 pub use self::stdio::{StdoutLock, StderrLock, StdinLock};
285 #[unstable(feature = "print_internals", issue = "0")]
286 pub use self::stdio::{_print, _eprint};
287 #[unstable(feature = "libstd_io_internals", issue = "42788")]
288 #[doc(no_inline, hidden)]
289 pub use self::stdio::{set_panic, set_print};
300 const DEFAULT_BUF_SIZE: usize = crate::sys_common::io::DEFAULT_BUF_SIZE;
302 struct Guard<'a> { buf: &'a mut Vec<u8>, len: usize }
304 impl Drop for Guard<'_> {
306 unsafe { self.buf.set_len(self.len); }
310 // A few methods below (read_to_string, read_line) will append data into a
311 // `String` buffer, but we need to be pretty careful when doing this. The
312 // implementation will just call `.as_mut_vec()` and then delegate to a
313 // byte-oriented reading method, but we must ensure that when returning we never
314 // leave `buf` in a state such that it contains invalid UTF-8 in its bounds.
316 // To this end, we use an RAII guard (to protect against panics) which updates
317 // the length of the string when it is dropped. This guard initially truncates
318 // the string to the prior length and only after we've validated that the
319 // new contents are valid UTF-8 do we allow it to set a longer length.
321 // The unsafety in this function is twofold:
323 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
325 // 2. We're passing a raw buffer to the function `f`, and it is expected that
326 // the function only *appends* bytes to the buffer. We'll get undefined
327 // behavior if existing bytes are overwritten to have non-UTF-8 data.
328 fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
329 where F: FnOnce(&mut Vec<u8>) -> Result<usize>
332 let mut g = Guard { len: buf.len(), buf: buf.as_mut_vec() };
334 if str::from_utf8(&g.buf[g.len..]).is_err() {
336 Err(Error::new(ErrorKind::InvalidData,
337 "stream did not contain valid UTF-8"))
346 // This uses an adaptive system to extend the vector when it fills. We want to
347 // avoid paying to allocate and zero a huge chunk of memory if the reader only
348 // has 4 bytes while still making large reads if the reader does have a ton
349 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
350 // time is 4,500 times (!) slower than a default reservation size of 32 if the
351 // reader has a very small amount of data to return.
353 // Because we're extending the buffer with uninitialized data for trusted
354 // readers, we need to make sure to truncate that if any of this panics.
355 fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
356 read_to_end_with_reservation(r, buf, 32)
359 fn read_to_end_with_reservation<R: Read + ?Sized>(r: &mut R,
361 reservation_size: usize) -> Result<usize>
363 let start_len = buf.len();
364 let mut g = Guard { len: buf.len(), buf: buf };
367 if g.len == g.buf.len() {
369 g.buf.reserve(reservation_size);
370 let capacity = g.buf.capacity();
371 g.buf.set_len(capacity);
372 r.initializer().initialize(&mut g.buf[g.len..]);
376 match r.read(&mut g.buf[g.len..]) {
378 ret = Ok(g.len - start_len);
382 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
393 pub(crate) fn default_read_vectored<F>(read: F, bufs: &mut [IoVecMut<'_>]) -> Result<usize>
395 F: FnOnce(&mut [u8]) -> Result<usize>
399 .find(|b| !b.is_empty())
400 .map_or(&mut [][..], |b| &mut **b);
404 pub(crate) fn default_write_vectored<F>(write: F, bufs: &[IoVec<'_>]) -> Result<usize>
406 F: FnOnce(&[u8]) -> Result<usize>
410 .find(|b| !b.is_empty())
411 .map_or(&[][..], |b| &**b);
415 /// The `Read` trait allows for reading bytes from a source.
417 /// Implementors of the `Read` trait are called 'readers'.
419 /// Readers are defined by one required method, [`read()`]. Each call to [`read()`]
420 /// will attempt to pull bytes from this source into a provided buffer. A
421 /// number of other methods are implemented in terms of [`read()`], giving
422 /// implementors a number of ways to read bytes while only needing to implement
425 /// Readers are intended to be composable with one another. Many implementors
426 /// throughout [`std::io`] take and provide types which implement the `Read`
429 /// Please note that each call to [`read()`] may involve a system call, and
430 /// therefore, using something that implements [`BufRead`], such as
431 /// [`BufReader`], will be more efficient.
435 /// [`File`]s implement `Read`:
439 /// use std::io::prelude::*;
440 /// use std::fs::File;
442 /// fn main() -> io::Result<()> {
443 /// let mut f = File::open("foo.txt")?;
444 /// let mut buffer = [0; 10];
446 /// // read up to 10 bytes
447 /// f.read(&mut buffer)?;
449 /// let mut buffer = Vec::new();
450 /// // read the whole file
451 /// f.read_to_end(&mut buffer)?;
453 /// // read into a String, so that you don't need to do the conversion.
454 /// let mut buffer = String::new();
455 /// f.read_to_string(&mut buffer)?;
457 /// // and more! See the other methods for more details.
462 /// Read from [`&str`] because [`&[u8]`][slice] implements `Read`:
466 /// use std::io::prelude::*;
468 /// fn main() -> io::Result<()> {
469 /// let mut b = "This string will be read".as_bytes();
470 /// let mut buffer = [0; 10];
472 /// // read up to 10 bytes
473 /// b.read(&mut buffer)?;
475 /// // etc... it works exactly as a File does!
480 /// [`read()`]: trait.Read.html#tymethod.read
481 /// [`std::io`]: ../../std/io/index.html
482 /// [`File`]: ../fs/struct.File.html
483 /// [`BufRead`]: trait.BufRead.html
484 /// [`BufReader`]: struct.BufReader.html
485 /// [`&str`]: ../../std/primitive.str.html
486 /// [slice]: ../../std/primitive.slice.html
487 #[stable(feature = "rust1", since = "1.0.0")]
490 /// Pull some bytes from this source into the specified buffer, returning
491 /// how many bytes were read.
493 /// This function does not provide any guarantees about whether it blocks
494 /// waiting for data, but if an object needs to block for a read but cannot
495 /// it will typically signal this via an [`Err`] return value.
497 /// If the return value of this method is [`Ok(n)`], then it must be
498 /// guaranteed that `0 <= n <= buf.len()`. A nonzero `n` value indicates
499 /// that the buffer `buf` has been filled in with `n` bytes of data from this
500 /// source. If `n` is `0`, then it can indicate one of two scenarios:
502 /// 1. This reader has reached its "end of file" and will likely no longer
503 /// be able to produce bytes. Note that this does not mean that the
504 /// reader will *always* no longer be able to produce bytes.
505 /// 2. The buffer specified was 0 bytes in length.
507 /// No guarantees are provided about the contents of `buf` when this
508 /// function is called, implementations cannot rely on any property of the
509 /// contents of `buf` being true. It is recommended that implementations
510 /// only write data to `buf` instead of reading its contents.
514 /// If this function encounters any form of I/O or other error, an error
515 /// variant will be returned. If an error is returned then it must be
516 /// guaranteed that no bytes were read.
518 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
519 /// operation should be retried if there is nothing else to do.
523 /// [`File`]s implement `Read`:
525 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
526 /// [`Ok(n)`]: ../../std/result/enum.Result.html#variant.Ok
527 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
528 /// [`File`]: ../fs/struct.File.html
532 /// use std::io::prelude::*;
533 /// use std::fs::File;
535 /// fn main() -> io::Result<()> {
536 /// let mut f = File::open("foo.txt")?;
537 /// let mut buffer = [0; 10];
539 /// // read up to 10 bytes
540 /// f.read(&mut buffer[..])?;
544 #[stable(feature = "rust1", since = "1.0.0")]
545 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
547 /// Like `read`, except that it reads into a slice of buffers.
549 /// Data is copied to fill each buffer in order, with the final buffer
550 /// written to possibly being only partially filled. This method must behave
551 /// as a single call to `read` with the buffers concatenated would.
553 /// The default implementation calls `read` with either the first nonempty
554 /// buffer provided, or an empty one if none exists.
555 #[unstable(feature = "iovec", issue = "58452")]
556 fn read_vectored(&mut self, bufs: &mut [IoVecMut<'_>]) -> Result<usize> {
557 default_read_vectored(|b| self.read(b), bufs)
560 /// Determines if this `Read`er can work with buffers of uninitialized
563 /// The default implementation returns an initializer which will zero
566 /// If a `Read`er guarantees that it can work properly with uninitialized
567 /// memory, it should call [`Initializer::nop()`]. See the documentation for
568 /// [`Initializer`] for details.
570 /// The behavior of this method must be independent of the state of the
571 /// `Read`er - the method only takes `&self` so that it can be used through
576 /// This method is unsafe because a `Read`er could otherwise return a
577 /// non-zeroing `Initializer` from another `Read` type without an `unsafe`
580 /// [`Initializer::nop()`]: ../../std/io/struct.Initializer.html#method.nop
581 /// [`Initializer`]: ../../std/io/struct.Initializer.html
582 #[unstable(feature = "read_initializer", issue = "42788")]
584 unsafe fn initializer(&self) -> Initializer {
585 Initializer::zeroing()
588 /// Read all bytes until EOF in this source, placing them into `buf`.
590 /// All bytes read from this source will be appended to the specified buffer
591 /// `buf`. This function will continuously call [`read()`] to append more data to
592 /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of
593 /// non-[`ErrorKind::Interrupted`] kind.
595 /// If successful, this function will return the total number of bytes read.
599 /// If this function encounters an error of the kind
600 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
603 /// If any other read error is encountered then this function immediately
604 /// returns. Any bytes which have already been read will be appended to
609 /// [`File`]s implement `Read`:
611 /// [`read()`]: trait.Read.html#tymethod.read
612 /// [`Ok(0)`]: ../../std/result/enum.Result.html#variant.Ok
613 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
614 /// [`File`]: ../fs/struct.File.html
618 /// use std::io::prelude::*;
619 /// use std::fs::File;
621 /// fn main() -> io::Result<()> {
622 /// let mut f = File::open("foo.txt")?;
623 /// let mut buffer = Vec::new();
625 /// // read the whole file
626 /// f.read_to_end(&mut buffer)?;
631 /// (See also the [`std::fs::read`] convenience function for reading from a
634 /// [`std::fs::read`]: ../fs/fn.read.html
635 #[stable(feature = "rust1", since = "1.0.0")]
636 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
637 read_to_end(self, buf)
640 /// Read all bytes until EOF in this source, appending them to `buf`.
642 /// If successful, this function returns the number of bytes which were read
643 /// and appended to `buf`.
647 /// If the data in this stream is *not* valid UTF-8 then an error is
648 /// returned and `buf` is unchanged.
650 /// See [`read_to_end`][readtoend] for other error semantics.
652 /// [readtoend]: #method.read_to_end
656 /// [`File`][file]s implement `Read`:
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 = String::new();
669 /// f.read_to_string(&mut buffer)?;
674 /// (See also the [`std::fs::read_to_string`] convenience function for
675 /// reading from a file.)
677 /// [`std::fs::read_to_string`]: ../fs/fn.read_to_string.html
678 #[stable(feature = "rust1", since = "1.0.0")]
679 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
680 // Note that we do *not* call `.read_to_end()` here. We are passing
681 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
682 // method to fill it up. An arbitrary implementation could overwrite the
683 // entire contents of the vector, not just append to it (which is what
684 // we are expecting).
686 // To prevent extraneously checking the UTF-8-ness of the entire buffer
687 // we pass it to our hardcoded `read_to_end` implementation which we
688 // know is guaranteed to only read data into the end of the buffer.
689 append_to_string(buf, |b| read_to_end(self, b))
692 /// Read the exact number of bytes required to fill `buf`.
694 /// This function reads as many bytes as necessary to completely fill the
695 /// specified buffer `buf`.
697 /// No guarantees are provided about the contents of `buf` when this
698 /// function is called, implementations cannot rely on any property of the
699 /// contents of `buf` being true. It is recommended that implementations
700 /// only write data to `buf` instead of reading its contents.
704 /// If this function encounters an error of the kind
705 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
708 /// If this function encounters an "end of file" before completely filling
709 /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
710 /// The contents of `buf` are unspecified in this case.
712 /// If any other read error is encountered then this function immediately
713 /// returns. The contents of `buf` are unspecified in this case.
715 /// If this function returns an error, it is unspecified how many bytes it
716 /// has read, but it will never read more than would be necessary to
717 /// completely fill the buffer.
721 /// [`File`]s implement `Read`:
723 /// [`File`]: ../fs/struct.File.html
724 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
725 /// [`ErrorKind::UnexpectedEof`]: ../../std/io/enum.ErrorKind.html#variant.UnexpectedEof
729 /// use std::io::prelude::*;
730 /// use std::fs::File;
732 /// fn main() -> io::Result<()> {
733 /// let mut f = File::open("foo.txt")?;
734 /// let mut buffer = [0; 10];
736 /// // read exactly 10 bytes
737 /// f.read_exact(&mut buffer)?;
741 #[stable(feature = "read_exact", since = "1.6.0")]
742 fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
743 while !buf.is_empty() {
744 match self.read(buf) {
746 Ok(n) => { let tmp = buf; buf = &mut tmp[n..]; }
747 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
748 Err(e) => return Err(e),
752 Err(Error::new(ErrorKind::UnexpectedEof,
753 "failed to fill whole buffer"))
759 /// Creates a "by reference" adaptor for this instance of `Read`.
761 /// The returned adaptor also implements `Read` and will simply borrow this
766 /// [`File`][file]s implement `Read`:
768 /// [file]: ../fs/struct.File.html
772 /// use std::io::Read;
773 /// use std::fs::File;
775 /// fn main() -> io::Result<()> {
776 /// let mut f = File::open("foo.txt")?;
777 /// let mut buffer = Vec::new();
778 /// let mut other_buffer = Vec::new();
781 /// let reference = f.by_ref();
783 /// // read at most 5 bytes
784 /// reference.take(5).read_to_end(&mut buffer)?;
786 /// } // drop our &mut reference so we can use f again
788 /// // original file still usable, read the rest
789 /// f.read_to_end(&mut other_buffer)?;
793 #[stable(feature = "rust1", since = "1.0.0")]
794 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
796 /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
798 /// The returned type implements [`Iterator`] where the `Item` is
799 /// [`Result`]`<`[`u8`]`, `[`io::Error`]`>`.
800 /// The yielded item is [`Ok`] if a byte was successfully read and [`Err`]
801 /// otherwise. EOF is mapped to returning [`None`] from this iterator.
805 /// [`File`][file]s implement `Read`:
807 /// [file]: ../fs/struct.File.html
808 /// [`Iterator`]: ../../std/iter/trait.Iterator.html
809 /// [`Result`]: ../../std/result/enum.Result.html
810 /// [`io::Error`]: ../../std/io/struct.Error.html
811 /// [`u8`]: ../../std/primitive.u8.html
812 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
813 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
814 /// [`None`]: ../../std/option/enum.Option.html#variant.None
818 /// use std::io::prelude::*;
819 /// use std::fs::File;
821 /// fn main() -> io::Result<()> {
822 /// let mut f = File::open("foo.txt")?;
824 /// for byte in f.bytes() {
825 /// println!("{}", byte.unwrap());
830 #[stable(feature = "rust1", since = "1.0.0")]
831 fn bytes(self) -> Bytes<Self> where Self: Sized {
832 Bytes { inner: self }
835 /// Creates an adaptor which will chain this stream with another.
837 /// The returned `Read` instance will first read all bytes from this object
838 /// until EOF is encountered. Afterwards the output is equivalent to the
839 /// output of `next`.
843 /// [`File`][file]s implement `Read`:
845 /// [file]: ../fs/struct.File.html
849 /// use std::io::prelude::*;
850 /// use std::fs::File;
852 /// fn main() -> io::Result<()> {
853 /// let mut f1 = File::open("foo.txt")?;
854 /// let mut f2 = File::open("bar.txt")?;
856 /// let mut handle = f1.chain(f2);
857 /// let mut buffer = String::new();
859 /// // read the value into a String. We could use any Read method here,
860 /// // this is just one example.
861 /// handle.read_to_string(&mut buffer)?;
865 #[stable(feature = "rust1", since = "1.0.0")]
866 fn chain<R: Read>(self, next: R) -> Chain<Self, R> where Self: Sized {
867 Chain { first: self, second: next, done_first: false }
870 /// Creates an adaptor which will read at most `limit` bytes from it.
872 /// This function returns a new instance of `Read` which will read at most
873 /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
874 /// read errors will not count towards the number of bytes read and future
875 /// calls to [`read()`] may succeed.
879 /// [`File`]s implement `Read`:
881 /// [`File`]: ../fs/struct.File.html
882 /// [`Ok(0)`]: ../../std/result/enum.Result.html#variant.Ok
883 /// [`read()`]: trait.Read.html#tymethod.read
887 /// use std::io::prelude::*;
888 /// use std::fs::File;
890 /// fn main() -> io::Result<()> {
891 /// let mut f = File::open("foo.txt")?;
892 /// let mut buffer = [0; 5];
894 /// // read at most five bytes
895 /// let mut handle = f.take(5);
897 /// handle.read(&mut buffer)?;
901 #[stable(feature = "rust1", since = "1.0.0")]
902 fn take(self, limit: u64) -> Take<Self> where Self: Sized {
903 Take { inner: self, limit: limit }
907 /// A buffer type used with `Read::read_vectored`.
909 /// It is semantically a wrapper around an `&mut [u8]`, but is guaranteed to be
910 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
912 #[unstable(feature = "iovec", issue = "58452")]
914 pub struct IoVecMut<'a>(sys::io::IoVecMut<'a>);
916 #[unstable(feature = "iovec", issue = "58452")]
917 impl<'a> fmt::Debug for IoVecMut<'a> {
918 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
919 fmt::Debug::fmt(self.0.as_slice(), fmt)
923 impl<'a> IoVecMut<'a> {
924 /// Creates a new `IoVecMut` wrapping a byte slice.
928 /// Panics on Windows if the slice is larger than 4GB.
929 #[unstable(feature = "iovec", issue = "58452")]
931 pub fn new(buf: &'a mut [u8]) -> IoVecMut<'a> {
932 IoVecMut(sys::io::IoVecMut::new(buf))
936 #[unstable(feature = "iovec", issue = "58452")]
937 impl<'a> Deref for IoVecMut<'a> {
941 fn deref(&self) -> &[u8] {
946 #[unstable(feature = "iovec", issue = "58452")]
947 impl<'a> DerefMut for IoVecMut<'a> {
949 fn deref_mut(&mut self) -> &mut [u8] {
950 self.0.as_mut_slice()
954 /// A buffer type used with `Write::write_vectored`.
956 /// It is semantically a wrapper around an `&[u8]`, but is guaranteed to be
957 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
959 #[unstable(feature = "iovec", issue = "58452")]
961 pub struct IoVec<'a>(sys::io::IoVec<'a>);
963 #[unstable(feature = "iovec", issue = "58452")]
964 impl<'a> fmt::Debug for IoVec<'a> {
965 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
966 fmt::Debug::fmt(self.0.as_slice(), fmt)
971 /// Creates a new `IoVec` wrapping a byte slice.
975 /// Panics on Windows if the slice is larger than 4GB.
976 #[unstable(feature = "iovec", issue = "58452")]
978 pub fn new(buf: &'a [u8]) -> IoVec<'a> {
979 IoVec(sys::io::IoVec::new(buf))
983 #[unstable(feature = "iovec", issue = "58452")]
984 impl<'a> Deref for IoVec<'a> {
988 fn deref(&self) -> &[u8] {
993 /// A type used to conditionally initialize buffers passed to `Read` methods.
994 #[unstable(feature = "read_initializer", issue = "42788")]
996 pub struct Initializer(bool);
999 /// Returns a new `Initializer` which will zero out buffers.
1000 #[unstable(feature = "read_initializer", issue = "42788")]
1002 pub fn zeroing() -> Initializer {
1006 /// Returns a new `Initializer` which will not zero out buffers.
1010 /// This may only be called by `Read`ers which guarantee that they will not
1011 /// read from buffers passed to `Read` methods, and that the return value of
1012 /// the method accurately reflects the number of bytes that have been
1013 /// written to the head of the buffer.
1014 #[unstable(feature = "read_initializer", issue = "42788")]
1016 pub unsafe fn nop() -> Initializer {
1020 /// Indicates if a buffer should be initialized.
1021 #[unstable(feature = "read_initializer", issue = "42788")]
1023 pub fn should_initialize(&self) -> bool {
1027 /// Initializes a buffer if necessary.
1028 #[unstable(feature = "read_initializer", issue = "42788")]
1030 pub fn initialize(&self, buf: &mut [u8]) {
1031 if self.should_initialize() {
1032 unsafe { ptr::write_bytes(buf.as_mut_ptr(), 0, buf.len()) }
1037 /// A trait for objects which are byte-oriented sinks.
1039 /// Implementors of the `Write` trait are sometimes called 'writers'.
1041 /// Writers are defined by two required methods, [`write`] and [`flush`]:
1043 /// * The [`write`] method will attempt to write some data into the object,
1044 /// returning how many bytes were successfully written.
1046 /// * The [`flush`] method is useful for adaptors and explicit buffers
1047 /// themselves for ensuring that all buffered data has been pushed out to the
1050 /// Writers are intended to be composable with one another. Many implementors
1051 /// throughout [`std::io`] take and provide types which implement the `Write`
1054 /// [`write`]: #tymethod.write
1055 /// [`flush`]: #tymethod.flush
1056 /// [`std::io`]: index.html
1061 /// use std::io::prelude::*;
1062 /// use std::fs::File;
1064 /// fn main() -> std::io::Result<()> {
1065 /// let mut buffer = File::create("foo.txt")?;
1067 /// buffer.write(b"some bytes")?;
1071 #[stable(feature = "rust1", since = "1.0.0")]
1074 /// Write a buffer into this writer, returning how many bytes were written.
1076 /// This function will attempt to write the entire contents of `buf`, but
1077 /// the entire write may not succeed, or the write may also generate an
1078 /// error. A call to `write` represents *at most one* attempt to write to
1079 /// any wrapped object.
1081 /// Calls to `write` are not guaranteed to block waiting for data to be
1082 /// written, and a write which would otherwise block can be indicated through
1083 /// an [`Err`] variant.
1085 /// If the return value is [`Ok(n)`] then it must be guaranteed that
1086 /// `0 <= n <= buf.len()`. A return value of `0` typically means that the
1087 /// underlying object is no longer able to accept bytes and will likely not
1088 /// be able to in the future as well, or that the buffer provided is empty.
1092 /// Each call to `write` may generate an I/O error indicating that the
1093 /// operation could not be completed. If an error is returned then no bytes
1094 /// in the buffer were written to this writer.
1096 /// It is **not** considered an error if the entire buffer could not be
1097 /// written to this writer.
1099 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the
1100 /// write operation should be retried if there is nothing else to do.
1102 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
1103 /// [`Ok(n)`]: ../../std/result/enum.Result.html#variant.Ok
1104 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
1109 /// use std::io::prelude::*;
1110 /// use std::fs::File;
1112 /// fn main() -> std::io::Result<()> {
1113 /// let mut buffer = File::create("foo.txt")?;
1115 /// // Writes some prefix of the byte string, not necessarily all of it.
1116 /// buffer.write(b"some bytes")?;
1120 #[stable(feature = "rust1", since = "1.0.0")]
1121 fn write(&mut self, buf: &[u8]) -> Result<usize>;
1123 /// Like `write`, except that it writes from a slice of buffers.
1125 /// Data is copied to from each buffer in order, with the final buffer
1126 /// read from possibly being only partially consumed. This method must
1127 /// behave as a call to `write` with the buffers concatenated would.
1129 /// The default implementation calls `write` with either the first nonempty
1130 /// buffer provided, or an empty one if none exists.
1131 #[unstable(feature = "iovec", issue = "58452")]
1132 fn write_vectored(&mut self, bufs: &[IoVec<'_>]) -> Result<usize> {
1133 default_write_vectored(|b| self.write(b), bufs)
1136 /// Flush this output stream, ensuring that all intermediately buffered
1137 /// contents reach their destination.
1141 /// It is considered an error if not all bytes could be written due to
1142 /// I/O errors or EOF being reached.
1147 /// use std::io::prelude::*;
1148 /// use std::io::BufWriter;
1149 /// use std::fs::File;
1151 /// fn main() -> std::io::Result<()> {
1152 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
1154 /// buffer.write(b"some bytes")?;
1155 /// buffer.flush()?;
1159 #[stable(feature = "rust1", since = "1.0.0")]
1160 fn flush(&mut self) -> Result<()>;
1162 /// Attempts to write an entire buffer into this writer.
1164 /// This method will continuously call [`write`] until there is no more data
1165 /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is
1166 /// returned. This method will not return until the entire buffer has been
1167 /// successfully written or such an error occurs. The first error that is
1168 /// not of [`ErrorKind::Interrupted`] kind generated from this method will be
1173 /// This function will return the first error of
1174 /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns.
1176 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
1177 /// [`write`]: #tymethod.write
1182 /// use std::io::prelude::*;
1183 /// use std::fs::File;
1185 /// fn main() -> std::io::Result<()> {
1186 /// let mut buffer = File::create("foo.txt")?;
1188 /// buffer.write_all(b"some bytes")?;
1192 #[stable(feature = "rust1", since = "1.0.0")]
1193 fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
1194 while !buf.is_empty() {
1195 match self.write(buf) {
1196 Ok(0) => return Err(Error::new(ErrorKind::WriteZero,
1197 "failed to write whole buffer")),
1198 Ok(n) => buf = &buf[n..],
1199 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1200 Err(e) => return Err(e),
1206 /// Writes a formatted string into this writer, returning any error
1209 /// This method is primarily used to interface with the
1210 /// [`format_args!`][formatargs] macro, but it is rare that this should
1211 /// explicitly be called. The [`write!`][write] macro should be favored to
1212 /// invoke this method instead.
1214 /// [formatargs]: ../macro.format_args.html
1215 /// [write]: ../macro.write.html
1217 /// This function internally uses the [`write_all`][writeall] method on
1218 /// this trait and hence will continuously write data so long as no errors
1219 /// are received. This also means that partial writes are not indicated in
1222 /// [writeall]: #method.write_all
1226 /// This function will return any I/O error reported while formatting.
1231 /// use std::io::prelude::*;
1232 /// use std::fs::File;
1234 /// fn main() -> std::io::Result<()> {
1235 /// let mut buffer = File::create("foo.txt")?;
1238 /// write!(buffer, "{:.*}", 2, 1.234567)?;
1239 /// // turns into this:
1240 /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1244 #[stable(feature = "rust1", since = "1.0.0")]
1245 fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()> {
1246 // Create a shim which translates a Write to a fmt::Write and saves
1247 // off I/O errors. instead of discarding them
1248 struct Adaptor<'a, T: ?Sized + 'a> {
1253 impl<T: Write + ?Sized> fmt::Write for Adaptor<'_, T> {
1254 fn write_str(&mut self, s: &str) -> fmt::Result {
1255 match self.inner.write_all(s.as_bytes()) {
1258 self.error = Err(e);
1265 let mut output = Adaptor { inner: self, error: Ok(()) };
1266 match fmt::write(&mut output, fmt) {
1269 // check if the error came from the underlying `Write` or not
1270 if output.error.is_err() {
1273 Err(Error::new(ErrorKind::Other, "formatter error"))
1279 /// Creates a "by reference" adaptor for this instance of `Write`.
1281 /// The returned adaptor also implements `Write` and will simply borrow this
1287 /// use std::io::Write;
1288 /// use std::fs::File;
1290 /// fn main() -> std::io::Result<()> {
1291 /// let mut buffer = File::create("foo.txt")?;
1293 /// let reference = buffer.by_ref();
1295 /// // we can use reference just like our original buffer
1296 /// reference.write_all(b"some bytes")?;
1300 #[stable(feature = "rust1", since = "1.0.0")]
1301 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1304 /// The `Seek` trait provides a cursor which can be moved within a stream of
1307 /// The stream typically has a fixed size, allowing seeking relative to either
1308 /// end or the current offset.
1312 /// [`File`][file]s implement `Seek`:
1314 /// [file]: ../fs/struct.File.html
1318 /// use std::io::prelude::*;
1319 /// use std::fs::File;
1320 /// use std::io::SeekFrom;
1322 /// fn main() -> io::Result<()> {
1323 /// let mut f = File::open("foo.txt")?;
1325 /// // move the cursor 42 bytes from the start of the file
1326 /// f.seek(SeekFrom::Start(42))?;
1330 #[stable(feature = "rust1", since = "1.0.0")]
1332 /// Seek to an offset, in bytes, in a stream.
1334 /// A seek beyond the end of a stream is allowed, but behavior is defined
1335 /// by the implementation.
1337 /// If the seek operation completed successfully,
1338 /// this method returns the new position from the start of the stream.
1339 /// That position can be used later with [`SeekFrom::Start`].
1343 /// Seeking to a negative offset is considered an error.
1345 /// [`SeekFrom::Start`]: enum.SeekFrom.html#variant.Start
1346 #[stable(feature = "rust1", since = "1.0.0")]
1347 fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1350 /// Enumeration of possible methods to seek within an I/O object.
1352 /// It is used by the [`Seek`] trait.
1354 /// [`Seek`]: trait.Seek.html
1355 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1356 #[stable(feature = "rust1", since = "1.0.0")]
1358 /// Sets the offset to the provided number of bytes.
1359 #[stable(feature = "rust1", since = "1.0.0")]
1360 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1362 /// Sets the offset to the size of this object plus the specified number of
1365 /// It is possible to seek beyond the end of an object, but it's an error to
1366 /// seek before byte 0.
1367 #[stable(feature = "rust1", since = "1.0.0")]
1368 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1370 /// Sets the offset to the current position plus the specified number of
1373 /// It is possible to seek beyond the end of an object, but it's an error to
1374 /// seek before byte 0.
1375 #[stable(feature = "rust1", since = "1.0.0")]
1376 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1379 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>)
1383 let (done, used) = {
1384 let available = match r.fill_buf() {
1386 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1387 Err(e) => return Err(e)
1389 match memchr::memchr(delim, available) {
1391 buf.extend_from_slice(&available[..=i]);
1395 buf.extend_from_slice(available);
1396 (false, available.len())
1402 if done || used == 0 {
1408 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1409 /// to perform extra ways of reading.
1411 /// For example, reading line-by-line is inefficient without using a buffer, so
1412 /// if you want to read by line, you'll need `BufRead`, which includes a
1413 /// [`read_line`] method as well as a [`lines`] iterator.
1417 /// A locked standard input implements `BufRead`:
1421 /// use std::io::prelude::*;
1423 /// let stdin = io::stdin();
1424 /// for line in stdin.lock().lines() {
1425 /// println!("{}", line.unwrap());
1429 /// If you have something that implements [`Read`], you can use the [`BufReader`
1430 /// type][`BufReader`] to turn it into a `BufRead`.
1432 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1433 /// [`BufReader`] to the rescue!
1435 /// [`BufReader`]: struct.BufReader.html
1436 /// [`File`]: ../fs/struct.File.html
1437 /// [`read_line`]: #method.read_line
1438 /// [`lines`]: #method.lines
1439 /// [`Read`]: trait.Read.html
1442 /// use std::io::{self, BufReader};
1443 /// use std::io::prelude::*;
1444 /// use std::fs::File;
1446 /// fn main() -> io::Result<()> {
1447 /// let f = File::open("foo.txt")?;
1448 /// let f = BufReader::new(f);
1450 /// for line in f.lines() {
1451 /// println!("{}", line.unwrap());
1458 #[stable(feature = "rust1", since = "1.0.0")]
1459 pub trait BufRead: Read {
1460 /// Returns the contents of the internal buffer, filling it with more data
1461 /// from the inner reader if it is empty.
1463 /// This function is a lower-level call. It needs to be paired with the
1464 /// [`consume`] method to function properly. When calling this
1465 /// method, none of the contents will be "read" in the sense that later
1466 /// calling `read` may return the same contents. As such, [`consume`] must
1467 /// be called with the number of bytes that are consumed from this buffer to
1468 /// ensure that the bytes are never returned twice.
1470 /// [`consume`]: #tymethod.consume
1472 /// An empty buffer returned indicates that the stream has reached EOF.
1476 /// This function will return an I/O error if the underlying reader was
1477 /// read, but returned an error.
1481 /// A locked standard input implements `BufRead`:
1485 /// use std::io::prelude::*;
1487 /// let stdin = io::stdin();
1488 /// let mut stdin = stdin.lock();
1490 /// // we can't have two `&mut` references to `stdin`, so use a block
1491 /// // to end the borrow early.
1493 /// let buffer = stdin.fill_buf().unwrap();
1495 /// // work with buffer
1496 /// println!("{:?}", buffer);
1501 /// // ensure the bytes we worked with aren't returned again later
1502 /// stdin.consume(length);
1504 #[stable(feature = "rust1", since = "1.0.0")]
1505 fn fill_buf(&mut self) -> Result<&[u8]>;
1507 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1508 /// so they should no longer be returned in calls to `read`.
1510 /// This function is a lower-level call. It needs to be paired with the
1511 /// [`fill_buf`] method to function properly. This function does
1512 /// not perform any I/O, it simply informs this object that some amount of
1513 /// its buffer, returned from [`fill_buf`], has been consumed and should
1514 /// no longer be returned. As such, this function may do odd things if
1515 /// [`fill_buf`] isn't called before calling it.
1517 /// The `amt` must be `<=` the number of bytes in the buffer returned by
1522 /// Since `consume()` is meant to be used with [`fill_buf`],
1523 /// that method's example includes an example of `consume()`.
1525 /// [`fill_buf`]: #tymethod.fill_buf
1526 #[stable(feature = "rust1", since = "1.0.0")]
1527 fn consume(&mut self, amt: usize);
1529 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
1531 /// This function will read bytes from the underlying stream until the
1532 /// delimiter or EOF is found. Once found, all bytes up to, and including,
1533 /// the delimiter (if found) will be appended to `buf`.
1535 /// If successful, this function will return the total number of bytes read.
1539 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1540 /// will otherwise return any errors returned by [`fill_buf`].
1542 /// If an I/O error is encountered then all bytes read so far will be
1543 /// present in `buf` and its length will have been adjusted appropriately.
1545 /// [`fill_buf`]: #tymethod.fill_buf
1546 /// [`ErrorKind::Interrupted`]: enum.ErrorKind.html#variant.Interrupted
1550 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1551 /// this example, we use [`Cursor`] to read all the bytes in a byte slice
1552 /// in hyphen delimited segments:
1554 /// [`Cursor`]: struct.Cursor.html
1557 /// use std::io::{self, BufRead};
1559 /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
1560 /// let mut buf = vec![];
1562 /// // cursor is at 'l'
1563 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1564 /// .expect("reading from cursor won't fail");
1565 /// assert_eq!(num_bytes, 6);
1566 /// assert_eq!(buf, b"lorem-");
1569 /// // cursor is at 'i'
1570 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1571 /// .expect("reading from cursor won't fail");
1572 /// assert_eq!(num_bytes, 5);
1573 /// assert_eq!(buf, b"ipsum");
1576 /// // cursor is at EOF
1577 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1578 /// .expect("reading from cursor won't fail");
1579 /// assert_eq!(num_bytes, 0);
1580 /// assert_eq!(buf, b"");
1582 #[stable(feature = "rust1", since = "1.0.0")]
1583 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
1584 read_until(self, byte, buf)
1587 /// Read all bytes until a newline (the 0xA byte) is reached, and append
1588 /// them to the provided buffer.
1590 /// This function will read bytes from the underlying stream until the
1591 /// newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes
1592 /// up to, and including, the delimiter (if found) will be appended to
1595 /// If successful, this function will return the total number of bytes read.
1597 /// If this function returns `Ok(0)`, the stream has reached EOF.
1601 /// This function has the same error semantics as [`read_until`] and will
1602 /// also return an error if the read bytes are not valid UTF-8. If an I/O
1603 /// error is encountered then `buf` may contain some bytes already read in
1604 /// the event that all data read so far was valid UTF-8.
1606 /// [`read_until`]: #method.read_until
1610 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1611 /// this example, we use [`Cursor`] to read all the lines in a byte slice:
1613 /// [`Cursor`]: struct.Cursor.html
1616 /// use std::io::{self, BufRead};
1618 /// let mut cursor = io::Cursor::new(b"foo\nbar");
1619 /// let mut buf = String::new();
1621 /// // cursor is at 'f'
1622 /// let num_bytes = cursor.read_line(&mut buf)
1623 /// .expect("reading from cursor won't fail");
1624 /// assert_eq!(num_bytes, 4);
1625 /// assert_eq!(buf, "foo\n");
1628 /// // cursor is at 'b'
1629 /// let num_bytes = cursor.read_line(&mut buf)
1630 /// .expect("reading from cursor won't fail");
1631 /// assert_eq!(num_bytes, 3);
1632 /// assert_eq!(buf, "bar");
1635 /// // cursor is at EOF
1636 /// let num_bytes = cursor.read_line(&mut buf)
1637 /// .expect("reading from cursor won't fail");
1638 /// assert_eq!(num_bytes, 0);
1639 /// assert_eq!(buf, "");
1641 #[stable(feature = "rust1", since = "1.0.0")]
1642 fn read_line(&mut self, buf: &mut String) -> Result<usize> {
1643 // Note that we are not calling the `.read_until` method here, but
1644 // rather our hardcoded implementation. For more details as to why, see
1645 // the comments in `read_to_end`.
1646 append_to_string(buf, |b| read_until(self, b'\n', b))
1649 /// Returns an iterator over the contents of this reader split on the byte
1652 /// The iterator returned from this function will return instances of
1653 /// [`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
1654 /// the delimiter byte at the end.
1656 /// This function will yield errors whenever [`read_until`] would have
1657 /// also yielded an error.
1659 /// [`io::Result`]: type.Result.html
1660 /// [`Vec<u8>`]: ../vec/struct.Vec.html
1661 /// [`read_until`]: #method.read_until
1665 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1666 /// this example, we use [`Cursor`] to iterate over all hyphen delimited
1667 /// segments in a byte slice
1669 /// [`Cursor`]: struct.Cursor.html
1672 /// use std::io::{self, BufRead};
1674 /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
1676 /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
1677 /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
1678 /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
1679 /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
1680 /// assert_eq!(split_iter.next(), None);
1682 #[stable(feature = "rust1", since = "1.0.0")]
1683 fn split(self, byte: u8) -> Split<Self> where Self: Sized {
1684 Split { buf: self, delim: byte }
1687 /// Returns an iterator over the lines of this reader.
1689 /// The iterator returned from this function will yield instances of
1690 /// [`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline
1691 /// byte (the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.
1693 /// [`io::Result`]: type.Result.html
1694 /// [`String`]: ../string/struct.String.html
1698 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1699 /// this example, we use [`Cursor`] to iterate over all the lines in a byte
1702 /// [`Cursor`]: struct.Cursor.html
1705 /// use std::io::{self, BufRead};
1707 /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
1709 /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
1710 /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
1711 /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
1712 /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
1713 /// assert_eq!(lines_iter.next(), None);
1718 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
1720 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
1721 #[stable(feature = "rust1", since = "1.0.0")]
1722 fn lines(self) -> Lines<Self> where Self: Sized {
1727 /// Adaptor to chain together two readers.
1729 /// This struct is generally created by calling [`chain`] on a reader.
1730 /// Please see the documentation of [`chain`] for more details.
1732 /// [`chain`]: trait.Read.html#method.chain
1733 #[stable(feature = "rust1", since = "1.0.0")]
1734 pub struct Chain<T, U> {
1740 impl<T, U> Chain<T, U> {
1741 /// Consumes the `Chain`, returning the wrapped readers.
1747 /// use std::io::prelude::*;
1748 /// use std::fs::File;
1750 /// fn main() -> io::Result<()> {
1751 /// let mut foo_file = File::open("foo.txt")?;
1752 /// let mut bar_file = File::open("bar.txt")?;
1754 /// let chain = foo_file.chain(bar_file);
1755 /// let (foo_file, bar_file) = chain.into_inner();
1759 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1760 pub fn into_inner(self) -> (T, U) {
1761 (self.first, self.second)
1764 /// Gets references to the underlying readers in this `Chain`.
1770 /// use std::io::prelude::*;
1771 /// use std::fs::File;
1773 /// fn main() -> io::Result<()> {
1774 /// let mut foo_file = File::open("foo.txt")?;
1775 /// let mut bar_file = File::open("bar.txt")?;
1777 /// let chain = foo_file.chain(bar_file);
1778 /// let (foo_file, bar_file) = chain.get_ref();
1782 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1783 pub fn get_ref(&self) -> (&T, &U) {
1784 (&self.first, &self.second)
1787 /// Gets mutable references to the underlying readers in this `Chain`.
1789 /// Care should be taken to avoid modifying the internal I/O state of the
1790 /// underlying readers as doing so may corrupt the internal state of this
1797 /// use std::io::prelude::*;
1798 /// use std::fs::File;
1800 /// fn main() -> io::Result<()> {
1801 /// let mut foo_file = File::open("foo.txt")?;
1802 /// let mut bar_file = File::open("bar.txt")?;
1804 /// let mut chain = foo_file.chain(bar_file);
1805 /// let (foo_file, bar_file) = chain.get_mut();
1809 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1810 pub fn get_mut(&mut self) -> (&mut T, &mut U) {
1811 (&mut self.first, &mut self.second)
1815 #[stable(feature = "std_debug", since = "1.16.0")]
1816 impl<T: fmt::Debug, U: fmt::Debug> fmt::Debug for Chain<T, U> {
1817 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1818 f.debug_struct("Chain")
1819 .field("t", &self.first)
1820 .field("u", &self.second)
1825 #[stable(feature = "rust1", since = "1.0.0")]
1826 impl<T: Read, U: Read> Read for Chain<T, U> {
1827 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1828 if !self.done_first {
1829 match self.first.read(buf)? {
1830 0 if buf.len() != 0 => self.done_first = true,
1834 self.second.read(buf)
1837 fn read_vectored(&mut self, bufs: &mut [IoVecMut<'_>]) -> Result<usize> {
1838 if !self.done_first {
1839 match self.first.read_vectored(bufs)? {
1840 0 if bufs.iter().any(|b| !b.is_empty()) => self.done_first = true,
1844 self.second.read_vectored(bufs)
1847 unsafe fn initializer(&self) -> Initializer {
1848 let initializer = self.first.initializer();
1849 if initializer.should_initialize() {
1852 self.second.initializer()
1857 #[stable(feature = "chain_bufread", since = "1.9.0")]
1858 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
1859 fn fill_buf(&mut self) -> Result<&[u8]> {
1860 if !self.done_first {
1861 match self.first.fill_buf()? {
1862 buf if buf.len() == 0 => { self.done_first = true; }
1863 buf => return Ok(buf),
1866 self.second.fill_buf()
1869 fn consume(&mut self, amt: usize) {
1870 if !self.done_first {
1871 self.first.consume(amt)
1873 self.second.consume(amt)
1878 /// Reader adaptor which limits the bytes read from an underlying reader.
1880 /// This struct is generally created by calling [`take`] on a reader.
1881 /// Please see the documentation of [`take`] for more details.
1883 /// [`take`]: trait.Read.html#method.take
1884 #[stable(feature = "rust1", since = "1.0.0")]
1886 pub struct Take<T> {
1892 /// Returns the number of bytes that can be read before this instance will
1897 /// This instance may reach `EOF` after reading fewer bytes than indicated by
1898 /// this method if the underlying [`Read`] instance reaches EOF.
1900 /// [`Read`]: ../../std/io/trait.Read.html
1906 /// use std::io::prelude::*;
1907 /// use std::fs::File;
1909 /// fn main() -> io::Result<()> {
1910 /// let f = File::open("foo.txt")?;
1912 /// // read at most five bytes
1913 /// let handle = f.take(5);
1915 /// println!("limit: {}", handle.limit());
1919 #[stable(feature = "rust1", since = "1.0.0")]
1920 pub fn limit(&self) -> u64 { self.limit }
1922 /// Sets the number of bytes that can be read before this instance will
1923 /// return EOF. This is the same as constructing a new `Take` instance, so
1924 /// the amount of bytes read and the previous limit value don't matter when
1925 /// calling this method.
1931 /// use std::io::prelude::*;
1932 /// use std::fs::File;
1934 /// fn main() -> io::Result<()> {
1935 /// let f = File::open("foo.txt")?;
1937 /// // read at most five bytes
1938 /// let mut handle = f.take(5);
1939 /// handle.set_limit(10);
1941 /// assert_eq!(handle.limit(), 10);
1945 #[stable(feature = "take_set_limit", since = "1.27.0")]
1946 pub fn set_limit(&mut self, limit: u64) {
1950 /// Consumes the `Take`, returning the wrapped reader.
1956 /// use std::io::prelude::*;
1957 /// use std::fs::File;
1959 /// fn main() -> io::Result<()> {
1960 /// let mut file = File::open("foo.txt")?;
1962 /// let mut buffer = [0; 5];
1963 /// let mut handle = file.take(5);
1964 /// handle.read(&mut buffer)?;
1966 /// let file = handle.into_inner();
1970 #[stable(feature = "io_take_into_inner", since = "1.15.0")]
1971 pub fn into_inner(self) -> T {
1975 /// Gets a reference to the underlying reader.
1981 /// use std::io::prelude::*;
1982 /// use std::fs::File;
1984 /// fn main() -> io::Result<()> {
1985 /// let mut file = File::open("foo.txt")?;
1987 /// let mut buffer = [0; 5];
1988 /// let mut handle = file.take(5);
1989 /// handle.read(&mut buffer)?;
1991 /// let file = handle.get_ref();
1995 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1996 pub fn get_ref(&self) -> &T {
2000 /// Gets a mutable reference to the underlying reader.
2002 /// Care should be taken to avoid modifying the internal I/O state of the
2003 /// underlying reader as doing so may corrupt the internal limit of this
2010 /// use std::io::prelude::*;
2011 /// use std::fs::File;
2013 /// fn main() -> io::Result<()> {
2014 /// let mut file = File::open("foo.txt")?;
2016 /// let mut buffer = [0; 5];
2017 /// let mut handle = file.take(5);
2018 /// handle.read(&mut buffer)?;
2020 /// let file = handle.get_mut();
2024 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2025 pub fn get_mut(&mut self) -> &mut T {
2030 #[stable(feature = "rust1", since = "1.0.0")]
2031 impl<T: Read> Read for Take<T> {
2032 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2033 // Don't call into inner reader at all at EOF because it may still block
2034 if self.limit == 0 {
2038 let max = cmp::min(buf.len() as u64, self.limit) as usize;
2039 let n = self.inner.read(&mut buf[..max])?;
2040 self.limit -= n as u64;
2044 unsafe fn initializer(&self) -> Initializer {
2045 self.inner.initializer()
2048 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
2049 let reservation_size = cmp::min(self.limit, 32) as usize;
2051 read_to_end_with_reservation(self, buf, reservation_size)
2055 #[stable(feature = "rust1", since = "1.0.0")]
2056 impl<T: BufRead> BufRead for Take<T> {
2057 fn fill_buf(&mut self) -> Result<&[u8]> {
2058 // Don't call into inner reader at all at EOF because it may still block
2059 if self.limit == 0 {
2063 let buf = self.inner.fill_buf()?;
2064 let cap = cmp::min(buf.len() as u64, self.limit) as usize;
2068 fn consume(&mut self, amt: usize) {
2069 // Don't let callers reset the limit by passing an overlarge value
2070 let amt = cmp::min(amt as u64, self.limit) as usize;
2071 self.limit -= amt as u64;
2072 self.inner.consume(amt);
2076 /// An iterator over `u8` values of a reader.
2078 /// This struct is generally created by calling [`bytes`] on a reader.
2079 /// Please see the documentation of [`bytes`] for more details.
2081 /// [`bytes`]: trait.Read.html#method.bytes
2082 #[stable(feature = "rust1", since = "1.0.0")]
2084 pub struct Bytes<R> {
2088 #[stable(feature = "rust1", since = "1.0.0")]
2089 impl<R: Read> Iterator for Bytes<R> {
2090 type Item = Result<u8>;
2092 fn next(&mut self) -> Option<Result<u8>> {
2095 return match self.inner.read(slice::from_mut(&mut byte)) {
2097 Ok(..) => Some(Ok(byte)),
2098 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
2099 Err(e) => Some(Err(e)),
2105 /// An iterator over the contents of an instance of `BufRead` split on a
2106 /// particular byte.
2108 /// This struct is generally created by calling [`split`][split] on a
2109 /// `BufRead`. Please see the documentation of `split()` for more details.
2111 /// [split]: trait.BufRead.html#method.split
2112 #[stable(feature = "rust1", since = "1.0.0")]
2114 pub struct Split<B> {
2119 #[stable(feature = "rust1", since = "1.0.0")]
2120 impl<B: BufRead> Iterator for Split<B> {
2121 type Item = Result<Vec<u8>>;
2123 fn next(&mut self) -> Option<Result<Vec<u8>>> {
2124 let mut buf = Vec::new();
2125 match self.buf.read_until(self.delim, &mut buf) {
2128 if buf[buf.len() - 1] == self.delim {
2133 Err(e) => Some(Err(e))
2138 /// An iterator over the lines of an instance of `BufRead`.
2140 /// This struct is generally created by calling [`lines`][lines] on a
2141 /// `BufRead`. Please see the documentation of `lines()` for more details.
2143 /// [lines]: trait.BufRead.html#method.lines
2144 #[stable(feature = "rust1", since = "1.0.0")]
2146 pub struct Lines<B> {
2150 #[stable(feature = "rust1", since = "1.0.0")]
2151 impl<B: BufRead> Iterator for Lines<B> {
2152 type Item = Result<String>;
2154 fn next(&mut self) -> Option<Result<String>> {
2155 let mut buf = String::new();
2156 match self.buf.read_line(&mut buf) {
2159 if buf.ends_with("\n") {
2161 if buf.ends_with("\r") {
2167 Err(e) => Some(Err(e))
2174 use crate::io::prelude::*;
2180 #[cfg_attr(target_os = "emscripten", ignore)]
2182 let mut buf = Cursor::new(&b"12"[..]);
2183 let mut v = Vec::new();
2184 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 2);
2185 assert_eq!(v, b"12");
2187 let mut buf = Cursor::new(&b"1233"[..]);
2188 let mut v = Vec::new();
2189 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 3);
2190 assert_eq!(v, b"123");
2192 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 1);
2193 assert_eq!(v, b"3");
2195 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 0);
2201 let buf = Cursor::new(&b"12"[..]);
2202 let mut s = buf.split(b'3');
2203 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2204 assert!(s.next().is_none());
2206 let buf = Cursor::new(&b"1233"[..]);
2207 let mut s = buf.split(b'3');
2208 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2209 assert_eq!(s.next().unwrap().unwrap(), vec![]);
2210 assert!(s.next().is_none());
2215 let mut buf = Cursor::new(&b"12"[..]);
2216 let mut v = String::new();
2217 assert_eq!(buf.read_line(&mut v).unwrap(), 2);
2218 assert_eq!(v, "12");
2220 let mut buf = Cursor::new(&b"12\n\n"[..]);
2221 let mut v = String::new();
2222 assert_eq!(buf.read_line(&mut v).unwrap(), 3);
2223 assert_eq!(v, "12\n");
2225 assert_eq!(buf.read_line(&mut v).unwrap(), 1);
2226 assert_eq!(v, "\n");
2228 assert_eq!(buf.read_line(&mut v).unwrap(), 0);
2234 let buf = Cursor::new(&b"12\r"[..]);
2235 let mut s = buf.lines();
2236 assert_eq!(s.next().unwrap().unwrap(), "12\r".to_string());
2237 assert!(s.next().is_none());
2239 let buf = Cursor::new(&b"12\r\n\n"[..]);
2240 let mut s = buf.lines();
2241 assert_eq!(s.next().unwrap().unwrap(), "12".to_string());
2242 assert_eq!(s.next().unwrap().unwrap(), "".to_string());
2243 assert!(s.next().is_none());
2248 let mut c = Cursor::new(&b""[..]);
2249 let mut v = Vec::new();
2250 assert_eq!(c.read_to_end(&mut v).unwrap(), 0);
2253 let mut c = Cursor::new(&b"1"[..]);
2254 let mut v = Vec::new();
2255 assert_eq!(c.read_to_end(&mut v).unwrap(), 1);
2256 assert_eq!(v, b"1");
2258 let cap = 1024 * 1024;
2259 let data = (0..cap).map(|i| (i / 3) as u8).collect::<Vec<_>>();
2260 let mut v = Vec::new();
2261 let (a, b) = data.split_at(data.len() / 2);
2262 assert_eq!(Cursor::new(a).read_to_end(&mut v).unwrap(), a.len());
2263 assert_eq!(Cursor::new(b).read_to_end(&mut v).unwrap(), b.len());
2264 assert_eq!(v, data);
2268 fn read_to_string() {
2269 let mut c = Cursor::new(&b""[..]);
2270 let mut v = String::new();
2271 assert_eq!(c.read_to_string(&mut v).unwrap(), 0);
2274 let mut c = Cursor::new(&b"1"[..]);
2275 let mut v = String::new();
2276 assert_eq!(c.read_to_string(&mut v).unwrap(), 1);
2279 let mut c = Cursor::new(&b"\xff"[..]);
2280 let mut v = String::new();
2281 assert!(c.read_to_string(&mut v).is_err());
2286 let mut buf = [0; 4];
2288 let mut c = Cursor::new(&b""[..]);
2289 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2290 io::ErrorKind::UnexpectedEof);
2292 let mut c = Cursor::new(&b"123"[..]).chain(Cursor::new(&b"456789"[..]));
2293 c.read_exact(&mut buf).unwrap();
2294 assert_eq!(&buf, b"1234");
2295 c.read_exact(&mut buf).unwrap();
2296 assert_eq!(&buf, b"5678");
2297 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2298 io::ErrorKind::UnexpectedEof);
2302 fn read_exact_slice() {
2303 let mut buf = [0; 4];
2305 let mut c = &b""[..];
2306 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2307 io::ErrorKind::UnexpectedEof);
2309 let mut c = &b"123"[..];
2310 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2311 io::ErrorKind::UnexpectedEof);
2312 // make sure the optimized (early returning) method is being used
2313 assert_eq!(&buf, &[0; 4]);
2315 let mut c = &b"1234"[..];
2316 c.read_exact(&mut buf).unwrap();
2317 assert_eq!(&buf, b"1234");
2319 let mut c = &b"56789"[..];
2320 c.read_exact(&mut buf).unwrap();
2321 assert_eq!(&buf, b"5678");
2322 assert_eq!(c, b"9");
2330 fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
2331 Err(io::Error::new(io::ErrorKind::Other, ""))
2334 impl BufRead for R {
2335 fn fill_buf(&mut self) -> io::Result<&[u8]> {
2336 Err(io::Error::new(io::ErrorKind::Other, ""))
2338 fn consume(&mut self, _amt: usize) { }
2341 let mut buf = [0; 1];
2342 assert_eq!(0, R.take(0).read(&mut buf).unwrap());
2343 assert_eq!(b"", R.take(0).fill_buf().unwrap());
2346 fn cmp_bufread<Br1: BufRead, Br2: BufRead>(mut br1: Br1, mut br2: Br2, exp: &[u8]) {
2347 let mut cat = Vec::new();
2350 let buf1 = br1.fill_buf().unwrap();
2351 let buf2 = br2.fill_buf().unwrap();
2352 let minlen = if buf1.len() < buf2.len() { buf1.len() } else { buf2.len() };
2353 assert_eq!(buf1[..minlen], buf2[..minlen]);
2354 cat.extend_from_slice(&buf1[..minlen]);
2360 br1.consume(consume);
2361 br2.consume(consume);
2363 assert_eq!(br1.fill_buf().unwrap().len(), 0);
2364 assert_eq!(br2.fill_buf().unwrap().len(), 0);
2365 assert_eq!(&cat[..], &exp[..])
2369 fn chain_bufread() {
2370 let testdata = b"ABCDEFGHIJKL";
2371 let chain1 = (&testdata[..3]).chain(&testdata[3..6])
2372 .chain(&testdata[6..9])
2373 .chain(&testdata[9..]);
2374 let chain2 = (&testdata[..4]).chain(&testdata[4..8])
2375 .chain(&testdata[8..]);
2376 cmp_bufread(chain1, chain2, &testdata[..]);
2380 fn chain_zero_length_read_is_not_eof() {
2383 let mut s = String::new();
2384 let mut chain = (&a[..]).chain(&b[..]);
2385 chain.read(&mut []).unwrap();
2386 chain.read_to_string(&mut s).unwrap();
2387 assert_eq!("AB", s);
2391 #[cfg_attr(target_os = "emscripten", ignore)]
2392 fn bench_read_to_end(b: &mut test::Bencher) {
2394 let mut lr = repeat(1).take(10000000);
2395 let mut vec = Vec::with_capacity(1024);
2396 super::read_to_end(&mut lr, &mut vec)