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 foo() -> 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 foo() -> 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 foo() -> 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 foo() -> 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 foo() -> 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`] (e.g. `main`). 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 foo() -> 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 foo() -> io::Result<()> {
189 //! let f = File::open("foo.txt")?;
190 //! let reader = BufReader::new(f);
192 //! for line in reader.lines() {
193 //! println!("{}", line?);
202 //! There are a number of [functions][functions-list] that offer access to various
203 //! features. For example, we can use three of these functions to copy everything
204 //! from standard input to standard output:
209 //! # fn foo() -> io::Result<()> {
210 //! io::copy(&mut io::stdin(), &mut io::stdout())?;
215 //! [functions-list]: #functions-1
219 //! Last, but certainly not least, is [`io::Result`]. This type is used
220 //! as the return type of many `std::io` functions that can cause an error, and
221 //! can be returned from your own functions as well. Many of the examples in this
222 //! module use the [`?` operator]:
227 //! fn read_input() -> io::Result<()> {
228 //! let mut input = String::new();
230 //! io::stdin().read_line(&mut input)?;
232 //! println!("You typed: {}", input.trim());
238 //! The return type of `read_input()`, [`io::Result<()>`][`io::Result`], is a very
239 //! common type for functions which don't have a 'real' return value, but do want to
240 //! return errors if they happen. In this case, the only purpose of this function is
241 //! to read the line and print it, so we use `()`.
243 //! ## Platform-specific behavior
245 //! Many I/O functions throughout the standard library are documented to indicate
246 //! what various library or syscalls they are delegated to. This is done to help
247 //! applications both understand what's happening under the hood as well as investigate
248 //! any possibly unclear semantics. Note, however, that this is informative, not a binding
249 //! contract. The implementation of many of these functions are subject to change over
250 //! time and may call fewer or more syscalls/library functions.
252 //! [`Read`]: trait.Read.html
253 //! [`Write`]: trait.Write.html
254 //! [`Seek`]: trait.Seek.html
255 //! [`BufRead`]: trait.BufRead.html
256 //! [`File`]: ../fs/struct.File.html
257 //! [`TcpStream`]: ../net/struct.TcpStream.html
258 //! [`Vec<T>`]: ../vec/struct.Vec.html
259 //! [`BufReader`]: struct.BufReader.html
260 //! [`BufWriter`]: struct.BufWriter.html
261 //! [`Write::write`]: trait.Write.html#tymethod.write
262 //! [`io::stdout`]: fn.stdout.html
263 //! [`println!`]: ../macro.println.html
264 //! [`Lines`]: struct.Lines.html
265 //! [`io::Result`]: type.Result.html
266 //! [`?` operator]: ../../book/first-edition/syntax-index.html
267 //! [`Read::read`]: trait.Read.html#tymethod.read
268 //! [`Result`]: ../result/enum.Result.html
269 //! [`.unwrap()`]: ../result/enum.Result.html#method.unwrap
271 #![stable(feature = "rust1", since = "1.0.0")]
274 use core::str as core_str;
275 use error as std_error;
282 #[stable(feature = "rust1", since = "1.0.0")]
283 pub use self::buffered::{BufReader, BufWriter, LineWriter};
284 #[stable(feature = "rust1", since = "1.0.0")]
285 pub use self::buffered::IntoInnerError;
286 #[stable(feature = "rust1", since = "1.0.0")]
287 pub use self::cursor::Cursor;
288 #[stable(feature = "rust1", since = "1.0.0")]
289 pub use self::error::{Result, Error, ErrorKind};
290 #[stable(feature = "rust1", since = "1.0.0")]
291 pub use self::util::{copy, sink, Sink, empty, Empty, repeat, Repeat};
292 #[stable(feature = "rust1", since = "1.0.0")]
293 pub use self::stdio::{stdin, stdout, stderr, Stdin, Stdout, Stderr};
294 #[stable(feature = "rust1", since = "1.0.0")]
295 pub use self::stdio::{StdoutLock, StderrLock, StdinLock};
296 #[unstable(feature = "print_internals", issue = "0")]
297 pub use self::stdio::{_print, _eprint};
298 #[unstable(feature = "libstd_io_internals", issue = "42788")]
299 #[doc(no_inline, hidden)]
300 pub use self::stdio::{set_panic, set_print};
311 const DEFAULT_BUF_SIZE: usize = ::sys_common::io::DEFAULT_BUF_SIZE;
313 struct Guard<'a> { buf: &'a mut Vec<u8>, len: usize }
315 impl<'a> Drop for Guard<'a> {
317 unsafe { self.buf.set_len(self.len); }
321 // A few methods below (read_to_string, read_line) will append data into a
322 // `String` buffer, but we need to be pretty careful when doing this. The
323 // implementation will just call `.as_mut_vec()` and then delegate to a
324 // byte-oriented reading method, but we must ensure that when returning we never
325 // leave `buf` in a state such that it contains invalid UTF-8 in its bounds.
327 // To this end, we use an RAII guard (to protect against panics) which updates
328 // the length of the string when it is dropped. This guard initially truncates
329 // the string to the prior length and only after we've validated that the
330 // new contents are valid UTF-8 do we allow it to set a longer length.
332 // The unsafety in this function is twofold:
334 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
336 // 2. We're passing a raw buffer to the function `f`, and it is expected that
337 // the function only *appends* bytes to the buffer. We'll get undefined
338 // behavior if existing bytes are overwritten to have non-UTF-8 data.
339 fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
340 where F: FnOnce(&mut Vec<u8>) -> Result<usize>
343 let mut g = Guard { len: buf.len(), buf: buf.as_mut_vec() };
345 if str::from_utf8(&g.buf[g.len..]).is_err() {
347 Err(Error::new(ErrorKind::InvalidData,
348 "stream did not contain valid UTF-8"))
357 // This uses an adaptive system to extend the vector when it fills. We want to
358 // avoid paying to allocate and zero a huge chunk of memory if the reader only
359 // has 4 bytes while still making large reads if the reader does have a ton
360 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
361 // time is 4,500 times (!) slower than this if the reader has a very small
362 // amount of data to return.
364 // Because we're extending the buffer with uninitialized data for trusted
365 // readers, we need to make sure to truncate that if any of this panics.
366 fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
367 let start_len = buf.len();
368 let mut g = Guard { len: buf.len(), buf: buf };
369 let mut new_write_size = 16;
372 if g.len == g.buf.len() {
373 if new_write_size < DEFAULT_BUF_SIZE {
377 g.buf.reserve(new_write_size);
378 g.buf.set_len(g.len + new_write_size);
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`:
422 /// [`read()`]: trait.Read.html#tymethod.read
423 /// [`std::io`]: ../../std/io/index.html
424 /// [`File`]: ../fs/struct.File.html
425 /// [`BufRead`]: trait.BufRead.html
426 /// [`BufReader`]: struct.BufReader.html
430 /// use std::io::prelude::*;
431 /// use std::fs::File;
433 /// # fn foo() -> io::Result<()> {
434 /// let mut f = File::open("foo.txt")?;
435 /// let mut buffer = [0; 10];
437 /// // read up to 10 bytes
438 /// f.read(&mut buffer)?;
440 /// let mut buffer = vec![0; 10];
441 /// // read the whole file
442 /// f.read_to_end(&mut buffer)?;
444 /// // read into a String, so that you don't need to do the conversion.
445 /// let mut buffer = String::new();
446 /// f.read_to_string(&mut buffer)?;
448 /// // and more! See the other methods for more details.
452 #[stable(feature = "rust1", since = "1.0.0")]
454 /// Pull some bytes from this source into the specified buffer, returning
455 /// how many bytes were read.
457 /// This function does not provide any guarantees about whether it blocks
458 /// waiting for data, but if an object needs to block for a read but cannot
459 /// it will typically signal this via an [`Err`] return value.
461 /// If the return value of this method is [`Ok(n)`], then it must be
462 /// guaranteed that `0 <= n <= buf.len()`. A nonzero `n` value indicates
463 /// that the buffer `buf` has been filled in with `n` bytes of data from this
464 /// source. If `n` is `0`, then it can indicate one of two scenarios:
466 /// 1. This reader has reached its "end of file" and will likely no longer
467 /// be able to produce bytes. Note that this does not mean that the
468 /// reader will *always* no longer be able to produce bytes.
469 /// 2. The buffer specified was 0 bytes in length.
471 /// No guarantees are provided about the contents of `buf` when this
472 /// function is called, implementations cannot rely on any property of the
473 /// contents of `buf` being true. It is recommended that implementations
474 /// only write data to `buf` instead of reading its contents.
478 /// If this function encounters any form of I/O or other error, an error
479 /// variant will be returned. If an error is returned then it must be
480 /// guaranteed that no bytes were read.
482 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
483 /// operation should be retried if there is nothing else to do.
487 /// [`File`]s implement `Read`:
489 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
490 /// [`Ok(n)`]: ../../std/result/enum.Result.html#variant.Ok
491 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
492 /// [`File`]: ../fs/struct.File.html
496 /// use std::io::prelude::*;
497 /// use std::fs::File;
499 /// # fn foo() -> io::Result<()> {
500 /// let mut f = File::open("foo.txt")?;
501 /// let mut buffer = [0; 10];
503 /// // read up to 10 bytes
504 /// f.read(&mut buffer[..])?;
508 #[stable(feature = "rust1", since = "1.0.0")]
509 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
511 /// Determines if this `Read`er can work with buffers of uninitialized
514 /// The default implementation returns an initializer which will zero
517 /// If a `Read`er guarantees that it can work properly with uninitialized
518 /// memory, it should call [`Initializer::nop()`]. See the documentation for
519 /// [`Initializer`] for details.
521 /// The behavior of this method must be independent of the state of the
522 /// `Read`er - the method only takes `&self` so that it can be used through
527 /// This method is unsafe because a `Read`er could otherwise return a
528 /// non-zeroing `Initializer` from another `Read` type without an `unsafe`
531 /// [`Initializer::nop()`]: ../../std/io/struct.Initializer.html#method.nop
532 /// [`Initializer`]: ../../std/io/struct.Initializer.html
533 #[unstable(feature = "read_initializer", issue = "42788")]
535 unsafe fn initializer(&self) -> Initializer {
536 Initializer::zeroing()
539 /// Read all bytes until EOF in this source, placing them into `buf`.
541 /// All bytes read from this source will be appended to the specified buffer
542 /// `buf`. This function will continuously call [`read()`] to append more data to
543 /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of
544 /// non-[`ErrorKind::Interrupted`] kind.
546 /// If successful, this function will return the total number of bytes read.
550 /// If this function encounters an error of the kind
551 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
554 /// If any other read error is encountered then this function immediately
555 /// returns. Any bytes which have already been read will be appended to
560 /// [`File`]s implement `Read`:
562 /// [`read()`]: trait.Read.html#tymethod.read
563 /// [`Ok(0)`]: ../../std/result/enum.Result.html#variant.Ok
564 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
565 /// [`File`]: ../fs/struct.File.html
569 /// use std::io::prelude::*;
570 /// use std::fs::File;
572 /// # fn foo() -> io::Result<()> {
573 /// let mut f = File::open("foo.txt")?;
574 /// let mut buffer = Vec::new();
576 /// // read the whole file
577 /// f.read_to_end(&mut buffer)?;
581 #[stable(feature = "rust1", since = "1.0.0")]
582 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
583 read_to_end(self, buf)
586 /// Read all bytes until EOF in this source, placing them into `buf`.
588 /// If successful, this function returns the number of bytes which were read
589 /// and appended to `buf`.
593 /// If the data in this stream is *not* valid UTF-8 then an error is
594 /// returned and `buf` is unchanged.
596 /// See [`read_to_end`][readtoend] for other error semantics.
598 /// [readtoend]: #method.read_to_end
602 /// [`File`][file]s implement `Read`:
604 /// [file]: ../fs/struct.File.html
608 /// use std::io::prelude::*;
609 /// use std::fs::File;
611 /// # fn foo() -> io::Result<()> {
612 /// let mut f = File::open("foo.txt")?;
613 /// let mut buffer = String::new();
615 /// f.read_to_string(&mut buffer)?;
619 #[stable(feature = "rust1", since = "1.0.0")]
620 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
621 // Note that we do *not* call `.read_to_end()` here. We are passing
622 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
623 // method to fill it up. An arbitrary implementation could overwrite the
624 // entire contents of the vector, not just append to it (which is what
625 // we are expecting).
627 // To prevent extraneously checking the UTF-8-ness of the entire buffer
628 // we pass it to our hardcoded `read_to_end` implementation which we
629 // know is guaranteed to only read data into the end of the buffer.
630 append_to_string(buf, |b| read_to_end(self, b))
633 /// Read the exact number of bytes required to fill `buf`.
635 /// This function reads as many bytes as necessary to completely fill the
636 /// specified buffer `buf`.
638 /// No guarantees are provided about the contents of `buf` when this
639 /// function is called, implementations cannot rely on any property of the
640 /// contents of `buf` being true. It is recommended that implementations
641 /// only write data to `buf` instead of reading its contents.
645 /// If this function encounters an error of the kind
646 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
649 /// If this function encounters an "end of file" before completely filling
650 /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
651 /// The contents of `buf` are unspecified in this case.
653 /// If any other read error is encountered then this function immediately
654 /// returns. The contents of `buf` are unspecified in this case.
656 /// If this function returns an error, it is unspecified how many bytes it
657 /// has read, but it will never read more than would be necessary to
658 /// completely fill the buffer.
662 /// [`File`]s implement `Read`:
664 /// [`File`]: ../fs/struct.File.html
665 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
666 /// [`ErrorKind::UnexpectedEof`]: ../../std/io/enum.ErrorKind.html#variant.UnexpectedEof
670 /// use std::io::prelude::*;
671 /// use std::fs::File;
673 /// # fn foo() -> io::Result<()> {
674 /// let mut f = File::open("foo.txt")?;
675 /// let mut buffer = [0; 10];
677 /// // read exactly 10 bytes
678 /// f.read_exact(&mut buffer)?;
682 #[stable(feature = "read_exact", since = "1.6.0")]
683 fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
684 while !buf.is_empty() {
685 match self.read(buf) {
687 Ok(n) => { let tmp = buf; buf = &mut tmp[n..]; }
688 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
689 Err(e) => return Err(e),
693 Err(Error::new(ErrorKind::UnexpectedEof,
694 "failed to fill whole buffer"))
700 /// Creates a "by reference" adaptor for this instance of `Read`.
702 /// The returned adaptor also implements `Read` and will simply borrow this
707 /// [`File`][file]s implement `Read`:
709 /// [file]: ../fs/struct.File.html
713 /// use std::io::Read;
714 /// use std::fs::File;
716 /// # fn foo() -> io::Result<()> {
717 /// let mut f = File::open("foo.txt")?;
718 /// let mut buffer = Vec::new();
719 /// let mut other_buffer = Vec::new();
722 /// let reference = f.by_ref();
724 /// // read at most 5 bytes
725 /// reference.take(5).read_to_end(&mut buffer)?;
727 /// } // drop our &mut reference so we can use f again
729 /// // original file still usable, read the rest
730 /// f.read_to_end(&mut other_buffer)?;
734 #[stable(feature = "rust1", since = "1.0.0")]
735 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
737 /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
739 /// The returned type implements [`Iterator`] where the `Item` is [`Result`]`<`[`u8`]`,
740 /// R::Err>`. The yielded item is [`Ok`] if a byte was successfully read and
741 /// [`Err`] otherwise for I/O errors. EOF is mapped to returning [`None`] from
746 /// [`File`][file]s implement `Read`:
748 /// [file]: ../fs/struct.File.html
749 /// [`Iterator`]: ../../std/iter/trait.Iterator.html
750 /// [`Result`]: ../../std/result/enum.Result.html
751 /// [`u8`]: ../../std/primitive.u8.html
752 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
753 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
754 /// [`None`]: ../../std/option/enum.Option.html#variant.None
758 /// use std::io::prelude::*;
759 /// use std::fs::File;
761 /// # fn foo() -> io::Result<()> {
762 /// let mut f = File::open("foo.txt")?;
764 /// for byte in f.bytes() {
765 /// println!("{}", byte.unwrap());
770 #[stable(feature = "rust1", since = "1.0.0")]
771 fn bytes(self) -> Bytes<Self> where Self: Sized {
772 Bytes { inner: self }
775 /// Transforms this `Read` instance to an [`Iterator`] over [`char`]s.
777 /// This adaptor will attempt to interpret this reader as a UTF-8 encoded
778 /// sequence of characters. The returned iterator will return [`None`] once
779 /// EOF is reached for this reader. Otherwise each element yielded will be a
780 /// [`Result`]`<`[`char`]`, E>` where `E` may contain information about what I/O error
781 /// occurred or where decoding failed.
783 /// Currently this adaptor will discard intermediate data read, and should
784 /// be avoided if this is not desired.
788 /// [`File`]s implement `Read`:
790 /// [`File`]: ../fs/struct.File.html
791 /// [`Iterator`]: ../../std/iter/trait.Iterator.html
792 /// [`Result`]: ../../std/result/enum.Result.html
793 /// [`char`]: ../../std/primitive.char.html
794 /// [`None`]: ../../std/option/enum.Option.html#variant.None
799 /// use std::io::prelude::*;
800 /// use std::fs::File;
802 /// # fn foo() -> io::Result<()> {
803 /// let mut f = File::open("foo.txt")?;
805 /// for c in f.chars() {
806 /// println!("{}", c.unwrap());
811 #[unstable(feature = "io", reason = "the semantics of a partial read/write \
812 of where errors happen is currently \
813 unclear and may change",
815 fn chars(self) -> Chars<Self> where Self: Sized {
816 Chars { inner: self }
819 /// Creates an adaptor which will chain this stream with another.
821 /// The returned `Read` instance will first read all bytes from this object
822 /// until EOF is encountered. Afterwards the output is equivalent to the
823 /// output of `next`.
827 /// [`File`][file]s implement `Read`:
829 /// [file]: ../fs/struct.File.html
833 /// use std::io::prelude::*;
834 /// use std::fs::File;
836 /// # fn foo() -> io::Result<()> {
837 /// let mut f1 = File::open("foo.txt")?;
838 /// let mut f2 = File::open("bar.txt")?;
840 /// let mut handle = f1.chain(f2);
841 /// let mut buffer = String::new();
843 /// // read the value into a String. We could use any Read method here,
844 /// // this is just one example.
845 /// handle.read_to_string(&mut buffer)?;
849 #[stable(feature = "rust1", since = "1.0.0")]
850 fn chain<R: Read>(self, next: R) -> Chain<Self, R> where Self: Sized {
851 Chain { first: self, second: next, done_first: false }
854 /// Creates an adaptor which will read at most `limit` bytes from it.
856 /// This function returns a new instance of `Read` which will read at most
857 /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
858 /// read errors will not count towards the number of bytes read and future
859 /// calls to [`read()`] may succeed.
863 /// [`File`]s implement `Read`:
865 /// [`File`]: ../fs/struct.File.html
866 /// [`Ok(0)`]: ../../std/result/enum.Result.html#variant.Ok
867 /// [`read()`]: trait.Read.html#tymethod.read
871 /// use std::io::prelude::*;
872 /// use std::fs::File;
874 /// # fn foo() -> io::Result<()> {
875 /// let mut f = File::open("foo.txt")?;
876 /// let mut buffer = [0; 5];
878 /// // read at most five bytes
879 /// let mut handle = f.take(5);
881 /// handle.read(&mut buffer)?;
885 #[stable(feature = "rust1", since = "1.0.0")]
886 fn take(self, limit: u64) -> Take<Self> where Self: Sized {
887 Take { inner: self, limit: limit }
891 /// A type used to conditionally initialize buffers passed to `Read` methods.
892 #[unstable(feature = "read_initializer", issue = "42788")]
894 pub struct Initializer(bool);
897 /// Returns a new `Initializer` which will zero out buffers.
898 #[unstable(feature = "read_initializer", issue = "42788")]
900 pub fn zeroing() -> Initializer {
904 /// Returns a new `Initializer` which will not zero out buffers.
908 /// This may only be called by `Read`ers which guarantee that they will not
909 /// read from buffers passed to `Read` methods, and that the return value of
910 /// the method accurately reflects the number of bytes that have been
911 /// written to the head of the buffer.
912 #[unstable(feature = "read_initializer", issue = "42788")]
914 pub unsafe fn nop() -> Initializer {
918 /// Indicates if a buffer should be initialized.
919 #[unstable(feature = "read_initializer", issue = "42788")]
921 pub fn should_initialize(&self) -> bool {
925 /// Initializes a buffer if necessary.
926 #[unstable(feature = "read_initializer", issue = "42788")]
928 pub fn initialize(&self, buf: &mut [u8]) {
929 if self.should_initialize() {
930 unsafe { ptr::write_bytes(buf.as_mut_ptr(), 0, buf.len()) }
935 /// A trait for objects which are byte-oriented sinks.
937 /// Implementors of the `Write` trait are sometimes called 'writers'.
939 /// Writers are defined by two required methods, [`write`] and [`flush`]:
941 /// * The [`write`] method will attempt to write some data into the object,
942 /// returning how many bytes were successfully written.
944 /// * The [`flush`] method is useful for adaptors and explicit buffers
945 /// themselves for ensuring that all buffered data has been pushed out to the
948 /// Writers are intended to be composable with one another. Many implementors
949 /// throughout [`std::io`] take and provide types which implement the `Write`
952 /// [`write`]: #tymethod.write
953 /// [`flush`]: #tymethod.flush
954 /// [`std::io`]: index.html
959 /// use std::io::prelude::*;
960 /// use std::fs::File;
962 /// # fn foo() -> std::io::Result<()> {
963 /// let mut buffer = File::create("foo.txt")?;
965 /// buffer.write(b"some bytes")?;
969 #[stable(feature = "rust1", since = "1.0.0")]
971 /// Write a buffer into this object, returning how many bytes were written.
973 /// This function will attempt to write the entire contents of `buf`, but
974 /// the entire write may not succeed, or the write may also generate an
975 /// error. A call to `write` represents *at most one* attempt to write to
976 /// any wrapped object.
978 /// Calls to `write` are not guaranteed to block waiting for data to be
979 /// written, and a write which would otherwise block can be indicated through
980 /// an `Err` variant.
982 /// If the return value is `Ok(n)` then it must be guaranteed that
983 /// `0 <= n <= buf.len()`. A return value of `0` typically means that the
984 /// underlying object is no longer able to accept bytes and will likely not
985 /// be able to in the future as well, or that the buffer provided is empty.
989 /// Each call to `write` may generate an I/O error indicating that the
990 /// operation could not be completed. If an error is returned then no bytes
991 /// in the buffer were written to this writer.
993 /// It is **not** considered an error if the entire buffer could not be
994 /// written to this writer.
996 /// An error of the `ErrorKind::Interrupted` kind is non-fatal and the
997 /// write operation should be retried if there is nothing else to do.
1002 /// use std::io::prelude::*;
1003 /// use std::fs::File;
1005 /// # fn foo() -> std::io::Result<()> {
1006 /// let mut buffer = File::create("foo.txt")?;
1008 /// // Writes some prefix of the byte string, not necessarily all of it.
1009 /// buffer.write(b"some bytes")?;
1013 #[stable(feature = "rust1", since = "1.0.0")]
1014 fn write(&mut self, buf: &[u8]) -> Result<usize>;
1016 /// Flush this output stream, ensuring that all intermediately buffered
1017 /// contents reach their destination.
1021 /// It is considered an error if not all bytes could be written due to
1022 /// I/O errors or EOF being reached.
1027 /// use std::io::prelude::*;
1028 /// use std::io::BufWriter;
1029 /// use std::fs::File;
1031 /// # fn foo() -> std::io::Result<()> {
1032 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
1034 /// buffer.write(b"some bytes")?;
1035 /// buffer.flush()?;
1039 #[stable(feature = "rust1", since = "1.0.0")]
1040 fn flush(&mut self) -> Result<()>;
1042 /// Attempts to write an entire buffer into this write.
1044 /// This method will continuously call `write` until there is no more data
1045 /// to be written or an error of non-`ErrorKind::Interrupted` kind is
1046 /// returned. This method will not return until the entire buffer has been
1047 /// successfully written or such an error occurs. The first error that is
1048 /// not of `ErrorKind::Interrupted` kind generated from this method will be
1053 /// This function will return the first error of
1054 /// non-`ErrorKind::Interrupted` kind that `write` returns.
1059 /// use std::io::prelude::*;
1060 /// use std::fs::File;
1062 /// # fn foo() -> std::io::Result<()> {
1063 /// let mut buffer = File::create("foo.txt")?;
1065 /// buffer.write_all(b"some bytes")?;
1069 #[stable(feature = "rust1", since = "1.0.0")]
1070 fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
1071 while !buf.is_empty() {
1072 match self.write(buf) {
1073 Ok(0) => return Err(Error::new(ErrorKind::WriteZero,
1074 "failed to write whole buffer")),
1075 Ok(n) => buf = &buf[n..],
1076 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1077 Err(e) => return Err(e),
1083 /// Writes a formatted string into this writer, returning any error
1086 /// This method is primarily used to interface with the
1087 /// [`format_args!`][formatargs] macro, but it is rare that this should
1088 /// explicitly be called. The [`write!`][write] macro should be favored to
1089 /// invoke this method instead.
1091 /// [formatargs]: ../macro.format_args.html
1092 /// [write]: ../macro.write.html
1094 /// This function internally uses the [`write_all`][writeall] method on
1095 /// this trait and hence will continuously write data so long as no errors
1096 /// are received. This also means that partial writes are not indicated in
1099 /// [writeall]: #method.write_all
1103 /// This function will return any I/O error reported while formatting.
1108 /// use std::io::prelude::*;
1109 /// use std::fs::File;
1111 /// # fn foo() -> std::io::Result<()> {
1112 /// let mut buffer = File::create("foo.txt")?;
1115 /// write!(buffer, "{:.*}", 2, 1.234567)?;
1116 /// // turns into this:
1117 /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1121 #[stable(feature = "rust1", since = "1.0.0")]
1122 fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()> {
1123 // Create a shim which translates a Write to a fmt::Write and saves
1124 // off I/O errors. instead of discarding them
1125 struct Adaptor<'a, T: ?Sized + 'a> {
1130 impl<'a, T: Write + ?Sized> fmt::Write for Adaptor<'a, T> {
1131 fn write_str(&mut self, s: &str) -> fmt::Result {
1132 match self.inner.write_all(s.as_bytes()) {
1135 self.error = Err(e);
1142 let mut output = Adaptor { inner: self, error: Ok(()) };
1143 match fmt::write(&mut output, fmt) {
1146 // check if the error came from the underlying `Write` or not
1147 if output.error.is_err() {
1150 Err(Error::new(ErrorKind::Other, "formatter error"))
1156 /// Creates a "by reference" adaptor for this instance of `Write`.
1158 /// The returned adaptor also implements `Write` and will simply borrow this
1164 /// use std::io::Write;
1165 /// use std::fs::File;
1167 /// # fn foo() -> std::io::Result<()> {
1168 /// let mut buffer = File::create("foo.txt")?;
1170 /// let reference = buffer.by_ref();
1172 /// // we can use reference just like our original buffer
1173 /// reference.write_all(b"some bytes")?;
1177 #[stable(feature = "rust1", since = "1.0.0")]
1178 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1181 /// The `Seek` trait provides a cursor which can be moved within a stream of
1184 /// The stream typically has a fixed size, allowing seeking relative to either
1185 /// end or the current offset.
1189 /// [`File`][file]s implement `Seek`:
1191 /// [file]: ../fs/struct.File.html
1195 /// use std::io::prelude::*;
1196 /// use std::fs::File;
1197 /// use std::io::SeekFrom;
1199 /// # fn foo() -> io::Result<()> {
1200 /// let mut f = File::open("foo.txt")?;
1202 /// // move the cursor 42 bytes from the start of the file
1203 /// f.seek(SeekFrom::Start(42))?;
1207 #[stable(feature = "rust1", since = "1.0.0")]
1209 /// Seek to an offset, in bytes, in a stream.
1211 /// A seek beyond the end of a stream is allowed, but implementation
1214 /// If the seek operation completed successfully,
1215 /// this method returns the new position from the start of the stream.
1216 /// That position can be used later with [`SeekFrom::Start`].
1220 /// Seeking to a negative offset is considered an error.
1222 /// [`SeekFrom::Start`]: enum.SeekFrom.html#variant.Start
1223 #[stable(feature = "rust1", since = "1.0.0")]
1224 fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1227 /// Enumeration of possible methods to seek within an I/O object.
1229 /// It is used by the [`Seek`] trait.
1231 /// [`Seek`]: trait.Seek.html
1232 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1233 #[stable(feature = "rust1", since = "1.0.0")]
1235 /// Set the offset to the provided number of bytes.
1236 #[stable(feature = "rust1", since = "1.0.0")]
1237 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1239 /// Set the offset to the size of this object plus the specified number of
1242 /// It is possible to seek beyond the end of an object, but it's an error to
1243 /// seek before byte 0.
1244 #[stable(feature = "rust1", since = "1.0.0")]
1245 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1247 /// Set the offset to the current position plus the specified number of
1250 /// It is possible to seek beyond the end of an object, but it's an error to
1251 /// seek before byte 0.
1252 #[stable(feature = "rust1", since = "1.0.0")]
1253 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1256 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>)
1260 let (done, used) = {
1261 let available = match r.fill_buf() {
1263 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1264 Err(e) => return Err(e)
1266 match memchr::memchr(delim, available) {
1268 buf.extend_from_slice(&available[..i + 1]);
1272 buf.extend_from_slice(available);
1273 (false, available.len())
1279 if done || used == 0 {
1285 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1286 /// to perform extra ways of reading.
1288 /// For example, reading line-by-line is inefficient without using a buffer, so
1289 /// if you want to read by line, you'll need `BufRead`, which includes a
1290 /// [`read_line`] method as well as a [`lines`] iterator.
1294 /// A locked standard input implements `BufRead`:
1298 /// use std::io::prelude::*;
1300 /// let stdin = io::stdin();
1301 /// for line in stdin.lock().lines() {
1302 /// println!("{}", line.unwrap());
1306 /// If you have something that implements [`Read`], you can use the [`BufReader`
1307 /// type][`BufReader`] to turn it into a `BufRead`.
1309 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1310 /// [`BufReader`] to the rescue!
1312 /// [`BufReader`]: struct.BufReader.html
1313 /// [`File`]: ../fs/struct.File.html
1314 /// [`read_line`]: #method.read_line
1315 /// [`lines`]: #method.lines
1316 /// [`Read`]: trait.Read.html
1319 /// use std::io::{self, BufReader};
1320 /// use std::io::prelude::*;
1321 /// use std::fs::File;
1323 /// # fn foo() -> io::Result<()> {
1324 /// let f = File::open("foo.txt")?;
1325 /// let f = BufReader::new(f);
1327 /// for line in f.lines() {
1328 /// println!("{}", line.unwrap());
1335 #[stable(feature = "rust1", since = "1.0.0")]
1336 pub trait BufRead: Read {
1337 /// Fills the internal buffer of this object, returning the buffer contents.
1339 /// This function is a lower-level call. It needs to be paired with the
1340 /// [`consume`] method to function properly. When calling this
1341 /// method, none of the contents will be "read" in the sense that later
1342 /// calling `read` may return the same contents. As such, [`consume`] must
1343 /// be called with the number of bytes that are consumed from this buffer to
1344 /// ensure that the bytes are never returned twice.
1346 /// [`consume`]: #tymethod.consume
1348 /// An empty buffer returned indicates that the stream has reached EOF.
1352 /// This function will return an I/O error if the underlying reader was
1353 /// read, but returned an error.
1357 /// A locked standard input implements `BufRead`:
1361 /// use std::io::prelude::*;
1363 /// let stdin = io::stdin();
1364 /// let mut stdin = stdin.lock();
1366 /// // we can't have two `&mut` references to `stdin`, so use a block
1367 /// // to end the borrow early.
1369 /// let buffer = stdin.fill_buf().unwrap();
1371 /// // work with buffer
1372 /// println!("{:?}", buffer);
1377 /// // ensure the bytes we worked with aren't returned again later
1378 /// stdin.consume(length);
1380 #[stable(feature = "rust1", since = "1.0.0")]
1381 fn fill_buf(&mut self) -> Result<&[u8]>;
1383 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1384 /// so they should no longer be returned in calls to `read`.
1386 /// This function is a lower-level call. It needs to be paired with the
1387 /// [`fill_buf`] method to function properly. This function does
1388 /// not perform any I/O, it simply informs this object that some amount of
1389 /// its buffer, returned from [`fill_buf`], has been consumed and should
1390 /// no longer be returned. As such, this function may do odd things if
1391 /// [`fill_buf`] isn't called before calling it.
1393 /// The `amt` must be `<=` the number of bytes in the buffer returned by
1398 /// Since `consume()` is meant to be used with [`fill_buf`],
1399 /// that method's example includes an example of `consume()`.
1401 /// [`fill_buf`]: #tymethod.fill_buf
1402 #[stable(feature = "rust1", since = "1.0.0")]
1403 fn consume(&mut self, amt: usize);
1405 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
1407 /// This function will read bytes from the underlying stream until the
1408 /// delimiter or EOF is found. Once found, all bytes up to, and including,
1409 /// the delimiter (if found) will be appended to `buf`.
1411 /// If successful, this function will return the total number of bytes read.
1415 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1416 /// will otherwise return any errors returned by [`fill_buf`].
1418 /// If an I/O error is encountered then all bytes read so far will be
1419 /// present in `buf` and its length will have been adjusted appropriately.
1421 /// [`fill_buf`]: #tymethod.fill_buf
1422 /// [`ErrorKind::Interrupted`]: enum.ErrorKind.html#variant.Interrupted
1426 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1427 /// this example, we use [`Cursor`] to read all the bytes in a byte slice
1428 /// in hyphen delimited segments:
1430 /// [`Cursor`]: struct.Cursor.html
1433 /// use std::io::{self, BufRead};
1435 /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
1436 /// let mut buf = vec![];
1438 /// // cursor is at 'l'
1439 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1440 /// .expect("reading from cursor won't fail");
1441 /// assert_eq!(num_bytes, 6);
1442 /// assert_eq!(buf, b"lorem-");
1445 /// // cursor is at 'i'
1446 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1447 /// .expect("reading from cursor won't fail");
1448 /// assert_eq!(num_bytes, 5);
1449 /// assert_eq!(buf, b"ipsum");
1452 /// // cursor is at EOF
1453 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1454 /// .expect("reading from cursor won't fail");
1455 /// assert_eq!(num_bytes, 0);
1456 /// assert_eq!(buf, b"");
1458 #[stable(feature = "rust1", since = "1.0.0")]
1459 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
1460 read_until(self, byte, buf)
1463 /// Read all bytes until a newline (the 0xA byte) is reached, and append
1464 /// them to the provided buffer.
1466 /// This function will read bytes from the underlying stream until the
1467 /// newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes
1468 /// up to, and including, the delimiter (if found) will be appended to
1471 /// If successful, this function will return the total number of bytes read.
1475 /// This function has the same error semantics as [`read_until`] and will
1476 /// also return an error if the read bytes are not valid UTF-8. If an I/O
1477 /// error is encountered then `buf` may contain some bytes already read in
1478 /// the event that all data read so far was valid UTF-8.
1482 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1483 /// this example, we use [`Cursor`] to read all the lines in a byte slice:
1485 /// [`Cursor`]: struct.Cursor.html
1488 /// use std::io::{self, BufRead};
1490 /// let mut cursor = io::Cursor::new(b"foo\nbar");
1491 /// let mut buf = String::new();
1493 /// // cursor is at 'f'
1494 /// let num_bytes = cursor.read_line(&mut buf)
1495 /// .expect("reading from cursor won't fail");
1496 /// assert_eq!(num_bytes, 4);
1497 /// assert_eq!(buf, "foo\n");
1500 /// // cursor is at 'b'
1501 /// let num_bytes = cursor.read_line(&mut buf)
1502 /// .expect("reading from cursor won't fail");
1503 /// assert_eq!(num_bytes, 3);
1504 /// assert_eq!(buf, "bar");
1507 /// // cursor is at EOF
1508 /// let num_bytes = cursor.read_line(&mut buf)
1509 /// .expect("reading from cursor won't fail");
1510 /// assert_eq!(num_bytes, 0);
1511 /// assert_eq!(buf, "");
1513 #[stable(feature = "rust1", since = "1.0.0")]
1514 fn read_line(&mut self, buf: &mut String) -> Result<usize> {
1515 // Note that we are not calling the `.read_until` method here, but
1516 // rather our hardcoded implementation. For more details as to why, see
1517 // the comments in `read_to_end`.
1518 append_to_string(buf, |b| read_until(self, b'\n', b))
1521 /// Returns an iterator over the contents of this reader split on the byte
1524 /// The iterator returned from this function will return instances of
1525 /// [`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
1526 /// the delimiter byte at the end.
1528 /// This function will yield errors whenever [`read_until`] would have
1529 /// also yielded an error.
1531 /// [`io::Result`]: type.Result.html
1532 /// [`Vec<u8>`]: ../vec/struct.Vec.html
1533 /// [`read_until`]: #method.read_until
1537 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1538 /// this example, we use [`Cursor`] to iterate over all hyphen delimited
1539 /// segments in a byte slice
1541 /// [`Cursor`]: struct.Cursor.html
1544 /// use std::io::{self, BufRead};
1546 /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
1548 /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
1549 /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
1550 /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
1551 /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
1552 /// assert_eq!(split_iter.next(), None);
1554 #[stable(feature = "rust1", since = "1.0.0")]
1555 fn split(self, byte: u8) -> Split<Self> where Self: Sized {
1556 Split { buf: self, delim: byte }
1559 /// Returns an iterator over the lines of this reader.
1561 /// The iterator returned from this function will yield instances of
1562 /// [`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline
1563 /// byte (the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.
1565 /// [`io::Result`]: type.Result.html
1566 /// [`String`]: ../string/struct.String.html
1570 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1571 /// this example, we use [`Cursor`] to iterate over all the lines in a byte
1574 /// [`Cursor`]: struct.Cursor.html
1577 /// use std::io::{self, BufRead};
1579 /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
1581 /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
1582 /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
1583 /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
1584 /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
1585 /// assert_eq!(lines_iter.next(), None);
1590 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
1592 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
1593 #[stable(feature = "rust1", since = "1.0.0")]
1594 fn lines(self) -> Lines<Self> where Self: Sized {
1599 /// Adaptor to chain together two readers.
1601 /// This struct is generally created by calling [`chain`] on a reader.
1602 /// Please see the documentation of [`chain`] for more details.
1604 /// [`chain`]: trait.Read.html#method.chain
1605 #[stable(feature = "rust1", since = "1.0.0")]
1606 pub struct Chain<T, U> {
1612 impl<T, U> Chain<T, U> {
1613 /// Consumes the `Chain`, returning the wrapped readers.
1619 /// use std::io::prelude::*;
1620 /// use std::fs::File;
1622 /// # fn foo() -> io::Result<()> {
1623 /// let mut foo_file = File::open("foo.txt")?;
1624 /// let mut bar_file = File::open("bar.txt")?;
1626 /// let chain = foo_file.chain(bar_file);
1627 /// let (foo_file, bar_file) = chain.into_inner();
1631 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1632 pub fn into_inner(self) -> (T, U) {
1633 (self.first, self.second)
1636 /// Gets references to the underlying readers in this `Chain`.
1642 /// use std::io::prelude::*;
1643 /// use std::fs::File;
1645 /// # fn foo() -> io::Result<()> {
1646 /// let mut foo_file = File::open("foo.txt")?;
1647 /// let mut bar_file = File::open("bar.txt")?;
1649 /// let chain = foo_file.chain(bar_file);
1650 /// let (foo_file, bar_file) = chain.get_ref();
1654 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1655 pub fn get_ref(&self) -> (&T, &U) {
1656 (&self.first, &self.second)
1659 /// Gets mutable references to the underlying readers in this `Chain`.
1661 /// Care should be taken to avoid modifying the internal I/O state of the
1662 /// underlying readers as doing so may corrupt the internal state of this
1669 /// use std::io::prelude::*;
1670 /// use std::fs::File;
1672 /// # fn foo() -> io::Result<()> {
1673 /// let mut foo_file = File::open("foo.txt")?;
1674 /// let mut bar_file = File::open("bar.txt")?;
1676 /// let mut chain = foo_file.chain(bar_file);
1677 /// let (foo_file, bar_file) = chain.get_mut();
1681 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1682 pub fn get_mut(&mut self) -> (&mut T, &mut U) {
1683 (&mut self.first, &mut self.second)
1687 #[stable(feature = "std_debug", since = "1.16.0")]
1688 impl<T: fmt::Debug, U: fmt::Debug> fmt::Debug for Chain<T, U> {
1689 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1690 f.debug_struct("Chain")
1691 .field("t", &self.first)
1692 .field("u", &self.second)
1697 #[stable(feature = "rust1", since = "1.0.0")]
1698 impl<T: Read, U: Read> Read for Chain<T, U> {
1699 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1700 if !self.done_first {
1701 match self.first.read(buf)? {
1702 0 if buf.len() != 0 => { self.done_first = true; }
1706 self.second.read(buf)
1709 unsafe fn initializer(&self) -> Initializer {
1710 let initializer = self.first.initializer();
1711 if initializer.should_initialize() {
1714 self.second.initializer()
1719 #[stable(feature = "chain_bufread", since = "1.9.0")]
1720 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
1721 fn fill_buf(&mut self) -> Result<&[u8]> {
1722 if !self.done_first {
1723 match self.first.fill_buf()? {
1724 buf if buf.len() == 0 => { self.done_first = true; }
1725 buf => return Ok(buf),
1728 self.second.fill_buf()
1731 fn consume(&mut self, amt: usize) {
1732 if !self.done_first {
1733 self.first.consume(amt)
1735 self.second.consume(amt)
1740 /// Reader adaptor which limits the bytes read from an underlying reader.
1742 /// This struct is generally created by calling [`take`] on a reader.
1743 /// Please see the documentation of [`take`] for more details.
1745 /// [`take`]: trait.Read.html#method.take
1746 #[stable(feature = "rust1", since = "1.0.0")]
1748 pub struct Take<T> {
1754 /// Returns the number of bytes that can be read before this instance will
1759 /// This instance may reach `EOF` after reading fewer bytes than indicated by
1760 /// this method if the underlying [`Read`] instance reaches EOF.
1762 /// [`Read`]: ../../std/io/trait.Read.html
1768 /// use std::io::prelude::*;
1769 /// use std::fs::File;
1771 /// # fn foo() -> io::Result<()> {
1772 /// let f = File::open("foo.txt")?;
1774 /// // read at most five bytes
1775 /// let handle = f.take(5);
1777 /// println!("limit: {}", handle.limit());
1781 #[stable(feature = "rust1", since = "1.0.0")]
1782 pub fn limit(&self) -> u64 { self.limit }
1784 /// Sets the number of bytes that can be read before this instance will
1785 /// return EOF. This is the same as constructing a new `Take` instance, so
1786 /// the amount of bytes read and the previous limit value don't matter when
1787 /// calling this method.
1792 /// #![feature(take_set_limit)]
1794 /// use std::io::prelude::*;
1795 /// use std::fs::File;
1797 /// # fn foo() -> 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 #[unstable(feature = "take_set_limit", issue = "42781")]
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 foo() -> 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 foo() -> 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 foo() -> 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()
1912 #[stable(feature = "rust1", since = "1.0.0")]
1913 impl<T: BufRead> BufRead for Take<T> {
1914 fn fill_buf(&mut self) -> Result<&[u8]> {
1915 // Don't call into inner reader at all at EOF because it may still block
1916 if self.limit == 0 {
1920 let buf = self.inner.fill_buf()?;
1921 let cap = cmp::min(buf.len() as u64, self.limit) as usize;
1925 fn consume(&mut self, amt: usize) {
1926 // Don't let callers reset the limit by passing an overlarge value
1927 let amt = cmp::min(amt as u64, self.limit) as usize;
1928 self.limit -= amt as u64;
1929 self.inner.consume(amt);
1933 fn read_one_byte(reader: &mut Read) -> Option<Result<u8>> {
1936 return match reader.read(&mut buf) {
1938 Ok(..) => Some(Ok(buf[0])),
1939 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1940 Err(e) => Some(Err(e)),
1945 /// An iterator over `u8` values of a reader.
1947 /// This struct is generally created by calling [`bytes`] on a reader.
1948 /// Please see the documentation of [`bytes`] for more details.
1950 /// [`bytes`]: trait.Read.html#method.bytes
1951 #[stable(feature = "rust1", since = "1.0.0")]
1953 pub struct Bytes<R> {
1957 #[stable(feature = "rust1", since = "1.0.0")]
1958 impl<R: Read> Iterator for Bytes<R> {
1959 type Item = Result<u8>;
1961 fn next(&mut self) -> Option<Result<u8>> {
1962 read_one_byte(&mut self.inner)
1966 /// An iterator over the `char`s of a reader.
1968 /// This struct is generally created by calling [`chars`][chars] on a reader.
1969 /// Please see the documentation of `chars()` for more details.
1971 /// [chars]: trait.Read.html#method.chars
1972 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1975 pub struct Chars<R> {
1979 /// An enumeration of possible errors that can be generated from the `Chars`
1982 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1984 pub enum CharsError {
1985 /// Variant representing that the underlying stream was read successfully
1986 /// but it did not contain valid utf8 data.
1989 /// Variant representing that an I/O error occurred.
1993 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1995 impl<R: Read> Iterator for Chars<R> {
1996 type Item = result::Result<char, CharsError>;
1998 fn next(&mut self) -> Option<result::Result<char, CharsError>> {
1999 let first_byte = match read_one_byte(&mut self.inner) {
2000 None => return None,
2002 Some(Err(e)) => return Some(Err(CharsError::Other(e))),
2004 let width = core_str::utf8_char_width(first_byte);
2005 if width == 1 { return Some(Ok(first_byte as char)) }
2006 if width == 0 { return Some(Err(CharsError::NotUtf8)) }
2007 let mut buf = [first_byte, 0, 0, 0];
2010 while start < width {
2011 match self.inner.read(&mut buf[start..width]) {
2012 Ok(0) => return Some(Err(CharsError::NotUtf8)),
2013 Ok(n) => start += n,
2014 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
2015 Err(e) => return Some(Err(CharsError::Other(e))),
2019 Some(match str::from_utf8(&buf[..width]).ok() {
2020 Some(s) => Ok(s.chars().next().unwrap()),
2021 None => Err(CharsError::NotUtf8),
2026 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
2028 impl std_error::Error for CharsError {
2029 fn description(&self) -> &str {
2031 CharsError::NotUtf8 => "invalid utf8 encoding",
2032 CharsError::Other(ref e) => std_error::Error::description(e),
2035 fn cause(&self) -> Option<&std_error::Error> {
2037 CharsError::NotUtf8 => None,
2038 CharsError::Other(ref e) => e.cause(),
2043 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
2045 impl fmt::Display for CharsError {
2046 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2048 CharsError::NotUtf8 => {
2049 "byte stream did not contain valid utf8".fmt(f)
2051 CharsError::Other(ref e) => e.fmt(f),
2056 /// An iterator over the contents of an instance of `BufRead` split on a
2057 /// particular byte.
2059 /// This struct is generally created by calling [`split`][split] on a
2060 /// `BufRead`. Please see the documentation of `split()` for more details.
2062 /// [split]: trait.BufRead.html#method.split
2063 #[stable(feature = "rust1", since = "1.0.0")]
2065 pub struct Split<B> {
2070 #[stable(feature = "rust1", since = "1.0.0")]
2071 impl<B: BufRead> Iterator for Split<B> {
2072 type Item = Result<Vec<u8>>;
2074 fn next(&mut self) -> Option<Result<Vec<u8>>> {
2075 let mut buf = Vec::new();
2076 match self.buf.read_until(self.delim, &mut buf) {
2079 if buf[buf.len() - 1] == self.delim {
2084 Err(e) => Some(Err(e))
2089 /// An iterator over the lines of an instance of `BufRead`.
2091 /// This struct is generally created by calling [`lines`][lines] on a
2092 /// `BufRead`. Please see the documentation of `lines()` for more details.
2094 /// [lines]: trait.BufRead.html#method.lines
2095 #[stable(feature = "rust1", since = "1.0.0")]
2097 pub struct Lines<B> {
2101 #[stable(feature = "rust1", since = "1.0.0")]
2102 impl<B: BufRead> Iterator for Lines<B> {
2103 type Item = Result<String>;
2105 fn next(&mut self) -> Option<Result<String>> {
2106 let mut buf = String::new();
2107 match self.buf.read_line(&mut buf) {
2110 if buf.ends_with("\n") {
2112 if buf.ends_with("\r") {
2118 Err(e) => Some(Err(e))
2132 #[cfg_attr(target_os = "emscripten", ignore)]
2134 let mut buf = Cursor::new(&b"12"[..]);
2135 let mut v = Vec::new();
2136 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 2);
2137 assert_eq!(v, b"12");
2139 let mut buf = Cursor::new(&b"1233"[..]);
2140 let mut v = Vec::new();
2141 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 3);
2142 assert_eq!(v, b"123");
2144 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 1);
2145 assert_eq!(v, b"3");
2147 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 0);
2153 let buf = Cursor::new(&b"12"[..]);
2154 let mut s = buf.split(b'3');
2155 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2156 assert!(s.next().is_none());
2158 let buf = Cursor::new(&b"1233"[..]);
2159 let mut s = buf.split(b'3');
2160 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2161 assert_eq!(s.next().unwrap().unwrap(), vec![]);
2162 assert!(s.next().is_none());
2167 let mut buf = Cursor::new(&b"12"[..]);
2168 let mut v = String::new();
2169 assert_eq!(buf.read_line(&mut v).unwrap(), 2);
2170 assert_eq!(v, "12");
2172 let mut buf = Cursor::new(&b"12\n\n"[..]);
2173 let mut v = String::new();
2174 assert_eq!(buf.read_line(&mut v).unwrap(), 3);
2175 assert_eq!(v, "12\n");
2177 assert_eq!(buf.read_line(&mut v).unwrap(), 1);
2178 assert_eq!(v, "\n");
2180 assert_eq!(buf.read_line(&mut v).unwrap(), 0);
2186 let buf = Cursor::new(&b"12\r"[..]);
2187 let mut s = buf.lines();
2188 assert_eq!(s.next().unwrap().unwrap(), "12\r".to_string());
2189 assert!(s.next().is_none());
2191 let buf = Cursor::new(&b"12\r\n\n"[..]);
2192 let mut s = buf.lines();
2193 assert_eq!(s.next().unwrap().unwrap(), "12".to_string());
2194 assert_eq!(s.next().unwrap().unwrap(), "".to_string());
2195 assert!(s.next().is_none());
2200 let mut c = Cursor::new(&b""[..]);
2201 let mut v = Vec::new();
2202 assert_eq!(c.read_to_end(&mut v).unwrap(), 0);
2205 let mut c = Cursor::new(&b"1"[..]);
2206 let mut v = Vec::new();
2207 assert_eq!(c.read_to_end(&mut v).unwrap(), 1);
2208 assert_eq!(v, b"1");
2210 let cap = 1024 * 1024;
2211 let data = (0..cap).map(|i| (i / 3) as u8).collect::<Vec<_>>();
2212 let mut v = Vec::new();
2213 let (a, b) = data.split_at(data.len() / 2);
2214 assert_eq!(Cursor::new(a).read_to_end(&mut v).unwrap(), a.len());
2215 assert_eq!(Cursor::new(b).read_to_end(&mut v).unwrap(), b.len());
2216 assert_eq!(v, data);
2220 fn read_to_string() {
2221 let mut c = Cursor::new(&b""[..]);
2222 let mut v = String::new();
2223 assert_eq!(c.read_to_string(&mut v).unwrap(), 0);
2226 let mut c = Cursor::new(&b"1"[..]);
2227 let mut v = String::new();
2228 assert_eq!(c.read_to_string(&mut v).unwrap(), 1);
2231 let mut c = Cursor::new(&b"\xff"[..]);
2232 let mut v = String::new();
2233 assert!(c.read_to_string(&mut v).is_err());
2238 let mut buf = [0; 4];
2240 let mut c = Cursor::new(&b""[..]);
2241 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2242 io::ErrorKind::UnexpectedEof);
2244 let mut c = Cursor::new(&b"123"[..]).chain(Cursor::new(&b"456789"[..]));
2245 c.read_exact(&mut buf).unwrap();
2246 assert_eq!(&buf, b"1234");
2247 c.read_exact(&mut buf).unwrap();
2248 assert_eq!(&buf, b"5678");
2249 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2250 io::ErrorKind::UnexpectedEof);
2254 fn read_exact_slice() {
2255 let mut buf = [0; 4];
2257 let mut c = &b""[..];
2258 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2259 io::ErrorKind::UnexpectedEof);
2261 let mut c = &b"123"[..];
2262 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2263 io::ErrorKind::UnexpectedEof);
2264 // make sure the optimized (early returning) method is being used
2265 assert_eq!(&buf, &[0; 4]);
2267 let mut c = &b"1234"[..];
2268 c.read_exact(&mut buf).unwrap();
2269 assert_eq!(&buf, b"1234");
2271 let mut c = &b"56789"[..];
2272 c.read_exact(&mut buf).unwrap();
2273 assert_eq!(&buf, b"5678");
2274 assert_eq!(c, b"9");
2282 fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
2283 Err(io::Error::new(io::ErrorKind::Other, ""))
2286 impl BufRead for R {
2287 fn fill_buf(&mut self) -> io::Result<&[u8]> {
2288 Err(io::Error::new(io::ErrorKind::Other, ""))
2290 fn consume(&mut self, _amt: usize) { }
2293 let mut buf = [0; 1];
2294 assert_eq!(0, R.take(0).read(&mut buf).unwrap());
2295 assert_eq!(b"", R.take(0).fill_buf().unwrap());
2298 fn cmp_bufread<Br1: BufRead, Br2: BufRead>(mut br1: Br1, mut br2: Br2, exp: &[u8]) {
2299 let mut cat = Vec::new();
2302 let buf1 = br1.fill_buf().unwrap();
2303 let buf2 = br2.fill_buf().unwrap();
2304 let minlen = if buf1.len() < buf2.len() { buf1.len() } else { buf2.len() };
2305 assert_eq!(buf1[..minlen], buf2[..minlen]);
2306 cat.extend_from_slice(&buf1[..minlen]);
2312 br1.consume(consume);
2313 br2.consume(consume);
2315 assert_eq!(br1.fill_buf().unwrap().len(), 0);
2316 assert_eq!(br2.fill_buf().unwrap().len(), 0);
2317 assert_eq!(&cat[..], &exp[..])
2321 fn chain_bufread() {
2322 let testdata = b"ABCDEFGHIJKL";
2323 let chain1 = (&testdata[..3]).chain(&testdata[3..6])
2324 .chain(&testdata[6..9])
2325 .chain(&testdata[9..]);
2326 let chain2 = (&testdata[..4]).chain(&testdata[4..8])
2327 .chain(&testdata[8..]);
2328 cmp_bufread(chain1, chain2, &testdata[..]);
2332 fn chain_zero_length_read_is_not_eof() {
2335 let mut s = String::new();
2336 let mut chain = (&a[..]).chain(&b[..]);
2337 chain.read(&mut []).unwrap();
2338 chain.read_to_string(&mut s).unwrap();
2339 assert_eq!("AB", s);
2343 #[cfg_attr(target_os = "emscripten", ignore)]
2344 fn bench_read_to_end(b: &mut test::Bencher) {
2346 let mut lr = repeat(1).take(10000000);
2347 let mut vec = Vec::with_capacity(1024);
2348 super::read_to_end(&mut lr, &mut vec)