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`][bufread], such as
416 /// [`BufReader`][bufreader], will be more efficient.
418 /// [bufread]: trait.BufRead.html
419 /// [bufreader]: struct.BufReader.html
423 /// [`File`][file]s implement `Read`:
425 /// [file]: ../fs/struct.File.html
429 /// use std::io::prelude::*;
430 /// use std::fs::File;
432 /// # fn foo() -> io::Result<()> {
433 /// let mut f = File::open("foo.txt")?;
434 /// let mut buffer = [0; 10];
436 /// // read up to 10 bytes
437 /// f.read(&mut buffer)?;
439 /// let mut buffer = vec![0; 10];
440 /// // read the whole file
441 /// f.read_to_end(&mut buffer)?;
443 /// // read into a String, so that you don't need to do the conversion.
444 /// let mut buffer = String::new();
445 /// f.read_to_string(&mut buffer)?;
447 /// // and more! See the other methods for more details.
451 #[stable(feature = "rust1", since = "1.0.0")]
453 /// Pull some bytes from this source into the specified buffer, returning
454 /// how many bytes were read.
456 /// This function does not provide any guarantees about whether it blocks
457 /// waiting for data, but if an object needs to block for a read but cannot
458 /// it will typically signal this via an `Err` return value.
460 /// If the return value of this method is `Ok(n)`, then it must be
461 /// guaranteed that `0 <= n <= buf.len()`. A nonzero `n` value indicates
462 /// that the buffer `buf` has been filled in with `n` bytes of data from this
463 /// source. If `n` is `0`, then it can indicate one of two scenarios:
465 /// 1. This reader has reached its "end of file" and will likely no longer
466 /// be able to produce bytes. Note that this does not mean that the
467 /// reader will *always* no longer be able to produce bytes.
468 /// 2. The buffer specified was 0 bytes in length.
470 /// No guarantees are provided about the contents of `buf` when this
471 /// function is called, implementations cannot rely on any property of the
472 /// contents of `buf` being true. It is recommended that implementations
473 /// only write data to `buf` instead of reading its contents.
477 /// If this function encounters any form of I/O or other error, an error
478 /// variant will be returned. If an error is returned then it must be
479 /// guaranteed that no bytes were read.
481 /// An error of the `ErrorKind::Interrupted` kind is non-fatal and the read
482 /// operation should be retried if there is nothing else to do.
486 /// [`File`][file]s implement `Read`:
488 /// [file]: ../fs/struct.File.html
492 /// use std::io::prelude::*;
493 /// use std::fs::File;
495 /// # fn foo() -> io::Result<()> {
496 /// let mut f = File::open("foo.txt")?;
497 /// let mut buffer = [0; 10];
499 /// // read up to 10 bytes
500 /// f.read(&mut buffer[..])?;
504 #[stable(feature = "rust1", since = "1.0.0")]
505 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
507 /// Determines if this `Read`er can work with buffers of uninitialized
510 /// The default implementation returns an initializer which will zero
513 /// If a `Read`er guarantees that it can work properly with uninitialized
514 /// memory, it should call `Initializer::nop()`. See the documentation for
515 /// `Initializer` for details.
517 /// The behavior of this method must be independent of the state of the
518 /// `Read`er - the method only takes `&self` so that it can be used through
523 /// This method is unsafe because a `Read`er could otherwise return a
524 /// non-zeroing `Initializer` from another `Read` type without an `unsafe`
526 #[unstable(feature = "read_initializer", issue = "42788")]
528 unsafe fn initializer(&self) -> Initializer {
529 Initializer::zeroing()
532 /// Read all bytes until EOF in this source, placing them into `buf`.
534 /// All bytes read from this source will be appended to the specified buffer
535 /// `buf`. This function will continuously call `read` to append more data to
536 /// `buf` until `read` returns either `Ok(0)` or an error of
537 /// non-`ErrorKind::Interrupted` kind.
539 /// If successful, this function will return the total number of bytes read.
543 /// If this function encounters an error of the kind
544 /// `ErrorKind::Interrupted` then the error is ignored and the operation
547 /// If any other read error is encountered then this function immediately
548 /// returns. Any bytes which have already been read will be appended to
553 /// [`File`][file]s implement `Read`:
555 /// [file]: ../fs/struct.File.html
559 /// use std::io::prelude::*;
560 /// use std::fs::File;
562 /// # fn foo() -> io::Result<()> {
563 /// let mut f = File::open("foo.txt")?;
564 /// let mut buffer = Vec::new();
566 /// // read the whole file
567 /// f.read_to_end(&mut buffer)?;
571 #[stable(feature = "rust1", since = "1.0.0")]
572 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
573 read_to_end(self, buf)
576 /// Read all bytes until EOF in this source, placing them into `buf`.
578 /// If successful, this function returns the number of bytes which were read
579 /// and appended to `buf`.
583 /// If the data in this stream is *not* valid UTF-8 then an error is
584 /// returned and `buf` is unchanged.
586 /// See [`read_to_end`][readtoend] for other error semantics.
588 /// [readtoend]: #method.read_to_end
592 /// [`File`][file]s implement `Read`:
594 /// [file]: ../fs/struct.File.html
598 /// use std::io::prelude::*;
599 /// use std::fs::File;
601 /// # fn foo() -> io::Result<()> {
602 /// let mut f = File::open("foo.txt")?;
603 /// let mut buffer = String::new();
605 /// f.read_to_string(&mut buffer)?;
609 #[stable(feature = "rust1", since = "1.0.0")]
610 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
611 // Note that we do *not* call `.read_to_end()` here. We are passing
612 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
613 // method to fill it up. An arbitrary implementation could overwrite the
614 // entire contents of the vector, not just append to it (which is what
615 // we are expecting).
617 // To prevent extraneously checking the UTF-8-ness of the entire buffer
618 // we pass it to our hardcoded `read_to_end` implementation which we
619 // know is guaranteed to only read data into the end of the buffer.
620 append_to_string(buf, |b| read_to_end(self, b))
623 /// Read the exact number of bytes required to fill `buf`.
625 /// This function reads as many bytes as necessary to completely fill the
626 /// specified buffer `buf`.
628 /// No guarantees are provided about the contents of `buf` when this
629 /// function is called, implementations cannot rely on any property of the
630 /// contents of `buf` being true. It is recommended that implementations
631 /// only write data to `buf` instead of reading its contents.
635 /// If this function encounters an error of the kind
636 /// `ErrorKind::Interrupted` then the error is ignored and the operation
639 /// If this function encounters an "end of file" before completely filling
640 /// the buffer, it returns an error of the kind `ErrorKind::UnexpectedEof`.
641 /// The contents of `buf` are unspecified in this case.
643 /// If any other read error is encountered then this function immediately
644 /// returns. The contents of `buf` are unspecified in this case.
646 /// If this function returns an error, it is unspecified how many bytes it
647 /// has read, but it will never read more than would be necessary to
648 /// completely fill the buffer.
652 /// [`File`][file]s implement `Read`:
654 /// [file]: ../fs/struct.File.html
658 /// use std::io::prelude::*;
659 /// use std::fs::File;
661 /// # fn foo() -> io::Result<()> {
662 /// let mut f = File::open("foo.txt")?;
663 /// let mut buffer = [0; 10];
665 /// // read exactly 10 bytes
666 /// f.read_exact(&mut buffer)?;
670 #[stable(feature = "read_exact", since = "1.6.0")]
671 fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
672 while !buf.is_empty() {
673 match self.read(buf) {
675 Ok(n) => { let tmp = buf; buf = &mut tmp[n..]; }
676 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
677 Err(e) => return Err(e),
681 Err(Error::new(ErrorKind::UnexpectedEof,
682 "failed to fill whole buffer"))
688 /// Creates a "by reference" adaptor for this instance of `Read`.
690 /// The returned adaptor also implements `Read` and will simply borrow this
695 /// [`File`][file]s implement `Read`:
697 /// [file]: ../fs/struct.File.html
701 /// use std::io::Read;
702 /// use std::fs::File;
704 /// # fn foo() -> io::Result<()> {
705 /// let mut f = File::open("foo.txt")?;
706 /// let mut buffer = Vec::new();
707 /// let mut other_buffer = Vec::new();
710 /// let reference = f.by_ref();
712 /// // read at most 5 bytes
713 /// reference.take(5).read_to_end(&mut buffer)?;
715 /// } // drop our &mut reference so we can use f again
717 /// // original file still usable, read the rest
718 /// f.read_to_end(&mut other_buffer)?;
722 #[stable(feature = "rust1", since = "1.0.0")]
723 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
725 /// Transforms this `Read` instance to an `Iterator` over its bytes.
727 /// The returned type implements `Iterator` where the `Item` is `Result<u8,
728 /// R::Err>`. The yielded item is `Ok` if a byte was successfully read and
729 /// `Err` otherwise for I/O errors. EOF is mapped to returning `None` from
734 /// [`File`][file]s implement `Read`:
736 /// [file]: ../fs/struct.File.html
740 /// use std::io::prelude::*;
741 /// use std::fs::File;
743 /// # fn foo() -> io::Result<()> {
744 /// let mut f = File::open("foo.txt")?;
746 /// for byte in f.bytes() {
747 /// println!("{}", byte.unwrap());
752 #[stable(feature = "rust1", since = "1.0.0")]
753 fn bytes(self) -> Bytes<Self> where Self: Sized {
754 Bytes { inner: self }
757 /// Transforms this `Read` instance to an `Iterator` over `char`s.
759 /// This adaptor will attempt to interpret this reader as a UTF-8 encoded
760 /// sequence of characters. The returned iterator will return `None` once
761 /// EOF is reached for this reader. Otherwise each element yielded will be a
762 /// `Result<char, E>` where `E` may contain information about what I/O error
763 /// occurred or where decoding failed.
765 /// Currently this adaptor will discard intermediate data read, and should
766 /// be avoided if this is not desired.
770 /// [`File`][file]s implement `Read`:
772 /// [file]: ../fs/struct.File.html
777 /// use std::io::prelude::*;
778 /// use std::fs::File;
780 /// # fn foo() -> io::Result<()> {
781 /// let mut f = File::open("foo.txt")?;
783 /// for c in f.chars() {
784 /// println!("{}", c.unwrap());
789 #[unstable(feature = "io", reason = "the semantics of a partial read/write \
790 of where errors happen is currently \
791 unclear and may change",
793 fn chars(self) -> Chars<Self> where Self: Sized {
794 Chars { inner: self }
797 /// Creates an adaptor which will chain this stream with another.
799 /// The returned `Read` instance will first read all bytes from this object
800 /// until EOF is encountered. Afterwards the output is equivalent to the
801 /// output of `next`.
805 /// [`File`][file]s implement `Read`:
807 /// [file]: ../fs/struct.File.html
811 /// use std::io::prelude::*;
812 /// use std::fs::File;
814 /// # fn foo() -> io::Result<()> {
815 /// let mut f1 = File::open("foo.txt")?;
816 /// let mut f2 = File::open("bar.txt")?;
818 /// let mut handle = f1.chain(f2);
819 /// let mut buffer = String::new();
821 /// // read the value into a String. We could use any Read method here,
822 /// // this is just one example.
823 /// handle.read_to_string(&mut buffer)?;
827 #[stable(feature = "rust1", since = "1.0.0")]
828 fn chain<R: Read>(self, next: R) -> Chain<Self, R> where Self: Sized {
829 Chain { first: self, second: next, done_first: false }
832 /// Creates an adaptor which will read at most `limit` bytes from it.
834 /// This function returns a new instance of `Read` which will read at most
835 /// `limit` bytes, after which it will always return EOF (`Ok(0)`). Any
836 /// read errors will not count towards the number of bytes read and future
837 /// calls to `read` may succeed.
841 /// [`File`][file]s implement `Read`:
843 /// [file]: ../fs/struct.File.html
847 /// use std::io::prelude::*;
848 /// use std::fs::File;
850 /// # fn foo() -> io::Result<()> {
851 /// let mut f = File::open("foo.txt")?;
852 /// let mut buffer = [0; 5];
854 /// // read at most five bytes
855 /// let mut handle = f.take(5);
857 /// handle.read(&mut buffer)?;
861 #[stable(feature = "rust1", since = "1.0.0")]
862 fn take(self, limit: u64) -> Take<Self> where Self: Sized {
863 Take { inner: self, limit: limit }
867 /// A type used to conditionally initialize buffers passed to `Read` methods.
868 #[unstable(feature = "read_initializer", issue = "42788")]
870 pub struct Initializer(bool);
873 /// Returns a new `Initializer` which will zero out buffers.
874 #[unstable(feature = "read_initializer", issue = "42788")]
876 pub fn zeroing() -> Initializer {
880 /// Returns a new `Initializer` which will not zero out buffers.
884 /// This may only be called by `Read`ers which guarantee that they will not
885 /// read from buffers passed to `Read` methods, and that the return value of
886 /// the method accurately reflects the number of bytes that have been
887 /// written to the head of the buffer.
888 #[unstable(feature = "read_initializer", issue = "42788")]
890 pub unsafe fn nop() -> Initializer {
894 /// Indicates if a buffer should be initialized.
895 #[unstable(feature = "read_initializer", issue = "42788")]
897 pub fn should_initialize(&self) -> bool {
901 /// Initializes a buffer if necessary.
902 #[unstable(feature = "read_initializer", issue = "42788")]
904 pub fn initialize(&self, buf: &mut [u8]) {
905 if self.should_initialize() {
906 unsafe { ptr::write_bytes(buf.as_mut_ptr(), 0, buf.len()) }
911 /// A trait for objects which are byte-oriented sinks.
913 /// Implementors of the `Write` trait are sometimes called 'writers'.
915 /// Writers are defined by two required methods, [`write`] and [`flush`]:
917 /// * The [`write`] method will attempt to write some data into the object,
918 /// returning how many bytes were successfully written.
920 /// * The [`flush`] method is useful for adaptors and explicit buffers
921 /// themselves for ensuring that all buffered data has been pushed out to the
924 /// Writers are intended to be composable with one another. Many implementors
925 /// throughout [`std::io`] take and provide types which implement the `Write`
928 /// [`write`]: #tymethod.write
929 /// [`flush`]: #tymethod.flush
930 /// [`std::io`]: index.html
935 /// use std::io::prelude::*;
936 /// use std::fs::File;
938 /// # fn foo() -> std::io::Result<()> {
939 /// let mut buffer = File::create("foo.txt")?;
941 /// buffer.write(b"some bytes")?;
945 #[stable(feature = "rust1", since = "1.0.0")]
947 /// Write a buffer into this object, returning how many bytes were written.
949 /// This function will attempt to write the entire contents of `buf`, but
950 /// the entire write may not succeed, or the write may also generate an
951 /// error. A call to `write` represents *at most one* attempt to write to
952 /// any wrapped object.
954 /// Calls to `write` are not guaranteed to block waiting for data to be
955 /// written, and a write which would otherwise block can be indicated through
956 /// an `Err` variant.
958 /// If the return value is `Ok(n)` then it must be guaranteed that
959 /// `0 <= n <= buf.len()`. A return value of `0` typically means that the
960 /// underlying object is no longer able to accept bytes and will likely not
961 /// be able to in the future as well, or that the buffer provided is empty.
965 /// Each call to `write` may generate an I/O error indicating that the
966 /// operation could not be completed. If an error is returned then no bytes
967 /// in the buffer were written to this writer.
969 /// It is **not** considered an error if the entire buffer could not be
970 /// written to this writer.
972 /// An error of the `ErrorKind::Interrupted` kind is non-fatal and the
973 /// write operation should be retried if there is nothing else to do.
978 /// use std::io::prelude::*;
979 /// use std::fs::File;
981 /// # fn foo() -> std::io::Result<()> {
982 /// let mut buffer = File::create("foo.txt")?;
984 /// // Writes some prefix of the byte string, not necessarily all of it.
985 /// buffer.write(b"some bytes")?;
989 #[stable(feature = "rust1", since = "1.0.0")]
990 fn write(&mut self, buf: &[u8]) -> Result<usize>;
992 /// Flush this output stream, ensuring that all intermediately buffered
993 /// contents reach their destination.
997 /// It is considered an error if not all bytes could be written due to
998 /// I/O errors or EOF being reached.
1003 /// use std::io::prelude::*;
1004 /// use std::io::BufWriter;
1005 /// use std::fs::File;
1007 /// # fn foo() -> std::io::Result<()> {
1008 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
1010 /// buffer.write(b"some bytes")?;
1011 /// buffer.flush()?;
1015 #[stable(feature = "rust1", since = "1.0.0")]
1016 fn flush(&mut self) -> Result<()>;
1018 /// Attempts to write an entire buffer into this write.
1020 /// This method will continuously call `write` until there is no more data
1021 /// to be written or an error of non-`ErrorKind::Interrupted` kind is
1022 /// returned. This method will not return until the entire buffer has been
1023 /// successfully written or such an error occurs. The first error that is
1024 /// not of `ErrorKind::Interrupted` kind generated from this method will be
1029 /// This function will return the first error of
1030 /// non-`ErrorKind::Interrupted` kind that `write` returns.
1035 /// use std::io::prelude::*;
1036 /// use std::fs::File;
1038 /// # fn foo() -> std::io::Result<()> {
1039 /// let mut buffer = File::create("foo.txt")?;
1041 /// buffer.write_all(b"some bytes")?;
1045 #[stable(feature = "rust1", since = "1.0.0")]
1046 fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
1047 while !buf.is_empty() {
1048 match self.write(buf) {
1049 Ok(0) => return Err(Error::new(ErrorKind::WriteZero,
1050 "failed to write whole buffer")),
1051 Ok(n) => buf = &buf[n..],
1052 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1053 Err(e) => return Err(e),
1059 /// Writes a formatted string into this writer, returning any error
1062 /// This method is primarily used to interface with the
1063 /// [`format_args!`][formatargs] macro, but it is rare that this should
1064 /// explicitly be called. The [`write!`][write] macro should be favored to
1065 /// invoke this method instead.
1067 /// [formatargs]: ../macro.format_args.html
1068 /// [write]: ../macro.write.html
1070 /// This function internally uses the [`write_all`][writeall] method on
1071 /// this trait and hence will continuously write data so long as no errors
1072 /// are received. This also means that partial writes are not indicated in
1075 /// [writeall]: #method.write_all
1079 /// This function will return any I/O error reported while formatting.
1084 /// use std::io::prelude::*;
1085 /// use std::fs::File;
1087 /// # fn foo() -> std::io::Result<()> {
1088 /// let mut buffer = File::create("foo.txt")?;
1091 /// write!(buffer, "{:.*}", 2, 1.234567)?;
1092 /// // turns into this:
1093 /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1097 #[stable(feature = "rust1", since = "1.0.0")]
1098 fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()> {
1099 // Create a shim which translates a Write to a fmt::Write and saves
1100 // off I/O errors. instead of discarding them
1101 struct Adaptor<'a, T: ?Sized + 'a> {
1106 impl<'a, T: Write + ?Sized> fmt::Write for Adaptor<'a, T> {
1107 fn write_str(&mut self, s: &str) -> fmt::Result {
1108 match self.inner.write_all(s.as_bytes()) {
1111 self.error = Err(e);
1118 let mut output = Adaptor { inner: self, error: Ok(()) };
1119 match fmt::write(&mut output, fmt) {
1122 // check if the error came from the underlying `Write` or not
1123 if output.error.is_err() {
1126 Err(Error::new(ErrorKind::Other, "formatter error"))
1132 /// Creates a "by reference" adaptor for this instance of `Write`.
1134 /// The returned adaptor also implements `Write` and will simply borrow this
1140 /// use std::io::Write;
1141 /// use std::fs::File;
1143 /// # fn foo() -> std::io::Result<()> {
1144 /// let mut buffer = File::create("foo.txt")?;
1146 /// let reference = buffer.by_ref();
1148 /// // we can use reference just like our original buffer
1149 /// reference.write_all(b"some bytes")?;
1153 #[stable(feature = "rust1", since = "1.0.0")]
1154 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1157 /// The `Seek` trait provides a cursor which can be moved within a stream of
1160 /// The stream typically has a fixed size, allowing seeking relative to either
1161 /// end or the current offset.
1165 /// [`File`][file]s implement `Seek`:
1167 /// [file]: ../fs/struct.File.html
1171 /// use std::io::prelude::*;
1172 /// use std::fs::File;
1173 /// use std::io::SeekFrom;
1175 /// # fn foo() -> io::Result<()> {
1176 /// let mut f = File::open("foo.txt")?;
1178 /// // move the cursor 42 bytes from the start of the file
1179 /// f.seek(SeekFrom::Start(42))?;
1183 #[stable(feature = "rust1", since = "1.0.0")]
1185 /// Seek to an offset, in bytes, in a stream.
1187 /// A seek beyond the end of a stream is allowed, but implementation
1190 /// If the seek operation completed successfully,
1191 /// this method returns the new position from the start of the stream.
1192 /// That position can be used later with [`SeekFrom::Start`].
1196 /// Seeking to a negative offset is considered an error.
1198 /// [`SeekFrom::Start`]: enum.SeekFrom.html#variant.Start
1199 #[stable(feature = "rust1", since = "1.0.0")]
1200 fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1203 /// Enumeration of possible methods to seek within an I/O object.
1205 /// It is used by the [`Seek`] trait.
1207 /// [`Seek`]: trait.Seek.html
1208 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1209 #[stable(feature = "rust1", since = "1.0.0")]
1211 /// Set the offset to the provided number of bytes.
1212 #[stable(feature = "rust1", since = "1.0.0")]
1213 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1215 /// Set the offset to the size of this object plus the specified number of
1218 /// It is possible to seek beyond the end of an object, but it's an error to
1219 /// seek before byte 0.
1220 #[stable(feature = "rust1", since = "1.0.0")]
1221 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1223 /// Set the offset to the current position plus the specified number of
1226 /// It is possible to seek beyond the end of an object, but it's an error to
1227 /// seek before byte 0.
1228 #[stable(feature = "rust1", since = "1.0.0")]
1229 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1232 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>)
1236 let (done, used) = {
1237 let available = match r.fill_buf() {
1239 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1240 Err(e) => return Err(e)
1242 match memchr::memchr(delim, available) {
1244 buf.extend_from_slice(&available[..i + 1]);
1248 buf.extend_from_slice(available);
1249 (false, available.len())
1255 if done || used == 0 {
1261 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1262 /// to perform extra ways of reading.
1264 /// For example, reading line-by-line is inefficient without using a buffer, so
1265 /// if you want to read by line, you'll need `BufRead`, which includes a
1266 /// [`read_line`] method as well as a [`lines`] iterator.
1270 /// A locked standard input implements `BufRead`:
1274 /// use std::io::prelude::*;
1276 /// let stdin = io::stdin();
1277 /// for line in stdin.lock().lines() {
1278 /// println!("{}", line.unwrap());
1282 /// If you have something that implements [`Read`], you can use the [`BufReader`
1283 /// type][`BufReader`] to turn it into a `BufRead`.
1285 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1286 /// [`BufReader`] to the rescue!
1288 /// [`BufReader`]: struct.BufReader.html
1289 /// [`File`]: ../fs/struct.File.html
1290 /// [`read_line`]: #method.read_line
1291 /// [`lines`]: #method.lines
1292 /// [`Read`]: trait.Read.html
1295 /// use std::io::{self, BufReader};
1296 /// use std::io::prelude::*;
1297 /// use std::fs::File;
1299 /// # fn foo() -> io::Result<()> {
1300 /// let f = File::open("foo.txt")?;
1301 /// let f = BufReader::new(f);
1303 /// for line in f.lines() {
1304 /// println!("{}", line.unwrap());
1311 #[stable(feature = "rust1", since = "1.0.0")]
1312 pub trait BufRead: Read {
1313 /// Fills the internal buffer of this object, returning the buffer contents.
1315 /// This function is a lower-level call. It needs to be paired with the
1316 /// [`consume`] method to function properly. When calling this
1317 /// method, none of the contents will be "read" in the sense that later
1318 /// calling `read` may return the same contents. As such, [`consume`] must
1319 /// be called with the number of bytes that are consumed from this buffer to
1320 /// ensure that the bytes are never returned twice.
1322 /// [`consume`]: #tymethod.consume
1324 /// An empty buffer returned indicates that the stream has reached EOF.
1328 /// This function will return an I/O error if the underlying reader was
1329 /// read, but returned an error.
1333 /// A locked standard input implements `BufRead`:
1337 /// use std::io::prelude::*;
1339 /// let stdin = io::stdin();
1340 /// let mut stdin = stdin.lock();
1342 /// // we can't have two `&mut` references to `stdin`, so use a block
1343 /// // to end the borrow early.
1345 /// let buffer = stdin.fill_buf().unwrap();
1347 /// // work with buffer
1348 /// println!("{:?}", buffer);
1353 /// // ensure the bytes we worked with aren't returned again later
1354 /// stdin.consume(length);
1356 #[stable(feature = "rust1", since = "1.0.0")]
1357 fn fill_buf(&mut self) -> Result<&[u8]>;
1359 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1360 /// so they should no longer be returned in calls to `read`.
1362 /// This function is a lower-level call. It needs to be paired with the
1363 /// [`fill_buf`] method to function properly. This function does
1364 /// not perform any I/O, it simply informs this object that some amount of
1365 /// its buffer, returned from [`fill_buf`], has been consumed and should
1366 /// no longer be returned. As such, this function may do odd things if
1367 /// [`fill_buf`] isn't called before calling it.
1369 /// The `amt` must be `<=` the number of bytes in the buffer returned by
1374 /// Since `consume()` is meant to be used with [`fill_buf`],
1375 /// that method's example includes an example of `consume()`.
1377 /// [`fill_buf`]: #tymethod.fill_buf
1378 #[stable(feature = "rust1", since = "1.0.0")]
1379 fn consume(&mut self, amt: usize);
1381 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
1383 /// This function will read bytes from the underlying stream until the
1384 /// delimiter or EOF is found. Once found, all bytes up to, and including,
1385 /// the delimiter (if found) will be appended to `buf`.
1387 /// If successful, this function will return the total number of bytes read.
1391 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1392 /// will otherwise return any errors returned by [`fill_buf`].
1394 /// If an I/O error is encountered then all bytes read so far will be
1395 /// present in `buf` and its length will have been adjusted appropriately.
1397 /// [`fill_buf`]: #tymethod.fill_buf
1398 /// [`ErrorKind::Interrupted`]: enum.ErrorKind.html#variant.Interrupted
1402 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1403 /// this example, we use [`Cursor`] to read all the bytes in a byte slice
1404 /// in hyphen delimited segments:
1406 /// [`Cursor`]: struct.Cursor.html
1409 /// use std::io::{self, BufRead};
1411 /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
1412 /// let mut buf = vec![];
1414 /// // cursor is at 'l'
1415 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1416 /// .expect("reading from cursor won't fail");
1417 /// assert_eq!(num_bytes, 6);
1418 /// assert_eq!(buf, b"lorem-");
1421 /// // cursor is at 'i'
1422 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1423 /// .expect("reading from cursor won't fail");
1424 /// assert_eq!(num_bytes, 5);
1425 /// assert_eq!(buf, b"ipsum");
1428 /// // cursor is at EOF
1429 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1430 /// .expect("reading from cursor won't fail");
1431 /// assert_eq!(num_bytes, 0);
1432 /// assert_eq!(buf, b"");
1434 #[stable(feature = "rust1", since = "1.0.0")]
1435 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
1436 read_until(self, byte, buf)
1439 /// Read all bytes until a newline (the 0xA byte) is reached, and append
1440 /// them to the provided buffer.
1442 /// This function will read bytes from the underlying stream until the
1443 /// newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes
1444 /// up to, and including, the delimiter (if found) will be appended to
1447 /// If successful, this function will return the total number of bytes read.
1451 /// This function has the same error semantics as [`read_until`] and will
1452 /// also return an error if the read bytes are not valid UTF-8. If an I/O
1453 /// error is encountered then `buf` may contain some bytes already read in
1454 /// the event that all data read so far was valid UTF-8.
1458 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1459 /// this example, we use [`Cursor`] to read all the lines in a byte slice:
1461 /// [`Cursor`]: struct.Cursor.html
1464 /// use std::io::{self, BufRead};
1466 /// let mut cursor = io::Cursor::new(b"foo\nbar");
1467 /// let mut buf = String::new();
1469 /// // cursor is at 'f'
1470 /// let num_bytes = cursor.read_line(&mut buf)
1471 /// .expect("reading from cursor won't fail");
1472 /// assert_eq!(num_bytes, 4);
1473 /// assert_eq!(buf, "foo\n");
1476 /// // cursor is at 'b'
1477 /// let num_bytes = cursor.read_line(&mut buf)
1478 /// .expect("reading from cursor won't fail");
1479 /// assert_eq!(num_bytes, 3);
1480 /// assert_eq!(buf, "bar");
1483 /// // cursor is at EOF
1484 /// let num_bytes = cursor.read_line(&mut buf)
1485 /// .expect("reading from cursor won't fail");
1486 /// assert_eq!(num_bytes, 0);
1487 /// assert_eq!(buf, "");
1489 #[stable(feature = "rust1", since = "1.0.0")]
1490 fn read_line(&mut self, buf: &mut String) -> Result<usize> {
1491 // Note that we are not calling the `.read_until` method here, but
1492 // rather our hardcoded implementation. For more details as to why, see
1493 // the comments in `read_to_end`.
1494 append_to_string(buf, |b| read_until(self, b'\n', b))
1497 /// Returns an iterator over the contents of this reader split on the byte
1500 /// The iterator returned from this function will return instances of
1501 /// [`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
1502 /// the delimiter byte at the end.
1504 /// This function will yield errors whenever [`read_until`] would have
1505 /// also yielded an error.
1507 /// [`io::Result`]: type.Result.html
1508 /// [`Vec<u8>`]: ../vec/struct.Vec.html
1509 /// [`read_until`]: #method.read_until
1513 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1514 /// this example, we use [`Cursor`] to iterate over all hyphen delimited
1515 /// segments in a byte slice
1517 /// [`Cursor`]: struct.Cursor.html
1520 /// use std::io::{self, BufRead};
1522 /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
1524 /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
1525 /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
1526 /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
1527 /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
1528 /// assert_eq!(split_iter.next(), None);
1530 #[stable(feature = "rust1", since = "1.0.0")]
1531 fn split(self, byte: u8) -> Split<Self> where Self: Sized {
1532 Split { buf: self, delim: byte }
1535 /// Returns an iterator over the lines of this reader.
1537 /// The iterator returned from this function will yield instances of
1538 /// [`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline
1539 /// byte (the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.
1541 /// [`io::Result`]: type.Result.html
1542 /// [`String`]: ../string/struct.String.html
1546 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1547 /// this example, we use [`Cursor`] to iterate over all the lines in a byte
1550 /// [`Cursor`]: struct.Cursor.html
1553 /// use std::io::{self, BufRead};
1555 /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
1557 /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
1558 /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
1559 /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
1560 /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
1561 /// assert_eq!(lines_iter.next(), None);
1566 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
1568 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
1569 #[stable(feature = "rust1", since = "1.0.0")]
1570 fn lines(self) -> Lines<Self> where Self: Sized {
1575 /// Adaptor to chain together two readers.
1577 /// This struct is generally created by calling [`chain`] on a reader.
1578 /// Please see the documentation of [`chain`] for more details.
1580 /// [`chain`]: trait.Read.html#method.chain
1581 #[stable(feature = "rust1", since = "1.0.0")]
1582 pub struct Chain<T, U> {
1588 impl<T, U> Chain<T, U> {
1589 /// Consumes the `Chain`, returning the wrapped readers.
1595 /// use std::io::prelude::*;
1596 /// use std::fs::File;
1598 /// # fn foo() -> io::Result<()> {
1599 /// let mut foo_file = File::open("foo.txt")?;
1600 /// let mut bar_file = File::open("bar.txt")?;
1602 /// let chain = foo_file.chain(bar_file);
1603 /// let (foo_file, bar_file) = chain.into_inner();
1607 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1608 pub fn into_inner(self) -> (T, U) {
1609 (self.first, self.second)
1612 /// Gets references to the underlying readers in this `Chain`.
1618 /// use std::io::prelude::*;
1619 /// use std::fs::File;
1621 /// # fn foo() -> io::Result<()> {
1622 /// let mut foo_file = File::open("foo.txt")?;
1623 /// let mut bar_file = File::open("bar.txt")?;
1625 /// let chain = foo_file.chain(bar_file);
1626 /// let (foo_file, bar_file) = chain.get_ref();
1630 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1631 pub fn get_ref(&self) -> (&T, &U) {
1632 (&self.first, &self.second)
1635 /// Gets mutable references to the underlying readers in this `Chain`.
1637 /// Care should be taken to avoid modifying the internal I/O state of the
1638 /// underlying readers as doing so may corrupt the internal state of this
1645 /// use std::io::prelude::*;
1646 /// use std::fs::File;
1648 /// # fn foo() -> io::Result<()> {
1649 /// let mut foo_file = File::open("foo.txt")?;
1650 /// let mut bar_file = File::open("bar.txt")?;
1652 /// let mut chain = foo_file.chain(bar_file);
1653 /// let (foo_file, bar_file) = chain.get_mut();
1657 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1658 pub fn get_mut(&mut self) -> (&mut T, &mut U) {
1659 (&mut self.first, &mut self.second)
1663 #[stable(feature = "std_debug", since = "1.16.0")]
1664 impl<T: fmt::Debug, U: fmt::Debug> fmt::Debug for Chain<T, U> {
1665 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1666 f.debug_struct("Chain")
1667 .field("t", &self.first)
1668 .field("u", &self.second)
1673 #[stable(feature = "rust1", since = "1.0.0")]
1674 impl<T: Read, U: Read> Read for Chain<T, U> {
1675 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1676 if !self.done_first {
1677 match self.first.read(buf)? {
1678 0 if buf.len() != 0 => { self.done_first = true; }
1682 self.second.read(buf)
1685 unsafe fn initializer(&self) -> Initializer {
1686 let initializer = self.first.initializer();
1687 if initializer.should_initialize() {
1690 self.second.initializer()
1695 #[stable(feature = "chain_bufread", since = "1.9.0")]
1696 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
1697 fn fill_buf(&mut self) -> Result<&[u8]> {
1698 if !self.done_first {
1699 match self.first.fill_buf()? {
1700 buf if buf.len() == 0 => { self.done_first = true; }
1701 buf => return Ok(buf),
1704 self.second.fill_buf()
1707 fn consume(&mut self, amt: usize) {
1708 if !self.done_first {
1709 self.first.consume(amt)
1711 self.second.consume(amt)
1716 /// Reader adaptor which limits the bytes read from an underlying reader.
1718 /// This struct is generally created by calling [`take`] on a reader.
1719 /// Please see the documentation of [`take`] for more details.
1721 /// [`take`]: trait.Read.html#method.take
1722 #[stable(feature = "rust1", since = "1.0.0")]
1724 pub struct Take<T> {
1730 /// Returns the number of bytes that can be read before this instance will
1735 /// This instance may reach `EOF` after reading fewer bytes than indicated by
1736 /// this method if the underlying [`Read`] instance reaches EOF.
1738 /// [`Read`]: ../../std/io/trait.Read.html
1744 /// use std::io::prelude::*;
1745 /// use std::fs::File;
1747 /// # fn foo() -> io::Result<()> {
1748 /// let f = File::open("foo.txt")?;
1750 /// // read at most five bytes
1751 /// let handle = f.take(5);
1753 /// println!("limit: {}", handle.limit());
1757 #[stable(feature = "rust1", since = "1.0.0")]
1758 pub fn limit(&self) -> u64 { self.limit }
1760 /// Sets the number of bytes that can be read before this instance will
1761 /// return EOF. This is the same as constructing a new `Take` instance, so
1762 /// the amount of bytes read and the previous limit value don't matter when
1763 /// calling this method.
1768 /// #![feature(take_set_limit)]
1770 /// use std::io::prelude::*;
1771 /// use std::fs::File;
1773 /// # fn foo() -> io::Result<()> {
1774 /// let f = File::open("foo.txt")?;
1776 /// // read at most five bytes
1777 /// let mut handle = f.take(5);
1778 /// handle.set_limit(10);
1780 /// assert_eq!(handle.limit(), 10);
1784 #[unstable(feature = "take_set_limit", issue = "42781")]
1785 pub fn set_limit(&mut self, limit: u64) {
1789 /// Consumes the `Take`, returning the wrapped reader.
1795 /// use std::io::prelude::*;
1796 /// use std::fs::File;
1798 /// # fn foo() -> io::Result<()> {
1799 /// let mut file = File::open("foo.txt")?;
1801 /// let mut buffer = [0; 5];
1802 /// let mut handle = file.take(5);
1803 /// handle.read(&mut buffer)?;
1805 /// let file = handle.into_inner();
1809 #[stable(feature = "io_take_into_inner", since = "1.15.0")]
1810 pub fn into_inner(self) -> T {
1814 /// Gets a reference to the underlying reader.
1820 /// use std::io::prelude::*;
1821 /// use std::fs::File;
1823 /// # fn foo() -> io::Result<()> {
1824 /// let mut file = File::open("foo.txt")?;
1826 /// let mut buffer = [0; 5];
1827 /// let mut handle = file.take(5);
1828 /// handle.read(&mut buffer)?;
1830 /// let file = handle.get_ref();
1834 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1835 pub fn get_ref(&self) -> &T {
1839 /// Gets a mutable reference to the underlying reader.
1841 /// Care should be taken to avoid modifying the internal I/O state of the
1842 /// underlying reader as doing so may corrupt the internal limit of this
1849 /// use std::io::prelude::*;
1850 /// use std::fs::File;
1852 /// # fn foo() -> io::Result<()> {
1853 /// let mut file = File::open("foo.txt")?;
1855 /// let mut buffer = [0; 5];
1856 /// let mut handle = file.take(5);
1857 /// handle.read(&mut buffer)?;
1859 /// let file = handle.get_mut();
1863 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1864 pub fn get_mut(&mut self) -> &mut T {
1869 #[stable(feature = "rust1", since = "1.0.0")]
1870 impl<T: Read> Read for Take<T> {
1871 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1872 // Don't call into inner reader at all at EOF because it may still block
1873 if self.limit == 0 {
1877 let max = cmp::min(buf.len() as u64, self.limit) as usize;
1878 let n = self.inner.read(&mut buf[..max])?;
1879 self.limit -= n as u64;
1883 unsafe fn initializer(&self) -> Initializer {
1884 self.inner.initializer()
1888 #[stable(feature = "rust1", since = "1.0.0")]
1889 impl<T: BufRead> BufRead for Take<T> {
1890 fn fill_buf(&mut self) -> Result<&[u8]> {
1891 // Don't call into inner reader at all at EOF because it may still block
1892 if self.limit == 0 {
1896 let buf = self.inner.fill_buf()?;
1897 let cap = cmp::min(buf.len() as u64, self.limit) as usize;
1901 fn consume(&mut self, amt: usize) {
1902 // Don't let callers reset the limit by passing an overlarge value
1903 let amt = cmp::min(amt as u64, self.limit) as usize;
1904 self.limit -= amt as u64;
1905 self.inner.consume(amt);
1909 fn read_one_byte(reader: &mut Read) -> Option<Result<u8>> {
1912 return match reader.read(&mut buf) {
1914 Ok(..) => Some(Ok(buf[0])),
1915 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1916 Err(e) => Some(Err(e)),
1921 /// An iterator over `u8` values of a reader.
1923 /// This struct is generally created by calling [`bytes`] on a reader.
1924 /// Please see the documentation of [`bytes`] for more details.
1926 /// [`bytes`]: trait.Read.html#method.bytes
1927 #[stable(feature = "rust1", since = "1.0.0")]
1929 pub struct Bytes<R> {
1933 #[stable(feature = "rust1", since = "1.0.0")]
1934 impl<R: Read> Iterator for Bytes<R> {
1935 type Item = Result<u8>;
1937 fn next(&mut self) -> Option<Result<u8>> {
1938 read_one_byte(&mut self.inner)
1942 /// An iterator over the `char`s of a reader.
1944 /// This struct is generally created by calling [`chars`][chars] on a reader.
1945 /// Please see the documentation of `chars()` for more details.
1947 /// [chars]: trait.Read.html#method.chars
1948 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1951 pub struct Chars<R> {
1955 /// An enumeration of possible errors that can be generated from the `Chars`
1958 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1960 pub enum CharsError {
1961 /// Variant representing that the underlying stream was read successfully
1962 /// but it did not contain valid utf8 data.
1965 /// Variant representing that an I/O error occurred.
1969 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1971 impl<R: Read> Iterator for Chars<R> {
1972 type Item = result::Result<char, CharsError>;
1974 fn next(&mut self) -> Option<result::Result<char, CharsError>> {
1975 let first_byte = match read_one_byte(&mut self.inner) {
1976 None => return None,
1978 Some(Err(e)) => return Some(Err(CharsError::Other(e))),
1980 let width = core_str::utf8_char_width(first_byte);
1981 if width == 1 { return Some(Ok(first_byte as char)) }
1982 if width == 0 { return Some(Err(CharsError::NotUtf8)) }
1983 let mut buf = [first_byte, 0, 0, 0];
1986 while start < width {
1987 match self.inner.read(&mut buf[start..width]) {
1988 Ok(0) => return Some(Err(CharsError::NotUtf8)),
1989 Ok(n) => start += n,
1990 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1991 Err(e) => return Some(Err(CharsError::Other(e))),
1995 Some(match str::from_utf8(&buf[..width]).ok() {
1996 Some(s) => Ok(s.chars().next().unwrap()),
1997 None => Err(CharsError::NotUtf8),
2002 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
2004 impl std_error::Error for CharsError {
2005 fn description(&self) -> &str {
2007 CharsError::NotUtf8 => "invalid utf8 encoding",
2008 CharsError::Other(ref e) => std_error::Error::description(e),
2011 fn cause(&self) -> Option<&std_error::Error> {
2013 CharsError::NotUtf8 => None,
2014 CharsError::Other(ref e) => e.cause(),
2019 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
2021 impl fmt::Display for CharsError {
2022 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2024 CharsError::NotUtf8 => {
2025 "byte stream did not contain valid utf8".fmt(f)
2027 CharsError::Other(ref e) => e.fmt(f),
2032 /// An iterator over the contents of an instance of `BufRead` split on a
2033 /// particular byte.
2035 /// This struct is generally created by calling [`split`][split] on a
2036 /// `BufRead`. Please see the documentation of `split()` for more details.
2038 /// [split]: trait.BufRead.html#method.split
2039 #[stable(feature = "rust1", since = "1.0.0")]
2041 pub struct Split<B> {
2046 #[stable(feature = "rust1", since = "1.0.0")]
2047 impl<B: BufRead> Iterator for Split<B> {
2048 type Item = Result<Vec<u8>>;
2050 fn next(&mut self) -> Option<Result<Vec<u8>>> {
2051 let mut buf = Vec::new();
2052 match self.buf.read_until(self.delim, &mut buf) {
2055 if buf[buf.len() - 1] == self.delim {
2060 Err(e) => Some(Err(e))
2065 /// An iterator over the lines of an instance of `BufRead`.
2067 /// This struct is generally created by calling [`lines`][lines] on a
2068 /// `BufRead`. Please see the documentation of `lines()` for more details.
2070 /// [lines]: trait.BufRead.html#method.lines
2071 #[stable(feature = "rust1", since = "1.0.0")]
2073 pub struct Lines<B> {
2077 #[stable(feature = "rust1", since = "1.0.0")]
2078 impl<B: BufRead> Iterator for Lines<B> {
2079 type Item = Result<String>;
2081 fn next(&mut self) -> Option<Result<String>> {
2082 let mut buf = String::new();
2083 match self.buf.read_line(&mut buf) {
2086 if buf.ends_with("\n") {
2088 if buf.ends_with("\r") {
2094 Err(e) => Some(Err(e))
2108 #[cfg_attr(target_os = "emscripten", ignore)]
2110 let mut buf = Cursor::new(&b"12"[..]);
2111 let mut v = Vec::new();
2112 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 2);
2113 assert_eq!(v, b"12");
2115 let mut buf = Cursor::new(&b"1233"[..]);
2116 let mut v = Vec::new();
2117 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 3);
2118 assert_eq!(v, b"123");
2120 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 1);
2121 assert_eq!(v, b"3");
2123 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 0);
2129 let buf = Cursor::new(&b"12"[..]);
2130 let mut s = buf.split(b'3');
2131 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2132 assert!(s.next().is_none());
2134 let buf = Cursor::new(&b"1233"[..]);
2135 let mut s = buf.split(b'3');
2136 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2137 assert_eq!(s.next().unwrap().unwrap(), vec![]);
2138 assert!(s.next().is_none());
2143 let mut buf = Cursor::new(&b"12"[..]);
2144 let mut v = String::new();
2145 assert_eq!(buf.read_line(&mut v).unwrap(), 2);
2146 assert_eq!(v, "12");
2148 let mut buf = Cursor::new(&b"12\n\n"[..]);
2149 let mut v = String::new();
2150 assert_eq!(buf.read_line(&mut v).unwrap(), 3);
2151 assert_eq!(v, "12\n");
2153 assert_eq!(buf.read_line(&mut v).unwrap(), 1);
2154 assert_eq!(v, "\n");
2156 assert_eq!(buf.read_line(&mut v).unwrap(), 0);
2162 let buf = Cursor::new(&b"12\r"[..]);
2163 let mut s = buf.lines();
2164 assert_eq!(s.next().unwrap().unwrap(), "12\r".to_string());
2165 assert!(s.next().is_none());
2167 let buf = Cursor::new(&b"12\r\n\n"[..]);
2168 let mut s = buf.lines();
2169 assert_eq!(s.next().unwrap().unwrap(), "12".to_string());
2170 assert_eq!(s.next().unwrap().unwrap(), "".to_string());
2171 assert!(s.next().is_none());
2176 let mut c = Cursor::new(&b""[..]);
2177 let mut v = Vec::new();
2178 assert_eq!(c.read_to_end(&mut v).unwrap(), 0);
2181 let mut c = Cursor::new(&b"1"[..]);
2182 let mut v = Vec::new();
2183 assert_eq!(c.read_to_end(&mut v).unwrap(), 1);
2184 assert_eq!(v, b"1");
2186 let cap = 1024 * 1024;
2187 let data = (0..cap).map(|i| (i / 3) as u8).collect::<Vec<_>>();
2188 let mut v = Vec::new();
2189 let (a, b) = data.split_at(data.len() / 2);
2190 assert_eq!(Cursor::new(a).read_to_end(&mut v).unwrap(), a.len());
2191 assert_eq!(Cursor::new(b).read_to_end(&mut v).unwrap(), b.len());
2192 assert_eq!(v, data);
2196 fn read_to_string() {
2197 let mut c = Cursor::new(&b""[..]);
2198 let mut v = String::new();
2199 assert_eq!(c.read_to_string(&mut v).unwrap(), 0);
2202 let mut c = Cursor::new(&b"1"[..]);
2203 let mut v = String::new();
2204 assert_eq!(c.read_to_string(&mut v).unwrap(), 1);
2207 let mut c = Cursor::new(&b"\xff"[..]);
2208 let mut v = String::new();
2209 assert!(c.read_to_string(&mut v).is_err());
2214 let mut buf = [0; 4];
2216 let mut c = Cursor::new(&b""[..]);
2217 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2218 io::ErrorKind::UnexpectedEof);
2220 let mut c = Cursor::new(&b"123"[..]).chain(Cursor::new(&b"456789"[..]));
2221 c.read_exact(&mut buf).unwrap();
2222 assert_eq!(&buf, b"1234");
2223 c.read_exact(&mut buf).unwrap();
2224 assert_eq!(&buf, b"5678");
2225 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2226 io::ErrorKind::UnexpectedEof);
2230 fn read_exact_slice() {
2231 let mut buf = [0; 4];
2233 let mut c = &b""[..];
2234 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2235 io::ErrorKind::UnexpectedEof);
2237 let mut c = &b"123"[..];
2238 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2239 io::ErrorKind::UnexpectedEof);
2240 // make sure the optimized (early returning) method is being used
2241 assert_eq!(&buf, &[0; 4]);
2243 let mut c = &b"1234"[..];
2244 c.read_exact(&mut buf).unwrap();
2245 assert_eq!(&buf, b"1234");
2247 let mut c = &b"56789"[..];
2248 c.read_exact(&mut buf).unwrap();
2249 assert_eq!(&buf, b"5678");
2250 assert_eq!(c, b"9");
2258 fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
2259 Err(io::Error::new(io::ErrorKind::Other, ""))
2262 impl BufRead for R {
2263 fn fill_buf(&mut self) -> io::Result<&[u8]> {
2264 Err(io::Error::new(io::ErrorKind::Other, ""))
2266 fn consume(&mut self, _amt: usize) { }
2269 let mut buf = [0; 1];
2270 assert_eq!(0, R.take(0).read(&mut buf).unwrap());
2271 assert_eq!(b"", R.take(0).fill_buf().unwrap());
2274 fn cmp_bufread<Br1: BufRead, Br2: BufRead>(mut br1: Br1, mut br2: Br2, exp: &[u8]) {
2275 let mut cat = Vec::new();
2278 let buf1 = br1.fill_buf().unwrap();
2279 let buf2 = br2.fill_buf().unwrap();
2280 let minlen = if buf1.len() < buf2.len() { buf1.len() } else { buf2.len() };
2281 assert_eq!(buf1[..minlen], buf2[..minlen]);
2282 cat.extend_from_slice(&buf1[..minlen]);
2288 br1.consume(consume);
2289 br2.consume(consume);
2291 assert_eq!(br1.fill_buf().unwrap().len(), 0);
2292 assert_eq!(br2.fill_buf().unwrap().len(), 0);
2293 assert_eq!(&cat[..], &exp[..])
2297 fn chain_bufread() {
2298 let testdata = b"ABCDEFGHIJKL";
2299 let chain1 = (&testdata[..3]).chain(&testdata[3..6])
2300 .chain(&testdata[6..9])
2301 .chain(&testdata[9..]);
2302 let chain2 = (&testdata[..4]).chain(&testdata[4..8])
2303 .chain(&testdata[8..]);
2304 cmp_bufread(chain1, chain2, &testdata[..]);
2308 fn chain_zero_length_read_is_not_eof() {
2311 let mut s = String::new();
2312 let mut chain = (&a[..]).chain(&b[..]);
2313 chain.read(&mut []).unwrap();
2314 chain.read_to_string(&mut s).unwrap();
2315 assert_eq!("AB", s);
2319 #[cfg_attr(target_os = "emscripten", ignore)]
2320 fn bench_read_to_end(b: &mut test::Bencher) {
2322 let mut lr = repeat(1).take(10000000);
2323 let mut vec = Vec::with_capacity(1024);
2324 super::read_to_end(&mut lr, &mut vec)