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")]
270 #[stable(feature = "rust1", since = "1.0.0")]
271 pub use self::buffered::{BufReader, BufWriter, LineWriter};
272 #[stable(feature = "rust1", since = "1.0.0")]
273 pub use self::buffered::IntoInnerError;
274 #[stable(feature = "rust1", since = "1.0.0")]
275 pub use self::cursor::Cursor;
276 #[stable(feature = "rust1", since = "1.0.0")]
277 pub use self::error::{Result, Error, ErrorKind};
278 #[stable(feature = "rust1", since = "1.0.0")]
279 pub use self::util::{copy, sink, Sink, empty, Empty, repeat, Repeat};
280 #[stable(feature = "rust1", since = "1.0.0")]
281 pub use self::stdio::{stdin, stdout, stderr, Stdin, Stdout, Stderr};
282 #[stable(feature = "rust1", since = "1.0.0")]
283 pub use self::stdio::{StdoutLock, StderrLock, StdinLock};
284 #[unstable(feature = "print_internals", issue = "0")]
285 pub use self::stdio::{_print, _eprint};
286 #[unstable(feature = "libstd_io_internals", issue = "42788")]
287 #[doc(no_inline, hidden)]
288 pub use self::stdio::{set_panic, set_print};
299 const DEFAULT_BUF_SIZE: usize = ::sys_common::io::DEFAULT_BUF_SIZE;
301 struct Guard<'a> { buf: &'a mut Vec<u8>, len: usize }
303 impl<'a> Drop for Guard<'a> {
305 unsafe { self.buf.set_len(self.len); }
309 // A few methods below (read_to_string, read_line) will append data into a
310 // `String` buffer, but we need to be pretty careful when doing this. The
311 // implementation will just call `.as_mut_vec()` and then delegate to a
312 // byte-oriented reading method, but we must ensure that when returning we never
313 // leave `buf` in a state such that it contains invalid UTF-8 in its bounds.
315 // To this end, we use an RAII guard (to protect against panics) which updates
316 // the length of the string when it is dropped. This guard initially truncates
317 // the string to the prior length and only after we've validated that the
318 // new contents are valid UTF-8 do we allow it to set a longer length.
320 // The unsafety in this function is twofold:
322 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
324 // 2. We're passing a raw buffer to the function `f`, and it is expected that
325 // the function only *appends* bytes to the buffer. We'll get undefined
326 // behavior if existing bytes are overwritten to have non-UTF-8 data.
327 fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
328 where F: FnOnce(&mut Vec<u8>) -> Result<usize>
331 let mut g = Guard { len: buf.len(), buf: buf.as_mut_vec() };
333 if str::from_utf8(&g.buf[g.len..]).is_err() {
335 Err(Error::new(ErrorKind::InvalidData,
336 "stream did not contain valid UTF-8"))
345 // This uses an adaptive system to extend the vector when it fills. We want to
346 // avoid paying to allocate and zero a huge chunk of memory if the reader only
347 // has 4 bytes while still making large reads if the reader does have a ton
348 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
349 // time is 4,500 times (!) slower than a default reservation size of 32 if the
350 // reader has a very small amount of data to return.
352 // Because we're extending the buffer with uninitialized data for trusted
353 // readers, we need to make sure to truncate that if any of this panics.
354 fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
355 read_to_end_with_reservation(r, buf, 32)
358 fn read_to_end_with_reservation<R: Read + ?Sized>(r: &mut R,
360 reservation_size: usize) -> Result<usize>
362 let start_len = buf.len();
363 let mut g = Guard { len: buf.len(), buf: buf };
366 if g.len == g.buf.len() {
368 g.buf.reserve(reservation_size);
369 let capacity = g.buf.capacity();
370 g.buf.set_len(capacity);
371 r.initializer().initialize(&mut g.buf[g.len..]);
375 match r.read(&mut g.buf[g.len..]) {
377 ret = Ok(g.len - start_len);
381 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
392 /// The `Read` trait allows for reading bytes from a source.
394 /// Implementors of the `Read` trait are called 'readers'.
396 /// Readers are defined by one required method, [`read()`]. Each call to [`read()`]
397 /// will attempt to pull bytes from this source into a provided buffer. A
398 /// number of other methods are implemented in terms of [`read()`], giving
399 /// implementors a number of ways to read bytes while only needing to implement
402 /// Readers are intended to be composable with one another. Many implementors
403 /// throughout [`std::io`] take and provide types which implement the `Read`
406 /// Please note that each call to [`read()`] may involve a system call, and
407 /// therefore, using something that implements [`BufRead`], such as
408 /// [`BufReader`], will be more efficient.
412 /// [`File`]s implement `Read`:
416 /// use std::io::prelude::*;
417 /// use std::fs::File;
419 /// fn main() -> io::Result<()> {
420 /// let mut f = File::open("foo.txt")?;
421 /// let mut buffer = [0; 10];
423 /// // read up to 10 bytes
424 /// f.read(&mut buffer)?;
426 /// let mut buffer = Vec::new();
427 /// // read the whole file
428 /// f.read_to_end(&mut buffer)?;
430 /// // read into a String, so that you don't need to do the conversion.
431 /// let mut buffer = String::new();
432 /// f.read_to_string(&mut buffer)?;
434 /// // and more! See the other methods for more details.
439 /// Read from [`&str`] because [`&[u8]`][slice] implements `Read`:
443 /// use std::io::prelude::*;
445 /// fn main() -> io::Result<()> {
446 /// let mut b = "This string will be read".as_bytes();
447 /// let mut buffer = [0; 10];
449 /// // read up to 10 bytes
450 /// b.read(&mut buffer)?;
452 /// // etc... it works exactly as a File does!
457 /// [`read()`]: trait.Read.html#tymethod.read
458 /// [`std::io`]: ../../std/io/index.html
459 /// [`File`]: ../fs/struct.File.html
460 /// [`BufRead`]: trait.BufRead.html
461 /// [`BufReader`]: struct.BufReader.html
462 /// [`&str`]: ../../std/primitive.str.html
463 /// [slice]: ../../std/primitive.slice.html
464 #[stable(feature = "rust1", since = "1.0.0")]
467 /// Pull some bytes from this source into the specified buffer, returning
468 /// how many bytes were read.
470 /// This function does not provide any guarantees about whether it blocks
471 /// waiting for data, but if an object needs to block for a read but cannot
472 /// it will typically signal this via an [`Err`] return value.
474 /// If the return value of this method is [`Ok(n)`], then it must be
475 /// guaranteed that `0 <= n <= buf.len()`. A nonzero `n` value indicates
476 /// that the buffer `buf` has been filled in with `n` bytes of data from this
477 /// source. If `n` is `0`, then it can indicate one of two scenarios:
479 /// 1. This reader has reached its "end of file" and will likely no longer
480 /// be able to produce bytes. Note that this does not mean that the
481 /// reader will *always* no longer be able to produce bytes.
482 /// 2. The buffer specified was 0 bytes in length.
484 /// No guarantees are provided about the contents of `buf` when this
485 /// function is called, implementations cannot rely on any property of the
486 /// contents of `buf` being true. It is recommended that implementations
487 /// only write data to `buf` instead of reading its contents.
491 /// If this function encounters any form of I/O or other error, an error
492 /// variant will be returned. If an error is returned then it must be
493 /// guaranteed that no bytes were read.
495 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
496 /// operation should be retried if there is nothing else to do.
500 /// [`File`]s implement `Read`:
502 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
503 /// [`Ok(n)`]: ../../std/result/enum.Result.html#variant.Ok
504 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
505 /// [`File`]: ../fs/struct.File.html
509 /// use std::io::prelude::*;
510 /// use std::fs::File;
512 /// fn main() -> io::Result<()> {
513 /// let mut f = File::open("foo.txt")?;
514 /// let mut buffer = [0; 10];
516 /// // read up to 10 bytes
517 /// f.read(&mut buffer[..])?;
521 #[stable(feature = "rust1", since = "1.0.0")]
522 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
524 /// Like `read`, except that it reads into a slice of buffers.
526 /// Data is copied to fill each buffer in order, with the final buffer
527 /// written to possibly being only partially filled. This method must behave
528 /// as a single call to `read` with the buffers concatenated would.
530 /// The default implementation simply passes the first nonempty buffer to
532 #[unstable(feature = "iovec", issue = "0")]
533 fn read_vectored(&mut self, bufs: &mut [IoVecMut<'_>]) -> Result<usize> {
534 match bufs.iter_mut().map(|b| b.as_mut_slice()).find(|b| !b.is_empty()) {
535 Some(buf) => self.read(buf),
540 /// Determines if this `Read`er can work with buffers of uninitialized
543 /// The default implementation returns an initializer which will zero
546 /// If a `Read`er guarantees that it can work properly with uninitialized
547 /// memory, it should call [`Initializer::nop()`]. See the documentation for
548 /// [`Initializer`] for details.
550 /// The behavior of this method must be independent of the state of the
551 /// `Read`er - the method only takes `&self` so that it can be used through
556 /// This method is unsafe because a `Read`er could otherwise return a
557 /// non-zeroing `Initializer` from another `Read` type without an `unsafe`
560 /// [`Initializer::nop()`]: ../../std/io/struct.Initializer.html#method.nop
561 /// [`Initializer`]: ../../std/io/struct.Initializer.html
562 #[unstable(feature = "read_initializer", issue = "42788")]
564 unsafe fn initializer(&self) -> Initializer {
565 Initializer::zeroing()
568 /// Read all bytes until EOF in this source, placing them into `buf`.
570 /// All bytes read from this source will be appended to the specified buffer
571 /// `buf`. This function will continuously call [`read()`] to append more data to
572 /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of
573 /// non-[`ErrorKind::Interrupted`] kind.
575 /// If successful, this function will return the total number of bytes read.
579 /// If this function encounters an error of the kind
580 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
583 /// If any other read error is encountered then this function immediately
584 /// returns. Any bytes which have already been read will be appended to
589 /// [`File`]s implement `Read`:
591 /// [`read()`]: trait.Read.html#tymethod.read
592 /// [`Ok(0)`]: ../../std/result/enum.Result.html#variant.Ok
593 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
594 /// [`File`]: ../fs/struct.File.html
598 /// use std::io::prelude::*;
599 /// use std::fs::File;
601 /// fn main() -> io::Result<()> {
602 /// let mut f = File::open("foo.txt")?;
603 /// let mut buffer = Vec::new();
605 /// // read the whole file
606 /// f.read_to_end(&mut buffer)?;
611 /// (See also the [`std::fs::read`] convenience function for reading from a
614 /// [`std::fs::read`]: ../fs/fn.read.html
615 #[stable(feature = "rust1", since = "1.0.0")]
616 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
617 read_to_end(self, buf)
620 /// Read all bytes until EOF in this source, appending them to `buf`.
622 /// If successful, this function returns the number of bytes which were read
623 /// and appended to `buf`.
627 /// If the data in this stream is *not* valid UTF-8 then an error is
628 /// returned and `buf` is unchanged.
630 /// See [`read_to_end`][readtoend] for other error semantics.
632 /// [readtoend]: #method.read_to_end
636 /// [`File`][file]s implement `Read`:
638 /// [file]: ../fs/struct.File.html
642 /// use std::io::prelude::*;
643 /// use std::fs::File;
645 /// fn main() -> io::Result<()> {
646 /// let mut f = File::open("foo.txt")?;
647 /// let mut buffer = String::new();
649 /// f.read_to_string(&mut buffer)?;
654 /// (See also the [`std::fs::read_to_string`] convenience function for
655 /// reading from a file.)
657 /// [`std::fs::read_to_string`]: ../fs/fn.read_to_string.html
658 #[stable(feature = "rust1", since = "1.0.0")]
659 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
660 // Note that we do *not* call `.read_to_end()` here. We are passing
661 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
662 // method to fill it up. An arbitrary implementation could overwrite the
663 // entire contents of the vector, not just append to it (which is what
664 // we are expecting).
666 // To prevent extraneously checking the UTF-8-ness of the entire buffer
667 // we pass it to our hardcoded `read_to_end` implementation which we
668 // know is guaranteed to only read data into the end of the buffer.
669 append_to_string(buf, |b| read_to_end(self, b))
672 /// Read the exact number of bytes required to fill `buf`.
674 /// This function reads as many bytes as necessary to completely fill the
675 /// specified buffer `buf`.
677 /// No guarantees are provided about the contents of `buf` when this
678 /// function is called, implementations cannot rely on any property of the
679 /// contents of `buf` being true. It is recommended that implementations
680 /// only write data to `buf` instead of reading its contents.
684 /// If this function encounters an error of the kind
685 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
688 /// If this function encounters an "end of file" before completely filling
689 /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
690 /// The contents of `buf` are unspecified in this case.
692 /// If any other read error is encountered then this function immediately
693 /// returns. The contents of `buf` are unspecified in this case.
695 /// If this function returns an error, it is unspecified how many bytes it
696 /// has read, but it will never read more than would be necessary to
697 /// completely fill the buffer.
701 /// [`File`]s implement `Read`:
703 /// [`File`]: ../fs/struct.File.html
704 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
705 /// [`ErrorKind::UnexpectedEof`]: ../../std/io/enum.ErrorKind.html#variant.UnexpectedEof
709 /// use std::io::prelude::*;
710 /// use std::fs::File;
712 /// fn main() -> io::Result<()> {
713 /// let mut f = File::open("foo.txt")?;
714 /// let mut buffer = [0; 10];
716 /// // read exactly 10 bytes
717 /// f.read_exact(&mut buffer)?;
721 #[stable(feature = "read_exact", since = "1.6.0")]
722 fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
723 while !buf.is_empty() {
724 match self.read(buf) {
726 Ok(n) => { let tmp = buf; buf = &mut tmp[n..]; }
727 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
728 Err(e) => return Err(e),
732 Err(Error::new(ErrorKind::UnexpectedEof,
733 "failed to fill whole buffer"))
739 /// Creates a "by reference" adaptor for this instance of `Read`.
741 /// The returned adaptor also implements `Read` and will simply borrow this
746 /// [`File`][file]s implement `Read`:
748 /// [file]: ../fs/struct.File.html
752 /// use std::io::Read;
753 /// use std::fs::File;
755 /// fn main() -> io::Result<()> {
756 /// let mut f = File::open("foo.txt")?;
757 /// let mut buffer = Vec::new();
758 /// let mut other_buffer = Vec::new();
761 /// let reference = f.by_ref();
763 /// // read at most 5 bytes
764 /// reference.take(5).read_to_end(&mut buffer)?;
766 /// } // drop our &mut reference so we can use f again
768 /// // original file still usable, read the rest
769 /// f.read_to_end(&mut other_buffer)?;
773 #[stable(feature = "rust1", since = "1.0.0")]
774 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
776 /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
778 /// The returned type implements [`Iterator`] where the `Item` is
779 /// [`Result`]`<`[`u8`]`, `[`io::Error`]`>`.
780 /// The yielded item is [`Ok`] if a byte was successfully read and [`Err`]
781 /// otherwise. EOF is mapped to returning [`None`] from this iterator.
785 /// [`File`][file]s implement `Read`:
787 /// [file]: ../fs/struct.File.html
788 /// [`Iterator`]: ../../std/iter/trait.Iterator.html
789 /// [`Result`]: ../../std/result/enum.Result.html
790 /// [`io::Error`]: ../../std/io/struct.Error.html
791 /// [`u8`]: ../../std/primitive.u8.html
792 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
793 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
794 /// [`None`]: ../../std/option/enum.Option.html#variant.None
798 /// use std::io::prelude::*;
799 /// use std::fs::File;
801 /// fn main() -> io::Result<()> {
802 /// let mut f = File::open("foo.txt")?;
804 /// for byte in f.bytes() {
805 /// println!("{}", byte.unwrap());
810 #[stable(feature = "rust1", since = "1.0.0")]
811 fn bytes(self) -> Bytes<Self> where Self: Sized {
812 Bytes { inner: self }
815 /// Creates an adaptor which will chain this stream with another.
817 /// The returned `Read` instance will first read all bytes from this object
818 /// until EOF is encountered. Afterwards the output is equivalent to the
819 /// output of `next`.
823 /// [`File`][file]s implement `Read`:
825 /// [file]: ../fs/struct.File.html
829 /// use std::io::prelude::*;
830 /// use std::fs::File;
832 /// fn main() -> io::Result<()> {
833 /// let mut f1 = File::open("foo.txt")?;
834 /// let mut f2 = File::open("bar.txt")?;
836 /// let mut handle = f1.chain(f2);
837 /// let mut buffer = String::new();
839 /// // read the value into a String. We could use any Read method here,
840 /// // this is just one example.
841 /// handle.read_to_string(&mut buffer)?;
845 #[stable(feature = "rust1", since = "1.0.0")]
846 fn chain<R: Read>(self, next: R) -> Chain<Self, R> where Self: Sized {
847 Chain { first: self, second: next, done_first: false }
850 /// Creates an adaptor which will read at most `limit` bytes from it.
852 /// This function returns a new instance of `Read` which will read at most
853 /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
854 /// read errors will not count towards the number of bytes read and future
855 /// calls to [`read()`] may succeed.
859 /// [`File`]s implement `Read`:
861 /// [`File`]: ../fs/struct.File.html
862 /// [`Ok(0)`]: ../../std/result/enum.Result.html#variant.Ok
863 /// [`read()`]: trait.Read.html#tymethod.read
867 /// use std::io::prelude::*;
868 /// use std::fs::File;
870 /// fn main() -> io::Result<()> {
871 /// let mut f = File::open("foo.txt")?;
872 /// let mut buffer = [0; 5];
874 /// // read at most five bytes
875 /// let mut handle = f.take(5);
877 /// handle.read(&mut buffer)?;
881 #[stable(feature = "rust1", since = "1.0.0")]
882 fn take(self, limit: u64) -> Take<Self> where Self: Sized {
883 Take { inner: self, limit: limit }
887 /// A buffer type used with `Read::read_vectored`.
889 /// It is semantically a wrapper around an `&mut [u8]`, but is guaranteed to be
890 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
892 #[unstable(feature = "iovec", issue = "0")]
894 pub struct IoVecMut<'a>(sys::io::IoVecMut<'a>);
896 #[unstable(feature = "iovec", issue = "0")]
897 impl<'a> fmt::Debug for IoVecMut<'a> {
898 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
899 fmt::Debug::fmt(self.as_slice(), fmt)
903 impl<'a> IoVecMut<'a> {
904 /// Creates a new `IoVecMut` wrapping a byte slice.
908 /// Panics on Windows if the slice is larger than 4GB.
909 #[unstable(feature = "iovec", issue = "0")]
911 pub fn new(buf: &'a mut [u8]) -> IoVecMut<'a> {
912 IoVecMut(sys::io::IoVecMut::new(buf))
915 /// Returns a shared reference to the inner slice.
916 #[unstable(feature = "iovec", issue = "0")]
918 pub fn as_slice(&self) -> &'a [u8] {
922 /// Returns a mutable reference to the inner slice.
923 #[unstable(feature = "iovec", issue = "0")]
925 pub fn as_mut_slice(&mut self) -> &'a mut [u8] {
926 self.0.as_mut_slice()
930 /// A buffer type used with `Write::write_vectored`.
932 /// It is semantically a wrapper around an `&[u8]`, but is guaranteed to be
933 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
935 #[unstable(feature = "iovec", issue = "0")]
937 pub struct IoVec<'a>(sys::io::IoVec<'a>);
939 #[unstable(feature = "iovec", issue = "0")]
940 impl<'a> fmt::Debug for IoVec<'a> {
941 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
942 fmt::Debug::fmt(self.as_slice(), fmt)
947 /// Creates a new `IoVec` wrapping a byte slice.
951 /// Panics on Windows if the slice is larger than 4GB.
952 #[unstable(feature = "iovec", issue = "0")]
954 pub fn new(buf: &'a [u8]) -> IoVec<'a> {
955 IoVec(sys::io::IoVec::new(buf))
958 /// Returns a shared reference to the inner slice.
959 #[unstable(feature = "iovec", issue = "0")]
961 pub fn as_slice(&self) -> &'a [u8] {
966 /// A type used to conditionally initialize buffers passed to `Read` methods.
967 #[unstable(feature = "read_initializer", issue = "42788")]
969 pub struct Initializer(bool);
972 /// Returns a new `Initializer` which will zero out buffers.
973 #[unstable(feature = "read_initializer", issue = "42788")]
975 pub fn zeroing() -> Initializer {
979 /// Returns a new `Initializer` which will not zero out buffers.
983 /// This may only be called by `Read`ers which guarantee that they will not
984 /// read from buffers passed to `Read` methods, and that the return value of
985 /// the method accurately reflects the number of bytes that have been
986 /// written to the head of the buffer.
987 #[unstable(feature = "read_initializer", issue = "42788")]
989 pub unsafe fn nop() -> Initializer {
993 /// Indicates if a buffer should be initialized.
994 #[unstable(feature = "read_initializer", issue = "42788")]
996 pub fn should_initialize(&self) -> bool {
1000 /// Initializes a buffer if necessary.
1001 #[unstable(feature = "read_initializer", issue = "42788")]
1003 pub fn initialize(&self, buf: &mut [u8]) {
1004 if self.should_initialize() {
1005 unsafe { ptr::write_bytes(buf.as_mut_ptr(), 0, buf.len()) }
1010 /// A trait for objects which are byte-oriented sinks.
1012 /// Implementors of the `Write` trait are sometimes called 'writers'.
1014 /// Writers are defined by two required methods, [`write`] and [`flush`]:
1016 /// * The [`write`] method will attempt to write some data into the object,
1017 /// returning how many bytes were successfully written.
1019 /// * The [`flush`] method is useful for adaptors and explicit buffers
1020 /// themselves for ensuring that all buffered data has been pushed out to the
1023 /// Writers are intended to be composable with one another. Many implementors
1024 /// throughout [`std::io`] take and provide types which implement the `Write`
1027 /// [`write`]: #tymethod.write
1028 /// [`flush`]: #tymethod.flush
1029 /// [`std::io`]: index.html
1034 /// use std::io::prelude::*;
1035 /// use std::fs::File;
1037 /// fn main() -> std::io::Result<()> {
1038 /// let mut buffer = File::create("foo.txt")?;
1040 /// buffer.write(b"some bytes")?;
1044 #[stable(feature = "rust1", since = "1.0.0")]
1047 /// Write a buffer into this writer, returning how many bytes were written.
1049 /// This function will attempt to write the entire contents of `buf`, but
1050 /// the entire write may not succeed, or the write may also generate an
1051 /// error. A call to `write` represents *at most one* attempt to write to
1052 /// any wrapped object.
1054 /// Calls to `write` are not guaranteed to block waiting for data to be
1055 /// written, and a write which would otherwise block can be indicated through
1056 /// an [`Err`] variant.
1058 /// If the return value is [`Ok(n)`] then it must be guaranteed that
1059 /// `0 <= n <= buf.len()`. A return value of `0` typically means that the
1060 /// underlying object is no longer able to accept bytes and will likely not
1061 /// be able to in the future as well, or that the buffer provided is empty.
1065 /// Each call to `write` may generate an I/O error indicating that the
1066 /// operation could not be completed. If an error is returned then no bytes
1067 /// in the buffer were written to this writer.
1069 /// It is **not** considered an error if the entire buffer could not be
1070 /// written to this writer.
1072 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the
1073 /// write operation should be retried if there is nothing else to do.
1075 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
1076 /// [`Ok(n)`]: ../../std/result/enum.Result.html#variant.Ok
1077 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
1082 /// use std::io::prelude::*;
1083 /// use std::fs::File;
1085 /// fn main() -> std::io::Result<()> {
1086 /// let mut buffer = File::create("foo.txt")?;
1088 /// // Writes some prefix of the byte string, not necessarily all of it.
1089 /// buffer.write(b"some bytes")?;
1093 #[stable(feature = "rust1", since = "1.0.0")]
1094 fn write(&mut self, buf: &[u8]) -> Result<usize>;
1096 /// Like `write`, except that it writes from a slice of buffers.
1098 /// Data is copied to from each buffer in order, with the final buffer
1099 /// read from possibly being only partially consumed. This method must
1100 /// behave as a call to `write` with the buffers concatenated would.
1102 /// The default implementation simply passes the first nonempty buffer to
1104 #[unstable(feature = "iovec", issue = "0")]
1105 fn write_vectored(&mut self, bufs: &[IoVec<'_>]) -> Result<usize> {
1106 match bufs.iter().map(|b| b.as_slice()).find(|b| !b.is_empty()) {
1107 Some(buf) => self.write(buf),
1112 /// Flush this output stream, ensuring that all intermediately buffered
1113 /// contents reach their destination.
1117 /// It is considered an error if not all bytes could be written due to
1118 /// I/O errors or EOF being reached.
1123 /// use std::io::prelude::*;
1124 /// use std::io::BufWriter;
1125 /// use std::fs::File;
1127 /// fn main() -> std::io::Result<()> {
1128 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
1130 /// buffer.write(b"some bytes")?;
1131 /// buffer.flush()?;
1135 #[stable(feature = "rust1", since = "1.0.0")]
1136 fn flush(&mut self) -> Result<()>;
1138 /// Attempts to write an entire buffer into this writer.
1140 /// This method will continuously call [`write`] until there is no more data
1141 /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is
1142 /// returned. This method will not return until the entire buffer has been
1143 /// successfully written or such an error occurs. The first error that is
1144 /// not of [`ErrorKind::Interrupted`] kind generated from this method will be
1149 /// This function will return the first error of
1150 /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns.
1152 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
1153 /// [`write`]: #tymethod.write
1158 /// use std::io::prelude::*;
1159 /// use std::fs::File;
1161 /// fn main() -> std::io::Result<()> {
1162 /// let mut buffer = File::create("foo.txt")?;
1164 /// buffer.write_all(b"some bytes")?;
1168 #[stable(feature = "rust1", since = "1.0.0")]
1169 fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
1170 while !buf.is_empty() {
1171 match self.write(buf) {
1172 Ok(0) => return Err(Error::new(ErrorKind::WriteZero,
1173 "failed to write whole buffer")),
1174 Ok(n) => buf = &buf[n..],
1175 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1176 Err(e) => return Err(e),
1182 /// Writes a formatted string into this writer, returning any error
1185 /// This method is primarily used to interface with the
1186 /// [`format_args!`][formatargs] macro, but it is rare that this should
1187 /// explicitly be called. The [`write!`][write] macro should be favored to
1188 /// invoke this method instead.
1190 /// [formatargs]: ../macro.format_args.html
1191 /// [write]: ../macro.write.html
1193 /// This function internally uses the [`write_all`][writeall] method on
1194 /// this trait and hence will continuously write data so long as no errors
1195 /// are received. This also means that partial writes are not indicated in
1198 /// [writeall]: #method.write_all
1202 /// This function will return any I/O error reported while formatting.
1207 /// use std::io::prelude::*;
1208 /// use std::fs::File;
1210 /// fn main() -> std::io::Result<()> {
1211 /// let mut buffer = File::create("foo.txt")?;
1214 /// write!(buffer, "{:.*}", 2, 1.234567)?;
1215 /// // turns into this:
1216 /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1220 #[stable(feature = "rust1", since = "1.0.0")]
1221 fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()> {
1222 // Create a shim which translates a Write to a fmt::Write and saves
1223 // off I/O errors. instead of discarding them
1224 struct Adaptor<'a, T: ?Sized + 'a> {
1229 impl<'a, T: Write + ?Sized> fmt::Write for Adaptor<'a, T> {
1230 fn write_str(&mut self, s: &str) -> fmt::Result {
1231 match self.inner.write_all(s.as_bytes()) {
1234 self.error = Err(e);
1241 let mut output = Adaptor { inner: self, error: Ok(()) };
1242 match fmt::write(&mut output, fmt) {
1245 // check if the error came from the underlying `Write` or not
1246 if output.error.is_err() {
1249 Err(Error::new(ErrorKind::Other, "formatter error"))
1255 /// Creates a "by reference" adaptor for this instance of `Write`.
1257 /// The returned adaptor also implements `Write` and will simply borrow this
1263 /// use std::io::Write;
1264 /// use std::fs::File;
1266 /// fn main() -> std::io::Result<()> {
1267 /// let mut buffer = File::create("foo.txt")?;
1269 /// let reference = buffer.by_ref();
1271 /// // we can use reference just like our original buffer
1272 /// reference.write_all(b"some bytes")?;
1276 #[stable(feature = "rust1", since = "1.0.0")]
1277 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1280 /// The `Seek` trait provides a cursor which can be moved within a stream of
1283 /// The stream typically has a fixed size, allowing seeking relative to either
1284 /// end or the current offset.
1288 /// [`File`][file]s implement `Seek`:
1290 /// [file]: ../fs/struct.File.html
1294 /// use std::io::prelude::*;
1295 /// use std::fs::File;
1296 /// use std::io::SeekFrom;
1298 /// fn main() -> io::Result<()> {
1299 /// let mut f = File::open("foo.txt")?;
1301 /// // move the cursor 42 bytes from the start of the file
1302 /// f.seek(SeekFrom::Start(42))?;
1306 #[stable(feature = "rust1", since = "1.0.0")]
1308 /// Seek to an offset, in bytes, in a stream.
1310 /// A seek beyond the end of a stream is allowed, but behavior is defined
1311 /// by the implementation.
1313 /// If the seek operation completed successfully,
1314 /// this method returns the new position from the start of the stream.
1315 /// That position can be used later with [`SeekFrom::Start`].
1319 /// Seeking to a negative offset is considered an error.
1321 /// [`SeekFrom::Start`]: enum.SeekFrom.html#variant.Start
1322 #[stable(feature = "rust1", since = "1.0.0")]
1323 fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1326 /// Enumeration of possible methods to seek within an I/O object.
1328 /// It is used by the [`Seek`] trait.
1330 /// [`Seek`]: trait.Seek.html
1331 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1332 #[stable(feature = "rust1", since = "1.0.0")]
1334 /// Sets the offset to the provided number of bytes.
1335 #[stable(feature = "rust1", since = "1.0.0")]
1336 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1338 /// Sets the offset to the size of this object plus the specified number of
1341 /// It is possible to seek beyond the end of an object, but it's an error to
1342 /// seek before byte 0.
1343 #[stable(feature = "rust1", since = "1.0.0")]
1344 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1346 /// Sets the offset to the current position 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 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1355 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>)
1359 let (done, used) = {
1360 let available = match r.fill_buf() {
1362 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1363 Err(e) => return Err(e)
1365 match memchr::memchr(delim, available) {
1367 buf.extend_from_slice(&available[..=i]);
1371 buf.extend_from_slice(available);
1372 (false, available.len())
1378 if done || used == 0 {
1384 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1385 /// to perform extra ways of reading.
1387 /// For example, reading line-by-line is inefficient without using a buffer, so
1388 /// if you want to read by line, you'll need `BufRead`, which includes a
1389 /// [`read_line`] method as well as a [`lines`] iterator.
1393 /// A locked standard input implements `BufRead`:
1397 /// use std::io::prelude::*;
1399 /// let stdin = io::stdin();
1400 /// for line in stdin.lock().lines() {
1401 /// println!("{}", line.unwrap());
1405 /// If you have something that implements [`Read`], you can use the [`BufReader`
1406 /// type][`BufReader`] to turn it into a `BufRead`.
1408 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1409 /// [`BufReader`] to the rescue!
1411 /// [`BufReader`]: struct.BufReader.html
1412 /// [`File`]: ../fs/struct.File.html
1413 /// [`read_line`]: #method.read_line
1414 /// [`lines`]: #method.lines
1415 /// [`Read`]: trait.Read.html
1418 /// use std::io::{self, BufReader};
1419 /// use std::io::prelude::*;
1420 /// use std::fs::File;
1422 /// fn main() -> io::Result<()> {
1423 /// let f = File::open("foo.txt")?;
1424 /// let f = BufReader::new(f);
1426 /// for line in f.lines() {
1427 /// println!("{}", line.unwrap());
1434 #[stable(feature = "rust1", since = "1.0.0")]
1435 pub trait BufRead: Read {
1436 /// Returns the contents of the internal buffer, filling it with more data
1437 /// from the inner reader if it is empty.
1439 /// This function is a lower-level call. It needs to be paired with the
1440 /// [`consume`] method to function properly. When calling this
1441 /// method, none of the contents will be "read" in the sense that later
1442 /// calling `read` may return the same contents. As such, [`consume`] must
1443 /// be called with the number of bytes that are consumed from this buffer to
1444 /// ensure that the bytes are never returned twice.
1446 /// [`consume`]: #tymethod.consume
1448 /// An empty buffer returned indicates that the stream has reached EOF.
1452 /// This function will return an I/O error if the underlying reader was
1453 /// read, but returned an error.
1457 /// A locked standard input implements `BufRead`:
1461 /// use std::io::prelude::*;
1463 /// let stdin = io::stdin();
1464 /// let mut stdin = stdin.lock();
1466 /// // we can't have two `&mut` references to `stdin`, so use a block
1467 /// // to end the borrow early.
1469 /// let buffer = stdin.fill_buf().unwrap();
1471 /// // work with buffer
1472 /// println!("{:?}", buffer);
1477 /// // ensure the bytes we worked with aren't returned again later
1478 /// stdin.consume(length);
1480 #[stable(feature = "rust1", since = "1.0.0")]
1481 fn fill_buf(&mut self) -> Result<&[u8]>;
1483 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1484 /// so they should no longer be returned in calls to `read`.
1486 /// This function is a lower-level call. It needs to be paired with the
1487 /// [`fill_buf`] method to function properly. This function does
1488 /// not perform any I/O, it simply informs this object that some amount of
1489 /// its buffer, returned from [`fill_buf`], has been consumed and should
1490 /// no longer be returned. As such, this function may do odd things if
1491 /// [`fill_buf`] isn't called before calling it.
1493 /// The `amt` must be `<=` the number of bytes in the buffer returned by
1498 /// Since `consume()` is meant to be used with [`fill_buf`],
1499 /// that method's example includes an example of `consume()`.
1501 /// [`fill_buf`]: #tymethod.fill_buf
1502 #[stable(feature = "rust1", since = "1.0.0")]
1503 fn consume(&mut self, amt: usize);
1505 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
1507 /// This function will read bytes from the underlying stream until the
1508 /// delimiter or EOF is found. Once found, all bytes up to, and including,
1509 /// the delimiter (if found) will be appended to `buf`.
1511 /// If successful, this function will return the total number of bytes read.
1515 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1516 /// will otherwise return any errors returned by [`fill_buf`].
1518 /// If an I/O error is encountered then all bytes read so far will be
1519 /// present in `buf` and its length will have been adjusted appropriately.
1521 /// [`fill_buf`]: #tymethod.fill_buf
1522 /// [`ErrorKind::Interrupted`]: enum.ErrorKind.html#variant.Interrupted
1526 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1527 /// this example, we use [`Cursor`] to read all the bytes in a byte slice
1528 /// in hyphen delimited segments:
1530 /// [`Cursor`]: struct.Cursor.html
1533 /// use std::io::{self, BufRead};
1535 /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
1536 /// let mut buf = vec![];
1538 /// // cursor is at 'l'
1539 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1540 /// .expect("reading from cursor won't fail");
1541 /// assert_eq!(num_bytes, 6);
1542 /// assert_eq!(buf, b"lorem-");
1545 /// // cursor is at 'i'
1546 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1547 /// .expect("reading from cursor won't fail");
1548 /// assert_eq!(num_bytes, 5);
1549 /// assert_eq!(buf, b"ipsum");
1552 /// // cursor is at EOF
1553 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1554 /// .expect("reading from cursor won't fail");
1555 /// assert_eq!(num_bytes, 0);
1556 /// assert_eq!(buf, b"");
1558 #[stable(feature = "rust1", since = "1.0.0")]
1559 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
1560 read_until(self, byte, buf)
1563 /// Read all bytes until a newline (the 0xA byte) is reached, and append
1564 /// them to the provided buffer.
1566 /// This function will read bytes from the underlying stream until the
1567 /// newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes
1568 /// up to, and including, the delimiter (if found) will be appended to
1571 /// If successful, this function will return the total number of bytes read.
1573 /// An empty buffer returned indicates that the stream has reached EOF.
1577 /// This function has the same error semantics as [`read_until`] and will
1578 /// also return an error if the read bytes are not valid UTF-8. If an I/O
1579 /// error is encountered then `buf` may contain some bytes already read in
1580 /// the event that all data read so far was valid UTF-8.
1582 /// [`read_until`]: #method.read_until
1586 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1587 /// this example, we use [`Cursor`] to read all the lines in a byte slice:
1589 /// [`Cursor`]: struct.Cursor.html
1592 /// use std::io::{self, BufRead};
1594 /// let mut cursor = io::Cursor::new(b"foo\nbar");
1595 /// let mut buf = String::new();
1597 /// // cursor is at 'f'
1598 /// let num_bytes = cursor.read_line(&mut buf)
1599 /// .expect("reading from cursor won't fail");
1600 /// assert_eq!(num_bytes, 4);
1601 /// assert_eq!(buf, "foo\n");
1604 /// // cursor is at 'b'
1605 /// let num_bytes = cursor.read_line(&mut buf)
1606 /// .expect("reading from cursor won't fail");
1607 /// assert_eq!(num_bytes, 3);
1608 /// assert_eq!(buf, "bar");
1611 /// // cursor is at EOF
1612 /// let num_bytes = cursor.read_line(&mut buf)
1613 /// .expect("reading from cursor won't fail");
1614 /// assert_eq!(num_bytes, 0);
1615 /// assert_eq!(buf, "");
1617 #[stable(feature = "rust1", since = "1.0.0")]
1618 fn read_line(&mut self, buf: &mut String) -> Result<usize> {
1619 // Note that we are not calling the `.read_until` method here, but
1620 // rather our hardcoded implementation. For more details as to why, see
1621 // the comments in `read_to_end`.
1622 append_to_string(buf, |b| read_until(self, b'\n', b))
1625 /// Returns an iterator over the contents of this reader split on the byte
1628 /// The iterator returned from this function will return instances of
1629 /// [`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
1630 /// the delimiter byte at the end.
1632 /// This function will yield errors whenever [`read_until`] would have
1633 /// also yielded an error.
1635 /// [`io::Result`]: type.Result.html
1636 /// [`Vec<u8>`]: ../vec/struct.Vec.html
1637 /// [`read_until`]: #method.read_until
1641 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1642 /// this example, we use [`Cursor`] to iterate over all hyphen delimited
1643 /// segments in a byte slice
1645 /// [`Cursor`]: struct.Cursor.html
1648 /// use std::io::{self, BufRead};
1650 /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
1652 /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
1653 /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
1654 /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
1655 /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
1656 /// assert_eq!(split_iter.next(), None);
1658 #[stable(feature = "rust1", since = "1.0.0")]
1659 fn split(self, byte: u8) -> Split<Self> where Self: Sized {
1660 Split { buf: self, delim: byte }
1663 /// Returns an iterator over the lines of this reader.
1665 /// The iterator returned from this function will yield instances of
1666 /// [`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline
1667 /// byte (the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.
1669 /// [`io::Result`]: type.Result.html
1670 /// [`String`]: ../string/struct.String.html
1674 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1675 /// this example, we use [`Cursor`] to iterate over all the lines in a byte
1678 /// [`Cursor`]: struct.Cursor.html
1681 /// use std::io::{self, BufRead};
1683 /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
1685 /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
1686 /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
1687 /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
1688 /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
1689 /// assert_eq!(lines_iter.next(), None);
1694 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
1696 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
1697 #[stable(feature = "rust1", since = "1.0.0")]
1698 fn lines(self) -> Lines<Self> where Self: Sized {
1703 /// Adaptor to chain together two readers.
1705 /// This struct is generally created by calling [`chain`] on a reader.
1706 /// Please see the documentation of [`chain`] for more details.
1708 /// [`chain`]: trait.Read.html#method.chain
1709 #[stable(feature = "rust1", since = "1.0.0")]
1710 pub struct Chain<T, U> {
1716 impl<T, U> Chain<T, U> {
1717 /// Consumes the `Chain`, returning the wrapped readers.
1723 /// use std::io::prelude::*;
1724 /// use std::fs::File;
1726 /// fn main() -> io::Result<()> {
1727 /// let mut foo_file = File::open("foo.txt")?;
1728 /// let mut bar_file = File::open("bar.txt")?;
1730 /// let chain = foo_file.chain(bar_file);
1731 /// let (foo_file, bar_file) = chain.into_inner();
1735 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1736 pub fn into_inner(self) -> (T, U) {
1737 (self.first, self.second)
1740 /// Gets references to the underlying readers in this `Chain`.
1746 /// use std::io::prelude::*;
1747 /// use std::fs::File;
1749 /// fn main() -> io::Result<()> {
1750 /// let mut foo_file = File::open("foo.txt")?;
1751 /// let mut bar_file = File::open("bar.txt")?;
1753 /// let chain = foo_file.chain(bar_file);
1754 /// let (foo_file, bar_file) = chain.get_ref();
1758 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1759 pub fn get_ref(&self) -> (&T, &U) {
1760 (&self.first, &self.second)
1763 /// Gets mutable references to the underlying readers in this `Chain`.
1765 /// Care should be taken to avoid modifying the internal I/O state of the
1766 /// underlying readers as doing so may corrupt the internal state of this
1773 /// use std::io::prelude::*;
1774 /// use std::fs::File;
1776 /// fn main() -> io::Result<()> {
1777 /// let mut foo_file = File::open("foo.txt")?;
1778 /// let mut bar_file = File::open("bar.txt")?;
1780 /// let mut chain = foo_file.chain(bar_file);
1781 /// let (foo_file, bar_file) = chain.get_mut();
1785 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1786 pub fn get_mut(&mut self) -> (&mut T, &mut U) {
1787 (&mut self.first, &mut self.second)
1791 #[stable(feature = "std_debug", since = "1.16.0")]
1792 impl<T: fmt::Debug, U: fmt::Debug> fmt::Debug for Chain<T, U> {
1793 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1794 f.debug_struct("Chain")
1795 .field("t", &self.first)
1796 .field("u", &self.second)
1801 #[stable(feature = "rust1", since = "1.0.0")]
1802 impl<T: Read, U: Read> Read for Chain<T, U> {
1803 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1804 if !self.done_first {
1805 match self.first.read(buf)? {
1806 0 if buf.len() != 0 => self.done_first = true,
1810 self.second.read(buf)
1813 fn read_vectored(&mut self, bufs: &mut [IoVecMut<'_>]) -> Result<usize> {
1814 if !self.done_first {
1815 match self.first.read_vectored(bufs)? {
1816 0 if bufs.iter().any(|b| !b.as_slice().is_empty()) => self.done_first = true,
1820 self.second.read_vectored(bufs)
1823 unsafe fn initializer(&self) -> Initializer {
1824 let initializer = self.first.initializer();
1825 if initializer.should_initialize() {
1828 self.second.initializer()
1833 #[stable(feature = "chain_bufread", since = "1.9.0")]
1834 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
1835 fn fill_buf(&mut self) -> Result<&[u8]> {
1836 if !self.done_first {
1837 match self.first.fill_buf()? {
1838 buf if buf.len() == 0 => { self.done_first = true; }
1839 buf => return Ok(buf),
1842 self.second.fill_buf()
1845 fn consume(&mut self, amt: usize) {
1846 if !self.done_first {
1847 self.first.consume(amt)
1849 self.second.consume(amt)
1854 /// Reader adaptor which limits the bytes read from an underlying reader.
1856 /// This struct is generally created by calling [`take`] on a reader.
1857 /// Please see the documentation of [`take`] for more details.
1859 /// [`take`]: trait.Read.html#method.take
1860 #[stable(feature = "rust1", since = "1.0.0")]
1862 pub struct Take<T> {
1868 /// Returns the number of bytes that can be read before this instance will
1873 /// This instance may reach `EOF` after reading fewer bytes than indicated by
1874 /// this method if the underlying [`Read`] instance reaches EOF.
1876 /// [`Read`]: ../../std/io/trait.Read.html
1882 /// use std::io::prelude::*;
1883 /// use std::fs::File;
1885 /// fn main() -> io::Result<()> {
1886 /// let f = File::open("foo.txt")?;
1888 /// // read at most five bytes
1889 /// let handle = f.take(5);
1891 /// println!("limit: {}", handle.limit());
1895 #[stable(feature = "rust1", since = "1.0.0")]
1896 pub fn limit(&self) -> u64 { self.limit }
1898 /// Sets the number of bytes that can be read before this instance will
1899 /// return EOF. This is the same as constructing a new `Take` instance, so
1900 /// the amount of bytes read and the previous limit value don't matter when
1901 /// calling this method.
1907 /// use std::io::prelude::*;
1908 /// use std::fs::File;
1910 /// fn main() -> io::Result<()> {
1911 /// let f = File::open("foo.txt")?;
1913 /// // read at most five bytes
1914 /// let mut handle = f.take(5);
1915 /// handle.set_limit(10);
1917 /// assert_eq!(handle.limit(), 10);
1921 #[stable(feature = "take_set_limit", since = "1.27.0")]
1922 pub fn set_limit(&mut self, limit: u64) {
1926 /// Consumes the `Take`, returning the wrapped reader.
1932 /// use std::io::prelude::*;
1933 /// use std::fs::File;
1935 /// fn main() -> io::Result<()> {
1936 /// let mut file = File::open("foo.txt")?;
1938 /// let mut buffer = [0; 5];
1939 /// let mut handle = file.take(5);
1940 /// handle.read(&mut buffer)?;
1942 /// let file = handle.into_inner();
1946 #[stable(feature = "io_take_into_inner", since = "1.15.0")]
1947 pub fn into_inner(self) -> T {
1951 /// Gets a reference to the underlying reader.
1957 /// use std::io::prelude::*;
1958 /// use std::fs::File;
1960 /// fn main() -> io::Result<()> {
1961 /// let mut file = File::open("foo.txt")?;
1963 /// let mut buffer = [0; 5];
1964 /// let mut handle = file.take(5);
1965 /// handle.read(&mut buffer)?;
1967 /// let file = handle.get_ref();
1971 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1972 pub fn get_ref(&self) -> &T {
1976 /// Gets a mutable reference to the underlying reader.
1978 /// Care should be taken to avoid modifying the internal I/O state of the
1979 /// underlying reader as doing so may corrupt the internal limit of this
1986 /// use std::io::prelude::*;
1987 /// use std::fs::File;
1989 /// fn main() -> io::Result<()> {
1990 /// let mut file = File::open("foo.txt")?;
1992 /// let mut buffer = [0; 5];
1993 /// let mut handle = file.take(5);
1994 /// handle.read(&mut buffer)?;
1996 /// let file = handle.get_mut();
2000 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2001 pub fn get_mut(&mut self) -> &mut T {
2006 #[stable(feature = "rust1", since = "1.0.0")]
2007 impl<T: Read> Read for Take<T> {
2008 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2009 // Don't call into inner reader at all at EOF because it may still block
2010 if self.limit == 0 {
2014 let max = cmp::min(buf.len() as u64, self.limit) as usize;
2015 let n = self.inner.read(&mut buf[..max])?;
2016 self.limit -= n as u64;
2020 unsafe fn initializer(&self) -> Initializer {
2021 self.inner.initializer()
2024 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
2025 let reservation_size = cmp::min(self.limit, 32) as usize;
2027 read_to_end_with_reservation(self, buf, reservation_size)
2031 #[stable(feature = "rust1", since = "1.0.0")]
2032 impl<T: BufRead> BufRead for Take<T> {
2033 fn fill_buf(&mut self) -> Result<&[u8]> {
2034 // Don't call into inner reader at all at EOF because it may still block
2035 if self.limit == 0 {
2039 let buf = self.inner.fill_buf()?;
2040 let cap = cmp::min(buf.len() as u64, self.limit) as usize;
2044 fn consume(&mut self, amt: usize) {
2045 // Don't let callers reset the limit by passing an overlarge value
2046 let amt = cmp::min(amt as u64, self.limit) as usize;
2047 self.limit -= amt as u64;
2048 self.inner.consume(amt);
2052 /// An iterator over `u8` values of a reader.
2054 /// This struct is generally created by calling [`bytes`] on a reader.
2055 /// Please see the documentation of [`bytes`] for more details.
2057 /// [`bytes`]: trait.Read.html#method.bytes
2058 #[stable(feature = "rust1", since = "1.0.0")]
2060 pub struct Bytes<R> {
2064 #[stable(feature = "rust1", since = "1.0.0")]
2065 impl<R: Read> Iterator for Bytes<R> {
2066 type Item = Result<u8>;
2068 fn next(&mut self) -> Option<Result<u8>> {
2071 return match self.inner.read(slice::from_mut(&mut byte)) {
2073 Ok(..) => Some(Ok(byte)),
2074 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
2075 Err(e) => Some(Err(e)),
2081 /// An iterator over the contents of an instance of `BufRead` split on a
2082 /// particular byte.
2084 /// This struct is generally created by calling [`split`][split] on a
2085 /// `BufRead`. Please see the documentation of `split()` for more details.
2087 /// [split]: trait.BufRead.html#method.split
2088 #[stable(feature = "rust1", since = "1.0.0")]
2090 pub struct Split<B> {
2095 #[stable(feature = "rust1", since = "1.0.0")]
2096 impl<B: BufRead> Iterator for Split<B> {
2097 type Item = Result<Vec<u8>>;
2099 fn next(&mut self) -> Option<Result<Vec<u8>>> {
2100 let mut buf = Vec::new();
2101 match self.buf.read_until(self.delim, &mut buf) {
2104 if buf[buf.len() - 1] == self.delim {
2109 Err(e) => Some(Err(e))
2114 /// An iterator over the lines of an instance of `BufRead`.
2116 /// This struct is generally created by calling [`lines`][lines] on a
2117 /// `BufRead`. Please see the documentation of `lines()` for more details.
2119 /// [lines]: trait.BufRead.html#method.lines
2120 #[stable(feature = "rust1", since = "1.0.0")]
2122 pub struct Lines<B> {
2126 #[stable(feature = "rust1", since = "1.0.0")]
2127 impl<B: BufRead> Iterator for Lines<B> {
2128 type Item = Result<String>;
2130 fn next(&mut self) -> Option<Result<String>> {
2131 let mut buf = String::new();
2132 match self.buf.read_line(&mut buf) {
2135 if buf.ends_with("\n") {
2137 if buf.ends_with("\r") {
2143 Err(e) => Some(Err(e))
2157 #[cfg_attr(target_os = "emscripten", ignore)]
2159 let mut buf = Cursor::new(&b"12"[..]);
2160 let mut v = Vec::new();
2161 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 2);
2162 assert_eq!(v, b"12");
2164 let mut buf = Cursor::new(&b"1233"[..]);
2165 let mut v = Vec::new();
2166 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 3);
2167 assert_eq!(v, b"123");
2169 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 1);
2170 assert_eq!(v, b"3");
2172 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 0);
2178 let buf = Cursor::new(&b"12"[..]);
2179 let mut s = buf.split(b'3');
2180 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2181 assert!(s.next().is_none());
2183 let buf = Cursor::new(&b"1233"[..]);
2184 let mut s = buf.split(b'3');
2185 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2186 assert_eq!(s.next().unwrap().unwrap(), vec![]);
2187 assert!(s.next().is_none());
2192 let mut buf = Cursor::new(&b"12"[..]);
2193 let mut v = String::new();
2194 assert_eq!(buf.read_line(&mut v).unwrap(), 2);
2195 assert_eq!(v, "12");
2197 let mut buf = Cursor::new(&b"12\n\n"[..]);
2198 let mut v = String::new();
2199 assert_eq!(buf.read_line(&mut v).unwrap(), 3);
2200 assert_eq!(v, "12\n");
2202 assert_eq!(buf.read_line(&mut v).unwrap(), 1);
2203 assert_eq!(v, "\n");
2205 assert_eq!(buf.read_line(&mut v).unwrap(), 0);
2211 let buf = Cursor::new(&b"12\r"[..]);
2212 let mut s = buf.lines();
2213 assert_eq!(s.next().unwrap().unwrap(), "12\r".to_string());
2214 assert!(s.next().is_none());
2216 let buf = Cursor::new(&b"12\r\n\n"[..]);
2217 let mut s = buf.lines();
2218 assert_eq!(s.next().unwrap().unwrap(), "12".to_string());
2219 assert_eq!(s.next().unwrap().unwrap(), "".to_string());
2220 assert!(s.next().is_none());
2225 let mut c = Cursor::new(&b""[..]);
2226 let mut v = Vec::new();
2227 assert_eq!(c.read_to_end(&mut v).unwrap(), 0);
2230 let mut c = Cursor::new(&b"1"[..]);
2231 let mut v = Vec::new();
2232 assert_eq!(c.read_to_end(&mut v).unwrap(), 1);
2233 assert_eq!(v, b"1");
2235 let cap = 1024 * 1024;
2236 let data = (0..cap).map(|i| (i / 3) as u8).collect::<Vec<_>>();
2237 let mut v = Vec::new();
2238 let (a, b) = data.split_at(data.len() / 2);
2239 assert_eq!(Cursor::new(a).read_to_end(&mut v).unwrap(), a.len());
2240 assert_eq!(Cursor::new(b).read_to_end(&mut v).unwrap(), b.len());
2241 assert_eq!(v, data);
2245 fn read_to_string() {
2246 let mut c = Cursor::new(&b""[..]);
2247 let mut v = String::new();
2248 assert_eq!(c.read_to_string(&mut v).unwrap(), 0);
2251 let mut c = Cursor::new(&b"1"[..]);
2252 let mut v = String::new();
2253 assert_eq!(c.read_to_string(&mut v).unwrap(), 1);
2256 let mut c = Cursor::new(&b"\xff"[..]);
2257 let mut v = String::new();
2258 assert!(c.read_to_string(&mut v).is_err());
2263 let mut buf = [0; 4];
2265 let mut c = Cursor::new(&b""[..]);
2266 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2267 io::ErrorKind::UnexpectedEof);
2269 let mut c = Cursor::new(&b"123"[..]).chain(Cursor::new(&b"456789"[..]));
2270 c.read_exact(&mut buf).unwrap();
2271 assert_eq!(&buf, b"1234");
2272 c.read_exact(&mut buf).unwrap();
2273 assert_eq!(&buf, b"5678");
2274 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2275 io::ErrorKind::UnexpectedEof);
2279 fn read_exact_slice() {
2280 let mut buf = [0; 4];
2282 let mut c = &b""[..];
2283 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2284 io::ErrorKind::UnexpectedEof);
2286 let mut c = &b"123"[..];
2287 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2288 io::ErrorKind::UnexpectedEof);
2289 // make sure the optimized (early returning) method is being used
2290 assert_eq!(&buf, &[0; 4]);
2292 let mut c = &b"1234"[..];
2293 c.read_exact(&mut buf).unwrap();
2294 assert_eq!(&buf, b"1234");
2296 let mut c = &b"56789"[..];
2297 c.read_exact(&mut buf).unwrap();
2298 assert_eq!(&buf, b"5678");
2299 assert_eq!(c, b"9");
2307 fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
2308 Err(io::Error::new(io::ErrorKind::Other, ""))
2311 impl BufRead for R {
2312 fn fill_buf(&mut self) -> io::Result<&[u8]> {
2313 Err(io::Error::new(io::ErrorKind::Other, ""))
2315 fn consume(&mut self, _amt: usize) { }
2318 let mut buf = [0; 1];
2319 assert_eq!(0, R.take(0).read(&mut buf).unwrap());
2320 assert_eq!(b"", R.take(0).fill_buf().unwrap());
2323 fn cmp_bufread<Br1: BufRead, Br2: BufRead>(mut br1: Br1, mut br2: Br2, exp: &[u8]) {
2324 let mut cat = Vec::new();
2327 let buf1 = br1.fill_buf().unwrap();
2328 let buf2 = br2.fill_buf().unwrap();
2329 let minlen = if buf1.len() < buf2.len() { buf1.len() } else { buf2.len() };
2330 assert_eq!(buf1[..minlen], buf2[..minlen]);
2331 cat.extend_from_slice(&buf1[..minlen]);
2337 br1.consume(consume);
2338 br2.consume(consume);
2340 assert_eq!(br1.fill_buf().unwrap().len(), 0);
2341 assert_eq!(br2.fill_buf().unwrap().len(), 0);
2342 assert_eq!(&cat[..], &exp[..])
2346 fn chain_bufread() {
2347 let testdata = b"ABCDEFGHIJKL";
2348 let chain1 = (&testdata[..3]).chain(&testdata[3..6])
2349 .chain(&testdata[6..9])
2350 .chain(&testdata[9..]);
2351 let chain2 = (&testdata[..4]).chain(&testdata[4..8])
2352 .chain(&testdata[8..]);
2353 cmp_bufread(chain1, chain2, &testdata[..]);
2357 fn chain_zero_length_read_is_not_eof() {
2360 let mut s = String::new();
2361 let mut chain = (&a[..]).chain(&b[..]);
2362 chain.read(&mut []).unwrap();
2363 chain.read_to_string(&mut s).unwrap();
2364 assert_eq!("AB", s);
2368 #[cfg_attr(target_os = "emscripten", ignore)]
2369 fn bench_read_to_end(b: &mut test::Bencher) {
2371 let mut lr = repeat(1).take(10000000);
2372 let mut vec = Vec::with_capacity(1024);
2373 super::read_to_end(&mut lr, &mut vec)