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>` (e.g. `main`). Instead, you can call `.unwrap()` or `match`
151 //! 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
269 #![stable(feature = "rust1", since = "1.0.0")]
272 use core::str as core_str;
273 use error as std_error;
280 #[stable(feature = "rust1", since = "1.0.0")]
281 pub use self::buffered::{BufReader, BufWriter, LineWriter};
282 #[stable(feature = "rust1", since = "1.0.0")]
283 pub use self::buffered::IntoInnerError;
284 #[stable(feature = "rust1", since = "1.0.0")]
285 pub use self::cursor::Cursor;
286 #[stable(feature = "rust1", since = "1.0.0")]
287 pub use self::error::{Result, Error, ErrorKind};
288 #[stable(feature = "rust1", since = "1.0.0")]
289 pub use self::util::{copy, sink, Sink, empty, Empty, repeat, Repeat};
290 #[stable(feature = "rust1", since = "1.0.0")]
291 pub use self::stdio::{stdin, stdout, stderr, Stdin, Stdout, Stderr};
292 #[stable(feature = "rust1", since = "1.0.0")]
293 pub use self::stdio::{StdoutLock, StderrLock, StdinLock};
294 #[unstable(feature = "print_internals", issue = "0")]
295 pub use self::stdio::{_print, _eprint};
296 #[unstable(feature = "libstd_io_internals", issue = "42788")]
297 #[doc(no_inline, hidden)]
298 pub use self::stdio::{set_panic, set_print};
309 const DEFAULT_BUF_SIZE: usize = ::sys_common::io::DEFAULT_BUF_SIZE;
311 struct Guard<'a> { buf: &'a mut Vec<u8>, len: usize }
313 impl<'a> Drop for Guard<'a> {
315 unsafe { self.buf.set_len(self.len); }
319 // A few methods below (read_to_string, read_line) will append data into a
320 // `String` buffer, but we need to be pretty careful when doing this. The
321 // implementation will just call `.as_mut_vec()` and then delegate to a
322 // byte-oriented reading method, but we must ensure that when returning we never
323 // leave `buf` in a state such that it contains invalid UTF-8 in its bounds.
325 // To this end, we use an RAII guard (to protect against panics) which updates
326 // the length of the string when it is dropped. This guard initially truncates
327 // the string to the prior length and only after we've validated that the
328 // new contents are valid UTF-8 do we allow it to set a longer length.
330 // The unsafety in this function is twofold:
332 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
334 // 2. We're passing a raw buffer to the function `f`, and it is expected that
335 // the function only *appends* bytes to the buffer. We'll get undefined
336 // behavior if existing bytes are overwritten to have non-UTF-8 data.
337 fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
338 where F: FnOnce(&mut Vec<u8>) -> Result<usize>
341 let mut g = Guard { len: buf.len(), buf: buf.as_mut_vec() };
343 if str::from_utf8(&g.buf[g.len..]).is_err() {
345 Err(Error::new(ErrorKind::InvalidData,
346 "stream did not contain valid UTF-8"))
355 // This uses an adaptive system to extend the vector when it fills. We want to
356 // avoid paying to allocate and zero a huge chunk of memory if the reader only
357 // has 4 bytes while still making large reads if the reader does have a ton
358 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
359 // time is 4,500 times (!) slower than this if the reader has a very small
360 // amount of data to return.
362 // Because we're extending the buffer with uninitialized data for trusted
363 // readers, we need to make sure to truncate that if any of this panics.
364 fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
365 let start_len = buf.len();
366 let mut g = Guard { len: buf.len(), buf: buf };
367 let mut new_write_size = 16;
370 if g.len == g.buf.len() {
371 if new_write_size < DEFAULT_BUF_SIZE {
375 g.buf.reserve(new_write_size);
376 g.buf.set_len(g.len + new_write_size);
377 r.initializer().initialize(&mut g.buf[g.len..]);
381 match r.read(&mut g.buf[g.len..]) {
383 ret = Ok(g.len - start_len);
387 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
398 /// The `Read` trait allows for reading bytes from a source.
400 /// Implementors of the `Read` trait are called 'readers'.
402 /// Readers are defined by one required method, `read()`. Each call to `read`
403 /// will attempt to pull bytes from this source into a provided buffer. A
404 /// number of other methods are implemented in terms of `read()`, giving
405 /// implementors a number of ways to read bytes while only needing to implement
408 /// Readers are intended to be composable with one another. Many implementors
409 /// throughout `std::io` take and provide types which implement the `Read`
412 /// Please note that each call to `read` may involve a system call, and
413 /// therefore, using something that implements [`BufRead`][bufread], such as
414 /// [`BufReader`][bufreader], will be more efficient.
416 /// [bufread]: trait.BufRead.html
417 /// [bufreader]: struct.BufReader.html
421 /// [`File`][file]s implement `Read`:
423 /// [file]: ../fs/struct.File.html
427 /// use std::io::prelude::*;
428 /// use std::fs::File;
430 /// # fn foo() -> io::Result<()> {
431 /// let mut f = File::open("foo.txt")?;
432 /// let mut buffer = [0; 10];
434 /// // read up to 10 bytes
435 /// f.read(&mut buffer)?;
437 /// let mut buffer = vec![0; 10];
438 /// // read the whole file
439 /// f.read_to_end(&mut buffer)?;
441 /// // read into a String, so that you don't need to do the conversion.
442 /// let mut buffer = String::new();
443 /// f.read_to_string(&mut buffer)?;
445 /// // and more! See the other methods for more details.
449 #[stable(feature = "rust1", since = "1.0.0")]
451 /// Pull some bytes from this source into the specified buffer, returning
452 /// how many bytes were read.
454 /// This function does not provide any guarantees about whether it blocks
455 /// waiting for data, but if an object needs to block for a read but cannot
456 /// it will typically signal this via an `Err` return value.
458 /// If the return value of this method is `Ok(n)`, then it must be
459 /// guaranteed that `0 <= n <= buf.len()`. A nonzero `n` value indicates
460 /// that the buffer `buf` has been filled in with `n` bytes of data from this
461 /// source. If `n` is `0`, then it can indicate one of two scenarios:
463 /// 1. This reader has reached its "end of file" and will likely no longer
464 /// be able to produce bytes. Note that this does not mean that the
465 /// reader will *always* no longer be able to produce bytes.
466 /// 2. The buffer specified was 0 bytes in length.
468 /// No guarantees are provided about the contents of `buf` when this
469 /// function is called, implementations cannot rely on any property of the
470 /// contents of `buf` being true. It is recommended that implementations
471 /// only write data to `buf` instead of reading its contents.
475 /// If this function encounters any form of I/O or other error, an error
476 /// variant will be returned. If an error is returned then it must be
477 /// guaranteed that no bytes were read.
479 /// An error of the `ErrorKind::Interrupted` kind is non-fatal and the read
480 /// operation should be retried if there is nothing else to do.
484 /// [`File`][file]s implement `Read`:
486 /// [file]: ../fs/struct.File.html
490 /// use std::io::prelude::*;
491 /// use std::fs::File;
493 /// # fn foo() -> io::Result<()> {
494 /// let mut f = File::open("foo.txt")?;
495 /// let mut buffer = [0; 10];
497 /// // read up to 10 bytes
498 /// f.read(&mut buffer[..])?;
502 #[stable(feature = "rust1", since = "1.0.0")]
503 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
505 /// Determines if this `Read`er can work with buffers of uninitialized
508 /// The default implementation returns an initializer which will zero
511 /// If a `Read`er guarantees that it can work properly with uninitialized
512 /// memory, it should call `Initializer::nop()`. See the documentation for
513 /// `Initializer` for details.
515 /// The behavior of this method must be independent of the state of the
516 /// `Read`er - the method only takes `&self` so that it can be used through
521 /// This method is unsafe because a `Read`er could otherwise return a
522 /// non-zeroing `Initializer` from another `Read` type without an `unsafe`
524 #[unstable(feature = "read_initializer", issue = "42788")]
526 unsafe fn initializer(&self) -> Initializer {
527 Initializer::zeroing()
530 /// Read all bytes until EOF in this source, placing them into `buf`.
532 /// All bytes read from this source will be appended to the specified buffer
533 /// `buf`. This function will continuously call `read` to append more data to
534 /// `buf` until `read` returns either `Ok(0)` or an error of
535 /// non-`ErrorKind::Interrupted` kind.
537 /// If successful, this function will return the total number of bytes read.
541 /// If this function encounters an error of the kind
542 /// `ErrorKind::Interrupted` then the error is ignored and the operation
545 /// If any other read error is encountered then this function immediately
546 /// returns. Any bytes which have already been read will be appended to
551 /// [`File`][file]s implement `Read`:
553 /// [file]: ../fs/struct.File.html
557 /// use std::io::prelude::*;
558 /// use std::fs::File;
560 /// # fn foo() -> io::Result<()> {
561 /// let mut f = File::open("foo.txt")?;
562 /// let mut buffer = Vec::new();
564 /// // read the whole file
565 /// f.read_to_end(&mut buffer)?;
569 #[stable(feature = "rust1", since = "1.0.0")]
570 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
571 read_to_end(self, buf)
574 /// Read all bytes until EOF in this source, placing them into `buf`.
576 /// If successful, this function returns the number of bytes which were read
577 /// and appended to `buf`.
581 /// If the data in this stream is *not* valid UTF-8 then an error is
582 /// returned and `buf` is unchanged.
584 /// See [`read_to_end`][readtoend] for other error semantics.
586 /// [readtoend]: #method.read_to_end
590 /// [`File`][file]s implement `Read`:
592 /// [file]: ../fs/struct.File.html
596 /// use std::io::prelude::*;
597 /// use std::fs::File;
599 /// # fn foo() -> io::Result<()> {
600 /// let mut f = File::open("foo.txt")?;
601 /// let mut buffer = String::new();
603 /// f.read_to_string(&mut buffer)?;
607 #[stable(feature = "rust1", since = "1.0.0")]
608 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
609 // Note that we do *not* call `.read_to_end()` here. We are passing
610 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
611 // method to fill it up. An arbitrary implementation could overwrite the
612 // entire contents of the vector, not just append to it (which is what
613 // we are expecting).
615 // To prevent extraneously checking the UTF-8-ness of the entire buffer
616 // we pass it to our hardcoded `read_to_end` implementation which we
617 // know is guaranteed to only read data into the end of the buffer.
618 append_to_string(buf, |b| read_to_end(self, b))
621 /// Read the exact number of bytes required to fill `buf`.
623 /// This function reads as many bytes as necessary to completely fill the
624 /// specified buffer `buf`.
626 /// No guarantees are provided about the contents of `buf` when this
627 /// function is called, implementations cannot rely on any property of the
628 /// contents of `buf` being true. It is recommended that implementations
629 /// only write data to `buf` instead of reading its contents.
633 /// If this function encounters an error of the kind
634 /// `ErrorKind::Interrupted` then the error is ignored and the operation
637 /// If this function encounters an "end of file" before completely filling
638 /// the buffer, it returns an error of the kind `ErrorKind::UnexpectedEof`.
639 /// The contents of `buf` are unspecified in this case.
641 /// If any other read error is encountered then this function immediately
642 /// returns. The contents of `buf` are unspecified in this case.
644 /// If this function returns an error, it is unspecified how many bytes it
645 /// has read, but it will never read more than would be necessary to
646 /// completely fill the buffer.
650 /// [`File`][file]s implement `Read`:
652 /// [file]: ../fs/struct.File.html
656 /// use std::io::prelude::*;
657 /// use std::fs::File;
659 /// # fn foo() -> io::Result<()> {
660 /// let mut f = File::open("foo.txt")?;
661 /// let mut buffer = [0; 10];
663 /// // read exactly 10 bytes
664 /// f.read_exact(&mut buffer)?;
668 #[stable(feature = "read_exact", since = "1.6.0")]
669 fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
670 while !buf.is_empty() {
671 match self.read(buf) {
673 Ok(n) => { let tmp = buf; buf = &mut tmp[n..]; }
674 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
675 Err(e) => return Err(e),
679 Err(Error::new(ErrorKind::UnexpectedEof,
680 "failed to fill whole buffer"))
686 /// Creates a "by reference" adaptor for this instance of `Read`.
688 /// The returned adaptor also implements `Read` and will simply borrow this
693 /// [`File`][file]s implement `Read`:
695 /// [file]: ../fs/struct.File.html
699 /// use std::io::Read;
700 /// use std::fs::File;
702 /// # fn foo() -> io::Result<()> {
703 /// let mut f = File::open("foo.txt")?;
704 /// let mut buffer = Vec::new();
705 /// let mut other_buffer = Vec::new();
708 /// let reference = f.by_ref();
710 /// // read at most 5 bytes
711 /// reference.take(5).read_to_end(&mut buffer)?;
713 /// } // drop our &mut reference so we can use f again
715 /// // original file still usable, read the rest
716 /// f.read_to_end(&mut other_buffer)?;
720 #[stable(feature = "rust1", since = "1.0.0")]
721 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
723 /// Transforms this `Read` instance to an `Iterator` over its bytes.
725 /// The returned type implements `Iterator` where the `Item` is `Result<u8,
726 /// R::Err>`. The yielded item is `Ok` if a byte was successfully read and
727 /// `Err` otherwise for I/O errors. EOF is mapped to returning `None` from
732 /// [`File`][file]s implement `Read`:
734 /// [file]: ../fs/struct.File.html
738 /// use std::io::prelude::*;
739 /// use std::fs::File;
741 /// # fn foo() -> io::Result<()> {
742 /// let mut f = File::open("foo.txt")?;
744 /// for byte in f.bytes() {
745 /// println!("{}", byte.unwrap());
750 #[stable(feature = "rust1", since = "1.0.0")]
751 fn bytes(self) -> Bytes<Self> where Self: Sized {
752 Bytes { inner: self }
755 /// Transforms this `Read` instance to an `Iterator` over `char`s.
757 /// This adaptor will attempt to interpret this reader as a UTF-8 encoded
758 /// sequence of characters. The returned iterator will return `None` once
759 /// EOF is reached for this reader. Otherwise each element yielded will be a
760 /// `Result<char, E>` where `E` may contain information about what I/O error
761 /// occurred or where decoding failed.
763 /// Currently this adaptor will discard intermediate data read, and should
764 /// be avoided if this is not desired.
768 /// [`File`][file]s implement `Read`:
770 /// [file]: ../fs/struct.File.html
775 /// use std::io::prelude::*;
776 /// use std::fs::File;
778 /// # fn foo() -> io::Result<()> {
779 /// let mut f = File::open("foo.txt")?;
781 /// for c in f.chars() {
782 /// println!("{}", c.unwrap());
787 #[unstable(feature = "io", reason = "the semantics of a partial read/write \
788 of where errors happen is currently \
789 unclear and may change",
791 fn chars(self) -> Chars<Self> where Self: Sized {
792 Chars { inner: self }
795 /// Creates an adaptor which will chain this stream with another.
797 /// The returned `Read` instance will first read all bytes from this object
798 /// until EOF is encountered. Afterwards the output is equivalent to the
799 /// output of `next`.
803 /// [`File`][file]s implement `Read`:
805 /// [file]: ../fs/struct.File.html
809 /// use std::io::prelude::*;
810 /// use std::fs::File;
812 /// # fn foo() -> io::Result<()> {
813 /// let mut f1 = File::open("foo.txt")?;
814 /// let mut f2 = File::open("bar.txt")?;
816 /// let mut handle = f1.chain(f2);
817 /// let mut buffer = String::new();
819 /// // read the value into a String. We could use any Read method here,
820 /// // this is just one example.
821 /// handle.read_to_string(&mut buffer)?;
825 #[stable(feature = "rust1", since = "1.0.0")]
826 fn chain<R: Read>(self, next: R) -> Chain<Self, R> where Self: Sized {
827 Chain { first: self, second: next, done_first: false }
830 /// Creates an adaptor which will read at most `limit` bytes from it.
832 /// This function returns a new instance of `Read` which will read at most
833 /// `limit` bytes, after which it will always return EOF (`Ok(0)`). Any
834 /// read errors will not count towards the number of bytes read and future
835 /// calls to `read` may succeed.
839 /// [`File`][file]s implement `Read`:
841 /// [file]: ../fs/struct.File.html
845 /// use std::io::prelude::*;
846 /// use std::fs::File;
848 /// # fn foo() -> io::Result<()> {
849 /// let mut f = File::open("foo.txt")?;
850 /// let mut buffer = [0; 5];
852 /// // read at most five bytes
853 /// let mut handle = f.take(5);
855 /// handle.read(&mut buffer)?;
859 #[stable(feature = "rust1", since = "1.0.0")]
860 fn take(self, limit: u64) -> Take<Self> where Self: Sized {
861 Take { inner: self, limit: limit }
865 /// A type used to conditionally initialize buffers passed to `Read` methods.
866 #[unstable(feature = "read_initializer", issue = "42788")]
868 pub struct Initializer(bool);
871 /// Returns a new `Initializer` which will zero out buffers.
872 #[unstable(feature = "read_initializer", issue = "42788")]
874 pub fn zeroing() -> Initializer {
878 /// Returns a new `Initializer` which will not zero out buffers.
882 /// This may only be called by `Read`ers which guarantee that they will not
883 /// read from buffers passed to `Read` methods, and that the return value of
884 /// the method accurately reflects the number of bytes that have been
885 /// written to the head of the buffer.
886 #[unstable(feature = "read_initializer", issue = "42788")]
888 pub unsafe fn nop() -> Initializer {
892 /// Indicates if a buffer should be initialized.
893 #[unstable(feature = "read_initializer", issue = "42788")]
895 pub fn should_initialize(&self) -> bool {
899 /// Initializes a buffer if necessary.
900 #[unstable(feature = "read_initializer", issue = "42788")]
902 pub fn initialize(&self, buf: &mut [u8]) {
903 if self.should_initialize() {
904 unsafe { ptr::write_bytes(buf.as_mut_ptr(), 0, buf.len()) }
909 /// A trait for objects which are byte-oriented sinks.
911 /// Implementors of the `Write` trait are sometimes called 'writers'.
913 /// Writers are defined by two required methods, [`write`] and [`flush`]:
915 /// * The [`write`] method will attempt to write some data into the object,
916 /// returning how many bytes were successfully written.
918 /// * The [`flush`] method is useful for adaptors and explicit buffers
919 /// themselves for ensuring that all buffered data has been pushed out to the
922 /// Writers are intended to be composable with one another. Many implementors
923 /// throughout [`std::io`] take and provide types which implement the `Write`
926 /// [`write`]: #tymethod.write
927 /// [`flush`]: #tymethod.flush
928 /// [`std::io`]: index.html
933 /// use std::io::prelude::*;
934 /// use std::fs::File;
936 /// # fn foo() -> std::io::Result<()> {
937 /// let mut buffer = File::create("foo.txt")?;
939 /// buffer.write(b"some bytes")?;
943 #[stable(feature = "rust1", since = "1.0.0")]
945 /// Write a buffer into this object, returning how many bytes were written.
947 /// This function will attempt to write the entire contents of `buf`, but
948 /// the entire write may not succeed, or the write may also generate an
949 /// error. A call to `write` represents *at most one* attempt to write to
950 /// any wrapped object.
952 /// Calls to `write` are not guaranteed to block waiting for data to be
953 /// written, and a write which would otherwise block can be indicated through
954 /// an `Err` variant.
956 /// If the return value is `Ok(n)` then it must be guaranteed that
957 /// `0 <= n <= buf.len()`. A return value of `0` typically means that the
958 /// underlying object is no longer able to accept bytes and will likely not
959 /// be able to in the future as well, or that the buffer provided is empty.
963 /// Each call to `write` may generate an I/O error indicating that the
964 /// operation could not be completed. If an error is returned then no bytes
965 /// in the buffer were written to this writer.
967 /// It is **not** considered an error if the entire buffer could not be
968 /// written to this writer.
970 /// An error of the `ErrorKind::Interrupted` kind is non-fatal and the
971 /// write operation should be retried if there is nothing else to do.
976 /// use std::io::prelude::*;
977 /// use std::fs::File;
979 /// # fn foo() -> std::io::Result<()> {
980 /// let mut buffer = File::create("foo.txt")?;
982 /// // Writes some prefix of the byte string, not necessarily all of it.
983 /// buffer.write(b"some bytes")?;
987 #[stable(feature = "rust1", since = "1.0.0")]
988 fn write(&mut self, buf: &[u8]) -> Result<usize>;
990 /// Flush this output stream, ensuring that all intermediately buffered
991 /// contents reach their destination.
995 /// It is considered an error if not all bytes could be written due to
996 /// I/O errors or EOF being reached.
1001 /// use std::io::prelude::*;
1002 /// use std::io::BufWriter;
1003 /// use std::fs::File;
1005 /// # fn foo() -> std::io::Result<()> {
1006 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
1008 /// buffer.write(b"some bytes")?;
1009 /// buffer.flush()?;
1013 #[stable(feature = "rust1", since = "1.0.0")]
1014 fn flush(&mut self) -> Result<()>;
1016 /// Attempts to write an entire buffer into this write.
1018 /// This method will continuously call `write` until there is no more data
1019 /// to be written or an error of non-`ErrorKind::Interrupted` kind is
1020 /// returned. This method will not return until the entire buffer has been
1021 /// successfully written or such an error occurs. The first error that is
1022 /// not of `ErrorKind::Interrupted` kind generated from this method will be
1027 /// This function will return the first error of
1028 /// non-`ErrorKind::Interrupted` kind that `write` returns.
1033 /// use std::io::prelude::*;
1034 /// use std::fs::File;
1036 /// # fn foo() -> std::io::Result<()> {
1037 /// let mut buffer = File::create("foo.txt")?;
1039 /// buffer.write_all(b"some bytes")?;
1043 #[stable(feature = "rust1", since = "1.0.0")]
1044 fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
1045 while !buf.is_empty() {
1046 match self.write(buf) {
1047 Ok(0) => return Err(Error::new(ErrorKind::WriteZero,
1048 "failed to write whole buffer")),
1049 Ok(n) => buf = &buf[n..],
1050 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1051 Err(e) => return Err(e),
1057 /// Writes a formatted string into this writer, returning any error
1060 /// This method is primarily used to interface with the
1061 /// [`format_args!`][formatargs] macro, but it is rare that this should
1062 /// explicitly be called. The [`write!`][write] macro should be favored to
1063 /// invoke this method instead.
1065 /// [formatargs]: ../macro.format_args.html
1066 /// [write]: ../macro.write.html
1068 /// This function internally uses the [`write_all`][writeall] method on
1069 /// this trait and hence will continuously write data so long as no errors
1070 /// are received. This also means that partial writes are not indicated in
1073 /// [writeall]: #method.write_all
1077 /// This function will return any I/O error reported while formatting.
1082 /// use std::io::prelude::*;
1083 /// use std::fs::File;
1085 /// # fn foo() -> std::io::Result<()> {
1086 /// let mut buffer = File::create("foo.txt")?;
1089 /// write!(buffer, "{:.*}", 2, 1.234567)?;
1090 /// // turns into this:
1091 /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1095 #[stable(feature = "rust1", since = "1.0.0")]
1096 fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()> {
1097 // Create a shim which translates a Write to a fmt::Write and saves
1098 // off I/O errors. instead of discarding them
1099 struct Adaptor<'a, T: ?Sized + 'a> {
1104 impl<'a, T: Write + ?Sized> fmt::Write for Adaptor<'a, T> {
1105 fn write_str(&mut self, s: &str) -> fmt::Result {
1106 match self.inner.write_all(s.as_bytes()) {
1109 self.error = Err(e);
1116 let mut output = Adaptor { inner: self, error: Ok(()) };
1117 match fmt::write(&mut output, fmt) {
1120 // check if the error came from the underlying `Write` or not
1121 if output.error.is_err() {
1124 Err(Error::new(ErrorKind::Other, "formatter error"))
1130 /// Creates a "by reference" adaptor for this instance of `Write`.
1132 /// The returned adaptor also implements `Write` and will simply borrow this
1138 /// use std::io::Write;
1139 /// use std::fs::File;
1141 /// # fn foo() -> std::io::Result<()> {
1142 /// let mut buffer = File::create("foo.txt")?;
1144 /// let reference = buffer.by_ref();
1146 /// // we can use reference just like our original buffer
1147 /// reference.write_all(b"some bytes")?;
1151 #[stable(feature = "rust1", since = "1.0.0")]
1152 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1155 /// The `Seek` trait provides a cursor which can be moved within a stream of
1158 /// The stream typically has a fixed size, allowing seeking relative to either
1159 /// end or the current offset.
1163 /// [`File`][file]s implement `Seek`:
1165 /// [file]: ../fs/struct.File.html
1169 /// use std::io::prelude::*;
1170 /// use std::fs::File;
1171 /// use std::io::SeekFrom;
1173 /// # fn foo() -> io::Result<()> {
1174 /// let mut f = File::open("foo.txt")?;
1176 /// // move the cursor 42 bytes from the start of the file
1177 /// f.seek(SeekFrom::Start(42))?;
1181 #[stable(feature = "rust1", since = "1.0.0")]
1183 /// Seek to an offset, in bytes, in a stream.
1185 /// A seek beyond the end of a stream is allowed, but implementation
1188 /// If the seek operation completed successfully,
1189 /// this method returns the new position from the start of the stream.
1190 /// That position can be used later with [`SeekFrom::Start`].
1194 /// Seeking to a negative offset is considered an error.
1196 /// [`SeekFrom::Start`]: enum.SeekFrom.html#variant.Start
1197 #[stable(feature = "rust1", since = "1.0.0")]
1198 fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1201 /// Enumeration of possible methods to seek within an I/O object.
1203 /// It is used by the [`Seek`] trait.
1205 /// [`Seek`]: trait.Seek.html
1206 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1207 #[stable(feature = "rust1", since = "1.0.0")]
1209 /// Set the offset to the provided number of bytes.
1210 #[stable(feature = "rust1", since = "1.0.0")]
1211 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1213 /// Set the offset to the size of this object plus the specified number of
1216 /// It is possible to seek beyond the end of an object, but it's an error to
1217 /// seek before byte 0.
1218 #[stable(feature = "rust1", since = "1.0.0")]
1219 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1221 /// Set the offset to the current position plus the specified number of
1224 /// It is possible to seek beyond the end of an object, but it's an error to
1225 /// seek before byte 0.
1226 #[stable(feature = "rust1", since = "1.0.0")]
1227 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1230 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>)
1234 let (done, used) = {
1235 let available = match r.fill_buf() {
1237 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1238 Err(e) => return Err(e)
1240 match memchr::memchr(delim, available) {
1242 buf.extend_from_slice(&available[..i + 1]);
1246 buf.extend_from_slice(available);
1247 (false, available.len())
1253 if done || used == 0 {
1259 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1260 /// to perform extra ways of reading.
1262 /// For example, reading line-by-line is inefficient without using a buffer, so
1263 /// if you want to read by line, you'll need `BufRead`, which includes a
1264 /// [`read_line`] method as well as a [`lines`] iterator.
1268 /// A locked standard input implements `BufRead`:
1272 /// use std::io::prelude::*;
1274 /// let stdin = io::stdin();
1275 /// for line in stdin.lock().lines() {
1276 /// println!("{}", line.unwrap());
1280 /// If you have something that implements [`Read`], you can use the [`BufReader`
1281 /// type][`BufReader`] to turn it into a `BufRead`.
1283 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1284 /// [`BufReader`] to the rescue!
1286 /// [`BufReader`]: struct.BufReader.html
1287 /// [`File`]: ../fs/struct.File.html
1288 /// [`read_line`]: #method.read_line
1289 /// [`lines`]: #method.lines
1290 /// [`Read`]: trait.Read.html
1293 /// use std::io::{self, BufReader};
1294 /// use std::io::prelude::*;
1295 /// use std::fs::File;
1297 /// # fn foo() -> io::Result<()> {
1298 /// let f = File::open("foo.txt")?;
1299 /// let f = BufReader::new(f);
1301 /// for line in f.lines() {
1302 /// println!("{}", line.unwrap());
1309 #[stable(feature = "rust1", since = "1.0.0")]
1310 pub trait BufRead: Read {
1311 /// Fills the internal buffer of this object, returning the buffer contents.
1313 /// This function is a lower-level call. It needs to be paired with the
1314 /// [`consume`] method to function properly. When calling this
1315 /// method, none of the contents will be "read" in the sense that later
1316 /// calling `read` may return the same contents. As such, [`consume`] must
1317 /// be called with the number of bytes that are consumed from this buffer to
1318 /// ensure that the bytes are never returned twice.
1320 /// [`consume`]: #tymethod.consume
1322 /// An empty buffer returned indicates that the stream has reached EOF.
1326 /// This function will return an I/O error if the underlying reader was
1327 /// read, but returned an error.
1331 /// A locked standard input implements `BufRead`:
1335 /// use std::io::prelude::*;
1337 /// let stdin = io::stdin();
1338 /// let mut stdin = stdin.lock();
1340 /// // we can't have two `&mut` references to `stdin`, so use a block
1341 /// // to end the borrow early.
1343 /// let buffer = stdin.fill_buf().unwrap();
1345 /// // work with buffer
1346 /// println!("{:?}", buffer);
1351 /// // ensure the bytes we worked with aren't returned again later
1352 /// stdin.consume(length);
1354 #[stable(feature = "rust1", since = "1.0.0")]
1355 fn fill_buf(&mut self) -> Result<&[u8]>;
1357 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1358 /// so they should no longer be returned in calls to `read`.
1360 /// This function is a lower-level call. It needs to be paired with the
1361 /// [`fill_buf`] method to function properly. This function does
1362 /// not perform any I/O, it simply informs this object that some amount of
1363 /// its buffer, returned from [`fill_buf`], has been consumed and should
1364 /// no longer be returned. As such, this function may do odd things if
1365 /// [`fill_buf`] isn't called before calling it.
1367 /// The `amt` must be `<=` the number of bytes in the buffer returned by
1372 /// Since `consume()` is meant to be used with [`fill_buf`],
1373 /// that method's example includes an example of `consume()`.
1375 /// [`fill_buf`]: #tymethod.fill_buf
1376 #[stable(feature = "rust1", since = "1.0.0")]
1377 fn consume(&mut self, amt: usize);
1379 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
1381 /// This function will read bytes from the underlying stream until the
1382 /// delimiter or EOF is found. Once found, all bytes up to, and including,
1383 /// the delimiter (if found) will be appended to `buf`.
1385 /// If successful, this function will return the total number of bytes read.
1389 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1390 /// will otherwise return any errors returned by [`fill_buf`].
1392 /// If an I/O error is encountered then all bytes read so far will be
1393 /// present in `buf` and its length will have been adjusted appropriately.
1395 /// [`fill_buf`]: #tymethod.fill_buf
1396 /// [`ErrorKind::Interrupted`]: enum.ErrorKind.html#variant.Interrupted
1400 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1401 /// this example, we use [`Cursor`] to read all the bytes in a byte slice
1402 /// in hyphen delimited segments:
1404 /// [`Cursor`]: struct.Cursor.html
1407 /// use std::io::{self, BufRead};
1409 /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
1410 /// let mut buf = vec![];
1412 /// // cursor is at 'l'
1413 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1414 /// .expect("reading from cursor won't fail");
1415 /// assert_eq!(num_bytes, 6);
1416 /// assert_eq!(buf, b"lorem-");
1419 /// // cursor is at 'i'
1420 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1421 /// .expect("reading from cursor won't fail");
1422 /// assert_eq!(num_bytes, 5);
1423 /// assert_eq!(buf, b"ipsum");
1426 /// // cursor is at EOF
1427 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1428 /// .expect("reading from cursor won't fail");
1429 /// assert_eq!(num_bytes, 0);
1430 /// assert_eq!(buf, b"");
1432 #[stable(feature = "rust1", since = "1.0.0")]
1433 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
1434 read_until(self, byte, buf)
1437 /// Read all bytes until a newline (the 0xA byte) is reached, and append
1438 /// them to the provided buffer.
1440 /// This function will read bytes from the underlying stream until the
1441 /// newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes
1442 /// up to, and including, the delimiter (if found) will be appended to
1445 /// If successful, this function will return the total number of bytes read.
1449 /// This function has the same error semantics as [`read_until`] and will
1450 /// also return an error if the read bytes are not valid UTF-8. If an I/O
1451 /// error is encountered then `buf` may contain some bytes already read in
1452 /// the event that all data read so far was valid UTF-8.
1456 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1457 /// this example, we use [`Cursor`] to read all the lines in a byte slice:
1459 /// [`Cursor`]: struct.Cursor.html
1462 /// use std::io::{self, BufRead};
1464 /// let mut cursor = io::Cursor::new(b"foo\nbar");
1465 /// let mut buf = String::new();
1467 /// // cursor is at 'f'
1468 /// let num_bytes = cursor.read_line(&mut buf)
1469 /// .expect("reading from cursor won't fail");
1470 /// assert_eq!(num_bytes, 4);
1471 /// assert_eq!(buf, "foo\n");
1474 /// // cursor is at 'b'
1475 /// let num_bytes = cursor.read_line(&mut buf)
1476 /// .expect("reading from cursor won't fail");
1477 /// assert_eq!(num_bytes, 3);
1478 /// assert_eq!(buf, "bar");
1481 /// // cursor is at EOF
1482 /// let num_bytes = cursor.read_line(&mut buf)
1483 /// .expect("reading from cursor won't fail");
1484 /// assert_eq!(num_bytes, 0);
1485 /// assert_eq!(buf, "");
1487 #[stable(feature = "rust1", since = "1.0.0")]
1488 fn read_line(&mut self, buf: &mut String) -> Result<usize> {
1489 // Note that we are not calling the `.read_until` method here, but
1490 // rather our hardcoded implementation. For more details as to why, see
1491 // the comments in `read_to_end`.
1492 append_to_string(buf, |b| read_until(self, b'\n', b))
1495 /// Returns an iterator over the contents of this reader split on the byte
1498 /// The iterator returned from this function will return instances of
1499 /// [`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
1500 /// the delimiter byte at the end.
1502 /// This function will yield errors whenever [`read_until`] would have
1503 /// also yielded an error.
1505 /// [`io::Result`]: type.Result.html
1506 /// [`Vec<u8>`]: ../vec/struct.Vec.html
1507 /// [`read_until`]: #method.read_until
1511 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1512 /// this example, we use [`Cursor`] to iterate over all hyphen delimited
1513 /// segments in a byte slice
1515 /// [`Cursor`]: struct.Cursor.html
1518 /// use std::io::{self, BufRead};
1520 /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
1522 /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
1523 /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
1524 /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
1525 /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
1526 /// assert_eq!(split_iter.next(), None);
1528 #[stable(feature = "rust1", since = "1.0.0")]
1529 fn split(self, byte: u8) -> Split<Self> where Self: Sized {
1530 Split { buf: self, delim: byte }
1533 /// Returns an iterator over the lines of this reader.
1535 /// The iterator returned from this function will yield instances of
1536 /// [`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline
1537 /// byte (the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.
1539 /// [`io::Result`]: type.Result.html
1540 /// [`String`]: ../string/struct.String.html
1544 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1545 /// this example, we use [`Cursor`] to iterate over all the lines in a byte
1548 /// [`Cursor`]: struct.Cursor.html
1551 /// use std::io::{self, BufRead};
1553 /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
1555 /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
1556 /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
1557 /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
1558 /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
1559 /// assert_eq!(lines_iter.next(), None);
1564 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
1566 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
1567 #[stable(feature = "rust1", since = "1.0.0")]
1568 fn lines(self) -> Lines<Self> where Self: Sized {
1573 /// Adaptor to chain together two readers.
1575 /// This struct is generally created by calling [`chain`] on a reader.
1576 /// Please see the documentation of [`chain`] for more details.
1578 /// [`chain`]: trait.Read.html#method.chain
1579 #[stable(feature = "rust1", since = "1.0.0")]
1580 pub struct Chain<T, U> {
1586 impl<T, U> Chain<T, U> {
1587 /// Consumes the `Chain`, returning the wrapped readers.
1593 /// use std::io::prelude::*;
1594 /// use std::fs::File;
1596 /// # fn foo() -> io::Result<()> {
1597 /// let mut foo_file = File::open("foo.txt")?;
1598 /// let mut bar_file = File::open("bar.txt")?;
1600 /// let chain = foo_file.chain(bar_file);
1601 /// let (foo_file, bar_file) = chain.into_inner();
1605 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1606 pub fn into_inner(self) -> (T, U) {
1607 (self.first, self.second)
1610 /// Gets references to the underlying readers in this `Chain`.
1616 /// use std::io::prelude::*;
1617 /// use std::fs::File;
1619 /// # fn foo() -> io::Result<()> {
1620 /// let mut foo_file = File::open("foo.txt")?;
1621 /// let mut bar_file = File::open("bar.txt")?;
1623 /// let chain = foo_file.chain(bar_file);
1624 /// let (foo_file, bar_file) = chain.get_ref();
1628 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1629 pub fn get_ref(&self) -> (&T, &U) {
1630 (&self.first, &self.second)
1633 /// Gets mutable references to the underlying readers in this `Chain`.
1635 /// Care should be taken to avoid modifying the internal I/O state of the
1636 /// underlying readers as doing so may corrupt the internal state of this
1643 /// use std::io::prelude::*;
1644 /// use std::fs::File;
1646 /// # fn foo() -> io::Result<()> {
1647 /// let mut foo_file = File::open("foo.txt")?;
1648 /// let mut bar_file = File::open("bar.txt")?;
1650 /// let mut chain = foo_file.chain(bar_file);
1651 /// let (foo_file, bar_file) = chain.get_mut();
1655 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1656 pub fn get_mut(&mut self) -> (&mut T, &mut U) {
1657 (&mut self.first, &mut self.second)
1661 #[stable(feature = "std_debug", since = "1.16.0")]
1662 impl<T: fmt::Debug, U: fmt::Debug> fmt::Debug for Chain<T, U> {
1663 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1664 f.debug_struct("Chain")
1665 .field("t", &self.first)
1666 .field("u", &self.second)
1671 #[stable(feature = "rust1", since = "1.0.0")]
1672 impl<T: Read, U: Read> Read for Chain<T, U> {
1673 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1674 if !self.done_first {
1675 match self.first.read(buf)? {
1676 0 if buf.len() != 0 => { self.done_first = true; }
1680 self.second.read(buf)
1683 unsafe fn initializer(&self) -> Initializer {
1684 let initializer = self.first.initializer();
1685 if initializer.should_initialize() {
1688 self.second.initializer()
1693 #[stable(feature = "chain_bufread", since = "1.9.0")]
1694 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
1695 fn fill_buf(&mut self) -> Result<&[u8]> {
1696 if !self.done_first {
1697 match self.first.fill_buf()? {
1698 buf if buf.len() == 0 => { self.done_first = true; }
1699 buf => return Ok(buf),
1702 self.second.fill_buf()
1705 fn consume(&mut self, amt: usize) {
1706 if !self.done_first {
1707 self.first.consume(amt)
1709 self.second.consume(amt)
1714 /// Reader adaptor which limits the bytes read from an underlying reader.
1716 /// This struct is generally created by calling [`take`] on a reader.
1717 /// Please see the documentation of [`take`] for more details.
1719 /// [`take`]: trait.Read.html#method.take
1720 #[stable(feature = "rust1", since = "1.0.0")]
1722 pub struct Take<T> {
1728 /// Returns the number of bytes that can be read before this instance will
1733 /// This instance may reach `EOF` after reading fewer bytes than indicated by
1734 /// this method if the underlying [`Read`] instance reaches EOF.
1736 /// [`Read`]: ../../std/io/trait.Read.html
1742 /// use std::io::prelude::*;
1743 /// use std::fs::File;
1745 /// # fn foo() -> io::Result<()> {
1746 /// let f = File::open("foo.txt")?;
1748 /// // read at most five bytes
1749 /// let handle = f.take(5);
1751 /// println!("limit: {}", handle.limit());
1755 #[stable(feature = "rust1", since = "1.0.0")]
1756 pub fn limit(&self) -> u64 { self.limit }
1758 /// Sets the number of bytes that can be read before this instance will
1759 /// return EOF. This is the same as constructing a new `Take` instance, so
1760 /// the amount of bytes read and the previous limit value don't matter when
1761 /// calling this method.
1766 /// #![feature(take_set_limit)]
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 mut handle = f.take(5);
1776 /// handle.set_limit(10);
1778 /// assert_eq!(handle.limit(), 10);
1782 #[unstable(feature = "take_set_limit", issue = "42781")]
1783 pub fn set_limit(&mut self, limit: u64) {
1787 /// Consumes the `Take`, returning the wrapped reader.
1793 /// use std::io::prelude::*;
1794 /// use std::fs::File;
1796 /// # fn foo() -> io::Result<()> {
1797 /// let mut file = File::open("foo.txt")?;
1799 /// let mut buffer = [0; 5];
1800 /// let mut handle = file.take(5);
1801 /// handle.read(&mut buffer)?;
1803 /// let file = handle.into_inner();
1807 #[stable(feature = "io_take_into_inner", since = "1.15.0")]
1808 pub fn into_inner(self) -> T {
1812 /// Gets a reference to the underlying reader.
1818 /// use std::io::prelude::*;
1819 /// use std::fs::File;
1821 /// # fn foo() -> io::Result<()> {
1822 /// let mut file = File::open("foo.txt")?;
1824 /// let mut buffer = [0; 5];
1825 /// let mut handle = file.take(5);
1826 /// handle.read(&mut buffer)?;
1828 /// let file = handle.get_ref();
1832 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1833 pub fn get_ref(&self) -> &T {
1837 /// Gets a mutable reference to the underlying reader.
1839 /// Care should be taken to avoid modifying the internal I/O state of the
1840 /// underlying reader as doing so may corrupt the internal limit of this
1847 /// use std::io::prelude::*;
1848 /// use std::fs::File;
1850 /// # fn foo() -> io::Result<()> {
1851 /// let mut file = File::open("foo.txt")?;
1853 /// let mut buffer = [0; 5];
1854 /// let mut handle = file.take(5);
1855 /// handle.read(&mut buffer)?;
1857 /// let file = handle.get_mut();
1861 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1862 pub fn get_mut(&mut self) -> &mut T {
1867 #[stable(feature = "rust1", since = "1.0.0")]
1868 impl<T: Read> Read for Take<T> {
1869 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1870 // Don't call into inner reader at all at EOF because it may still block
1871 if self.limit == 0 {
1875 let max = cmp::min(buf.len() as u64, self.limit) as usize;
1876 let n = self.inner.read(&mut buf[..max])?;
1877 self.limit -= n as u64;
1881 unsafe fn initializer(&self) -> Initializer {
1882 self.inner.initializer()
1886 #[stable(feature = "rust1", since = "1.0.0")]
1887 impl<T: BufRead> BufRead for Take<T> {
1888 fn fill_buf(&mut self) -> Result<&[u8]> {
1889 // Don't call into inner reader at all at EOF because it may still block
1890 if self.limit == 0 {
1894 let buf = self.inner.fill_buf()?;
1895 let cap = cmp::min(buf.len() as u64, self.limit) as usize;
1899 fn consume(&mut self, amt: usize) {
1900 // Don't let callers reset the limit by passing an overlarge value
1901 let amt = cmp::min(amt as u64, self.limit) as usize;
1902 self.limit -= amt as u64;
1903 self.inner.consume(amt);
1907 fn read_one_byte(reader: &mut Read) -> Option<Result<u8>> {
1910 return match reader.read(&mut buf) {
1912 Ok(..) => Some(Ok(buf[0])),
1913 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1914 Err(e) => Some(Err(e)),
1919 /// An iterator over `u8` values of a reader.
1921 /// This struct is generally created by calling [`bytes`] on a reader.
1922 /// Please see the documentation of [`bytes`] for more details.
1924 /// [`bytes`]: trait.Read.html#method.bytes
1925 #[stable(feature = "rust1", since = "1.0.0")]
1927 pub struct Bytes<R> {
1931 #[stable(feature = "rust1", since = "1.0.0")]
1932 impl<R: Read> Iterator for Bytes<R> {
1933 type Item = Result<u8>;
1935 fn next(&mut self) -> Option<Result<u8>> {
1936 read_one_byte(&mut self.inner)
1940 /// An iterator over the `char`s of a reader.
1942 /// This struct is generally created by calling [`chars`][chars] on a reader.
1943 /// Please see the documentation of `chars()` for more details.
1945 /// [chars]: trait.Read.html#method.chars
1946 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1949 pub struct Chars<R> {
1953 /// An enumeration of possible errors that can be generated from the `Chars`
1956 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1958 pub enum CharsError {
1959 /// Variant representing that the underlying stream was read successfully
1960 /// but it did not contain valid utf8 data.
1963 /// Variant representing that an I/O error occurred.
1967 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1969 impl<R: Read> Iterator for Chars<R> {
1970 type Item = result::Result<char, CharsError>;
1972 fn next(&mut self) -> Option<result::Result<char, CharsError>> {
1973 let first_byte = match read_one_byte(&mut self.inner) {
1974 None => return None,
1976 Some(Err(e)) => return Some(Err(CharsError::Other(e))),
1978 let width = core_str::utf8_char_width(first_byte);
1979 if width == 1 { return Some(Ok(first_byte as char)) }
1980 if width == 0 { return Some(Err(CharsError::NotUtf8)) }
1981 let mut buf = [first_byte, 0, 0, 0];
1984 while start < width {
1985 match self.inner.read(&mut buf[start..width]) {
1986 Ok(0) => return Some(Err(CharsError::NotUtf8)),
1987 Ok(n) => start += n,
1988 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1989 Err(e) => return Some(Err(CharsError::Other(e))),
1993 Some(match str::from_utf8(&buf[..width]).ok() {
1994 Some(s) => Ok(s.chars().next().unwrap()),
1995 None => Err(CharsError::NotUtf8),
2000 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
2002 impl std_error::Error for CharsError {
2003 fn description(&self) -> &str {
2005 CharsError::NotUtf8 => "invalid utf8 encoding",
2006 CharsError::Other(ref e) => std_error::Error::description(e),
2009 fn cause(&self) -> Option<&std_error::Error> {
2011 CharsError::NotUtf8 => None,
2012 CharsError::Other(ref e) => e.cause(),
2017 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
2019 impl fmt::Display for CharsError {
2020 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2022 CharsError::NotUtf8 => {
2023 "byte stream did not contain valid utf8".fmt(f)
2025 CharsError::Other(ref e) => e.fmt(f),
2030 /// An iterator over the contents of an instance of `BufRead` split on a
2031 /// particular byte.
2033 /// This struct is generally created by calling [`split`][split] on a
2034 /// `BufRead`. Please see the documentation of `split()` for more details.
2036 /// [split]: trait.BufRead.html#method.split
2037 #[stable(feature = "rust1", since = "1.0.0")]
2039 pub struct Split<B> {
2044 #[stable(feature = "rust1", since = "1.0.0")]
2045 impl<B: BufRead> Iterator for Split<B> {
2046 type Item = Result<Vec<u8>>;
2048 fn next(&mut self) -> Option<Result<Vec<u8>>> {
2049 let mut buf = Vec::new();
2050 match self.buf.read_until(self.delim, &mut buf) {
2053 if buf[buf.len() - 1] == self.delim {
2058 Err(e) => Some(Err(e))
2063 /// An iterator over the lines of an instance of `BufRead`.
2065 /// This struct is generally created by calling [`lines`][lines] on a
2066 /// `BufRead`. Please see the documentation of `lines()` for more details.
2068 /// [lines]: trait.BufRead.html#method.lines
2069 #[stable(feature = "rust1", since = "1.0.0")]
2071 pub struct Lines<B> {
2075 #[stable(feature = "rust1", since = "1.0.0")]
2076 impl<B: BufRead> Iterator for Lines<B> {
2077 type Item = Result<String>;
2079 fn next(&mut self) -> Option<Result<String>> {
2080 let mut buf = String::new();
2081 match self.buf.read_line(&mut buf) {
2084 if buf.ends_with("\n") {
2086 if buf.ends_with("\r") {
2092 Err(e) => Some(Err(e))
2106 #[cfg_attr(target_os = "emscripten", ignore)]
2108 let mut buf = Cursor::new(&b"12"[..]);
2109 let mut v = Vec::new();
2110 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 2);
2111 assert_eq!(v, b"12");
2113 let mut buf = Cursor::new(&b"1233"[..]);
2114 let mut v = Vec::new();
2115 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 3);
2116 assert_eq!(v, b"123");
2118 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 1);
2119 assert_eq!(v, b"3");
2121 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 0);
2127 let buf = Cursor::new(&b"12"[..]);
2128 let mut s = buf.split(b'3');
2129 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2130 assert!(s.next().is_none());
2132 let buf = Cursor::new(&b"1233"[..]);
2133 let mut s = buf.split(b'3');
2134 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2135 assert_eq!(s.next().unwrap().unwrap(), vec![]);
2136 assert!(s.next().is_none());
2141 let mut buf = Cursor::new(&b"12"[..]);
2142 let mut v = String::new();
2143 assert_eq!(buf.read_line(&mut v).unwrap(), 2);
2144 assert_eq!(v, "12");
2146 let mut buf = Cursor::new(&b"12\n\n"[..]);
2147 let mut v = String::new();
2148 assert_eq!(buf.read_line(&mut v).unwrap(), 3);
2149 assert_eq!(v, "12\n");
2151 assert_eq!(buf.read_line(&mut v).unwrap(), 1);
2152 assert_eq!(v, "\n");
2154 assert_eq!(buf.read_line(&mut v).unwrap(), 0);
2160 let buf = Cursor::new(&b"12\r"[..]);
2161 let mut s = buf.lines();
2162 assert_eq!(s.next().unwrap().unwrap(), "12\r".to_string());
2163 assert!(s.next().is_none());
2165 let buf = Cursor::new(&b"12\r\n\n"[..]);
2166 let mut s = buf.lines();
2167 assert_eq!(s.next().unwrap().unwrap(), "12".to_string());
2168 assert_eq!(s.next().unwrap().unwrap(), "".to_string());
2169 assert!(s.next().is_none());
2174 let mut c = Cursor::new(&b""[..]);
2175 let mut v = Vec::new();
2176 assert_eq!(c.read_to_end(&mut v).unwrap(), 0);
2179 let mut c = Cursor::new(&b"1"[..]);
2180 let mut v = Vec::new();
2181 assert_eq!(c.read_to_end(&mut v).unwrap(), 1);
2182 assert_eq!(v, b"1");
2184 let cap = 1024 * 1024;
2185 let data = (0..cap).map(|i| (i / 3) as u8).collect::<Vec<_>>();
2186 let mut v = Vec::new();
2187 let (a, b) = data.split_at(data.len() / 2);
2188 assert_eq!(Cursor::new(a).read_to_end(&mut v).unwrap(), a.len());
2189 assert_eq!(Cursor::new(b).read_to_end(&mut v).unwrap(), b.len());
2190 assert_eq!(v, data);
2194 fn read_to_string() {
2195 let mut c = Cursor::new(&b""[..]);
2196 let mut v = String::new();
2197 assert_eq!(c.read_to_string(&mut v).unwrap(), 0);
2200 let mut c = Cursor::new(&b"1"[..]);
2201 let mut v = String::new();
2202 assert_eq!(c.read_to_string(&mut v).unwrap(), 1);
2205 let mut c = Cursor::new(&b"\xff"[..]);
2206 let mut v = String::new();
2207 assert!(c.read_to_string(&mut v).is_err());
2212 let mut buf = [0; 4];
2214 let mut c = Cursor::new(&b""[..]);
2215 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2216 io::ErrorKind::UnexpectedEof);
2218 let mut c = Cursor::new(&b"123"[..]).chain(Cursor::new(&b"456789"[..]));
2219 c.read_exact(&mut buf).unwrap();
2220 assert_eq!(&buf, b"1234");
2221 c.read_exact(&mut buf).unwrap();
2222 assert_eq!(&buf, b"5678");
2223 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2224 io::ErrorKind::UnexpectedEof);
2228 fn read_exact_slice() {
2229 let mut buf = [0; 4];
2231 let mut c = &b""[..];
2232 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2233 io::ErrorKind::UnexpectedEof);
2235 let mut c = &b"123"[..];
2236 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2237 io::ErrorKind::UnexpectedEof);
2238 // make sure the optimized (early returning) method is being used
2239 assert_eq!(&buf, &[0; 4]);
2241 let mut c = &b"1234"[..];
2242 c.read_exact(&mut buf).unwrap();
2243 assert_eq!(&buf, b"1234");
2245 let mut c = &b"56789"[..];
2246 c.read_exact(&mut buf).unwrap();
2247 assert_eq!(&buf, b"5678");
2248 assert_eq!(c, b"9");
2256 fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
2257 Err(io::Error::new(io::ErrorKind::Other, ""))
2260 impl BufRead for R {
2261 fn fill_buf(&mut self) -> io::Result<&[u8]> {
2262 Err(io::Error::new(io::ErrorKind::Other, ""))
2264 fn consume(&mut self, _amt: usize) { }
2267 let mut buf = [0; 1];
2268 assert_eq!(0, R.take(0).read(&mut buf).unwrap());
2269 assert_eq!(b"", R.take(0).fill_buf().unwrap());
2272 fn cmp_bufread<Br1: BufRead, Br2: BufRead>(mut br1: Br1, mut br2: Br2, exp: &[u8]) {
2273 let mut cat = Vec::new();
2276 let buf1 = br1.fill_buf().unwrap();
2277 let buf2 = br2.fill_buf().unwrap();
2278 let minlen = if buf1.len() < buf2.len() { buf1.len() } else { buf2.len() };
2279 assert_eq!(buf1[..minlen], buf2[..minlen]);
2280 cat.extend_from_slice(&buf1[..minlen]);
2286 br1.consume(consume);
2287 br2.consume(consume);
2289 assert_eq!(br1.fill_buf().unwrap().len(), 0);
2290 assert_eq!(br2.fill_buf().unwrap().len(), 0);
2291 assert_eq!(&cat[..], &exp[..])
2295 fn chain_bufread() {
2296 let testdata = b"ABCDEFGHIJKL";
2297 let chain1 = (&testdata[..3]).chain(&testdata[3..6])
2298 .chain(&testdata[6..9])
2299 .chain(&testdata[9..]);
2300 let chain2 = (&testdata[..4]).chain(&testdata[4..8])
2301 .chain(&testdata[8..]);
2302 cmp_bufread(chain1, chain2, &testdata[..]);
2306 fn chain_zero_length_read_is_not_eof() {
2309 let mut s = String::new();
2310 let mut chain = (&a[..]).chain(&b[..]);
2311 chain.read(&mut []).unwrap();
2312 chain.read_to_string(&mut s).unwrap();
2313 assert_eq!("AB", s);
2317 #[cfg_attr(target_os = "emscripten", ignore)]
2318 fn bench_read_to_end(b: &mut test::Bencher) {
2320 let mut lr = repeat(1).take(10000000);
2321 let mut vec = Vec::with_capacity(1024);
2322 super::read_to_end(&mut lr, &mut vec)