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/first-edition/syntax-index.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")]
269 #[stable(feature = "rust1", since = "1.0.0")]
270 pub use self::buffered::{BufReader, BufWriter, LineWriter};
271 #[stable(feature = "rust1", since = "1.0.0")]
272 pub use self::buffered::IntoInnerError;
273 #[stable(feature = "rust1", since = "1.0.0")]
274 pub use self::cursor::Cursor;
275 #[stable(feature = "rust1", since = "1.0.0")]
276 pub use self::error::{Result, Error, ErrorKind};
277 #[stable(feature = "rust1", since = "1.0.0")]
278 pub use self::util::{copy, sink, Sink, empty, Empty, repeat, Repeat};
279 #[stable(feature = "rust1", since = "1.0.0")]
280 pub use self::stdio::{stdin, stdout, stderr, Stdin, Stdout, Stderr};
281 #[stable(feature = "rust1", since = "1.0.0")]
282 pub use self::stdio::{StdoutLock, StderrLock, StdinLock};
283 #[unstable(feature = "print_internals", issue = "0")]
284 pub use self::stdio::{_print, _eprint};
285 #[unstable(feature = "libstd_io_internals", issue = "42788")]
286 #[doc(no_inline, hidden)]
287 pub use self::stdio::{set_panic, set_print};
298 const DEFAULT_BUF_SIZE: usize = ::sys_common::io::DEFAULT_BUF_SIZE;
300 struct Guard<'a> { buf: &'a mut Vec<u8>, len: usize }
302 impl<'a> Drop for Guard<'a> {
304 unsafe { self.buf.set_len(self.len); }
308 // A few methods below (read_to_string, read_line) will append data into a
309 // `String` buffer, but we need to be pretty careful when doing this. The
310 // implementation will just call `.as_mut_vec()` and then delegate to a
311 // byte-oriented reading method, but we must ensure that when returning we never
312 // leave `buf` in a state such that it contains invalid UTF-8 in its bounds.
314 // To this end, we use an RAII guard (to protect against panics) which updates
315 // the length of the string when it is dropped. This guard initially truncates
316 // the string to the prior length and only after we've validated that the
317 // new contents are valid UTF-8 do we allow it to set a longer length.
319 // The unsafety in this function is twofold:
321 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
323 // 2. We're passing a raw buffer to the function `f`, and it is expected that
324 // the function only *appends* bytes to the buffer. We'll get undefined
325 // behavior if existing bytes are overwritten to have non-UTF-8 data.
326 fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
327 where F: FnOnce(&mut Vec<u8>) -> Result<usize>
330 let mut g = Guard { len: buf.len(), buf: buf.as_mut_vec() };
332 if str::from_utf8(&g.buf[g.len..]).is_err() {
334 Err(Error::new(ErrorKind::InvalidData,
335 "stream did not contain valid UTF-8"))
344 // This uses an adaptive system to extend the vector when it fills. We want to
345 // avoid paying to allocate and zero a huge chunk of memory if the reader only
346 // has 4 bytes while still making large reads if the reader does have a ton
347 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
348 // time is 4,500 times (!) slower than a default reservation size of 32 if the
349 // reader has a very small amount of data to return.
351 // Because we're extending the buffer with uninitialized data for trusted
352 // readers, we need to make sure to truncate that if any of this panics.
353 fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
354 read_to_end_with_reservation(r, buf, 32)
357 fn read_to_end_with_reservation<R: Read + ?Sized>(r: &mut R,
359 reservation_size: usize) -> Result<usize>
361 let start_len = buf.len();
362 let mut g = Guard { len: buf.len(), buf: buf };
365 if g.len == g.buf.len() {
367 g.buf.reserve(reservation_size);
368 let capacity = g.buf.capacity();
369 g.buf.set_len(capacity);
370 r.initializer().initialize(&mut g.buf[g.len..]);
374 match r.read(&mut g.buf[g.len..]) {
376 ret = Ok(g.len - start_len);
380 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
391 /// The `Read` trait allows for reading bytes from a source.
393 /// Implementors of the `Read` trait are called 'readers'.
395 /// Readers are defined by one required method, [`read()`]. Each call to [`read()`]
396 /// will attempt to pull bytes from this source into a provided buffer. A
397 /// number of other methods are implemented in terms of [`read()`], giving
398 /// implementors a number of ways to read bytes while only needing to implement
401 /// Readers are intended to be composable with one another. Many implementors
402 /// throughout [`std::io`] take and provide types which implement the `Read`
405 /// Please note that each call to [`read()`] may involve a system call, and
406 /// therefore, using something that implements [`BufRead`], such as
407 /// [`BufReader`], will be more efficient.
411 /// [`File`]s implement `Read`:
415 /// use std::io::prelude::*;
416 /// use std::fs::File;
418 /// fn main() -> io::Result<()> {
419 /// let mut f = File::open("foo.txt")?;
420 /// let mut buffer = [0; 10];
422 /// // read up to 10 bytes
423 /// f.read(&mut buffer)?;
425 /// let mut buffer = Vec::new();
426 /// // read the whole file
427 /// f.read_to_end(&mut buffer)?;
429 /// // read into a String, so that you don't need to do the conversion.
430 /// let mut buffer = String::new();
431 /// f.read_to_string(&mut buffer)?;
433 /// // and more! See the other methods for more details.
438 /// Read from [`&str`] because [`&[u8]`][slice] implements `Read`:
442 /// use std::io::prelude::*;
444 /// fn main() -> io::Result<()> {
445 /// let mut b = "This string will be read".as_bytes();
446 /// let mut buffer = [0; 10];
448 /// // read up to 10 bytes
449 /// b.read(&mut buffer)?;
451 /// // etc... it works exactly as a File does!
456 /// [`read()`]: trait.Read.html#tymethod.read
457 /// [`std::io`]: ../../std/io/index.html
458 /// [`File`]: ../fs/struct.File.html
459 /// [`BufRead`]: trait.BufRead.html
460 /// [`BufReader`]: struct.BufReader.html
461 /// [`&str`]: ../../std/primitive.str.html
462 /// [slice]: ../../std/primitive.slice.html
463 #[stable(feature = "rust1", since = "1.0.0")]
466 /// Pull some bytes from this source into the specified buffer, returning
467 /// how many bytes were read.
469 /// This function does not provide any guarantees about whether it blocks
470 /// waiting for data, but if an object needs to block for a read but cannot
471 /// it will typically signal this via an [`Err`] return value.
473 /// If the return value of this method is [`Ok(n)`], then it must be
474 /// guaranteed that `0 <= n <= buf.len()`. A nonzero `n` value indicates
475 /// that the buffer `buf` has been filled in with `n` bytes of data from this
476 /// source. If `n` is `0`, then it can indicate one of two scenarios:
478 /// 1. This reader has reached its "end of file" and will likely no longer
479 /// be able to produce bytes. Note that this does not mean that the
480 /// reader will *always* no longer be able to produce bytes.
481 /// 2. The buffer specified was 0 bytes in length.
483 /// No guarantees are provided about the contents of `buf` when this
484 /// function is called, implementations cannot rely on any property of the
485 /// contents of `buf` being true. It is recommended that implementations
486 /// only write data to `buf` instead of reading its contents.
490 /// If this function encounters any form of I/O or other error, an error
491 /// variant will be returned. If an error is returned then it must be
492 /// guaranteed that no bytes were read.
494 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
495 /// operation should be retried if there is nothing else to do.
499 /// [`File`]s implement `Read`:
501 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
502 /// [`Ok(n)`]: ../../std/result/enum.Result.html#variant.Ok
503 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
504 /// [`File`]: ../fs/struct.File.html
508 /// use std::io::prelude::*;
509 /// use std::fs::File;
511 /// fn main() -> io::Result<()> {
512 /// let mut f = File::open("foo.txt")?;
513 /// let mut buffer = [0; 10];
515 /// // read up to 10 bytes
516 /// f.read(&mut buffer[..])?;
520 #[stable(feature = "rust1", since = "1.0.0")]
521 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
523 /// Determines if this `Read`er can work with buffers of uninitialized
526 /// The default implementation returns an initializer which will zero
529 /// If a `Read`er guarantees that it can work properly with uninitialized
530 /// memory, it should call [`Initializer::nop()`]. See the documentation for
531 /// [`Initializer`] for details.
533 /// The behavior of this method must be independent of the state of the
534 /// `Read`er - the method only takes `&self` so that it can be used through
539 /// This method is unsafe because a `Read`er could otherwise return a
540 /// non-zeroing `Initializer` from another `Read` type without an `unsafe`
543 /// [`Initializer::nop()`]: ../../std/io/struct.Initializer.html#method.nop
544 /// [`Initializer`]: ../../std/io/struct.Initializer.html
545 #[unstable(feature = "read_initializer", issue = "42788")]
547 unsafe fn initializer(&self) -> Initializer {
548 Initializer::zeroing()
551 /// Read all bytes until EOF in this source, placing them into `buf`.
553 /// All bytes read from this source will be appended to the specified buffer
554 /// `buf`. This function will continuously call [`read()`] to append more data to
555 /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of
556 /// non-[`ErrorKind::Interrupted`] kind.
558 /// If successful, this function will return the total number of bytes read.
562 /// If this function encounters an error of the kind
563 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
566 /// If any other read error is encountered then this function immediately
567 /// returns. Any bytes which have already been read will be appended to
572 /// [`File`]s implement `Read`:
574 /// [`read()`]: trait.Read.html#tymethod.read
575 /// [`Ok(0)`]: ../../std/result/enum.Result.html#variant.Ok
576 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
577 /// [`File`]: ../fs/struct.File.html
581 /// use std::io::prelude::*;
582 /// use std::fs::File;
584 /// fn main() -> io::Result<()> {
585 /// let mut f = File::open("foo.txt")?;
586 /// let mut buffer = Vec::new();
588 /// // read the whole file
589 /// f.read_to_end(&mut buffer)?;
594 /// (See also the [`std::fs::read`] convenience function for reading from a
597 /// [`std::fs::read`]: ../fs/fn.read.html
598 #[stable(feature = "rust1", since = "1.0.0")]
599 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
600 read_to_end(self, buf)
603 /// Read all bytes until EOF in this source, appending them to `buf`.
605 /// If successful, this function returns the number of bytes which were read
606 /// and appended to `buf`.
610 /// If the data in this stream is *not* valid UTF-8 then an error is
611 /// returned and `buf` is unchanged.
613 /// See [`read_to_end`][readtoend] for other error semantics.
615 /// [readtoend]: #method.read_to_end
619 /// [`File`][file]s implement `Read`:
621 /// [file]: ../fs/struct.File.html
625 /// use std::io::prelude::*;
626 /// use std::fs::File;
628 /// fn main() -> io::Result<()> {
629 /// let mut f = File::open("foo.txt")?;
630 /// let mut buffer = String::new();
632 /// f.read_to_string(&mut buffer)?;
637 /// (See also the [`std::fs::read_to_string`] convenience function for
638 /// reading from a file.)
640 /// [`std::fs::read_to_string`]: ../fs/fn.read_to_string.html
641 #[stable(feature = "rust1", since = "1.0.0")]
642 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
643 // Note that we do *not* call `.read_to_end()` here. We are passing
644 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
645 // method to fill it up. An arbitrary implementation could overwrite the
646 // entire contents of the vector, not just append to it (which is what
647 // we are expecting).
649 // To prevent extraneously checking the UTF-8-ness of the entire buffer
650 // we pass it to our hardcoded `read_to_end` implementation which we
651 // know is guaranteed to only read data into the end of the buffer.
652 append_to_string(buf, |b| read_to_end(self, b))
655 /// Read the exact number of bytes required to fill `buf`.
657 /// This function reads as many bytes as necessary to completely fill the
658 /// specified buffer `buf`.
660 /// No guarantees are provided about the contents of `buf` when this
661 /// function is called, implementations cannot rely on any property of the
662 /// contents of `buf` being true. It is recommended that implementations
663 /// only write data to `buf` instead of reading its contents.
667 /// If this function encounters an error of the kind
668 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
671 /// If this function encounters an "end of file" before completely filling
672 /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
673 /// The contents of `buf` are unspecified in this case.
675 /// If any other read error is encountered then this function immediately
676 /// returns. The contents of `buf` are unspecified in this case.
678 /// If this function returns an error, it is unspecified how many bytes it
679 /// has read, but it will never read more than would be necessary to
680 /// completely fill the buffer.
684 /// [`File`]s implement `Read`:
686 /// [`File`]: ../fs/struct.File.html
687 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
688 /// [`ErrorKind::UnexpectedEof`]: ../../std/io/enum.ErrorKind.html#variant.UnexpectedEof
692 /// use std::io::prelude::*;
693 /// use std::fs::File;
695 /// fn main() -> io::Result<()> {
696 /// let mut f = File::open("foo.txt")?;
697 /// let mut buffer = [0; 10];
699 /// // read exactly 10 bytes
700 /// f.read_exact(&mut buffer)?;
704 #[stable(feature = "read_exact", since = "1.6.0")]
705 fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
706 while !buf.is_empty() {
707 match self.read(buf) {
709 Ok(n) => { let tmp = buf; buf = &mut tmp[n..]; }
710 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
711 Err(e) => return Err(e),
715 Err(Error::new(ErrorKind::UnexpectedEof,
716 "failed to fill whole buffer"))
722 /// Creates a "by reference" adaptor for this instance of `Read`.
724 /// The returned adaptor also implements `Read` and will simply borrow this
729 /// [`File`][file]s implement `Read`:
731 /// [file]: ../fs/struct.File.html
735 /// use std::io::Read;
736 /// use std::fs::File;
738 /// fn main() -> io::Result<()> {
739 /// let mut f = File::open("foo.txt")?;
740 /// let mut buffer = Vec::new();
741 /// let mut other_buffer = Vec::new();
744 /// let reference = f.by_ref();
746 /// // read at most 5 bytes
747 /// reference.take(5).read_to_end(&mut buffer)?;
749 /// } // drop our &mut reference so we can use f again
751 /// // original file still usable, read the rest
752 /// f.read_to_end(&mut other_buffer)?;
756 #[stable(feature = "rust1", since = "1.0.0")]
757 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
759 /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
761 /// The returned type implements [`Iterator`] where the `Item` is
762 /// [`Result`]`<`[`u8`]`, `[`io::Error`]`>`.
763 /// The yielded item is [`Ok`] if a byte was successfully read and [`Err`]
764 /// otherwise. EOF is mapped to returning [`None`] from this iterator.
768 /// [`File`][file]s implement `Read`:
770 /// [file]: ../fs/struct.File.html
771 /// [`Iterator`]: ../../std/iter/trait.Iterator.html
772 /// [`Result`]: ../../std/result/enum.Result.html
773 /// [`io::Error`]: ../../std/io/struct.Error.html
774 /// [`u8`]: ../../std/primitive.u8.html
775 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
776 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
777 /// [`None`]: ../../std/option/enum.Option.html#variant.None
781 /// use std::io::prelude::*;
782 /// use std::fs::File;
784 /// fn main() -> io::Result<()> {
785 /// let mut f = File::open("foo.txt")?;
787 /// for byte in f.bytes() {
788 /// println!("{}", byte.unwrap());
793 #[stable(feature = "rust1", since = "1.0.0")]
794 fn bytes(self) -> Bytes<Self> where Self: Sized {
795 Bytes { inner: self }
798 /// Creates an adaptor which will chain this stream with another.
800 /// The returned `Read` instance will first read all bytes from this object
801 /// until EOF is encountered. Afterwards the output is equivalent to the
802 /// output of `next`.
806 /// [`File`][file]s implement `Read`:
808 /// [file]: ../fs/struct.File.html
812 /// use std::io::prelude::*;
813 /// use std::fs::File;
815 /// fn main() -> io::Result<()> {
816 /// let mut f1 = File::open("foo.txt")?;
817 /// let mut f2 = File::open("bar.txt")?;
819 /// let mut handle = f1.chain(f2);
820 /// let mut buffer = String::new();
822 /// // read the value into a String. We could use any Read method here,
823 /// // this is just one example.
824 /// handle.read_to_string(&mut buffer)?;
828 #[stable(feature = "rust1", since = "1.0.0")]
829 fn chain<R: Read>(self, next: R) -> Chain<Self, R> where Self: Sized {
830 Chain { first: self, second: next, done_first: false }
833 /// Creates an adaptor which will read at most `limit` bytes from it.
835 /// This function returns a new instance of `Read` which will read at most
836 /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
837 /// read errors will not count towards the number of bytes read and future
838 /// calls to [`read()`] may succeed.
842 /// [`File`]s implement `Read`:
844 /// [`File`]: ../fs/struct.File.html
845 /// [`Ok(0)`]: ../../std/result/enum.Result.html#variant.Ok
846 /// [`read()`]: trait.Read.html#tymethod.read
850 /// use std::io::prelude::*;
851 /// use std::fs::File;
853 /// fn main() -> io::Result<()> {
854 /// let mut f = File::open("foo.txt")?;
855 /// let mut buffer = [0; 5];
857 /// // read at most five bytes
858 /// let mut handle = f.take(5);
860 /// handle.read(&mut buffer)?;
864 #[stable(feature = "rust1", since = "1.0.0")]
865 fn take(self, limit: u64) -> Take<Self> where Self: Sized {
866 Take { inner: self, limit: limit }
870 /// A type used to conditionally initialize buffers passed to `Read` methods.
871 #[unstable(feature = "read_initializer", issue = "42788")]
873 pub struct Initializer(bool);
876 /// Returns a new `Initializer` which will zero out buffers.
877 #[unstable(feature = "read_initializer", issue = "42788")]
879 pub fn zeroing() -> Initializer {
883 /// Returns a new `Initializer` which will not zero out buffers.
887 /// This may only be called by `Read`ers which guarantee that they will not
888 /// read from buffers passed to `Read` methods, and that the return value of
889 /// the method accurately reflects the number of bytes that have been
890 /// written to the head of the buffer.
891 #[unstable(feature = "read_initializer", issue = "42788")]
893 pub unsafe fn nop() -> Initializer {
897 /// Indicates if a buffer should be initialized.
898 #[unstable(feature = "read_initializer", issue = "42788")]
900 pub fn should_initialize(&self) -> bool {
904 /// Initializes a buffer if necessary.
905 #[unstable(feature = "read_initializer", issue = "42788")]
907 pub fn initialize(&self, buf: &mut [u8]) {
908 if self.should_initialize() {
909 unsafe { ptr::write_bytes(buf.as_mut_ptr(), 0, buf.len()) }
914 /// A trait for objects which are byte-oriented sinks.
916 /// Implementors of the `Write` trait are sometimes called 'writers'.
918 /// Writers are defined by two required methods, [`write`] and [`flush`]:
920 /// * The [`write`] method will attempt to write some data into the object,
921 /// returning how many bytes were successfully written.
923 /// * The [`flush`] method is useful for adaptors and explicit buffers
924 /// themselves for ensuring that all buffered data has been pushed out to the
927 /// Writers are intended to be composable with one another. Many implementors
928 /// throughout [`std::io`] take and provide types which implement the `Write`
931 /// [`write`]: #tymethod.write
932 /// [`flush`]: #tymethod.flush
933 /// [`std::io`]: index.html
938 /// use std::io::prelude::*;
939 /// use std::fs::File;
941 /// fn main() -> std::io::Result<()> {
942 /// let mut buffer = File::create("foo.txt")?;
944 /// buffer.write(b"some bytes")?;
948 #[stable(feature = "rust1", since = "1.0.0")]
951 /// Write a buffer into this writer, returning how many bytes were written.
953 /// This function will attempt to write the entire contents of `buf`, but
954 /// the entire write may not succeed, or the write may also generate an
955 /// error. A call to `write` represents *at most one* attempt to write to
956 /// any wrapped object.
958 /// Calls to `write` are not guaranteed to block waiting for data to be
959 /// written, and a write which would otherwise block can be indicated through
960 /// an [`Err`] variant.
962 /// If the return value is [`Ok(n)`] then it must be guaranteed that
963 /// `0 <= n <= buf.len()`. A return value of `0` typically means that the
964 /// underlying object is no longer able to accept bytes and will likely not
965 /// be able to in the future as well, or that the buffer provided is empty.
969 /// Each call to `write` may generate an I/O error indicating that the
970 /// operation could not be completed. If an error is returned then no bytes
971 /// in the buffer were written to this writer.
973 /// It is **not** considered an error if the entire buffer could not be
974 /// written to this writer.
976 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the
977 /// write operation should be retried if there is nothing else to do.
979 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
980 /// [`Ok(n)`]: ../../std/result/enum.Result.html#variant.Ok
981 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
986 /// use std::io::prelude::*;
987 /// use std::fs::File;
989 /// fn main() -> std::io::Result<()> {
990 /// let mut buffer = File::create("foo.txt")?;
992 /// // Writes some prefix of the byte string, not necessarily all of it.
993 /// buffer.write(b"some bytes")?;
997 #[stable(feature = "rust1", since = "1.0.0")]
998 fn write(&mut self, buf: &[u8]) -> Result<usize>;
1000 /// Flush this output stream, ensuring that all intermediately buffered
1001 /// contents reach their destination.
1005 /// It is considered an error if not all bytes could be written due to
1006 /// I/O errors or EOF being reached.
1011 /// use std::io::prelude::*;
1012 /// use std::io::BufWriter;
1013 /// use std::fs::File;
1015 /// fn main() -> std::io::Result<()> {
1016 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
1018 /// buffer.write(b"some bytes")?;
1019 /// buffer.flush()?;
1023 #[stable(feature = "rust1", since = "1.0.0")]
1024 fn flush(&mut self) -> Result<()>;
1026 /// Attempts to write an entire buffer into this writer.
1028 /// This method will continuously call [`write`] until there is no more data
1029 /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is
1030 /// returned. This method will not return until the entire buffer has been
1031 /// successfully written or such an error occurs. The first error that is
1032 /// not of [`ErrorKind::Interrupted`] kind generated from this method will be
1037 /// This function will return the first error of
1038 /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns.
1040 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
1041 /// [`write`]: #tymethod.write
1046 /// use std::io::prelude::*;
1047 /// use std::fs::File;
1049 /// fn main() -> std::io::Result<()> {
1050 /// let mut buffer = File::create("foo.txt")?;
1052 /// buffer.write_all(b"some bytes")?;
1056 #[stable(feature = "rust1", since = "1.0.0")]
1057 fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
1058 while !buf.is_empty() {
1059 match self.write(buf) {
1060 Ok(0) => return Err(Error::new(ErrorKind::WriteZero,
1061 "failed to write whole buffer")),
1062 Ok(n) => buf = &buf[n..],
1063 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1064 Err(e) => return Err(e),
1070 /// Writes a formatted string into this writer, returning any error
1073 /// This method is primarily used to interface with the
1074 /// [`format_args!`][formatargs] macro, but it is rare that this should
1075 /// explicitly be called. The [`write!`][write] macro should be favored to
1076 /// invoke this method instead.
1078 /// [formatargs]: ../macro.format_args.html
1079 /// [write]: ../macro.write.html
1081 /// This function internally uses the [`write_all`][writeall] method on
1082 /// this trait and hence will continuously write data so long as no errors
1083 /// are received. This also means that partial writes are not indicated in
1086 /// [writeall]: #method.write_all
1090 /// This function will return any I/O error reported while formatting.
1095 /// use std::io::prelude::*;
1096 /// use std::fs::File;
1098 /// fn main() -> std::io::Result<()> {
1099 /// let mut buffer = File::create("foo.txt")?;
1102 /// write!(buffer, "{:.*}", 2, 1.234567)?;
1103 /// // turns into this:
1104 /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1108 #[stable(feature = "rust1", since = "1.0.0")]
1109 fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()> {
1110 // Create a shim which translates a Write to a fmt::Write and saves
1111 // off I/O errors. instead of discarding them
1112 struct Adaptor<'a, T: ?Sized + 'a> {
1117 impl<'a, T: Write + ?Sized> fmt::Write for Adaptor<'a, T> {
1118 fn write_str(&mut self, s: &str) -> fmt::Result {
1119 match self.inner.write_all(s.as_bytes()) {
1122 self.error = Err(e);
1129 let mut output = Adaptor { inner: self, error: Ok(()) };
1130 match fmt::write(&mut output, fmt) {
1133 // check if the error came from the underlying `Write` or not
1134 if output.error.is_err() {
1137 Err(Error::new(ErrorKind::Other, "formatter error"))
1143 /// Creates a "by reference" adaptor for this instance of `Write`.
1145 /// The returned adaptor also implements `Write` and will simply borrow this
1151 /// use std::io::Write;
1152 /// use std::fs::File;
1154 /// fn main() -> std::io::Result<()> {
1155 /// let mut buffer = File::create("foo.txt")?;
1157 /// let reference = buffer.by_ref();
1159 /// // we can use reference just like our original buffer
1160 /// reference.write_all(b"some bytes")?;
1164 #[stable(feature = "rust1", since = "1.0.0")]
1165 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1168 /// The `Seek` trait provides a cursor which can be moved within a stream of
1171 /// The stream typically has a fixed size, allowing seeking relative to either
1172 /// end or the current offset.
1176 /// [`File`][file]s implement `Seek`:
1178 /// [file]: ../fs/struct.File.html
1182 /// use std::io::prelude::*;
1183 /// use std::fs::File;
1184 /// use std::io::SeekFrom;
1186 /// fn main() -> io::Result<()> {
1187 /// let mut f = File::open("foo.txt")?;
1189 /// // move the cursor 42 bytes from the start of the file
1190 /// f.seek(SeekFrom::Start(42))?;
1194 #[stable(feature = "rust1", since = "1.0.0")]
1196 /// Seek to an offset, in bytes, in a stream.
1198 /// A seek beyond the end of a stream is allowed, but behavior is defined
1199 /// by the implementation.
1201 /// If the seek operation completed successfully,
1202 /// this method returns the new position from the start of the stream.
1203 /// That position can be used later with [`SeekFrom::Start`].
1207 /// Seeking to a negative offset is considered an error.
1209 /// [`SeekFrom::Start`]: enum.SeekFrom.html#variant.Start
1210 #[stable(feature = "rust1", since = "1.0.0")]
1211 fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1214 /// Enumeration of possible methods to seek within an I/O object.
1216 /// It is used by the [`Seek`] trait.
1218 /// [`Seek`]: trait.Seek.html
1219 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1220 #[stable(feature = "rust1", since = "1.0.0")]
1222 /// Set the offset to the provided number of bytes.
1223 #[stable(feature = "rust1", since = "1.0.0")]
1224 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1226 /// Set the offset to the size of this object plus the specified number of
1229 /// It is possible to seek beyond the end of an object, but it's an error to
1230 /// seek before byte 0.
1231 #[stable(feature = "rust1", since = "1.0.0")]
1232 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1234 /// Set the offset to the current position plus the specified number of
1237 /// It is possible to seek beyond the end of an object, but it's an error to
1238 /// seek before byte 0.
1239 #[stable(feature = "rust1", since = "1.0.0")]
1240 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1243 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>)
1247 let (done, used) = {
1248 let available = match r.fill_buf() {
1250 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1251 Err(e) => return Err(e)
1253 match memchr::memchr(delim, available) {
1255 buf.extend_from_slice(&available[..=i]);
1259 buf.extend_from_slice(available);
1260 (false, available.len())
1266 if done || used == 0 {
1272 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1273 /// to perform extra ways of reading.
1275 /// For example, reading line-by-line is inefficient without using a buffer, so
1276 /// if you want to read by line, you'll need `BufRead`, which includes a
1277 /// [`read_line`] method as well as a [`lines`] iterator.
1281 /// A locked standard input implements `BufRead`:
1285 /// use std::io::prelude::*;
1287 /// let stdin = io::stdin();
1288 /// for line in stdin.lock().lines() {
1289 /// println!("{}", line.unwrap());
1293 /// If you have something that implements [`Read`], you can use the [`BufReader`
1294 /// type][`BufReader`] to turn it into a `BufRead`.
1296 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1297 /// [`BufReader`] to the rescue!
1299 /// [`BufReader`]: struct.BufReader.html
1300 /// [`File`]: ../fs/struct.File.html
1301 /// [`read_line`]: #method.read_line
1302 /// [`lines`]: #method.lines
1303 /// [`Read`]: trait.Read.html
1306 /// use std::io::{self, BufReader};
1307 /// use std::io::prelude::*;
1308 /// use std::fs::File;
1310 /// fn main() -> io::Result<()> {
1311 /// let f = File::open("foo.txt")?;
1312 /// let f = BufReader::new(f);
1314 /// for line in f.lines() {
1315 /// println!("{}", line.unwrap());
1322 #[stable(feature = "rust1", since = "1.0.0")]
1323 pub trait BufRead: Read {
1324 /// Returns the contents of the internal buffer, filling it with more data
1325 /// from the inner reader if it is empty.
1327 /// This function is a lower-level call. It needs to be paired with the
1328 /// [`consume`] method to function properly. When calling this
1329 /// method, none of the contents will be "read" in the sense that later
1330 /// calling `read` may return the same contents. As such, [`consume`] must
1331 /// be called with the number of bytes that are consumed from this buffer to
1332 /// ensure that the bytes are never returned twice.
1334 /// [`consume`]: #tymethod.consume
1336 /// An empty buffer returned indicates that the stream has reached EOF.
1340 /// This function will return an I/O error if the underlying reader was
1341 /// read, but returned an error.
1345 /// A locked standard input implements `BufRead`:
1349 /// use std::io::prelude::*;
1351 /// let stdin = io::stdin();
1352 /// let mut stdin = stdin.lock();
1354 /// // we can't have two `&mut` references to `stdin`, so use a block
1355 /// // to end the borrow early.
1357 /// let buffer = stdin.fill_buf().unwrap();
1359 /// // work with buffer
1360 /// println!("{:?}", buffer);
1365 /// // ensure the bytes we worked with aren't returned again later
1366 /// stdin.consume(length);
1368 #[stable(feature = "rust1", since = "1.0.0")]
1369 fn fill_buf(&mut self) -> Result<&[u8]>;
1371 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1372 /// so they should no longer be returned in calls to `read`.
1374 /// This function is a lower-level call. It needs to be paired with the
1375 /// [`fill_buf`] method to function properly. This function does
1376 /// not perform any I/O, it simply informs this object that some amount of
1377 /// its buffer, returned from [`fill_buf`], has been consumed and should
1378 /// no longer be returned. As such, this function may do odd things if
1379 /// [`fill_buf`] isn't called before calling it.
1381 /// The `amt` must be `<=` the number of bytes in the buffer returned by
1386 /// Since `consume()` is meant to be used with [`fill_buf`],
1387 /// that method's example includes an example of `consume()`.
1389 /// [`fill_buf`]: #tymethod.fill_buf
1390 #[stable(feature = "rust1", since = "1.0.0")]
1391 fn consume(&mut self, amt: usize);
1393 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
1395 /// This function will read bytes from the underlying stream until the
1396 /// delimiter or EOF is found. Once found, all bytes up to, and including,
1397 /// the delimiter (if found) will be appended to `buf`.
1399 /// If successful, this function will return the total number of bytes read.
1403 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1404 /// will otherwise return any errors returned by [`fill_buf`].
1406 /// If an I/O error is encountered then all bytes read so far will be
1407 /// present in `buf` and its length will have been adjusted appropriately.
1409 /// [`fill_buf`]: #tymethod.fill_buf
1410 /// [`ErrorKind::Interrupted`]: enum.ErrorKind.html#variant.Interrupted
1414 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1415 /// this example, we use [`Cursor`] to read all the bytes in a byte slice
1416 /// in hyphen delimited segments:
1418 /// [`Cursor`]: struct.Cursor.html
1421 /// use std::io::{self, BufRead};
1423 /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
1424 /// let mut buf = vec![];
1426 /// // cursor is at 'l'
1427 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1428 /// .expect("reading from cursor won't fail");
1429 /// assert_eq!(num_bytes, 6);
1430 /// assert_eq!(buf, b"lorem-");
1433 /// // cursor is at 'i'
1434 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1435 /// .expect("reading from cursor won't fail");
1436 /// assert_eq!(num_bytes, 5);
1437 /// assert_eq!(buf, b"ipsum");
1440 /// // cursor is at EOF
1441 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1442 /// .expect("reading from cursor won't fail");
1443 /// assert_eq!(num_bytes, 0);
1444 /// assert_eq!(buf, b"");
1446 #[stable(feature = "rust1", since = "1.0.0")]
1447 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
1448 read_until(self, byte, buf)
1451 /// Read all bytes until a newline (the 0xA byte) is reached, and append
1452 /// them to the provided buffer.
1454 /// This function will read bytes from the underlying stream until the
1455 /// newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes
1456 /// up to, and including, the delimiter (if found) will be appended to
1459 /// If successful, this function will return the total number of bytes read.
1461 /// An empty buffer returned indicates that the stream has reached EOF.
1465 /// This function has the same error semantics as [`read_until`] and will
1466 /// also return an error if the read bytes are not valid UTF-8. If an I/O
1467 /// error is encountered then `buf` may contain some bytes already read in
1468 /// the event that all data read so far was valid UTF-8.
1470 /// [`read_until`]: #method.read_until
1474 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1475 /// this example, we use [`Cursor`] to read all the lines in a byte slice:
1477 /// [`Cursor`]: struct.Cursor.html
1480 /// use std::io::{self, BufRead};
1482 /// let mut cursor = io::Cursor::new(b"foo\nbar");
1483 /// let mut buf = String::new();
1485 /// // cursor is at 'f'
1486 /// let num_bytes = cursor.read_line(&mut buf)
1487 /// .expect("reading from cursor won't fail");
1488 /// assert_eq!(num_bytes, 4);
1489 /// assert_eq!(buf, "foo\n");
1492 /// // cursor is at 'b'
1493 /// let num_bytes = cursor.read_line(&mut buf)
1494 /// .expect("reading from cursor won't fail");
1495 /// assert_eq!(num_bytes, 3);
1496 /// assert_eq!(buf, "bar");
1499 /// // cursor is at EOF
1500 /// let num_bytes = cursor.read_line(&mut buf)
1501 /// .expect("reading from cursor won't fail");
1502 /// assert_eq!(num_bytes, 0);
1503 /// assert_eq!(buf, "");
1505 #[stable(feature = "rust1", since = "1.0.0")]
1506 fn read_line(&mut self, buf: &mut String) -> Result<usize> {
1507 // Note that we are not calling the `.read_until` method here, but
1508 // rather our hardcoded implementation. For more details as to why, see
1509 // the comments in `read_to_end`.
1510 append_to_string(buf, |b| read_until(self, b'\n', b))
1513 /// Returns an iterator over the contents of this reader split on the byte
1516 /// The iterator returned from this function will return instances of
1517 /// [`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
1518 /// the delimiter byte at the end.
1520 /// This function will yield errors whenever [`read_until`] would have
1521 /// also yielded an error.
1523 /// [`io::Result`]: type.Result.html
1524 /// [`Vec<u8>`]: ../vec/struct.Vec.html
1525 /// [`read_until`]: #method.read_until
1529 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1530 /// this example, we use [`Cursor`] to iterate over all hyphen delimited
1531 /// segments in a byte slice
1533 /// [`Cursor`]: struct.Cursor.html
1536 /// use std::io::{self, BufRead};
1538 /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
1540 /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
1541 /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
1542 /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
1543 /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
1544 /// assert_eq!(split_iter.next(), None);
1546 #[stable(feature = "rust1", since = "1.0.0")]
1547 fn split(self, byte: u8) -> Split<Self> where Self: Sized {
1548 Split { buf: self, delim: byte }
1551 /// Returns an iterator over the lines of this reader.
1553 /// The iterator returned from this function will yield instances of
1554 /// [`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline
1555 /// byte (the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.
1557 /// [`io::Result`]: type.Result.html
1558 /// [`String`]: ../string/struct.String.html
1562 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1563 /// this example, we use [`Cursor`] to iterate over all the lines in a byte
1566 /// [`Cursor`]: struct.Cursor.html
1569 /// use std::io::{self, BufRead};
1571 /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
1573 /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
1574 /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
1575 /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
1576 /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
1577 /// assert_eq!(lines_iter.next(), None);
1582 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
1584 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
1585 #[stable(feature = "rust1", since = "1.0.0")]
1586 fn lines(self) -> Lines<Self> where Self: Sized {
1591 /// Adaptor to chain together two readers.
1593 /// This struct is generally created by calling [`chain`] on a reader.
1594 /// Please see the documentation of [`chain`] for more details.
1596 /// [`chain`]: trait.Read.html#method.chain
1597 #[stable(feature = "rust1", since = "1.0.0")]
1598 pub struct Chain<T, U> {
1604 impl<T, U> Chain<T, U> {
1605 /// Consumes the `Chain`, returning the wrapped readers.
1611 /// use std::io::prelude::*;
1612 /// use std::fs::File;
1614 /// fn main() -> io::Result<()> {
1615 /// let mut foo_file = File::open("foo.txt")?;
1616 /// let mut bar_file = File::open("bar.txt")?;
1618 /// let chain = foo_file.chain(bar_file);
1619 /// let (foo_file, bar_file) = chain.into_inner();
1623 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1624 pub fn into_inner(self) -> (T, U) {
1625 (self.first, self.second)
1628 /// Gets references to the underlying readers in this `Chain`.
1634 /// use std::io::prelude::*;
1635 /// use std::fs::File;
1637 /// fn main() -> io::Result<()> {
1638 /// let mut foo_file = File::open("foo.txt")?;
1639 /// let mut bar_file = File::open("bar.txt")?;
1641 /// let chain = foo_file.chain(bar_file);
1642 /// let (foo_file, bar_file) = chain.get_ref();
1646 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1647 pub fn get_ref(&self) -> (&T, &U) {
1648 (&self.first, &self.second)
1651 /// Gets mutable references to the underlying readers in this `Chain`.
1653 /// Care should be taken to avoid modifying the internal I/O state of the
1654 /// underlying readers as doing so may corrupt the internal state of this
1661 /// use std::io::prelude::*;
1662 /// use std::fs::File;
1664 /// fn main() -> io::Result<()> {
1665 /// let mut foo_file = File::open("foo.txt")?;
1666 /// let mut bar_file = File::open("bar.txt")?;
1668 /// let mut chain = foo_file.chain(bar_file);
1669 /// let (foo_file, bar_file) = chain.get_mut();
1673 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1674 pub fn get_mut(&mut self) -> (&mut T, &mut U) {
1675 (&mut self.first, &mut self.second)
1679 #[stable(feature = "std_debug", since = "1.16.0")]
1680 impl<T: fmt::Debug, U: fmt::Debug> fmt::Debug for Chain<T, U> {
1681 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1682 f.debug_struct("Chain")
1683 .field("t", &self.first)
1684 .field("u", &self.second)
1689 #[stable(feature = "rust1", since = "1.0.0")]
1690 impl<T: Read, U: Read> Read for Chain<T, U> {
1691 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1692 if !self.done_first {
1693 match self.first.read(buf)? {
1694 0 if buf.len() != 0 => { self.done_first = true; }
1698 self.second.read(buf)
1701 unsafe fn initializer(&self) -> Initializer {
1702 let initializer = self.first.initializer();
1703 if initializer.should_initialize() {
1706 self.second.initializer()
1711 #[stable(feature = "chain_bufread", since = "1.9.0")]
1712 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
1713 fn fill_buf(&mut self) -> Result<&[u8]> {
1714 if !self.done_first {
1715 match self.first.fill_buf()? {
1716 buf if buf.len() == 0 => { self.done_first = true; }
1717 buf => return Ok(buf),
1720 self.second.fill_buf()
1723 fn consume(&mut self, amt: usize) {
1724 if !self.done_first {
1725 self.first.consume(amt)
1727 self.second.consume(amt)
1732 /// Reader adaptor which limits the bytes read from an underlying reader.
1734 /// This struct is generally created by calling [`take`] on a reader.
1735 /// Please see the documentation of [`take`] for more details.
1737 /// [`take`]: trait.Read.html#method.take
1738 #[stable(feature = "rust1", since = "1.0.0")]
1740 pub struct Take<T> {
1746 /// Returns the number of bytes that can be read before this instance will
1751 /// This instance may reach `EOF` after reading fewer bytes than indicated by
1752 /// this method if the underlying [`Read`] instance reaches EOF.
1754 /// [`Read`]: ../../std/io/trait.Read.html
1760 /// use std::io::prelude::*;
1761 /// use std::fs::File;
1763 /// fn main() -> io::Result<()> {
1764 /// let f = File::open("foo.txt")?;
1766 /// // read at most five bytes
1767 /// let handle = f.take(5);
1769 /// println!("limit: {}", handle.limit());
1773 #[stable(feature = "rust1", since = "1.0.0")]
1774 pub fn limit(&self) -> u64 { self.limit }
1776 /// Sets the number of bytes that can be read before this instance will
1777 /// return EOF. This is the same as constructing a new `Take` instance, so
1778 /// the amount of bytes read and the previous limit value don't matter when
1779 /// calling this method.
1785 /// use std::io::prelude::*;
1786 /// use std::fs::File;
1788 /// fn main() -> io::Result<()> {
1789 /// let f = File::open("foo.txt")?;
1791 /// // read at most five bytes
1792 /// let mut handle = f.take(5);
1793 /// handle.set_limit(10);
1795 /// assert_eq!(handle.limit(), 10);
1799 #[stable(feature = "take_set_limit", since = "1.27.0")]
1800 pub fn set_limit(&mut self, limit: u64) {
1804 /// Consumes the `Take`, returning the wrapped reader.
1810 /// use std::io::prelude::*;
1811 /// use std::fs::File;
1813 /// fn main() -> io::Result<()> {
1814 /// let mut file = File::open("foo.txt")?;
1816 /// let mut buffer = [0; 5];
1817 /// let mut handle = file.take(5);
1818 /// handle.read(&mut buffer)?;
1820 /// let file = handle.into_inner();
1824 #[stable(feature = "io_take_into_inner", since = "1.15.0")]
1825 pub fn into_inner(self) -> T {
1829 /// Gets a reference to the underlying reader.
1835 /// use std::io::prelude::*;
1836 /// use std::fs::File;
1838 /// fn main() -> io::Result<()> {
1839 /// let mut file = File::open("foo.txt")?;
1841 /// let mut buffer = [0; 5];
1842 /// let mut handle = file.take(5);
1843 /// handle.read(&mut buffer)?;
1845 /// let file = handle.get_ref();
1849 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1850 pub fn get_ref(&self) -> &T {
1854 /// Gets a mutable reference to the underlying reader.
1856 /// Care should be taken to avoid modifying the internal I/O state of the
1857 /// underlying reader as doing so may corrupt the internal limit of this
1864 /// use std::io::prelude::*;
1865 /// use std::fs::File;
1867 /// fn main() -> io::Result<()> {
1868 /// let mut file = File::open("foo.txt")?;
1870 /// let mut buffer = [0; 5];
1871 /// let mut handle = file.take(5);
1872 /// handle.read(&mut buffer)?;
1874 /// let file = handle.get_mut();
1878 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1879 pub fn get_mut(&mut self) -> &mut T {
1884 #[stable(feature = "rust1", since = "1.0.0")]
1885 impl<T: Read> Read for Take<T> {
1886 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1887 // Don't call into inner reader at all at EOF because it may still block
1888 if self.limit == 0 {
1892 let max = cmp::min(buf.len() as u64, self.limit) as usize;
1893 let n = self.inner.read(&mut buf[..max])?;
1894 self.limit -= n as u64;
1898 unsafe fn initializer(&self) -> Initializer {
1899 self.inner.initializer()
1902 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
1903 let reservation_size = cmp::min(self.limit, 32) as usize;
1905 read_to_end_with_reservation(self, buf, reservation_size)
1909 #[stable(feature = "rust1", since = "1.0.0")]
1910 impl<T: BufRead> BufRead for Take<T> {
1911 fn fill_buf(&mut self) -> Result<&[u8]> {
1912 // Don't call into inner reader at all at EOF because it may still block
1913 if self.limit == 0 {
1917 let buf = self.inner.fill_buf()?;
1918 let cap = cmp::min(buf.len() as u64, self.limit) as usize;
1922 fn consume(&mut self, amt: usize) {
1923 // Don't let callers reset the limit by passing an overlarge value
1924 let amt = cmp::min(amt as u64, self.limit) as usize;
1925 self.limit -= amt as u64;
1926 self.inner.consume(amt);
1930 /// An iterator over `u8` values of a reader.
1932 /// This struct is generally created by calling [`bytes`] on a reader.
1933 /// Please see the documentation of [`bytes`] for more details.
1935 /// [`bytes`]: trait.Read.html#method.bytes
1936 #[stable(feature = "rust1", since = "1.0.0")]
1938 pub struct Bytes<R> {
1942 #[stable(feature = "rust1", since = "1.0.0")]
1943 impl<R: Read> Iterator for Bytes<R> {
1944 type Item = Result<u8>;
1946 fn next(&mut self) -> Option<Result<u8>> {
1949 return match self.inner.read(slice::from_mut(&mut byte)) {
1951 Ok(..) => Some(Ok(byte)),
1952 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1953 Err(e) => Some(Err(e)),
1959 /// An iterator over the contents of an instance of `BufRead` split on a
1960 /// particular byte.
1962 /// This struct is generally created by calling [`split`][split] on a
1963 /// `BufRead`. Please see the documentation of `split()` for more details.
1965 /// [split]: trait.BufRead.html#method.split
1966 #[stable(feature = "rust1", since = "1.0.0")]
1968 pub struct Split<B> {
1973 #[stable(feature = "rust1", since = "1.0.0")]
1974 impl<B: BufRead> Iterator for Split<B> {
1975 type Item = Result<Vec<u8>>;
1977 fn next(&mut self) -> Option<Result<Vec<u8>>> {
1978 let mut buf = Vec::new();
1979 match self.buf.read_until(self.delim, &mut buf) {
1982 if buf[buf.len() - 1] == self.delim {
1987 Err(e) => Some(Err(e))
1992 /// An iterator over the lines of an instance of `BufRead`.
1994 /// This struct is generally created by calling [`lines`][lines] on a
1995 /// `BufRead`. Please see the documentation of `lines()` for more details.
1997 /// [lines]: trait.BufRead.html#method.lines
1998 #[stable(feature = "rust1", since = "1.0.0")]
2000 pub struct Lines<B> {
2004 #[stable(feature = "rust1", since = "1.0.0")]
2005 impl<B: BufRead> Iterator for Lines<B> {
2006 type Item = Result<String>;
2008 fn next(&mut self) -> Option<Result<String>> {
2009 let mut buf = String::new();
2010 match self.buf.read_line(&mut buf) {
2013 if buf.ends_with("\n") {
2015 if buf.ends_with("\r") {
2021 Err(e) => Some(Err(e))
2035 #[cfg_attr(target_os = "emscripten", ignore)]
2037 let mut buf = Cursor::new(&b"12"[..]);
2038 let mut v = Vec::new();
2039 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 2);
2040 assert_eq!(v, b"12");
2042 let mut buf = Cursor::new(&b"1233"[..]);
2043 let mut v = Vec::new();
2044 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 3);
2045 assert_eq!(v, b"123");
2047 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 1);
2048 assert_eq!(v, b"3");
2050 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 0);
2056 let buf = Cursor::new(&b"12"[..]);
2057 let mut s = buf.split(b'3');
2058 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2059 assert!(s.next().is_none());
2061 let buf = Cursor::new(&b"1233"[..]);
2062 let mut s = buf.split(b'3');
2063 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2064 assert_eq!(s.next().unwrap().unwrap(), vec![]);
2065 assert!(s.next().is_none());
2070 let mut buf = Cursor::new(&b"12"[..]);
2071 let mut v = String::new();
2072 assert_eq!(buf.read_line(&mut v).unwrap(), 2);
2073 assert_eq!(v, "12");
2075 let mut buf = Cursor::new(&b"12\n\n"[..]);
2076 let mut v = String::new();
2077 assert_eq!(buf.read_line(&mut v).unwrap(), 3);
2078 assert_eq!(v, "12\n");
2080 assert_eq!(buf.read_line(&mut v).unwrap(), 1);
2081 assert_eq!(v, "\n");
2083 assert_eq!(buf.read_line(&mut v).unwrap(), 0);
2089 let buf = Cursor::new(&b"12\r"[..]);
2090 let mut s = buf.lines();
2091 assert_eq!(s.next().unwrap().unwrap(), "12\r".to_string());
2092 assert!(s.next().is_none());
2094 let buf = Cursor::new(&b"12\r\n\n"[..]);
2095 let mut s = buf.lines();
2096 assert_eq!(s.next().unwrap().unwrap(), "12".to_string());
2097 assert_eq!(s.next().unwrap().unwrap(), "".to_string());
2098 assert!(s.next().is_none());
2103 let mut c = Cursor::new(&b""[..]);
2104 let mut v = Vec::new();
2105 assert_eq!(c.read_to_end(&mut v).unwrap(), 0);
2108 let mut c = Cursor::new(&b"1"[..]);
2109 let mut v = Vec::new();
2110 assert_eq!(c.read_to_end(&mut v).unwrap(), 1);
2111 assert_eq!(v, b"1");
2113 let cap = 1024 * 1024;
2114 let data = (0..cap).map(|i| (i / 3) as u8).collect::<Vec<_>>();
2115 let mut v = Vec::new();
2116 let (a, b) = data.split_at(data.len() / 2);
2117 assert_eq!(Cursor::new(a).read_to_end(&mut v).unwrap(), a.len());
2118 assert_eq!(Cursor::new(b).read_to_end(&mut v).unwrap(), b.len());
2119 assert_eq!(v, data);
2123 fn read_to_string() {
2124 let mut c = Cursor::new(&b""[..]);
2125 let mut v = String::new();
2126 assert_eq!(c.read_to_string(&mut v).unwrap(), 0);
2129 let mut c = Cursor::new(&b"1"[..]);
2130 let mut v = String::new();
2131 assert_eq!(c.read_to_string(&mut v).unwrap(), 1);
2134 let mut c = Cursor::new(&b"\xff"[..]);
2135 let mut v = String::new();
2136 assert!(c.read_to_string(&mut v).is_err());
2141 let mut buf = [0; 4];
2143 let mut c = Cursor::new(&b""[..]);
2144 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2145 io::ErrorKind::UnexpectedEof);
2147 let mut c = Cursor::new(&b"123"[..]).chain(Cursor::new(&b"456789"[..]));
2148 c.read_exact(&mut buf).unwrap();
2149 assert_eq!(&buf, b"1234");
2150 c.read_exact(&mut buf).unwrap();
2151 assert_eq!(&buf, b"5678");
2152 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2153 io::ErrorKind::UnexpectedEof);
2157 fn read_exact_slice() {
2158 let mut buf = [0; 4];
2160 let mut c = &b""[..];
2161 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2162 io::ErrorKind::UnexpectedEof);
2164 let mut c = &b"123"[..];
2165 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2166 io::ErrorKind::UnexpectedEof);
2167 // make sure the optimized (early returning) method is being used
2168 assert_eq!(&buf, &[0; 4]);
2170 let mut c = &b"1234"[..];
2171 c.read_exact(&mut buf).unwrap();
2172 assert_eq!(&buf, b"1234");
2174 let mut c = &b"56789"[..];
2175 c.read_exact(&mut buf).unwrap();
2176 assert_eq!(&buf, b"5678");
2177 assert_eq!(c, b"9");
2185 fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
2186 Err(io::Error::new(io::ErrorKind::Other, ""))
2189 impl BufRead for R {
2190 fn fill_buf(&mut self) -> io::Result<&[u8]> {
2191 Err(io::Error::new(io::ErrorKind::Other, ""))
2193 fn consume(&mut self, _amt: usize) { }
2196 let mut buf = [0; 1];
2197 assert_eq!(0, R.take(0).read(&mut buf).unwrap());
2198 assert_eq!(b"", R.take(0).fill_buf().unwrap());
2201 fn cmp_bufread<Br1: BufRead, Br2: BufRead>(mut br1: Br1, mut br2: Br2, exp: &[u8]) {
2202 let mut cat = Vec::new();
2205 let buf1 = br1.fill_buf().unwrap();
2206 let buf2 = br2.fill_buf().unwrap();
2207 let minlen = if buf1.len() < buf2.len() { buf1.len() } else { buf2.len() };
2208 assert_eq!(buf1[..minlen], buf2[..minlen]);
2209 cat.extend_from_slice(&buf1[..minlen]);
2215 br1.consume(consume);
2216 br2.consume(consume);
2218 assert_eq!(br1.fill_buf().unwrap().len(), 0);
2219 assert_eq!(br2.fill_buf().unwrap().len(), 0);
2220 assert_eq!(&cat[..], &exp[..])
2224 fn chain_bufread() {
2225 let testdata = b"ABCDEFGHIJKL";
2226 let chain1 = (&testdata[..3]).chain(&testdata[3..6])
2227 .chain(&testdata[6..9])
2228 .chain(&testdata[9..]);
2229 let chain2 = (&testdata[..4]).chain(&testdata[4..8])
2230 .chain(&testdata[8..]);
2231 cmp_bufread(chain1, chain2, &testdata[..]);
2235 fn chain_zero_length_read_is_not_eof() {
2238 let mut s = String::new();
2239 let mut chain = (&a[..]).chain(&b[..]);
2240 chain.read(&mut []).unwrap();
2241 chain.read_to_string(&mut s).unwrap();
2242 assert_eq!("AB", s);
2246 #[cfg_attr(target_os = "emscripten", ignore)]
2247 fn bench_read_to_end(b: &mut test::Bencher) {
2249 let mut lr = repeat(1).take(10000000);
2250 let mut vec = Vec::with_capacity(1024);
2251 super::read_to_end(&mut lr, &mut vec)