1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Traits, helpers, and type definitions for core I/O functionality.
13 //! The `std::io` module contains a number of common things you'll need
14 //! when doing input and output. The most core part of this module is
15 //! the [`Read`] and [`Write`] traits, which provide the
16 //! most general interface for reading and writing input and output.
20 //! Because they are traits, [`Read`] and [`Write`] are implemented by a number
21 //! of other types, and you can implement them for your types too. As such,
22 //! you'll see a few different types of I/O throughout the documentation in
23 //! this module: [`File`]s, [`TcpStream`]s, and sometimes even [`Vec<T>`]s. For
24 //! example, [`Read`] adds a [`read`][`Read::read`] method, which we can use on
29 //! use std::io::prelude::*;
30 //! use std::fs::File;
32 //! fn main() -> io::Result<()> {
33 //! let mut f = File::open("foo.txt")?;
34 //! let mut buffer = [0; 10];
36 //! // read up to 10 bytes
37 //! f.read(&mut buffer)?;
39 //! println!("The bytes: {:?}", buffer);
44 //! [`Read`] and [`Write`] are so important, implementors of the two traits have a
45 //! nickname: readers and writers. So you'll sometimes see 'a reader' instead
46 //! of 'a type that implements the [`Read`] trait'. Much easier!
48 //! ## Seek and BufRead
50 //! Beyond that, there are two important traits that are provided: [`Seek`]
51 //! and [`BufRead`]. Both of these build on top of a reader to control
52 //! how the reading happens. [`Seek`] lets you control where the next byte is
57 //! use std::io::prelude::*;
58 //! use std::io::SeekFrom;
59 //! use std::fs::File;
61 //! fn main() -> io::Result<()> {
62 //! let mut f = File::open("foo.txt")?;
63 //! let mut buffer = [0; 10];
65 //! // skip to the last 10 bytes of the file
66 //! f.seek(SeekFrom::End(-10))?;
68 //! // read up to 10 bytes
69 //! f.read(&mut buffer)?;
71 //! println!("The bytes: {:?}", buffer);
76 //! [`BufRead`] uses an internal buffer to provide a number of other ways to read, but
77 //! to show it off, we'll need to talk about buffers in general. Keep reading!
79 //! ## BufReader and BufWriter
81 //! Byte-based interfaces are unwieldy and can be inefficient, as we'd need to be
82 //! making near-constant calls to the operating system. To help with this,
83 //! `std::io` comes with two structs, [`BufReader`] and [`BufWriter`], which wrap
84 //! readers and writers. The wrapper uses a buffer, reducing the number of
85 //! calls and providing nicer methods for accessing exactly what you want.
87 //! For example, [`BufReader`] works with the [`BufRead`] trait to add extra
88 //! methods to any reader:
92 //! use std::io::prelude::*;
93 //! use std::io::BufReader;
94 //! use std::fs::File;
96 //! fn main() -> io::Result<()> {
97 //! let f = File::open("foo.txt")?;
98 //! let mut reader = BufReader::new(f);
99 //! let mut buffer = String::new();
101 //! // read a line into buffer
102 //! reader.read_line(&mut buffer)?;
104 //! println!("{}", buffer);
109 //! [`BufWriter`] doesn't add any new ways of writing; it just buffers every call
110 //! to [`write`][`Write::write`]:
114 //! use std::io::prelude::*;
115 //! use std::io::BufWriter;
116 //! use std::fs::File;
118 //! fn main() -> io::Result<()> {
119 //! let f = File::create("foo.txt")?;
121 //! let mut writer = BufWriter::new(f);
123 //! // write a byte to the buffer
124 //! writer.write(&[42])?;
126 //! } // the buffer is flushed once writer goes out of scope
132 //! ## Standard input and output
134 //! A very common source of input is standard input:
139 //! fn main() -> io::Result<()> {
140 //! let mut input = String::new();
142 //! io::stdin().read_line(&mut input)?;
144 //! println!("You typed: {}", input.trim());
149 //! Note that you cannot use the [`?` operator] in functions that do not return
150 //! a [`Result<T, E>`][`Result`]. Instead, you can call [`.unwrap()`]
151 //! or `match` on the return value to catch any possible errors:
156 //! let mut input = String::new();
158 //! io::stdin().read_line(&mut input).unwrap();
161 //! And a very common source of output is standard output:
165 //! use std::io::prelude::*;
167 //! fn main() -> io::Result<()> {
168 //! io::stdout().write(&[42])?;
173 //! Of course, using [`io::stdout`] directly is less common than something like
176 //! ## Iterator types
178 //! A large number of the structures provided by `std::io` are for various
179 //! ways of iterating over I/O. For example, [`Lines`] is used to split over
184 //! use std::io::prelude::*;
185 //! use std::io::BufReader;
186 //! use std::fs::File;
188 //! fn main() -> io::Result<()> {
189 //! let f = File::open("foo.txt")?;
190 //! let reader = BufReader::new(f);
192 //! for line in reader.lines() {
193 //! println!("{}", line?);
201 //! There are a number of [functions][functions-list] that offer access to various
202 //! features. For example, we can use three of these functions to copy everything
203 //! from standard input to standard output:
208 //! fn main() -> io::Result<()> {
209 //! io::copy(&mut io::stdin(), &mut io::stdout())?;
214 //! [functions-list]: #functions-1
218 //! Last, but certainly not least, is [`io::Result`]. This type is used
219 //! as the return type of many `std::io` functions that can cause an error, and
220 //! can be returned from your own functions as well. Many of the examples in this
221 //! module use the [`?` operator]:
226 //! fn read_input() -> io::Result<()> {
227 //! let mut input = String::new();
229 //! io::stdin().read_line(&mut input)?;
231 //! println!("You typed: {}", input.trim());
237 //! The return type of `read_input()`, [`io::Result<()>`][`io::Result`], is a very
238 //! common type for functions which don't have a 'real' return value, but do want to
239 //! return errors if they happen. In this case, the only purpose of this function is
240 //! to read the line and print it, so we use `()`.
242 //! ## Platform-specific behavior
244 //! Many I/O functions throughout the standard library are documented to indicate
245 //! what various library or syscalls they are delegated to. This is done to help
246 //! applications both understand what's happening under the hood as well as investigate
247 //! any possibly unclear semantics. Note, however, that this is informative, not a binding
248 //! contract. The implementation of many of these functions are subject to change over
249 //! time and may call fewer or more syscalls/library functions.
251 //! [`Read`]: trait.Read.html
252 //! [`Write`]: trait.Write.html
253 //! [`Seek`]: trait.Seek.html
254 //! [`BufRead`]: trait.BufRead.html
255 //! [`File`]: ../fs/struct.File.html
256 //! [`TcpStream`]: ../net/struct.TcpStream.html
257 //! [`Vec<T>`]: ../vec/struct.Vec.html
258 //! [`BufReader`]: struct.BufReader.html
259 //! [`BufWriter`]: struct.BufWriter.html
260 //! [`Write::write`]: trait.Write.html#tymethod.write
261 //! [`io::stdout`]: fn.stdout.html
262 //! [`println!`]: ../macro.println.html
263 //! [`Lines`]: struct.Lines.html
264 //! [`io::Result`]: type.Result.html
265 //! [`?` operator]: ../../book/first-edition/syntax-index.html
266 //! [`Read::read`]: trait.Read.html#tymethod.read
267 //! [`Result`]: ../result/enum.Result.html
268 //! [`.unwrap()`]: ../result/enum.Result.html#method.unwrap
270 #![stable(feature = "rust1", since = "1.0.0")]
278 #[stable(feature = "rust1", since = "1.0.0")]
279 pub use self::buffered::{BufReader, BufWriter, LineWriter};
280 #[stable(feature = "rust1", since = "1.0.0")]
281 pub use self::buffered::IntoInnerError;
282 #[stable(feature = "rust1", since = "1.0.0")]
283 pub use self::cursor::Cursor;
284 #[stable(feature = "rust1", since = "1.0.0")]
285 pub use self::error::{Result, Error, ErrorKind};
286 #[stable(feature = "rust1", since = "1.0.0")]
287 pub use self::util::{copy, sink, Sink, empty, Empty, repeat, Repeat};
288 #[stable(feature = "rust1", since = "1.0.0")]
289 pub use self::stdio::{stdin, stdout, stderr, Stdin, Stdout, Stderr};
290 #[stable(feature = "rust1", since = "1.0.0")]
291 pub use self::stdio::{StdoutLock, StderrLock, StdinLock};
292 #[unstable(feature = "print_internals", issue = "0")]
293 pub use self::stdio::{_print, _eprint};
294 #[unstable(feature = "libstd_io_internals", issue = "42788")]
295 #[doc(no_inline, hidden)]
296 pub use self::stdio::{set_panic, set_print};
307 const DEFAULT_BUF_SIZE: usize = ::sys_common::io::DEFAULT_BUF_SIZE;
309 struct Guard<'a> { buf: &'a mut Vec<u8>, len: usize }
311 impl<'a> Drop for Guard<'a> {
313 unsafe { self.buf.set_len(self.len); }
317 // A few methods below (read_to_string, read_line) will append data into a
318 // `String` buffer, but we need to be pretty careful when doing this. The
319 // implementation will just call `.as_mut_vec()` and then delegate to a
320 // byte-oriented reading method, but we must ensure that when returning we never
321 // leave `buf` in a state such that it contains invalid UTF-8 in its bounds.
323 // To this end, we use an RAII guard (to protect against panics) which updates
324 // the length of the string when it is dropped. This guard initially truncates
325 // the string to the prior length and only after we've validated that the
326 // new contents are valid UTF-8 do we allow it to set a longer length.
328 // The unsafety in this function is twofold:
330 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
332 // 2. We're passing a raw buffer to the function `f`, and it is expected that
333 // the function only *appends* bytes to the buffer. We'll get undefined
334 // behavior if existing bytes are overwritten to have non-UTF-8 data.
335 fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
336 where F: FnOnce(&mut Vec<u8>) -> Result<usize>
339 let mut g = Guard { len: buf.len(), buf: buf.as_mut_vec() };
341 if str::from_utf8(&g.buf[g.len..]).is_err() {
343 Err(Error::new(ErrorKind::InvalidData,
344 "stream did not contain valid UTF-8"))
353 // This uses an adaptive system to extend the vector when it fills. We want to
354 // avoid paying to allocate and zero a huge chunk of memory if the reader only
355 // has 4 bytes while still making large reads if the reader does have a ton
356 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
357 // time is 4,500 times (!) slower than a default reservation size of 32 if the
358 // reader has a very small amount of data to return.
360 // Because we're extending the buffer with uninitialized data for trusted
361 // readers, we need to make sure to truncate that if any of this panics.
362 fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
363 read_to_end_with_reservation(r, buf, 32)
366 fn read_to_end_with_reservation<R: Read + ?Sized>(r: &mut R,
368 reservation_size: usize) -> Result<usize>
370 let start_len = buf.len();
371 let mut g = Guard { len: buf.len(), buf: buf };
374 if g.len == g.buf.len() {
376 g.buf.reserve(reservation_size);
377 let capacity = g.buf.capacity();
378 g.buf.set_len(capacity);
379 r.initializer().initialize(&mut g.buf[g.len..]);
383 match r.read(&mut g.buf[g.len..]) {
385 ret = Ok(g.len - start_len);
389 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
400 /// The `Read` trait allows for reading bytes from a source.
402 /// Implementors of the `Read` trait are called 'readers'.
404 /// Readers are defined by one required method, [`read()`]. Each call to [`read()`]
405 /// will attempt to pull bytes from this source into a provided buffer. A
406 /// number of other methods are implemented in terms of [`read()`], giving
407 /// implementors a number of ways to read bytes while only needing to implement
410 /// Readers are intended to be composable with one another. Many implementors
411 /// throughout [`std::io`] take and provide types which implement the `Read`
414 /// Please note that each call to [`read()`] may involve a system call, and
415 /// therefore, using something that implements [`BufRead`], such as
416 /// [`BufReader`], will be more efficient.
420 /// [`File`]s implement `Read`:
424 /// use std::io::prelude::*;
425 /// use std::fs::File;
427 /// fn main() -> io::Result<()> {
428 /// let mut f = File::open("foo.txt")?;
429 /// let mut buffer = [0; 10];
431 /// // read up to 10 bytes
432 /// f.read(&mut buffer)?;
434 /// let mut buffer = vec![0; 10];
435 /// // read the whole file
436 /// f.read_to_end(&mut buffer)?;
438 /// // read into a String, so that you don't need to do the conversion.
439 /// let mut buffer = String::new();
440 /// f.read_to_string(&mut buffer)?;
442 /// // and more! See the other methods for more details.
447 /// Read from [`&str`] because [`&[u8]`][slice] implements `Read`:
451 /// use std::io::prelude::*;
453 /// fn main() -> io::Result<()> {
454 /// let mut b = "This string will be read".as_bytes();
455 /// let mut buffer = [0; 10];
457 /// // read up to 10 bytes
458 /// b.read(&mut buffer)?;
460 /// // etc... it works exactly as a File does!
465 /// [`read()`]: trait.Read.html#tymethod.read
466 /// [`std::io`]: ../../std/io/index.html
467 /// [`File`]: ../fs/struct.File.html
468 /// [`BufRead`]: trait.BufRead.html
469 /// [`BufReader`]: struct.BufReader.html
470 /// [`&str`]: ../../std/primitive.str.html
471 /// [slice]: ../../std/primitive.slice.html
472 #[stable(feature = "rust1", since = "1.0.0")]
475 /// Pull some bytes from this source into the specified buffer, returning
476 /// how many bytes were read.
478 /// This function does not provide any guarantees about whether it blocks
479 /// waiting for data, but if an object needs to block for a read but cannot
480 /// it will typically signal this via an [`Err`] return value.
482 /// If the return value of this method is [`Ok(n)`], then it must be
483 /// guaranteed that `0 <= n <= buf.len()`. A nonzero `n` value indicates
484 /// that the buffer `buf` has been filled in with `n` bytes of data from this
485 /// source. If `n` is `0`, then it can indicate one of two scenarios:
487 /// 1. This reader has reached its "end of file" and will likely no longer
488 /// be able to produce bytes. Note that this does not mean that the
489 /// reader will *always* no longer be able to produce bytes.
490 /// 2. The buffer specified was 0 bytes in length.
492 /// No guarantees are provided about the contents of `buf` when this
493 /// function is called, implementations cannot rely on any property of the
494 /// contents of `buf` being true. It is recommended that implementations
495 /// only write data to `buf` instead of reading its contents.
499 /// If this function encounters any form of I/O or other error, an error
500 /// variant will be returned. If an error is returned then it must be
501 /// guaranteed that no bytes were read.
503 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
504 /// operation should be retried if there is nothing else to do.
508 /// [`File`]s implement `Read`:
510 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
511 /// [`Ok(n)`]: ../../std/result/enum.Result.html#variant.Ok
512 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
513 /// [`File`]: ../fs/struct.File.html
517 /// use std::io::prelude::*;
518 /// use std::fs::File;
520 /// fn main() -> io::Result<()> {
521 /// let mut f = File::open("foo.txt")?;
522 /// let mut buffer = [0; 10];
524 /// // read up to 10 bytes
525 /// f.read(&mut buffer[..])?;
529 #[stable(feature = "rust1", since = "1.0.0")]
530 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
532 /// Determines if this `Read`er can work with buffers of uninitialized
535 /// The default implementation returns an initializer which will zero
538 /// If a `Read`er guarantees that it can work properly with uninitialized
539 /// memory, it should call [`Initializer::nop()`]. See the documentation for
540 /// [`Initializer`] for details.
542 /// The behavior of this method must be independent of the state of the
543 /// `Read`er - the method only takes `&self` so that it can be used through
548 /// This method is unsafe because a `Read`er could otherwise return a
549 /// non-zeroing `Initializer` from another `Read` type without an `unsafe`
552 /// [`Initializer::nop()`]: ../../std/io/struct.Initializer.html#method.nop
553 /// [`Initializer`]: ../../std/io/struct.Initializer.html
554 #[unstable(feature = "read_initializer", issue = "42788")]
556 unsafe fn initializer(&self) -> Initializer {
557 Initializer::zeroing()
560 /// Read all bytes until EOF in this source, placing them into `buf`.
562 /// All bytes read from this source will be appended to the specified buffer
563 /// `buf`. This function will continuously call [`read()`] to append more data to
564 /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of
565 /// non-[`ErrorKind::Interrupted`] kind.
567 /// If successful, this function will return the total number of bytes read.
571 /// If this function encounters an error of the kind
572 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
575 /// If any other read error is encountered then this function immediately
576 /// returns. Any bytes which have already been read will be appended to
581 /// [`File`]s implement `Read`:
583 /// [`read()`]: trait.Read.html#tymethod.read
584 /// [`Ok(0)`]: ../../std/result/enum.Result.html#variant.Ok
585 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
586 /// [`File`]: ../fs/struct.File.html
590 /// use std::io::prelude::*;
591 /// use std::fs::File;
593 /// fn main() -> io::Result<()> {
594 /// let mut f = File::open("foo.txt")?;
595 /// let mut buffer = Vec::new();
597 /// // read the whole file
598 /// f.read_to_end(&mut buffer)?;
603 /// (See also the [`std::fs::read`] convenience function for reading from a
606 /// [`std::fs::read`]: ../fs/fn.read.html
607 #[stable(feature = "rust1", since = "1.0.0")]
608 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
609 read_to_end(self, buf)
612 /// Read all bytes until EOF in this source, appending them to `buf`.
614 /// If successful, this function returns the number of bytes which were read
615 /// and appended to `buf`.
619 /// If the data in this stream is *not* valid UTF-8 then an error is
620 /// returned and `buf` is unchanged.
622 /// See [`read_to_end`][readtoend] for other error semantics.
624 /// [readtoend]: #method.read_to_end
628 /// [`File`][file]s implement `Read`:
630 /// [file]: ../fs/struct.File.html
634 /// use std::io::prelude::*;
635 /// use std::fs::File;
637 /// fn main() -> io::Result<()> {
638 /// let mut f = File::open("foo.txt")?;
639 /// let mut buffer = String::new();
641 /// f.read_to_string(&mut buffer)?;
646 /// (See also the [`std::fs::read_to_string`] convenience function for
647 /// reading from a file.)
649 /// [`std::fs::read_to_string`]: ../fs/fn.read_to_string.html
650 #[stable(feature = "rust1", since = "1.0.0")]
651 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
652 // Note that we do *not* call `.read_to_end()` here. We are passing
653 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
654 // method to fill it up. An arbitrary implementation could overwrite the
655 // entire contents of the vector, not just append to it (which is what
656 // we are expecting).
658 // To prevent extraneously checking the UTF-8-ness of the entire buffer
659 // we pass it to our hardcoded `read_to_end` implementation which we
660 // know is guaranteed to only read data into the end of the buffer.
661 append_to_string(buf, |b| read_to_end(self, b))
664 /// Read the exact number of bytes required to fill `buf`.
666 /// This function reads as many bytes as necessary to completely fill the
667 /// specified buffer `buf`.
669 /// No guarantees are provided about the contents of `buf` when this
670 /// function is called, implementations cannot rely on any property of the
671 /// contents of `buf` being true. It is recommended that implementations
672 /// only write data to `buf` instead of reading its contents.
676 /// If this function encounters an error of the kind
677 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
680 /// If this function encounters an "end of file" before completely filling
681 /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
682 /// The contents of `buf` are unspecified in this case.
684 /// If any other read error is encountered then this function immediately
685 /// returns. The contents of `buf` are unspecified in this case.
687 /// If this function returns an error, it is unspecified how many bytes it
688 /// has read, but it will never read more than would be necessary to
689 /// completely fill the buffer.
693 /// [`File`]s implement `Read`:
695 /// [`File`]: ../fs/struct.File.html
696 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
697 /// [`ErrorKind::UnexpectedEof`]: ../../std/io/enum.ErrorKind.html#variant.UnexpectedEof
701 /// use std::io::prelude::*;
702 /// use std::fs::File;
704 /// fn main() -> io::Result<()> {
705 /// let mut f = File::open("foo.txt")?;
706 /// let mut buffer = [0; 10];
708 /// // read exactly 10 bytes
709 /// f.read_exact(&mut buffer)?;
713 #[stable(feature = "read_exact", since = "1.6.0")]
714 fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
715 while !buf.is_empty() {
716 match self.read(buf) {
718 Ok(n) => { let tmp = buf; buf = &mut tmp[n..]; }
719 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
720 Err(e) => return Err(e),
724 Err(Error::new(ErrorKind::UnexpectedEof,
725 "failed to fill whole buffer"))
731 /// Creates a "by reference" adaptor for this instance of `Read`.
733 /// The returned adaptor also implements `Read` and will simply borrow this
738 /// [`File`][file]s implement `Read`:
740 /// [file]: ../fs/struct.File.html
744 /// use std::io::Read;
745 /// use std::fs::File;
747 /// fn main() -> io::Result<()> {
748 /// let mut f = File::open("foo.txt")?;
749 /// let mut buffer = Vec::new();
750 /// let mut other_buffer = Vec::new();
753 /// let reference = f.by_ref();
755 /// // read at most 5 bytes
756 /// reference.take(5).read_to_end(&mut buffer)?;
758 /// } // drop our &mut reference so we can use f again
760 /// // original file still usable, read the rest
761 /// f.read_to_end(&mut other_buffer)?;
765 #[stable(feature = "rust1", since = "1.0.0")]
766 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
768 /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
770 /// The returned type implements [`Iterator`] where the `Item` is
771 /// [`Result`]`<`[`u8`]`, `[`io::Error`]`>`.
772 /// The yielded item is [`Ok`] if a byte was successfully read and [`Err`]
773 /// otherwise. EOF is mapped to returning [`None`] from this iterator.
777 /// [`File`][file]s implement `Read`:
779 /// [file]: ../fs/struct.File.html
780 /// [`Iterator`]: ../../std/iter/trait.Iterator.html
781 /// [`Result`]: ../../std/result/enum.Result.html
782 /// [`io::Error`]: ../../std/io/struct.Error.html
783 /// [`u8`]: ../../std/primitive.u8.html
784 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
785 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
786 /// [`None`]: ../../std/option/enum.Option.html#variant.None
790 /// use std::io::prelude::*;
791 /// use std::fs::File;
793 /// fn main() -> io::Result<()> {
794 /// let mut f = File::open("foo.txt")?;
796 /// for byte in f.bytes() {
797 /// println!("{}", byte.unwrap());
802 #[stable(feature = "rust1", since = "1.0.0")]
803 fn bytes(self) -> Bytes<Self> where Self: Sized {
804 Bytes { inner: self }
807 /// Creates an adaptor which will chain this stream with another.
809 /// The returned `Read` instance will first read all bytes from this object
810 /// until EOF is encountered. Afterwards the output is equivalent to the
811 /// output of `next`.
815 /// [`File`][file]s implement `Read`:
817 /// [file]: ../fs/struct.File.html
821 /// use std::io::prelude::*;
822 /// use std::fs::File;
824 /// fn main() -> io::Result<()> {
825 /// let mut f1 = File::open("foo.txt")?;
826 /// let mut f2 = File::open("bar.txt")?;
828 /// let mut handle = f1.chain(f2);
829 /// let mut buffer = String::new();
831 /// // read the value into a String. We could use any Read method here,
832 /// // this is just one example.
833 /// handle.read_to_string(&mut buffer)?;
837 #[stable(feature = "rust1", since = "1.0.0")]
838 fn chain<R: Read>(self, next: R) -> Chain<Self, R> where Self: Sized {
839 Chain { first: self, second: next, done_first: false }
842 /// Creates an adaptor which will read at most `limit` bytes from it.
844 /// This function returns a new instance of `Read` which will read at most
845 /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
846 /// read errors will not count towards the number of bytes read and future
847 /// calls to [`read()`] may succeed.
851 /// [`File`]s implement `Read`:
853 /// [`File`]: ../fs/struct.File.html
854 /// [`Ok(0)`]: ../../std/result/enum.Result.html#variant.Ok
855 /// [`read()`]: trait.Read.html#tymethod.read
859 /// use std::io::prelude::*;
860 /// use std::fs::File;
862 /// fn main() -> io::Result<()> {
863 /// let mut f = File::open("foo.txt")?;
864 /// let mut buffer = [0; 5];
866 /// // read at most five bytes
867 /// let mut handle = f.take(5);
869 /// handle.read(&mut buffer)?;
873 #[stable(feature = "rust1", since = "1.0.0")]
874 fn take(self, limit: u64) -> Take<Self> where Self: Sized {
875 Take { inner: self, limit: limit }
879 /// A type used to conditionally initialize buffers passed to `Read` methods.
880 #[unstable(feature = "read_initializer", issue = "42788")]
882 pub struct Initializer(bool);
885 /// Returns a new `Initializer` which will zero out buffers.
886 #[unstable(feature = "read_initializer", issue = "42788")]
888 pub const fn zeroing() -> Initializer {
892 /// Returns a new `Initializer` which will not zero out buffers.
896 /// This may only be called by `Read`ers which guarantee that they will not
897 /// read from buffers passed to `Read` methods, and that the return value of
898 /// the method accurately reflects the number of bytes that have been
899 /// written to the head of the buffer.
900 #[unstable(feature = "read_initializer", issue = "42788")]
902 pub unsafe fn nop() -> Initializer {
906 /// Indicates if a buffer should be initialized.
907 #[unstable(feature = "read_initializer", issue = "42788")]
909 pub const fn should_initialize(&self) -> bool {
913 /// Initializes a buffer if necessary.
914 #[unstable(feature = "read_initializer", issue = "42788")]
916 pub fn initialize(&self, buf: &mut [u8]) {
917 if self.should_initialize() {
918 unsafe { ptr::write_bytes(buf.as_mut_ptr(), 0, buf.len()) }
923 /// A trait for objects which are byte-oriented sinks.
925 /// Implementors of the `Write` trait are sometimes called 'writers'.
927 /// Writers are defined by two required methods, [`write`] and [`flush`]:
929 /// * The [`write`] method will attempt to write some data into the object,
930 /// returning how many bytes were successfully written.
932 /// * The [`flush`] method is useful for adaptors and explicit buffers
933 /// themselves for ensuring that all buffered data has been pushed out to the
936 /// Writers are intended to be composable with one another. Many implementors
937 /// throughout [`std::io`] take and provide types which implement the `Write`
940 /// [`write`]: #tymethod.write
941 /// [`flush`]: #tymethod.flush
942 /// [`std::io`]: index.html
947 /// use std::io::prelude::*;
948 /// use std::fs::File;
950 /// fn main() -> std::io::Result<()> {
951 /// let mut buffer = File::create("foo.txt")?;
953 /// buffer.write(b"some bytes")?;
957 #[stable(feature = "rust1", since = "1.0.0")]
960 /// Write a buffer into this object, returning how many bytes were written.
962 /// This function will attempt to write the entire contents of `buf`, but
963 /// the entire write may not succeed, or the write may also generate an
964 /// error. A call to `write` represents *at most one* attempt to write to
965 /// any wrapped object.
967 /// Calls to `write` are not guaranteed to block waiting for data to be
968 /// written, and a write which would otherwise block can be indicated through
969 /// an [`Err`] variant.
971 /// If the return value is [`Ok(n)`] then it must be guaranteed that
972 /// `0 <= n <= buf.len()`. A return value of `0` typically means that the
973 /// underlying object is no longer able to accept bytes and will likely not
974 /// be able to in the future as well, or that the buffer provided is empty.
978 /// Each call to `write` may generate an I/O error indicating that the
979 /// operation could not be completed. If an error is returned then no bytes
980 /// in the buffer were written to this writer.
982 /// It is **not** considered an error if the entire buffer could not be
983 /// written to this writer.
985 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the
986 /// write operation should be retried if there is nothing else to do.
988 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
989 /// [`Ok(n)`]: ../../std/result/enum.Result.html#variant.Ok
990 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
995 /// use std::io::prelude::*;
996 /// use std::fs::File;
998 /// fn main() -> std::io::Result<()> {
999 /// let mut buffer = File::create("foo.txt")?;
1001 /// // Writes some prefix of the byte string, not necessarily all of it.
1002 /// buffer.write(b"some bytes")?;
1006 #[stable(feature = "rust1", since = "1.0.0")]
1007 fn write(&mut self, buf: &[u8]) -> Result<usize>;
1009 /// Flush this output stream, ensuring that all intermediately buffered
1010 /// contents reach their destination.
1014 /// It is considered an error if not all bytes could be written due to
1015 /// I/O errors or EOF being reached.
1020 /// use std::io::prelude::*;
1021 /// use std::io::BufWriter;
1022 /// use std::fs::File;
1024 /// fn main() -> std::io::Result<()> {
1025 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
1027 /// buffer.write(b"some bytes")?;
1028 /// buffer.flush()?;
1032 #[stable(feature = "rust1", since = "1.0.0")]
1033 fn flush(&mut self) -> Result<()>;
1035 /// Attempts to write an entire buffer into this write.
1037 /// This method will continuously call [`write`] until there is no more data
1038 /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is
1039 /// returned. This method will not return until the entire buffer has been
1040 /// successfully written or such an error occurs. The first error that is
1041 /// not of [`ErrorKind::Interrupted`] kind generated from this method will be
1046 /// This function will return the first error of
1047 /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns.
1049 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
1050 /// [`write`]: #tymethod.write
1055 /// use std::io::prelude::*;
1056 /// use std::fs::File;
1058 /// fn main() -> std::io::Result<()> {
1059 /// let mut buffer = File::create("foo.txt")?;
1061 /// buffer.write_all(b"some bytes")?;
1065 #[stable(feature = "rust1", since = "1.0.0")]
1066 fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
1067 while !buf.is_empty() {
1068 match self.write(buf) {
1069 Ok(0) => return Err(Error::new(ErrorKind::WriteZero,
1070 "failed to write whole buffer")),
1071 Ok(n) => buf = &buf[n..],
1072 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1073 Err(e) => return Err(e),
1079 /// Writes a formatted string into this writer, returning any error
1082 /// This method is primarily used to interface with the
1083 /// [`format_args!`][formatargs] macro, but it is rare that this should
1084 /// explicitly be called. The [`write!`][write] macro should be favored to
1085 /// invoke this method instead.
1087 /// [formatargs]: ../macro.format_args.html
1088 /// [write]: ../macro.write.html
1090 /// This function internally uses the [`write_all`][writeall] method on
1091 /// this trait and hence will continuously write data so long as no errors
1092 /// are received. This also means that partial writes are not indicated in
1095 /// [writeall]: #method.write_all
1099 /// This function will return any I/O error reported while formatting.
1104 /// use std::io::prelude::*;
1105 /// use std::fs::File;
1107 /// fn main() -> std::io::Result<()> {
1108 /// let mut buffer = File::create("foo.txt")?;
1111 /// write!(buffer, "{:.*}", 2, 1.234567)?;
1112 /// // turns into this:
1113 /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1117 #[stable(feature = "rust1", since = "1.0.0")]
1118 fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()> {
1119 // Create a shim which translates a Write to a fmt::Write and saves
1120 // off I/O errors. instead of discarding them
1121 struct Adaptor<'a, T: ?Sized + 'a> {
1126 impl<'a, T: Write + ?Sized> fmt::Write for Adaptor<'a, T> {
1127 fn write_str(&mut self, s: &str) -> fmt::Result {
1128 match self.inner.write_all(s.as_bytes()) {
1131 self.error = Err(e);
1138 let mut output = Adaptor { inner: self, error: Ok(()) };
1139 match fmt::write(&mut output, fmt) {
1142 // check if the error came from the underlying `Write` or not
1143 if output.error.is_err() {
1146 Err(Error::new(ErrorKind::Other, "formatter error"))
1152 /// Creates a "by reference" adaptor for this instance of `Write`.
1154 /// The returned adaptor also implements `Write` and will simply borrow this
1160 /// use std::io::Write;
1161 /// use std::fs::File;
1163 /// fn main() -> std::io::Result<()> {
1164 /// let mut buffer = File::create("foo.txt")?;
1166 /// let reference = buffer.by_ref();
1168 /// // we can use reference just like our original buffer
1169 /// reference.write_all(b"some bytes")?;
1173 #[stable(feature = "rust1", since = "1.0.0")]
1174 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1177 /// The `Seek` trait provides a cursor which can be moved within a stream of
1180 /// The stream typically has a fixed size, allowing seeking relative to either
1181 /// end or the current offset.
1185 /// [`File`][file]s implement `Seek`:
1187 /// [file]: ../fs/struct.File.html
1191 /// use std::io::prelude::*;
1192 /// use std::fs::File;
1193 /// use std::io::SeekFrom;
1195 /// fn main() -> io::Result<()> {
1196 /// let mut f = File::open("foo.txt")?;
1198 /// // move the cursor 42 bytes from the start of the file
1199 /// f.seek(SeekFrom::Start(42))?;
1203 #[stable(feature = "rust1", since = "1.0.0")]
1205 /// Seek to an offset, in bytes, in a stream.
1207 /// A seek beyond the end of a stream is allowed, but behavior is defined
1208 /// by the implementation.
1210 /// If the seek operation completed successfully,
1211 /// this method returns the new position from the start of the stream.
1212 /// That position can be used later with [`SeekFrom::Start`].
1216 /// Seeking to a negative offset is considered an error.
1218 /// [`SeekFrom::Start`]: enum.SeekFrom.html#variant.Start
1219 #[stable(feature = "rust1", since = "1.0.0")]
1220 fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1223 /// Enumeration of possible methods to seek within an I/O object.
1225 /// It is used by the [`Seek`] trait.
1227 /// [`Seek`]: trait.Seek.html
1228 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1229 #[stable(feature = "rust1", since = "1.0.0")]
1231 /// Set the offset to the provided number of bytes.
1232 #[stable(feature = "rust1", since = "1.0.0")]
1233 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1235 /// Set the offset to the size of this object plus the specified number of
1238 /// It is possible to seek beyond the end of an object, but it's an error to
1239 /// seek before byte 0.
1240 #[stable(feature = "rust1", since = "1.0.0")]
1241 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1243 /// Set the offset to the current position plus the specified number of
1246 /// It is possible to seek beyond the end of an object, but it's an error to
1247 /// seek before byte 0.
1248 #[stable(feature = "rust1", since = "1.0.0")]
1249 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1252 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>)
1256 let (done, used) = {
1257 let available = match r.fill_buf() {
1259 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1260 Err(e) => return Err(e)
1262 match memchr::memchr(delim, available) {
1264 buf.extend_from_slice(&available[..i + 1]);
1268 buf.extend_from_slice(available);
1269 (false, available.len())
1275 if done || used == 0 {
1281 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1282 /// to perform extra ways of reading.
1284 /// For example, reading line-by-line is inefficient without using a buffer, so
1285 /// if you want to read by line, you'll need `BufRead`, which includes a
1286 /// [`read_line`] method as well as a [`lines`] iterator.
1290 /// A locked standard input implements `BufRead`:
1294 /// use std::io::prelude::*;
1296 /// let stdin = io::stdin();
1297 /// for line in stdin.lock().lines() {
1298 /// println!("{}", line.unwrap());
1302 /// If you have something that implements [`Read`], you can use the [`BufReader`
1303 /// type][`BufReader`] to turn it into a `BufRead`.
1305 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1306 /// [`BufReader`] to the rescue!
1308 /// [`BufReader`]: struct.BufReader.html
1309 /// [`File`]: ../fs/struct.File.html
1310 /// [`read_line`]: #method.read_line
1311 /// [`lines`]: #method.lines
1312 /// [`Read`]: trait.Read.html
1315 /// use std::io::{self, BufReader};
1316 /// use std::io::prelude::*;
1317 /// use std::fs::File;
1319 /// fn main() -> io::Result<()> {
1320 /// let f = File::open("foo.txt")?;
1321 /// let f = BufReader::new(f);
1323 /// for line in f.lines() {
1324 /// println!("{}", line.unwrap());
1331 #[stable(feature = "rust1", since = "1.0.0")]
1332 pub trait BufRead: Read {
1333 /// Returns the contents of the internal buffer, filling it with more data
1334 /// from the inner reader if it is empty.
1336 /// This function is a lower-level call. It needs to be paired with the
1337 /// [`consume`] method to function properly. When calling this
1338 /// method, none of the contents will be "read" in the sense that later
1339 /// calling `read` may return the same contents. As such, [`consume`] must
1340 /// be called with the number of bytes that are consumed from this buffer to
1341 /// ensure that the bytes are never returned twice.
1343 /// [`consume`]: #tymethod.consume
1345 /// An empty buffer returned indicates that the stream has reached EOF.
1349 /// This function will return an I/O error if the underlying reader was
1350 /// read, but returned an error.
1354 /// A locked standard input implements `BufRead`:
1358 /// use std::io::prelude::*;
1360 /// let stdin = io::stdin();
1361 /// let mut stdin = stdin.lock();
1363 /// // we can't have two `&mut` references to `stdin`, so use a block
1364 /// // to end the borrow early.
1366 /// let buffer = stdin.fill_buf().unwrap();
1368 /// // work with buffer
1369 /// println!("{:?}", buffer);
1374 /// // ensure the bytes we worked with aren't returned again later
1375 /// stdin.consume(length);
1377 #[stable(feature = "rust1", since = "1.0.0")]
1378 fn fill_buf(&mut self) -> Result<&[u8]>;
1380 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1381 /// so they should no longer be returned in calls to `read`.
1383 /// This function is a lower-level call. It needs to be paired with the
1384 /// [`fill_buf`] method to function properly. This function does
1385 /// not perform any I/O, it simply informs this object that some amount of
1386 /// its buffer, returned from [`fill_buf`], has been consumed and should
1387 /// no longer be returned. As such, this function may do odd things if
1388 /// [`fill_buf`] isn't called before calling it.
1390 /// The `amt` must be `<=` the number of bytes in the buffer returned by
1395 /// Since `consume()` is meant to be used with [`fill_buf`],
1396 /// that method's example includes an example of `consume()`.
1398 /// [`fill_buf`]: #tymethod.fill_buf
1399 #[stable(feature = "rust1", since = "1.0.0")]
1400 fn consume(&mut self, amt: usize);
1402 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
1404 /// This function will read bytes from the underlying stream until the
1405 /// delimiter or EOF is found. Once found, all bytes up to, and including,
1406 /// the delimiter (if found) will be appended to `buf`.
1408 /// If successful, this function will return the total number of bytes read.
1412 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1413 /// will otherwise return any errors returned by [`fill_buf`].
1415 /// If an I/O error is encountered then all bytes read so far will be
1416 /// present in `buf` and its length will have been adjusted appropriately.
1418 /// [`fill_buf`]: #tymethod.fill_buf
1419 /// [`ErrorKind::Interrupted`]: enum.ErrorKind.html#variant.Interrupted
1423 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1424 /// this example, we use [`Cursor`] to read all the bytes in a byte slice
1425 /// in hyphen delimited segments:
1427 /// [`Cursor`]: struct.Cursor.html
1430 /// use std::io::{self, BufRead};
1432 /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
1433 /// let mut buf = vec![];
1435 /// // cursor is at 'l'
1436 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1437 /// .expect("reading from cursor won't fail");
1438 /// assert_eq!(num_bytes, 6);
1439 /// assert_eq!(buf, b"lorem-");
1442 /// // cursor is at 'i'
1443 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1444 /// .expect("reading from cursor won't fail");
1445 /// assert_eq!(num_bytes, 5);
1446 /// assert_eq!(buf, b"ipsum");
1449 /// // cursor is at EOF
1450 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1451 /// .expect("reading from cursor won't fail");
1452 /// assert_eq!(num_bytes, 0);
1453 /// assert_eq!(buf, b"");
1455 #[stable(feature = "rust1", since = "1.0.0")]
1456 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
1457 read_until(self, byte, buf)
1460 /// Read all bytes until a newline (the 0xA byte) is reached, and append
1461 /// them to the provided buffer.
1463 /// This function will read bytes from the underlying stream until the
1464 /// newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes
1465 /// up to, and including, the delimiter (if found) will be appended to
1468 /// If successful, this function will return the total number of bytes read.
1470 /// An empty buffer returned indicates that the stream has reached EOF.
1474 /// This function has the same error semantics as [`read_until`] and will
1475 /// also return an error if the read bytes are not valid UTF-8. If an I/O
1476 /// error is encountered then `buf` may contain some bytes already read in
1477 /// the event that all data read so far was valid UTF-8.
1479 /// [`read_until`]: #method.read_until
1483 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1484 /// this example, we use [`Cursor`] to read all the lines in a byte slice:
1486 /// [`Cursor`]: struct.Cursor.html
1489 /// use std::io::{self, BufRead};
1491 /// let mut cursor = io::Cursor::new(b"foo\nbar");
1492 /// let mut buf = String::new();
1494 /// // cursor is at 'f'
1495 /// let num_bytes = cursor.read_line(&mut buf)
1496 /// .expect("reading from cursor won't fail");
1497 /// assert_eq!(num_bytes, 4);
1498 /// assert_eq!(buf, "foo\n");
1501 /// // cursor is at 'b'
1502 /// let num_bytes = cursor.read_line(&mut buf)
1503 /// .expect("reading from cursor won't fail");
1504 /// assert_eq!(num_bytes, 3);
1505 /// assert_eq!(buf, "bar");
1508 /// // cursor is at EOF
1509 /// let num_bytes = cursor.read_line(&mut buf)
1510 /// .expect("reading from cursor won't fail");
1511 /// assert_eq!(num_bytes, 0);
1512 /// assert_eq!(buf, "");
1514 #[stable(feature = "rust1", since = "1.0.0")]
1515 fn read_line(&mut self, buf: &mut String) -> Result<usize> {
1516 // Note that we are not calling the `.read_until` method here, but
1517 // rather our hardcoded implementation. For more details as to why, see
1518 // the comments in `read_to_end`.
1519 append_to_string(buf, |b| read_until(self, b'\n', b))
1522 /// Returns an iterator over the contents of this reader split on the byte
1525 /// The iterator returned from this function will return instances of
1526 /// [`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
1527 /// the delimiter byte at the end.
1529 /// This function will yield errors whenever [`read_until`] would have
1530 /// also yielded an error.
1532 /// [`io::Result`]: type.Result.html
1533 /// [`Vec<u8>`]: ../vec/struct.Vec.html
1534 /// [`read_until`]: #method.read_until
1538 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1539 /// this example, we use [`Cursor`] to iterate over all hyphen delimited
1540 /// segments in a byte slice
1542 /// [`Cursor`]: struct.Cursor.html
1545 /// use std::io::{self, BufRead};
1547 /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
1549 /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
1550 /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
1551 /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
1552 /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
1553 /// assert_eq!(split_iter.next(), None);
1555 #[stable(feature = "rust1", since = "1.0.0")]
1556 fn split(self, byte: u8) -> Split<Self> where Self: Sized {
1557 Split { buf: self, delim: byte }
1560 /// Returns an iterator over the lines of this reader.
1562 /// The iterator returned from this function will yield instances of
1563 /// [`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline
1564 /// byte (the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.
1566 /// [`io::Result`]: type.Result.html
1567 /// [`String`]: ../string/struct.String.html
1571 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1572 /// this example, we use [`Cursor`] to iterate over all the lines in a byte
1575 /// [`Cursor`]: struct.Cursor.html
1578 /// use std::io::{self, BufRead};
1580 /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
1582 /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
1583 /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
1584 /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
1585 /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
1586 /// assert_eq!(lines_iter.next(), None);
1591 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
1593 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
1594 #[stable(feature = "rust1", since = "1.0.0")]
1595 fn lines(self) -> Lines<Self> where Self: Sized {
1600 /// Adaptor to chain together two readers.
1602 /// This struct is generally created by calling [`chain`] on a reader.
1603 /// Please see the documentation of [`chain`] for more details.
1605 /// [`chain`]: trait.Read.html#method.chain
1606 #[stable(feature = "rust1", since = "1.0.0")]
1607 pub struct Chain<T, U> {
1613 impl<T, U> Chain<T, U> {
1614 /// Consumes the `Chain`, returning the wrapped readers.
1620 /// use std::io::prelude::*;
1621 /// use std::fs::File;
1623 /// fn main() -> io::Result<()> {
1624 /// let mut foo_file = File::open("foo.txt")?;
1625 /// let mut bar_file = File::open("bar.txt")?;
1627 /// let chain = foo_file.chain(bar_file);
1628 /// let (foo_file, bar_file) = chain.into_inner();
1632 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1633 pub fn into_inner(self) -> (T, U) {
1634 (self.first, self.second)
1637 /// Gets references to the underlying readers in this `Chain`.
1643 /// use std::io::prelude::*;
1644 /// use std::fs::File;
1646 /// fn main() -> io::Result<()> {
1647 /// let mut foo_file = File::open("foo.txt")?;
1648 /// let mut bar_file = File::open("bar.txt")?;
1650 /// let chain = foo_file.chain(bar_file);
1651 /// let (foo_file, bar_file) = chain.get_ref();
1655 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1656 pub fn get_ref(&self) -> (&T, &U) {
1657 (&self.first, &self.second)
1660 /// Gets mutable references to the underlying readers in this `Chain`.
1662 /// Care should be taken to avoid modifying the internal I/O state of the
1663 /// underlying readers as doing so may corrupt the internal state of this
1670 /// use std::io::prelude::*;
1671 /// use std::fs::File;
1673 /// fn main() -> io::Result<()> {
1674 /// let mut foo_file = File::open("foo.txt")?;
1675 /// let mut bar_file = File::open("bar.txt")?;
1677 /// let mut chain = foo_file.chain(bar_file);
1678 /// let (foo_file, bar_file) = chain.get_mut();
1682 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1683 pub fn get_mut(&mut self) -> (&mut T, &mut U) {
1684 (&mut self.first, &mut self.second)
1688 #[stable(feature = "std_debug", since = "1.16.0")]
1689 impl<T: fmt::Debug, U: fmt::Debug> fmt::Debug for Chain<T, U> {
1690 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1691 f.debug_struct("Chain")
1692 .field("t", &self.first)
1693 .field("u", &self.second)
1698 #[stable(feature = "rust1", since = "1.0.0")]
1699 impl<T: Read, U: Read> Read for Chain<T, U> {
1700 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1701 if !self.done_first {
1702 match self.first.read(buf)? {
1703 0 if buf.len() != 0 => { self.done_first = true; }
1707 self.second.read(buf)
1710 unsafe fn initializer(&self) -> Initializer {
1711 let initializer = self.first.initializer();
1712 if initializer.should_initialize() {
1715 self.second.initializer()
1720 #[stable(feature = "chain_bufread", since = "1.9.0")]
1721 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
1722 fn fill_buf(&mut self) -> Result<&[u8]> {
1723 if !self.done_first {
1724 match self.first.fill_buf()? {
1725 buf if buf.len() == 0 => { self.done_first = true; }
1726 buf => return Ok(buf),
1729 self.second.fill_buf()
1732 fn consume(&mut self, amt: usize) {
1733 if !self.done_first {
1734 self.first.consume(amt)
1736 self.second.consume(amt)
1741 /// Reader adaptor which limits the bytes read from an underlying reader.
1743 /// This struct is generally created by calling [`take`] on a reader.
1744 /// Please see the documentation of [`take`] for more details.
1746 /// [`take`]: trait.Read.html#method.take
1747 #[stable(feature = "rust1", since = "1.0.0")]
1749 pub struct Take<T> {
1755 /// Returns the number of bytes that can be read before this instance will
1760 /// This instance may reach `EOF` after reading fewer bytes than indicated by
1761 /// this method if the underlying [`Read`] instance reaches EOF.
1763 /// [`Read`]: ../../std/io/trait.Read.html
1769 /// use std::io::prelude::*;
1770 /// use std::fs::File;
1772 /// fn main() -> io::Result<()> {
1773 /// let f = File::open("foo.txt")?;
1775 /// // read at most five bytes
1776 /// let handle = f.take(5);
1778 /// println!("limit: {}", handle.limit());
1782 #[stable(feature = "rust1", since = "1.0.0")]
1783 pub fn limit(&self) -> u64 { self.limit }
1785 /// Sets the number of bytes that can be read before this instance will
1786 /// return EOF. This is the same as constructing a new `Take` instance, so
1787 /// the amount of bytes read and the previous limit value don't matter when
1788 /// calling this method.
1794 /// use std::io::prelude::*;
1795 /// use std::fs::File;
1797 /// fn main() -> io::Result<()> {
1798 /// let f = File::open("foo.txt")?;
1800 /// // read at most five bytes
1801 /// let mut handle = f.take(5);
1802 /// handle.set_limit(10);
1804 /// assert_eq!(handle.limit(), 10);
1808 #[stable(feature = "take_set_limit", since = "1.27.0")]
1809 pub fn set_limit(&mut self, limit: u64) {
1813 /// Consumes the `Take`, returning the wrapped reader.
1819 /// use std::io::prelude::*;
1820 /// use std::fs::File;
1822 /// fn main() -> io::Result<()> {
1823 /// let mut file = File::open("foo.txt")?;
1825 /// let mut buffer = [0; 5];
1826 /// let mut handle = file.take(5);
1827 /// handle.read(&mut buffer)?;
1829 /// let file = handle.into_inner();
1833 #[stable(feature = "io_take_into_inner", since = "1.15.0")]
1834 pub fn into_inner(self) -> T {
1838 /// Gets a reference to the underlying reader.
1844 /// use std::io::prelude::*;
1845 /// use std::fs::File;
1847 /// fn main() -> io::Result<()> {
1848 /// let mut file = File::open("foo.txt")?;
1850 /// let mut buffer = [0; 5];
1851 /// let mut handle = file.take(5);
1852 /// handle.read(&mut buffer)?;
1854 /// let file = handle.get_ref();
1858 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1859 pub fn get_ref(&self) -> &T {
1863 /// Gets a mutable reference to the underlying reader.
1865 /// Care should be taken to avoid modifying the internal I/O state of the
1866 /// underlying reader as doing so may corrupt the internal limit of this
1873 /// use std::io::prelude::*;
1874 /// use std::fs::File;
1876 /// fn main() -> io::Result<()> {
1877 /// let mut file = File::open("foo.txt")?;
1879 /// let mut buffer = [0; 5];
1880 /// let mut handle = file.take(5);
1881 /// handle.read(&mut buffer)?;
1883 /// let file = handle.get_mut();
1887 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1888 pub fn get_mut(&mut self) -> &mut T {
1893 #[stable(feature = "rust1", since = "1.0.0")]
1894 impl<T: Read> Read for Take<T> {
1895 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1896 // Don't call into inner reader at all at EOF because it may still block
1897 if self.limit == 0 {
1901 let max = cmp::min(buf.len() as u64, self.limit) as usize;
1902 let n = self.inner.read(&mut buf[..max])?;
1903 self.limit -= n as u64;
1907 unsafe fn initializer(&self) -> Initializer {
1908 self.inner.initializer()
1911 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
1912 let reservation_size = cmp::min(self.limit, 32) as usize;
1914 read_to_end_with_reservation(self, buf, reservation_size)
1918 #[stable(feature = "rust1", since = "1.0.0")]
1919 impl<T: BufRead> BufRead for Take<T> {
1920 fn fill_buf(&mut self) -> Result<&[u8]> {
1921 // Don't call into inner reader at all at EOF because it may still block
1922 if self.limit == 0 {
1926 let buf = self.inner.fill_buf()?;
1927 let cap = cmp::min(buf.len() as u64, self.limit) as usize;
1931 fn consume(&mut self, amt: usize) {
1932 // Don't let callers reset the limit by passing an overlarge value
1933 let amt = cmp::min(amt as u64, self.limit) as usize;
1934 self.limit -= amt as u64;
1935 self.inner.consume(amt);
1939 fn read_one_byte(reader: &mut dyn Read) -> Option<Result<u8>> {
1942 return match reader.read(&mut buf) {
1944 Ok(..) => Some(Ok(buf[0])),
1945 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1946 Err(e) => Some(Err(e)),
1951 /// An iterator over `u8` values of a reader.
1953 /// This struct is generally created by calling [`bytes`] on a reader.
1954 /// Please see the documentation of [`bytes`] for more details.
1956 /// [`bytes`]: trait.Read.html#method.bytes
1957 #[stable(feature = "rust1", since = "1.0.0")]
1959 pub struct Bytes<R> {
1963 #[stable(feature = "rust1", since = "1.0.0")]
1964 impl<R: Read> Iterator for Bytes<R> {
1965 type Item = Result<u8>;
1967 fn next(&mut self) -> Option<Result<u8>> {
1968 read_one_byte(&mut self.inner)
1972 /// An iterator over the contents of an instance of `BufRead` split on a
1973 /// particular byte.
1975 /// This struct is generally created by calling [`split`][split] on a
1976 /// `BufRead`. Please see the documentation of `split()` for more details.
1978 /// [split]: trait.BufRead.html#method.split
1979 #[stable(feature = "rust1", since = "1.0.0")]
1981 pub struct Split<B> {
1986 #[stable(feature = "rust1", since = "1.0.0")]
1987 impl<B: BufRead> Iterator for Split<B> {
1988 type Item = Result<Vec<u8>>;
1990 fn next(&mut self) -> Option<Result<Vec<u8>>> {
1991 let mut buf = Vec::new();
1992 match self.buf.read_until(self.delim, &mut buf) {
1995 if buf[buf.len() - 1] == self.delim {
2000 Err(e) => Some(Err(e))
2005 /// An iterator over the lines of an instance of `BufRead`.
2007 /// This struct is generally created by calling [`lines`][lines] on a
2008 /// `BufRead`. Please see the documentation of `lines()` for more details.
2010 /// [lines]: trait.BufRead.html#method.lines
2011 #[stable(feature = "rust1", since = "1.0.0")]
2013 pub struct Lines<B> {
2017 #[stable(feature = "rust1", since = "1.0.0")]
2018 impl<B: BufRead> Iterator for Lines<B> {
2019 type Item = Result<String>;
2021 fn next(&mut self) -> Option<Result<String>> {
2022 let mut buf = String::new();
2023 match self.buf.read_line(&mut buf) {
2026 if buf.ends_with("\n") {
2028 if buf.ends_with("\r") {
2034 Err(e) => Some(Err(e))
2048 #[cfg_attr(target_os = "emscripten", ignore)]
2050 let mut buf = Cursor::new(&b"12"[..]);
2051 let mut v = Vec::new();
2052 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 2);
2053 assert_eq!(v, b"12");
2055 let mut buf = Cursor::new(&b"1233"[..]);
2056 let mut v = Vec::new();
2057 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 3);
2058 assert_eq!(v, b"123");
2060 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 1);
2061 assert_eq!(v, b"3");
2063 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 0);
2069 let buf = Cursor::new(&b"12"[..]);
2070 let mut s = buf.split(b'3');
2071 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2072 assert!(s.next().is_none());
2074 let buf = Cursor::new(&b"1233"[..]);
2075 let mut s = buf.split(b'3');
2076 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2077 assert_eq!(s.next().unwrap().unwrap(), vec![]);
2078 assert!(s.next().is_none());
2083 let mut buf = Cursor::new(&b"12"[..]);
2084 let mut v = String::new();
2085 assert_eq!(buf.read_line(&mut v).unwrap(), 2);
2086 assert_eq!(v, "12");
2088 let mut buf = Cursor::new(&b"12\n\n"[..]);
2089 let mut v = String::new();
2090 assert_eq!(buf.read_line(&mut v).unwrap(), 3);
2091 assert_eq!(v, "12\n");
2093 assert_eq!(buf.read_line(&mut v).unwrap(), 1);
2094 assert_eq!(v, "\n");
2096 assert_eq!(buf.read_line(&mut v).unwrap(), 0);
2102 let buf = Cursor::new(&b"12\r"[..]);
2103 let mut s = buf.lines();
2104 assert_eq!(s.next().unwrap().unwrap(), "12\r".to_string());
2105 assert!(s.next().is_none());
2107 let buf = Cursor::new(&b"12\r\n\n"[..]);
2108 let mut s = buf.lines();
2109 assert_eq!(s.next().unwrap().unwrap(), "12".to_string());
2110 assert_eq!(s.next().unwrap().unwrap(), "".to_string());
2111 assert!(s.next().is_none());
2116 let mut c = Cursor::new(&b""[..]);
2117 let mut v = Vec::new();
2118 assert_eq!(c.read_to_end(&mut v).unwrap(), 0);
2121 let mut c = Cursor::new(&b"1"[..]);
2122 let mut v = Vec::new();
2123 assert_eq!(c.read_to_end(&mut v).unwrap(), 1);
2124 assert_eq!(v, b"1");
2126 let cap = 1024 * 1024;
2127 let data = (0..cap).map(|i| (i / 3) as u8).collect::<Vec<_>>();
2128 let mut v = Vec::new();
2129 let (a, b) = data.split_at(data.len() / 2);
2130 assert_eq!(Cursor::new(a).read_to_end(&mut v).unwrap(), a.len());
2131 assert_eq!(Cursor::new(b).read_to_end(&mut v).unwrap(), b.len());
2132 assert_eq!(v, data);
2136 fn read_to_string() {
2137 let mut c = Cursor::new(&b""[..]);
2138 let mut v = String::new();
2139 assert_eq!(c.read_to_string(&mut v).unwrap(), 0);
2142 let mut c = Cursor::new(&b"1"[..]);
2143 let mut v = String::new();
2144 assert_eq!(c.read_to_string(&mut v).unwrap(), 1);
2147 let mut c = Cursor::new(&b"\xff"[..]);
2148 let mut v = String::new();
2149 assert!(c.read_to_string(&mut v).is_err());
2154 let mut buf = [0; 4];
2156 let mut c = Cursor::new(&b""[..]);
2157 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2158 io::ErrorKind::UnexpectedEof);
2160 let mut c = Cursor::new(&b"123"[..]).chain(Cursor::new(&b"456789"[..]));
2161 c.read_exact(&mut buf).unwrap();
2162 assert_eq!(&buf, b"1234");
2163 c.read_exact(&mut buf).unwrap();
2164 assert_eq!(&buf, b"5678");
2165 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2166 io::ErrorKind::UnexpectedEof);
2170 fn read_exact_slice() {
2171 let mut buf = [0; 4];
2173 let mut c = &b""[..];
2174 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2175 io::ErrorKind::UnexpectedEof);
2177 let mut c = &b"123"[..];
2178 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2179 io::ErrorKind::UnexpectedEof);
2180 // make sure the optimized (early returning) method is being used
2181 assert_eq!(&buf, &[0; 4]);
2183 let mut c = &b"1234"[..];
2184 c.read_exact(&mut buf).unwrap();
2185 assert_eq!(&buf, b"1234");
2187 let mut c = &b"56789"[..];
2188 c.read_exact(&mut buf).unwrap();
2189 assert_eq!(&buf, b"5678");
2190 assert_eq!(c, b"9");
2198 fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
2199 Err(io::Error::new(io::ErrorKind::Other, ""))
2202 impl BufRead for R {
2203 fn fill_buf(&mut self) -> io::Result<&[u8]> {
2204 Err(io::Error::new(io::ErrorKind::Other, ""))
2206 fn consume(&mut self, _amt: usize) { }
2209 let mut buf = [0; 1];
2210 assert_eq!(0, R.take(0).read(&mut buf).unwrap());
2211 assert_eq!(b"", R.take(0).fill_buf().unwrap());
2214 fn cmp_bufread<Br1: BufRead, Br2: BufRead>(mut br1: Br1, mut br2: Br2, exp: &[u8]) {
2215 let mut cat = Vec::new();
2218 let buf1 = br1.fill_buf().unwrap();
2219 let buf2 = br2.fill_buf().unwrap();
2220 let minlen = if buf1.len() < buf2.len() { buf1.len() } else { buf2.len() };
2221 assert_eq!(buf1[..minlen], buf2[..minlen]);
2222 cat.extend_from_slice(&buf1[..minlen]);
2228 br1.consume(consume);
2229 br2.consume(consume);
2231 assert_eq!(br1.fill_buf().unwrap().len(), 0);
2232 assert_eq!(br2.fill_buf().unwrap().len(), 0);
2233 assert_eq!(&cat[..], &exp[..])
2237 fn chain_bufread() {
2238 let testdata = b"ABCDEFGHIJKL";
2239 let chain1 = (&testdata[..3]).chain(&testdata[3..6])
2240 .chain(&testdata[6..9])
2241 .chain(&testdata[9..]);
2242 let chain2 = (&testdata[..4]).chain(&testdata[4..8])
2243 .chain(&testdata[8..]);
2244 cmp_bufread(chain1, chain2, &testdata[..]);
2248 fn chain_zero_length_read_is_not_eof() {
2251 let mut s = String::new();
2252 let mut chain = (&a[..]).chain(&b[..]);
2253 chain.read(&mut []).unwrap();
2254 chain.read_to_string(&mut s).unwrap();
2255 assert_eq!("AB", s);
2259 #[cfg_attr(target_os = "emscripten", ignore)]
2260 fn bench_read_to_end(b: &mut test::Bencher) {
2262 let mut lr = repeat(1).take(10000000);
2263 let mut vec = Vec::with_capacity(1024);
2264 super::read_to_end(&mut lr, &mut vec)