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 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 = ::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 /// The `Read` trait allows for reading bytes from a source.
395 /// Implementors of the `Read` trait are called 'readers'.
397 /// Readers are defined by one required method, [`read()`]. Each call to [`read()`]
398 /// will attempt to pull bytes from this source into a provided buffer. A
399 /// number of other methods are implemented in terms of [`read()`], giving
400 /// implementors a number of ways to read bytes while only needing to implement
403 /// Readers are intended to be composable with one another. Many implementors
404 /// throughout [`std::io`] take and provide types which implement the `Read`
407 /// Please note that each call to [`read()`] may involve a system call, and
408 /// therefore, using something that implements [`BufRead`], such as
409 /// [`BufReader`], will be more efficient.
413 /// [`File`]s implement `Read`:
417 /// use std::io::prelude::*;
418 /// use std::fs::File;
420 /// fn main() -> io::Result<()> {
421 /// let mut f = File::open("foo.txt")?;
422 /// let mut buffer = [0; 10];
424 /// // read up to 10 bytes
425 /// f.read(&mut buffer)?;
427 /// let mut buffer = Vec::new();
428 /// // read the whole file
429 /// f.read_to_end(&mut buffer)?;
431 /// // read into a String, so that you don't need to do the conversion.
432 /// let mut buffer = String::new();
433 /// f.read_to_string(&mut buffer)?;
435 /// // and more! See the other methods for more details.
440 /// Read from [`&str`] because [`&[u8]`][slice] implements `Read`:
444 /// use std::io::prelude::*;
446 /// fn main() -> io::Result<()> {
447 /// let mut b = "This string will be read".as_bytes();
448 /// let mut buffer = [0; 10];
450 /// // read up to 10 bytes
451 /// b.read(&mut buffer)?;
453 /// // etc... it works exactly as a File does!
458 /// [`read()`]: trait.Read.html#tymethod.read
459 /// [`std::io`]: ../../std/io/index.html
460 /// [`File`]: ../fs/struct.File.html
461 /// [`BufRead`]: trait.BufRead.html
462 /// [`BufReader`]: struct.BufReader.html
463 /// [`&str`]: ../../std/primitive.str.html
464 /// [slice]: ../../std/primitive.slice.html
465 #[stable(feature = "rust1", since = "1.0.0")]
468 /// Pull some bytes from this source into the specified buffer, returning
469 /// how many bytes were read.
471 /// This function does not provide any guarantees about whether it blocks
472 /// waiting for data, but if an object needs to block for a read but cannot
473 /// it will typically signal this via an [`Err`] return value.
475 /// If the return value of this method is [`Ok(n)`], then it must be
476 /// guaranteed that `0 <= n <= buf.len()`. A nonzero `n` value indicates
477 /// that the buffer `buf` has been filled in with `n` bytes of data from this
478 /// source. If `n` is `0`, then it can indicate one of two scenarios:
480 /// 1. This reader has reached its "end of file" and will likely no longer
481 /// be able to produce bytes. Note that this does not mean that the
482 /// reader will *always* no longer be able to produce bytes.
483 /// 2. The buffer specified was 0 bytes in length.
485 /// No guarantees are provided about the contents of `buf` when this
486 /// function is called, implementations cannot rely on any property of the
487 /// contents of `buf` being true. It is recommended that implementations
488 /// only write data to `buf` instead of reading its contents.
492 /// If this function encounters any form of I/O or other error, an error
493 /// variant will be returned. If an error is returned then it must be
494 /// guaranteed that no bytes were read.
496 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
497 /// operation should be retried if there is nothing else to do.
501 /// [`File`]s implement `Read`:
503 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
504 /// [`Ok(n)`]: ../../std/result/enum.Result.html#variant.Ok
505 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
506 /// [`File`]: ../fs/struct.File.html
510 /// use std::io::prelude::*;
511 /// use std::fs::File;
513 /// fn main() -> io::Result<()> {
514 /// let mut f = File::open("foo.txt")?;
515 /// let mut buffer = [0; 10];
517 /// // read up to 10 bytes
518 /// f.read(&mut buffer[..])?;
522 #[stable(feature = "rust1", since = "1.0.0")]
523 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
525 /// Like `read`, except that it reads into a slice of buffers.
527 /// Data is copied to fill each buffer in order, with the final buffer
528 /// written to possibly being only partially filled. This method must behave
529 /// as a single call to `read` with the buffers concatenated would.
531 /// The default implementation simply passes the first nonempty buffer to
533 #[unstable(feature = "iovec", issue = "58452")]
534 fn read_vectored(&mut self, bufs: &mut [IoVecMut<'_>]) -> Result<usize> {
535 match bufs.iter_mut().find(|b| !b.is_empty()) {
536 Some(buf) => self.read(buf),
541 /// Determines if this `Read`er can work with buffers of uninitialized
544 /// The default implementation returns an initializer which will zero
547 /// If a `Read`er guarantees that it can work properly with uninitialized
548 /// memory, it should call [`Initializer::nop()`]. See the documentation for
549 /// [`Initializer`] for details.
551 /// The behavior of this method must be independent of the state of the
552 /// `Read`er - the method only takes `&self` so that it can be used through
557 /// This method is unsafe because a `Read`er could otherwise return a
558 /// non-zeroing `Initializer` from another `Read` type without an `unsafe`
561 /// [`Initializer::nop()`]: ../../std/io/struct.Initializer.html#method.nop
562 /// [`Initializer`]: ../../std/io/struct.Initializer.html
563 #[unstable(feature = "read_initializer", issue = "42788")]
565 unsafe fn initializer(&self) -> Initializer {
566 Initializer::zeroing()
569 /// Read all bytes until EOF in this source, placing them into `buf`.
571 /// All bytes read from this source will be appended to the specified buffer
572 /// `buf`. This function will continuously call [`read()`] to append more data to
573 /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of
574 /// non-[`ErrorKind::Interrupted`] kind.
576 /// If successful, this function will return the total number of bytes read.
580 /// If this function encounters an error of the kind
581 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
584 /// If any other read error is encountered then this function immediately
585 /// returns. Any bytes which have already been read will be appended to
590 /// [`File`]s implement `Read`:
592 /// [`read()`]: trait.Read.html#tymethod.read
593 /// [`Ok(0)`]: ../../std/result/enum.Result.html#variant.Ok
594 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
595 /// [`File`]: ../fs/struct.File.html
599 /// use std::io::prelude::*;
600 /// use std::fs::File;
602 /// fn main() -> io::Result<()> {
603 /// let mut f = File::open("foo.txt")?;
604 /// let mut buffer = Vec::new();
606 /// // read the whole file
607 /// f.read_to_end(&mut buffer)?;
612 /// (See also the [`std::fs::read`] convenience function for reading from a
615 /// [`std::fs::read`]: ../fs/fn.read.html
616 #[stable(feature = "rust1", since = "1.0.0")]
617 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
618 read_to_end(self, buf)
621 /// Read all bytes until EOF in this source, appending them to `buf`.
623 /// If successful, this function returns the number of bytes which were read
624 /// and appended to `buf`.
628 /// If the data in this stream is *not* valid UTF-8 then an error is
629 /// returned and `buf` is unchanged.
631 /// See [`read_to_end`][readtoend] for other error semantics.
633 /// [readtoend]: #method.read_to_end
637 /// [`File`][file]s implement `Read`:
639 /// [file]: ../fs/struct.File.html
643 /// use std::io::prelude::*;
644 /// use std::fs::File;
646 /// fn main() -> io::Result<()> {
647 /// let mut f = File::open("foo.txt")?;
648 /// let mut buffer = String::new();
650 /// f.read_to_string(&mut buffer)?;
655 /// (See also the [`std::fs::read_to_string`] convenience function for
656 /// reading from a file.)
658 /// [`std::fs::read_to_string`]: ../fs/fn.read_to_string.html
659 #[stable(feature = "rust1", since = "1.0.0")]
660 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
661 // Note that we do *not* call `.read_to_end()` here. We are passing
662 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
663 // method to fill it up. An arbitrary implementation could overwrite the
664 // entire contents of the vector, not just append to it (which is what
665 // we are expecting).
667 // To prevent extraneously checking the UTF-8-ness of the entire buffer
668 // we pass it to our hardcoded `read_to_end` implementation which we
669 // know is guaranteed to only read data into the end of the buffer.
670 append_to_string(buf, |b| read_to_end(self, b))
673 /// Read the exact number of bytes required to fill `buf`.
675 /// This function reads as many bytes as necessary to completely fill the
676 /// specified buffer `buf`.
678 /// No guarantees are provided about the contents of `buf` when this
679 /// function is called, implementations cannot rely on any property of the
680 /// contents of `buf` being true. It is recommended that implementations
681 /// only write data to `buf` instead of reading its contents.
685 /// If this function encounters an error of the kind
686 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
689 /// If this function encounters an "end of file" before completely filling
690 /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
691 /// The contents of `buf` are unspecified in this case.
693 /// If any other read error is encountered then this function immediately
694 /// returns. The contents of `buf` are unspecified in this case.
696 /// If this function returns an error, it is unspecified how many bytes it
697 /// has read, but it will never read more than would be necessary to
698 /// completely fill the buffer.
702 /// [`File`]s implement `Read`:
704 /// [`File`]: ../fs/struct.File.html
705 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
706 /// [`ErrorKind::UnexpectedEof`]: ../../std/io/enum.ErrorKind.html#variant.UnexpectedEof
710 /// use std::io::prelude::*;
711 /// use std::fs::File;
713 /// fn main() -> io::Result<()> {
714 /// let mut f = File::open("foo.txt")?;
715 /// let mut buffer = [0; 10];
717 /// // read exactly 10 bytes
718 /// f.read_exact(&mut buffer)?;
722 #[stable(feature = "read_exact", since = "1.6.0")]
723 fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
724 while !buf.is_empty() {
725 match self.read(buf) {
727 Ok(n) => { let tmp = buf; buf = &mut tmp[n..]; }
728 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
729 Err(e) => return Err(e),
733 Err(Error::new(ErrorKind::UnexpectedEof,
734 "failed to fill whole buffer"))
740 /// Creates a "by reference" adaptor for this instance of `Read`.
742 /// The returned adaptor also implements `Read` and will simply borrow this
747 /// [`File`][file]s implement `Read`:
749 /// [file]: ../fs/struct.File.html
753 /// use std::io::Read;
754 /// use std::fs::File;
756 /// fn main() -> io::Result<()> {
757 /// let mut f = File::open("foo.txt")?;
758 /// let mut buffer = Vec::new();
759 /// let mut other_buffer = Vec::new();
762 /// let reference = f.by_ref();
764 /// // read at most 5 bytes
765 /// reference.take(5).read_to_end(&mut buffer)?;
767 /// } // drop our &mut reference so we can use f again
769 /// // original file still usable, read the rest
770 /// f.read_to_end(&mut other_buffer)?;
774 #[stable(feature = "rust1", since = "1.0.0")]
775 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
777 /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
779 /// The returned type implements [`Iterator`] where the `Item` is
780 /// [`Result`]`<`[`u8`]`, `[`io::Error`]`>`.
781 /// The yielded item is [`Ok`] if a byte was successfully read and [`Err`]
782 /// otherwise. EOF is mapped to returning [`None`] from this iterator.
786 /// [`File`][file]s implement `Read`:
788 /// [file]: ../fs/struct.File.html
789 /// [`Iterator`]: ../../std/iter/trait.Iterator.html
790 /// [`Result`]: ../../std/result/enum.Result.html
791 /// [`io::Error`]: ../../std/io/struct.Error.html
792 /// [`u8`]: ../../std/primitive.u8.html
793 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
794 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
795 /// [`None`]: ../../std/option/enum.Option.html#variant.None
799 /// use std::io::prelude::*;
800 /// use std::fs::File;
802 /// fn main() -> io::Result<()> {
803 /// let mut f = File::open("foo.txt")?;
805 /// for byte in f.bytes() {
806 /// println!("{}", byte.unwrap());
811 #[stable(feature = "rust1", since = "1.0.0")]
812 fn bytes(self) -> Bytes<Self> where Self: Sized {
813 Bytes { inner: self }
816 /// Creates an adaptor which will chain this stream with another.
818 /// The returned `Read` instance will first read all bytes from this object
819 /// until EOF is encountered. Afterwards the output is equivalent to the
820 /// output of `next`.
824 /// [`File`][file]s implement `Read`:
826 /// [file]: ../fs/struct.File.html
830 /// use std::io::prelude::*;
831 /// use std::fs::File;
833 /// fn main() -> io::Result<()> {
834 /// let mut f1 = File::open("foo.txt")?;
835 /// let mut f2 = File::open("bar.txt")?;
837 /// let mut handle = f1.chain(f2);
838 /// let mut buffer = String::new();
840 /// // read the value into a String. We could use any Read method here,
841 /// // this is just one example.
842 /// handle.read_to_string(&mut buffer)?;
846 #[stable(feature = "rust1", since = "1.0.0")]
847 fn chain<R: Read>(self, next: R) -> Chain<Self, R> where Self: Sized {
848 Chain { first: self, second: next, done_first: false }
851 /// Creates an adaptor which will read at most `limit` bytes from it.
853 /// This function returns a new instance of `Read` which will read at most
854 /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
855 /// read errors will not count towards the number of bytes read and future
856 /// calls to [`read()`] may succeed.
860 /// [`File`]s implement `Read`:
862 /// [`File`]: ../fs/struct.File.html
863 /// [`Ok(0)`]: ../../std/result/enum.Result.html#variant.Ok
864 /// [`read()`]: trait.Read.html#tymethod.read
868 /// use std::io::prelude::*;
869 /// use std::fs::File;
871 /// fn main() -> io::Result<()> {
872 /// let mut f = File::open("foo.txt")?;
873 /// let mut buffer = [0; 5];
875 /// // read at most five bytes
876 /// let mut handle = f.take(5);
878 /// handle.read(&mut buffer)?;
882 #[stable(feature = "rust1", since = "1.0.0")]
883 fn take(self, limit: u64) -> Take<Self> where Self: Sized {
884 Take { inner: self, limit: limit }
888 /// A buffer type used with `Read::read_vectored`.
890 /// It is semantically a wrapper around an `&mut [u8]`, but is guaranteed to be
891 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
893 #[unstable(feature = "iovec", issue = "58452")]
895 pub struct IoVecMut<'a>(sys::io::IoVecMut<'a>);
897 #[unstable(feature = "iovec", issue = "58452")]
898 impl<'a> fmt::Debug for IoVecMut<'a> {
899 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
900 fmt::Debug::fmt(self.0.as_slice(), fmt)
904 impl<'a> IoVecMut<'a> {
905 /// Creates a new `IoVecMut` wrapping a byte slice.
909 /// Panics on Windows if the slice is larger than 4GB.
910 #[unstable(feature = "iovec", issue = "58452")]
912 pub fn new(buf: &'a mut [u8]) -> IoVecMut<'a> {
913 IoVecMut(sys::io::IoVecMut::new(buf))
917 #[unstable(feature = "iovec", issue = "58452")]
918 impl<'a> Deref for IoVecMut<'a> {
922 fn deref(&self) -> &[u8] {
927 #[unstable(feature = "iovec", issue = "58452")]
928 impl<'a> DerefMut for IoVecMut<'a> {
930 fn deref_mut(&mut self) -> &mut [u8] {
931 self.0.as_mut_slice()
935 /// A buffer type used with `Write::write_vectored`.
937 /// It is semantically a wrapper around an `&[u8]`, but is guaranteed to be
938 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
940 #[unstable(feature = "iovec", issue = "58452")]
942 pub struct IoVec<'a>(sys::io::IoVec<'a>);
944 #[unstable(feature = "iovec", issue = "58452")]
945 impl<'a> fmt::Debug for IoVec<'a> {
946 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
947 fmt::Debug::fmt(self.0.as_slice(), fmt)
952 /// Creates a new `IoVec` wrapping a byte slice.
956 /// Panics on Windows if the slice is larger than 4GB.
957 #[unstable(feature = "iovec", issue = "58452")]
959 pub fn new(buf: &'a [u8]) -> IoVec<'a> {
960 IoVec(sys::io::IoVec::new(buf))
964 #[unstable(feature = "iovec", issue = "58452")]
965 impl<'a> Deref for IoVec<'a> {
969 fn deref(&self) -> &[u8] {
974 /// A type used to conditionally initialize buffers passed to `Read` methods.
975 #[unstable(feature = "read_initializer", issue = "42788")]
977 pub struct Initializer(bool);
980 /// Returns a new `Initializer` which will zero out buffers.
981 #[unstable(feature = "read_initializer", issue = "42788")]
983 pub fn zeroing() -> Initializer {
987 /// Returns a new `Initializer` which will not zero out buffers.
991 /// This may only be called by `Read`ers which guarantee that they will not
992 /// read from buffers passed to `Read` methods, and that the return value of
993 /// the method accurately reflects the number of bytes that have been
994 /// written to the head of the buffer.
995 #[unstable(feature = "read_initializer", issue = "42788")]
997 pub unsafe fn nop() -> Initializer {
1001 /// Indicates if a buffer should be initialized.
1002 #[unstable(feature = "read_initializer", issue = "42788")]
1004 pub fn should_initialize(&self) -> bool {
1008 /// Initializes a buffer if necessary.
1009 #[unstable(feature = "read_initializer", issue = "42788")]
1011 pub fn initialize(&self, buf: &mut [u8]) {
1012 if self.should_initialize() {
1013 unsafe { ptr::write_bytes(buf.as_mut_ptr(), 0, buf.len()) }
1018 /// A trait for objects which are byte-oriented sinks.
1020 /// Implementors of the `Write` trait are sometimes called 'writers'.
1022 /// Writers are defined by two required methods, [`write`] and [`flush`]:
1024 /// * The [`write`] method will attempt to write some data into the object,
1025 /// returning how many bytes were successfully written.
1027 /// * The [`flush`] method is useful for adaptors and explicit buffers
1028 /// themselves for ensuring that all buffered data has been pushed out to the
1031 /// Writers are intended to be composable with one another. Many implementors
1032 /// throughout [`std::io`] take and provide types which implement the `Write`
1035 /// [`write`]: #tymethod.write
1036 /// [`flush`]: #tymethod.flush
1037 /// [`std::io`]: index.html
1042 /// use std::io::prelude::*;
1043 /// use std::fs::File;
1045 /// fn main() -> std::io::Result<()> {
1046 /// let mut buffer = File::create("foo.txt")?;
1048 /// buffer.write(b"some bytes")?;
1052 #[stable(feature = "rust1", since = "1.0.0")]
1055 /// Write a buffer into this writer, returning how many bytes were written.
1057 /// This function will attempt to write the entire contents of `buf`, but
1058 /// the entire write may not succeed, or the write may also generate an
1059 /// error. A call to `write` represents *at most one* attempt to write to
1060 /// any wrapped object.
1062 /// Calls to `write` are not guaranteed to block waiting for data to be
1063 /// written, and a write which would otherwise block can be indicated through
1064 /// an [`Err`] variant.
1066 /// If the return value is [`Ok(n)`] then it must be guaranteed that
1067 /// `0 <= n <= buf.len()`. A return value of `0` typically means that the
1068 /// underlying object is no longer able to accept bytes and will likely not
1069 /// be able to in the future as well, or that the buffer provided is empty.
1073 /// Each call to `write` may generate an I/O error indicating that the
1074 /// operation could not be completed. If an error is returned then no bytes
1075 /// in the buffer were written to this writer.
1077 /// It is **not** considered an error if the entire buffer could not be
1078 /// written to this writer.
1080 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the
1081 /// write operation should be retried if there is nothing else to do.
1083 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
1084 /// [`Ok(n)`]: ../../std/result/enum.Result.html#variant.Ok
1085 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
1090 /// use std::io::prelude::*;
1091 /// use std::fs::File;
1093 /// fn main() -> std::io::Result<()> {
1094 /// let mut buffer = File::create("foo.txt")?;
1096 /// // Writes some prefix of the byte string, not necessarily all of it.
1097 /// buffer.write(b"some bytes")?;
1101 #[stable(feature = "rust1", since = "1.0.0")]
1102 fn write(&mut self, buf: &[u8]) -> Result<usize>;
1104 /// Like `write`, except that it writes from a slice of buffers.
1106 /// Data is copied to from each buffer in order, with the final buffer
1107 /// read from possibly being only partially consumed. This method must
1108 /// behave as a call to `write` with the buffers concatenated would.
1110 /// The default implementation simply passes the first nonempty buffer to
1112 #[unstable(feature = "iovec", issue = "58452")]
1113 fn write_vectored(&mut self, bufs: &[IoVec<'_>]) -> Result<usize> {
1114 match bufs.iter().find(|b| !b.is_empty()) {
1115 Some(buf) => self.write(buf),
1120 /// Flush this output stream, ensuring that all intermediately buffered
1121 /// contents reach their destination.
1125 /// It is considered an error if not all bytes could be written due to
1126 /// I/O errors or EOF being reached.
1131 /// use std::io::prelude::*;
1132 /// use std::io::BufWriter;
1133 /// use std::fs::File;
1135 /// fn main() -> std::io::Result<()> {
1136 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
1138 /// buffer.write(b"some bytes")?;
1139 /// buffer.flush()?;
1143 #[stable(feature = "rust1", since = "1.0.0")]
1144 fn flush(&mut self) -> Result<()>;
1146 /// Attempts to write an entire buffer into this writer.
1148 /// This method will continuously call [`write`] until there is no more data
1149 /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is
1150 /// returned. This method will not return until the entire buffer has been
1151 /// successfully written or such an error occurs. The first error that is
1152 /// not of [`ErrorKind::Interrupted`] kind generated from this method will be
1157 /// This function will return the first error of
1158 /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns.
1160 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
1161 /// [`write`]: #tymethod.write
1166 /// use std::io::prelude::*;
1167 /// use std::fs::File;
1169 /// fn main() -> std::io::Result<()> {
1170 /// let mut buffer = File::create("foo.txt")?;
1172 /// buffer.write_all(b"some bytes")?;
1176 #[stable(feature = "rust1", since = "1.0.0")]
1177 fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
1178 while !buf.is_empty() {
1179 match self.write(buf) {
1180 Ok(0) => return Err(Error::new(ErrorKind::WriteZero,
1181 "failed to write whole buffer")),
1182 Ok(n) => buf = &buf[n..],
1183 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1184 Err(e) => return Err(e),
1190 /// Writes a formatted string into this writer, returning any error
1193 /// This method is primarily used to interface with the
1194 /// [`format_args!`][formatargs] macro, but it is rare that this should
1195 /// explicitly be called. The [`write!`][write] macro should be favored to
1196 /// invoke this method instead.
1198 /// [formatargs]: ../macro.format_args.html
1199 /// [write]: ../macro.write.html
1201 /// This function internally uses the [`write_all`][writeall] method on
1202 /// this trait and hence will continuously write data so long as no errors
1203 /// are received. This also means that partial writes are not indicated in
1206 /// [writeall]: #method.write_all
1210 /// This function will return any I/O error reported while formatting.
1215 /// use std::io::prelude::*;
1216 /// use std::fs::File;
1218 /// fn main() -> std::io::Result<()> {
1219 /// let mut buffer = File::create("foo.txt")?;
1222 /// write!(buffer, "{:.*}", 2, 1.234567)?;
1223 /// // turns into this:
1224 /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1228 #[stable(feature = "rust1", since = "1.0.0")]
1229 fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()> {
1230 // Create a shim which translates a Write to a fmt::Write and saves
1231 // off I/O errors. instead of discarding them
1232 struct Adaptor<'a, T: ?Sized + 'a> {
1237 impl<T: Write + ?Sized> fmt::Write for Adaptor<'_, T> {
1238 fn write_str(&mut self, s: &str) -> fmt::Result {
1239 match self.inner.write_all(s.as_bytes()) {
1242 self.error = Err(e);
1249 let mut output = Adaptor { inner: self, error: Ok(()) };
1250 match fmt::write(&mut output, fmt) {
1253 // check if the error came from the underlying `Write` or not
1254 if output.error.is_err() {
1257 Err(Error::new(ErrorKind::Other, "formatter error"))
1263 /// Creates a "by reference" adaptor for this instance of `Write`.
1265 /// The returned adaptor also implements `Write` and will simply borrow this
1271 /// use std::io::Write;
1272 /// use std::fs::File;
1274 /// fn main() -> std::io::Result<()> {
1275 /// let mut buffer = File::create("foo.txt")?;
1277 /// let reference = buffer.by_ref();
1279 /// // we can use reference just like our original buffer
1280 /// reference.write_all(b"some bytes")?;
1284 #[stable(feature = "rust1", since = "1.0.0")]
1285 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1288 /// The `Seek` trait provides a cursor which can be moved within a stream of
1291 /// The stream typically has a fixed size, allowing seeking relative to either
1292 /// end or the current offset.
1296 /// [`File`][file]s implement `Seek`:
1298 /// [file]: ../fs/struct.File.html
1302 /// use std::io::prelude::*;
1303 /// use std::fs::File;
1304 /// use std::io::SeekFrom;
1306 /// fn main() -> io::Result<()> {
1307 /// let mut f = File::open("foo.txt")?;
1309 /// // move the cursor 42 bytes from the start of the file
1310 /// f.seek(SeekFrom::Start(42))?;
1314 #[stable(feature = "rust1", since = "1.0.0")]
1316 /// Seek to an offset, in bytes, in a stream.
1318 /// A seek beyond the end of a stream is allowed, but behavior is defined
1319 /// by the implementation.
1321 /// If the seek operation completed successfully,
1322 /// this method returns the new position from the start of the stream.
1323 /// That position can be used later with [`SeekFrom::Start`].
1327 /// Seeking to a negative offset is considered an error.
1329 /// [`SeekFrom::Start`]: enum.SeekFrom.html#variant.Start
1330 #[stable(feature = "rust1", since = "1.0.0")]
1331 fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1334 /// Enumeration of possible methods to seek within an I/O object.
1336 /// It is used by the [`Seek`] trait.
1338 /// [`Seek`]: trait.Seek.html
1339 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1340 #[stable(feature = "rust1", since = "1.0.0")]
1342 /// Sets the offset to the provided number of bytes.
1343 #[stable(feature = "rust1", since = "1.0.0")]
1344 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1346 /// Sets the offset to the size of this object plus the specified number of
1349 /// It is possible to seek beyond the end of an object, but it's an error to
1350 /// seek before byte 0.
1351 #[stable(feature = "rust1", since = "1.0.0")]
1352 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1354 /// Sets the offset to the current position plus the specified number of
1357 /// It is possible to seek beyond the end of an object, but it's an error to
1358 /// seek before byte 0.
1359 #[stable(feature = "rust1", since = "1.0.0")]
1360 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1363 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>)
1367 let (done, used) = {
1368 let available = match r.fill_buf() {
1370 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1371 Err(e) => return Err(e)
1373 match memchr::memchr(delim, available) {
1375 buf.extend_from_slice(&available[..=i]);
1379 buf.extend_from_slice(available);
1380 (false, available.len())
1386 if done || used == 0 {
1392 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1393 /// to perform extra ways of reading.
1395 /// For example, reading line-by-line is inefficient without using a buffer, so
1396 /// if you want to read by line, you'll need `BufRead`, which includes a
1397 /// [`read_line`] method as well as a [`lines`] iterator.
1401 /// A locked standard input implements `BufRead`:
1405 /// use std::io::prelude::*;
1407 /// let stdin = io::stdin();
1408 /// for line in stdin.lock().lines() {
1409 /// println!("{}", line.unwrap());
1413 /// If you have something that implements [`Read`], you can use the [`BufReader`
1414 /// type][`BufReader`] to turn it into a `BufRead`.
1416 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1417 /// [`BufReader`] to the rescue!
1419 /// [`BufReader`]: struct.BufReader.html
1420 /// [`File`]: ../fs/struct.File.html
1421 /// [`read_line`]: #method.read_line
1422 /// [`lines`]: #method.lines
1423 /// [`Read`]: trait.Read.html
1426 /// use std::io::{self, BufReader};
1427 /// use std::io::prelude::*;
1428 /// use std::fs::File;
1430 /// fn main() -> io::Result<()> {
1431 /// let f = File::open("foo.txt")?;
1432 /// let f = BufReader::new(f);
1434 /// for line in f.lines() {
1435 /// println!("{}", line.unwrap());
1442 #[stable(feature = "rust1", since = "1.0.0")]
1443 pub trait BufRead: Read {
1444 /// Returns the contents of the internal buffer, filling it with more data
1445 /// from the inner reader if it is empty.
1447 /// This function is a lower-level call. It needs to be paired with the
1448 /// [`consume`] method to function properly. When calling this
1449 /// method, none of the contents will be "read" in the sense that later
1450 /// calling `read` may return the same contents. As such, [`consume`] must
1451 /// be called with the number of bytes that are consumed from this buffer to
1452 /// ensure that the bytes are never returned twice.
1454 /// [`consume`]: #tymethod.consume
1456 /// An empty buffer returned indicates that the stream has reached EOF.
1460 /// This function will return an I/O error if the underlying reader was
1461 /// read, but returned an error.
1465 /// A locked standard input implements `BufRead`:
1469 /// use std::io::prelude::*;
1471 /// let stdin = io::stdin();
1472 /// let mut stdin = stdin.lock();
1474 /// // we can't have two `&mut` references to `stdin`, so use a block
1475 /// // to end the borrow early.
1477 /// let buffer = stdin.fill_buf().unwrap();
1479 /// // work with buffer
1480 /// println!("{:?}", buffer);
1485 /// // ensure the bytes we worked with aren't returned again later
1486 /// stdin.consume(length);
1488 #[stable(feature = "rust1", since = "1.0.0")]
1489 fn fill_buf(&mut self) -> Result<&[u8]>;
1491 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1492 /// so they should no longer be returned in calls to `read`.
1494 /// This function is a lower-level call. It needs to be paired with the
1495 /// [`fill_buf`] method to function properly. This function does
1496 /// not perform any I/O, it simply informs this object that some amount of
1497 /// its buffer, returned from [`fill_buf`], has been consumed and should
1498 /// no longer be returned. As such, this function may do odd things if
1499 /// [`fill_buf`] isn't called before calling it.
1501 /// The `amt` must be `<=` the number of bytes in the buffer returned by
1506 /// Since `consume()` is meant to be used with [`fill_buf`],
1507 /// that method's example includes an example of `consume()`.
1509 /// [`fill_buf`]: #tymethod.fill_buf
1510 #[stable(feature = "rust1", since = "1.0.0")]
1511 fn consume(&mut self, amt: usize);
1513 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
1515 /// This function will read bytes from the underlying stream until the
1516 /// delimiter or EOF is found. Once found, all bytes up to, and including,
1517 /// the delimiter (if found) will be appended to `buf`.
1519 /// If successful, this function will return the total number of bytes read.
1523 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1524 /// will otherwise return any errors returned by [`fill_buf`].
1526 /// If an I/O error is encountered then all bytes read so far will be
1527 /// present in `buf` and its length will have been adjusted appropriately.
1529 /// [`fill_buf`]: #tymethod.fill_buf
1530 /// [`ErrorKind::Interrupted`]: enum.ErrorKind.html#variant.Interrupted
1534 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1535 /// this example, we use [`Cursor`] to read all the bytes in a byte slice
1536 /// in hyphen delimited segments:
1538 /// [`Cursor`]: struct.Cursor.html
1541 /// use std::io::{self, BufRead};
1543 /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
1544 /// let mut buf = vec![];
1546 /// // cursor is at 'l'
1547 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1548 /// .expect("reading from cursor won't fail");
1549 /// assert_eq!(num_bytes, 6);
1550 /// assert_eq!(buf, b"lorem-");
1553 /// // cursor is at 'i'
1554 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1555 /// .expect("reading from cursor won't fail");
1556 /// assert_eq!(num_bytes, 5);
1557 /// assert_eq!(buf, b"ipsum");
1560 /// // cursor is at EOF
1561 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1562 /// .expect("reading from cursor won't fail");
1563 /// assert_eq!(num_bytes, 0);
1564 /// assert_eq!(buf, b"");
1566 #[stable(feature = "rust1", since = "1.0.0")]
1567 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
1568 read_until(self, byte, buf)
1571 /// Read all bytes until a newline (the 0xA byte) is reached, and append
1572 /// them to the provided buffer.
1574 /// This function will read bytes from the underlying stream until the
1575 /// newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes
1576 /// up to, and including, the delimiter (if found) will be appended to
1579 /// If successful, this function will return the total number of bytes read.
1581 /// An empty buffer returned indicates that the stream has reached EOF.
1585 /// This function has the same error semantics as [`read_until`] and will
1586 /// also return an error if the read bytes are not valid UTF-8. If an I/O
1587 /// error is encountered then `buf` may contain some bytes already read in
1588 /// the event that all data read so far was valid UTF-8.
1590 /// [`read_until`]: #method.read_until
1594 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1595 /// this example, we use [`Cursor`] to read all the lines in a byte slice:
1597 /// [`Cursor`]: struct.Cursor.html
1600 /// use std::io::{self, BufRead};
1602 /// let mut cursor = io::Cursor::new(b"foo\nbar");
1603 /// let mut buf = String::new();
1605 /// // cursor is at 'f'
1606 /// let num_bytes = cursor.read_line(&mut buf)
1607 /// .expect("reading from cursor won't fail");
1608 /// assert_eq!(num_bytes, 4);
1609 /// assert_eq!(buf, "foo\n");
1612 /// // cursor is at 'b'
1613 /// let num_bytes = cursor.read_line(&mut buf)
1614 /// .expect("reading from cursor won't fail");
1615 /// assert_eq!(num_bytes, 3);
1616 /// assert_eq!(buf, "bar");
1619 /// // cursor is at EOF
1620 /// let num_bytes = cursor.read_line(&mut buf)
1621 /// .expect("reading from cursor won't fail");
1622 /// assert_eq!(num_bytes, 0);
1623 /// assert_eq!(buf, "");
1625 #[stable(feature = "rust1", since = "1.0.0")]
1626 fn read_line(&mut self, buf: &mut String) -> Result<usize> {
1627 // Note that we are not calling the `.read_until` method here, but
1628 // rather our hardcoded implementation. For more details as to why, see
1629 // the comments in `read_to_end`.
1630 append_to_string(buf, |b| read_until(self, b'\n', b))
1633 /// Returns an iterator over the contents of this reader split on the byte
1636 /// The iterator returned from this function will return instances of
1637 /// [`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
1638 /// the delimiter byte at the end.
1640 /// This function will yield errors whenever [`read_until`] would have
1641 /// also yielded an error.
1643 /// [`io::Result`]: type.Result.html
1644 /// [`Vec<u8>`]: ../vec/struct.Vec.html
1645 /// [`read_until`]: #method.read_until
1649 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1650 /// this example, we use [`Cursor`] to iterate over all hyphen delimited
1651 /// segments in a byte slice
1653 /// [`Cursor`]: struct.Cursor.html
1656 /// use std::io::{self, BufRead};
1658 /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
1660 /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
1661 /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
1662 /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
1663 /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
1664 /// assert_eq!(split_iter.next(), None);
1666 #[stable(feature = "rust1", since = "1.0.0")]
1667 fn split(self, byte: u8) -> Split<Self> where Self: Sized {
1668 Split { buf: self, delim: byte }
1671 /// Returns an iterator over the lines of this reader.
1673 /// The iterator returned from this function will yield instances of
1674 /// [`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline
1675 /// byte (the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.
1677 /// [`io::Result`]: type.Result.html
1678 /// [`String`]: ../string/struct.String.html
1682 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1683 /// this example, we use [`Cursor`] to iterate over all the lines in a byte
1686 /// [`Cursor`]: struct.Cursor.html
1689 /// use std::io::{self, BufRead};
1691 /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
1693 /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
1694 /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
1695 /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
1696 /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
1697 /// assert_eq!(lines_iter.next(), None);
1702 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
1704 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
1705 #[stable(feature = "rust1", since = "1.0.0")]
1706 fn lines(self) -> Lines<Self> where Self: Sized {
1711 /// Adaptor to chain together two readers.
1713 /// This struct is generally created by calling [`chain`] on a reader.
1714 /// Please see the documentation of [`chain`] for more details.
1716 /// [`chain`]: trait.Read.html#method.chain
1717 #[stable(feature = "rust1", since = "1.0.0")]
1718 pub struct Chain<T, U> {
1724 impl<T, U> Chain<T, U> {
1725 /// Consumes the `Chain`, returning the wrapped readers.
1731 /// use std::io::prelude::*;
1732 /// use std::fs::File;
1734 /// fn main() -> io::Result<()> {
1735 /// let mut foo_file = File::open("foo.txt")?;
1736 /// let mut bar_file = File::open("bar.txt")?;
1738 /// let chain = foo_file.chain(bar_file);
1739 /// let (foo_file, bar_file) = chain.into_inner();
1743 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1744 pub fn into_inner(self) -> (T, U) {
1745 (self.first, self.second)
1748 /// Gets references to the underlying readers in this `Chain`.
1754 /// use std::io::prelude::*;
1755 /// use std::fs::File;
1757 /// fn main() -> io::Result<()> {
1758 /// let mut foo_file = File::open("foo.txt")?;
1759 /// let mut bar_file = File::open("bar.txt")?;
1761 /// let chain = foo_file.chain(bar_file);
1762 /// let (foo_file, bar_file) = chain.get_ref();
1766 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1767 pub fn get_ref(&self) -> (&T, &U) {
1768 (&self.first, &self.second)
1771 /// Gets mutable references to the underlying readers in this `Chain`.
1773 /// Care should be taken to avoid modifying the internal I/O state of the
1774 /// underlying readers as doing so may corrupt the internal state of this
1781 /// use std::io::prelude::*;
1782 /// use std::fs::File;
1784 /// fn main() -> io::Result<()> {
1785 /// let mut foo_file = File::open("foo.txt")?;
1786 /// let mut bar_file = File::open("bar.txt")?;
1788 /// let mut chain = foo_file.chain(bar_file);
1789 /// let (foo_file, bar_file) = chain.get_mut();
1793 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1794 pub fn get_mut(&mut self) -> (&mut T, &mut U) {
1795 (&mut self.first, &mut self.second)
1799 #[stable(feature = "std_debug", since = "1.16.0")]
1800 impl<T: fmt::Debug, U: fmt::Debug> fmt::Debug for Chain<T, U> {
1801 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1802 f.debug_struct("Chain")
1803 .field("t", &self.first)
1804 .field("u", &self.second)
1809 #[stable(feature = "rust1", since = "1.0.0")]
1810 impl<T: Read, U: Read> Read for Chain<T, U> {
1811 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1812 if !self.done_first {
1813 match self.first.read(buf)? {
1814 0 if buf.len() != 0 => self.done_first = true,
1818 self.second.read(buf)
1821 fn read_vectored(&mut self, bufs: &mut [IoVecMut<'_>]) -> Result<usize> {
1822 if !self.done_first {
1823 match self.first.read_vectored(bufs)? {
1824 0 if bufs.iter().any(|b| !b.is_empty()) => self.done_first = true,
1828 self.second.read_vectored(bufs)
1831 unsafe fn initializer(&self) -> Initializer {
1832 let initializer = self.first.initializer();
1833 if initializer.should_initialize() {
1836 self.second.initializer()
1841 #[stable(feature = "chain_bufread", since = "1.9.0")]
1842 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
1843 fn fill_buf(&mut self) -> Result<&[u8]> {
1844 if !self.done_first {
1845 match self.first.fill_buf()? {
1846 buf if buf.len() == 0 => { self.done_first = true; }
1847 buf => return Ok(buf),
1850 self.second.fill_buf()
1853 fn consume(&mut self, amt: usize) {
1854 if !self.done_first {
1855 self.first.consume(amt)
1857 self.second.consume(amt)
1862 /// Reader adaptor which limits the bytes read from an underlying reader.
1864 /// This struct is generally created by calling [`take`] on a reader.
1865 /// Please see the documentation of [`take`] for more details.
1867 /// [`take`]: trait.Read.html#method.take
1868 #[stable(feature = "rust1", since = "1.0.0")]
1870 pub struct Take<T> {
1876 /// Returns the number of bytes that can be read before this instance will
1881 /// This instance may reach `EOF` after reading fewer bytes than indicated by
1882 /// this method if the underlying [`Read`] instance reaches EOF.
1884 /// [`Read`]: ../../std/io/trait.Read.html
1890 /// use std::io::prelude::*;
1891 /// use std::fs::File;
1893 /// fn main() -> io::Result<()> {
1894 /// let f = File::open("foo.txt")?;
1896 /// // read at most five bytes
1897 /// let handle = f.take(5);
1899 /// println!("limit: {}", handle.limit());
1903 #[stable(feature = "rust1", since = "1.0.0")]
1904 pub fn limit(&self) -> u64 { self.limit }
1906 /// Sets the number of bytes that can be read before this instance will
1907 /// return EOF. This is the same as constructing a new `Take` instance, so
1908 /// the amount of bytes read and the previous limit value don't matter when
1909 /// calling this method.
1915 /// use std::io::prelude::*;
1916 /// use std::fs::File;
1918 /// fn main() -> io::Result<()> {
1919 /// let f = File::open("foo.txt")?;
1921 /// // read at most five bytes
1922 /// let mut handle = f.take(5);
1923 /// handle.set_limit(10);
1925 /// assert_eq!(handle.limit(), 10);
1929 #[stable(feature = "take_set_limit", since = "1.27.0")]
1930 pub fn set_limit(&mut self, limit: u64) {
1934 /// Consumes the `Take`, returning the wrapped reader.
1940 /// use std::io::prelude::*;
1941 /// use std::fs::File;
1943 /// fn main() -> io::Result<()> {
1944 /// let mut file = File::open("foo.txt")?;
1946 /// let mut buffer = [0; 5];
1947 /// let mut handle = file.take(5);
1948 /// handle.read(&mut buffer)?;
1950 /// let file = handle.into_inner();
1954 #[stable(feature = "io_take_into_inner", since = "1.15.0")]
1955 pub fn into_inner(self) -> T {
1959 /// Gets a reference to the underlying reader.
1965 /// use std::io::prelude::*;
1966 /// use std::fs::File;
1968 /// fn main() -> io::Result<()> {
1969 /// let mut file = File::open("foo.txt")?;
1971 /// let mut buffer = [0; 5];
1972 /// let mut handle = file.take(5);
1973 /// handle.read(&mut buffer)?;
1975 /// let file = handle.get_ref();
1979 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1980 pub fn get_ref(&self) -> &T {
1984 /// Gets a mutable reference to the underlying reader.
1986 /// Care should be taken to avoid modifying the internal I/O state of the
1987 /// underlying reader as doing so may corrupt the internal limit of this
1994 /// use std::io::prelude::*;
1995 /// use std::fs::File;
1997 /// fn main() -> io::Result<()> {
1998 /// let mut file = File::open("foo.txt")?;
2000 /// let mut buffer = [0; 5];
2001 /// let mut handle = file.take(5);
2002 /// handle.read(&mut buffer)?;
2004 /// let file = handle.get_mut();
2008 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2009 pub fn get_mut(&mut self) -> &mut T {
2014 #[stable(feature = "rust1", since = "1.0.0")]
2015 impl<T: Read> Read for Take<T> {
2016 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2017 // Don't call into inner reader at all at EOF because it may still block
2018 if self.limit == 0 {
2022 let max = cmp::min(buf.len() as u64, self.limit) as usize;
2023 let n = self.inner.read(&mut buf[..max])?;
2024 self.limit -= n as u64;
2028 unsafe fn initializer(&self) -> Initializer {
2029 self.inner.initializer()
2032 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
2033 let reservation_size = cmp::min(self.limit, 32) as usize;
2035 read_to_end_with_reservation(self, buf, reservation_size)
2039 #[stable(feature = "rust1", since = "1.0.0")]
2040 impl<T: BufRead> BufRead for Take<T> {
2041 fn fill_buf(&mut self) -> Result<&[u8]> {
2042 // Don't call into inner reader at all at EOF because it may still block
2043 if self.limit == 0 {
2047 let buf = self.inner.fill_buf()?;
2048 let cap = cmp::min(buf.len() as u64, self.limit) as usize;
2052 fn consume(&mut self, amt: usize) {
2053 // Don't let callers reset the limit by passing an overlarge value
2054 let amt = cmp::min(amt as u64, self.limit) as usize;
2055 self.limit -= amt as u64;
2056 self.inner.consume(amt);
2060 /// An iterator over `u8` values of a reader.
2062 /// This struct is generally created by calling [`bytes`] on a reader.
2063 /// Please see the documentation of [`bytes`] for more details.
2065 /// [`bytes`]: trait.Read.html#method.bytes
2066 #[stable(feature = "rust1", since = "1.0.0")]
2068 pub struct Bytes<R> {
2072 #[stable(feature = "rust1", since = "1.0.0")]
2073 impl<R: Read> Iterator for Bytes<R> {
2074 type Item = Result<u8>;
2076 fn next(&mut self) -> Option<Result<u8>> {
2079 return match self.inner.read(slice::from_mut(&mut byte)) {
2081 Ok(..) => Some(Ok(byte)),
2082 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
2083 Err(e) => Some(Err(e)),
2089 /// An iterator over the contents of an instance of `BufRead` split on a
2090 /// particular byte.
2092 /// This struct is generally created by calling [`split`][split] on a
2093 /// `BufRead`. Please see the documentation of `split()` for more details.
2095 /// [split]: trait.BufRead.html#method.split
2096 #[stable(feature = "rust1", since = "1.0.0")]
2098 pub struct Split<B> {
2103 #[stable(feature = "rust1", since = "1.0.0")]
2104 impl<B: BufRead> Iterator for Split<B> {
2105 type Item = Result<Vec<u8>>;
2107 fn next(&mut self) -> Option<Result<Vec<u8>>> {
2108 let mut buf = Vec::new();
2109 match self.buf.read_until(self.delim, &mut buf) {
2112 if buf[buf.len() - 1] == self.delim {
2117 Err(e) => Some(Err(e))
2122 /// An iterator over the lines of an instance of `BufRead`.
2124 /// This struct is generally created by calling [`lines`][lines] on a
2125 /// `BufRead`. Please see the documentation of `lines()` for more details.
2127 /// [lines]: trait.BufRead.html#method.lines
2128 #[stable(feature = "rust1", since = "1.0.0")]
2130 pub struct Lines<B> {
2134 #[stable(feature = "rust1", since = "1.0.0")]
2135 impl<B: BufRead> Iterator for Lines<B> {
2136 type Item = Result<String>;
2138 fn next(&mut self) -> Option<Result<String>> {
2139 let mut buf = String::new();
2140 match self.buf.read_line(&mut buf) {
2143 if buf.ends_with("\n") {
2145 if buf.ends_with("\r") {
2151 Err(e) => Some(Err(e))
2165 #[cfg_attr(target_os = "emscripten", ignore)]
2167 let mut buf = Cursor::new(&b"12"[..]);
2168 let mut v = Vec::new();
2169 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 2);
2170 assert_eq!(v, b"12");
2172 let mut buf = Cursor::new(&b"1233"[..]);
2173 let mut v = Vec::new();
2174 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 3);
2175 assert_eq!(v, b"123");
2177 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 1);
2178 assert_eq!(v, b"3");
2180 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 0);
2186 let buf = Cursor::new(&b"12"[..]);
2187 let mut s = buf.split(b'3');
2188 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2189 assert!(s.next().is_none());
2191 let buf = Cursor::new(&b"1233"[..]);
2192 let mut s = buf.split(b'3');
2193 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2194 assert_eq!(s.next().unwrap().unwrap(), vec![]);
2195 assert!(s.next().is_none());
2200 let mut buf = Cursor::new(&b"12"[..]);
2201 let mut v = String::new();
2202 assert_eq!(buf.read_line(&mut v).unwrap(), 2);
2203 assert_eq!(v, "12");
2205 let mut buf = Cursor::new(&b"12\n\n"[..]);
2206 let mut v = String::new();
2207 assert_eq!(buf.read_line(&mut v).unwrap(), 3);
2208 assert_eq!(v, "12\n");
2210 assert_eq!(buf.read_line(&mut v).unwrap(), 1);
2211 assert_eq!(v, "\n");
2213 assert_eq!(buf.read_line(&mut v).unwrap(), 0);
2219 let buf = Cursor::new(&b"12\r"[..]);
2220 let mut s = buf.lines();
2221 assert_eq!(s.next().unwrap().unwrap(), "12\r".to_string());
2222 assert!(s.next().is_none());
2224 let buf = Cursor::new(&b"12\r\n\n"[..]);
2225 let mut s = buf.lines();
2226 assert_eq!(s.next().unwrap().unwrap(), "12".to_string());
2227 assert_eq!(s.next().unwrap().unwrap(), "".to_string());
2228 assert!(s.next().is_none());
2233 let mut c = Cursor::new(&b""[..]);
2234 let mut v = Vec::new();
2235 assert_eq!(c.read_to_end(&mut v).unwrap(), 0);
2238 let mut c = Cursor::new(&b"1"[..]);
2239 let mut v = Vec::new();
2240 assert_eq!(c.read_to_end(&mut v).unwrap(), 1);
2241 assert_eq!(v, b"1");
2243 let cap = 1024 * 1024;
2244 let data = (0..cap).map(|i| (i / 3) as u8).collect::<Vec<_>>();
2245 let mut v = Vec::new();
2246 let (a, b) = data.split_at(data.len() / 2);
2247 assert_eq!(Cursor::new(a).read_to_end(&mut v).unwrap(), a.len());
2248 assert_eq!(Cursor::new(b).read_to_end(&mut v).unwrap(), b.len());
2249 assert_eq!(v, data);
2253 fn read_to_string() {
2254 let mut c = Cursor::new(&b""[..]);
2255 let mut v = String::new();
2256 assert_eq!(c.read_to_string(&mut v).unwrap(), 0);
2259 let mut c = Cursor::new(&b"1"[..]);
2260 let mut v = String::new();
2261 assert_eq!(c.read_to_string(&mut v).unwrap(), 1);
2264 let mut c = Cursor::new(&b"\xff"[..]);
2265 let mut v = String::new();
2266 assert!(c.read_to_string(&mut v).is_err());
2271 let mut buf = [0; 4];
2273 let mut c = Cursor::new(&b""[..]);
2274 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2275 io::ErrorKind::UnexpectedEof);
2277 let mut c = Cursor::new(&b"123"[..]).chain(Cursor::new(&b"456789"[..]));
2278 c.read_exact(&mut buf).unwrap();
2279 assert_eq!(&buf, b"1234");
2280 c.read_exact(&mut buf).unwrap();
2281 assert_eq!(&buf, b"5678");
2282 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2283 io::ErrorKind::UnexpectedEof);
2287 fn read_exact_slice() {
2288 let mut buf = [0; 4];
2290 let mut c = &b""[..];
2291 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2292 io::ErrorKind::UnexpectedEof);
2294 let mut c = &b"123"[..];
2295 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2296 io::ErrorKind::UnexpectedEof);
2297 // make sure the optimized (early returning) method is being used
2298 assert_eq!(&buf, &[0; 4]);
2300 let mut c = &b"1234"[..];
2301 c.read_exact(&mut buf).unwrap();
2302 assert_eq!(&buf, b"1234");
2304 let mut c = &b"56789"[..];
2305 c.read_exact(&mut buf).unwrap();
2306 assert_eq!(&buf, b"5678");
2307 assert_eq!(c, b"9");
2315 fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
2316 Err(io::Error::new(io::ErrorKind::Other, ""))
2319 impl BufRead for R {
2320 fn fill_buf(&mut self) -> io::Result<&[u8]> {
2321 Err(io::Error::new(io::ErrorKind::Other, ""))
2323 fn consume(&mut self, _amt: usize) { }
2326 let mut buf = [0; 1];
2327 assert_eq!(0, R.take(0).read(&mut buf).unwrap());
2328 assert_eq!(b"", R.take(0).fill_buf().unwrap());
2331 fn cmp_bufread<Br1: BufRead, Br2: BufRead>(mut br1: Br1, mut br2: Br2, exp: &[u8]) {
2332 let mut cat = Vec::new();
2335 let buf1 = br1.fill_buf().unwrap();
2336 let buf2 = br2.fill_buf().unwrap();
2337 let minlen = if buf1.len() < buf2.len() { buf1.len() } else { buf2.len() };
2338 assert_eq!(buf1[..minlen], buf2[..minlen]);
2339 cat.extend_from_slice(&buf1[..minlen]);
2345 br1.consume(consume);
2346 br2.consume(consume);
2348 assert_eq!(br1.fill_buf().unwrap().len(), 0);
2349 assert_eq!(br2.fill_buf().unwrap().len(), 0);
2350 assert_eq!(&cat[..], &exp[..])
2354 fn chain_bufread() {
2355 let testdata = b"ABCDEFGHIJKL";
2356 let chain1 = (&testdata[..3]).chain(&testdata[3..6])
2357 .chain(&testdata[6..9])
2358 .chain(&testdata[9..]);
2359 let chain2 = (&testdata[..4]).chain(&testdata[4..8])
2360 .chain(&testdata[8..]);
2361 cmp_bufread(chain1, chain2, &testdata[..]);
2365 fn chain_zero_length_read_is_not_eof() {
2368 let mut s = String::new();
2369 let mut chain = (&a[..]).chain(&b[..]);
2370 chain.read(&mut []).unwrap();
2371 chain.read_to_string(&mut s).unwrap();
2372 assert_eq!("AB", s);
2376 #[cfg_attr(target_os = "emscripten", ignore)]
2377 fn bench_read_to_end(b: &mut test::Bencher) {
2379 let mut lr = repeat(1).take(10000000);
2380 let mut vec = Vec::with_capacity(1024);
2381 super::read_to_end(&mut lr, &mut vec)