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`] method, which we can use on `File`s:
28 //! use std::io::prelude::*;
29 //! use std::fs::File;
31 //! # fn foo() -> io::Result<()> {
32 //! let mut f = File::open("foo.txt")?;
33 //! let mut buffer = [0; 10];
35 //! // read up to 10 bytes
36 //! f.read(&mut buffer)?;
38 //! println!("The bytes: {:?}", buffer);
43 //! [`Read`] and [`Write`] are so important, implementors of the two traits have a
44 //! nickname: readers and writers. So you'll sometimes see 'a reader' instead
45 //! of 'a type that implements the [`Read`] trait'. Much easier!
47 //! ## Seek and BufRead
49 //! Beyond that, there are two important traits that are provided: [`Seek`]
50 //! and [`BufRead`]. Both of these build on top of a reader to control
51 //! how the reading happens. [`Seek`] lets you control where the next byte is
56 //! use std::io::prelude::*;
57 //! use std::io::SeekFrom;
58 //! use std::fs::File;
60 //! # fn foo() -> io::Result<()> {
61 //! let mut f = File::open("foo.txt")?;
62 //! let mut buffer = [0; 10];
64 //! // skip to the last 10 bytes of the file
65 //! f.seek(SeekFrom::End(-10))?;
67 //! // read up to 10 bytes
68 //! f.read(&mut buffer)?;
70 //! println!("The bytes: {:?}", buffer);
75 //! [`BufRead`] uses an internal buffer to provide a number of other ways to read, but
76 //! to show it off, we'll need to talk about buffers in general. Keep reading!
78 //! ## BufReader and BufWriter
80 //! Byte-based interfaces are unwieldy and can be inefficient, as we'd need to be
81 //! making near-constant calls to the operating system. To help with this,
82 //! `std::io` comes with two structs, [`BufReader`] and [`BufWriter`], which wrap
83 //! readers and writers. The wrapper uses a buffer, reducing the number of
84 //! calls and providing nicer methods for accessing exactly what you want.
86 //! For example, [`BufReader`] works with the [`BufRead`] trait to add extra
87 //! methods to any reader:
91 //! use std::io::prelude::*;
92 //! use std::io::BufReader;
93 //! use std::fs::File;
95 //! # fn foo() -> io::Result<()> {
96 //! let f = File::open("foo.txt")?;
97 //! let mut reader = BufReader::new(f);
98 //! let mut buffer = String::new();
100 //! // read a line into buffer
101 //! reader.read_line(&mut buffer)?;
103 //! println!("{}", buffer);
108 //! [`BufWriter`] doesn't add any new ways of writing; it just buffers every call
113 //! use std::io::prelude::*;
114 //! use std::io::BufWriter;
115 //! use std::fs::File;
117 //! # fn foo() -> io::Result<()> {
118 //! let f = File::create("foo.txt")?;
120 //! let mut writer = BufWriter::new(f);
122 //! // write a byte to the buffer
123 //! writer.write(&[42])?;
125 //! } // the buffer is flushed once writer goes out of scope
131 //! ## Standard input and output
133 //! A very common source of input is standard input:
138 //! # fn foo() -> io::Result<()> {
139 //! let mut input = String::new();
141 //! io::stdin().read_line(&mut input)?;
143 //! println!("You typed: {}", input.trim());
148 //! Note that you cannot use the `?` operator in functions that do not return
149 //! a `Result<T, E>` (e.g. `main`). Instead, you can call `.unwrap()` or `match`
150 //! on the return value to catch any possible errors:
155 //! let mut input = String::new();
157 //! io::stdin().read_line(&mut input).unwrap();
160 //! And a very common source of output is standard output:
164 //! use std::io::prelude::*;
166 //! # fn foo() -> io::Result<()> {
167 //! io::stdout().write(&[42])?;
172 //! Of course, using [`io::stdout`] directly is less common than something like
175 //! ## Iterator types
177 //! A large number of the structures provided by `std::io` are for various
178 //! ways of iterating over I/O. For example, [`Lines`] is used to split over
183 //! use std::io::prelude::*;
184 //! use std::io::BufReader;
185 //! use std::fs::File;
187 //! # fn foo() -> io::Result<()> {
188 //! let f = File::open("foo.txt")?;
189 //! let reader = BufReader::new(f);
191 //! for line in reader.lines() {
192 //! println!("{}", line?);
201 //! There are a number of [functions][functions-list] that offer access to various
202 //! features. For example, we can use three of these functions to copy everything
203 //! from standard input to standard output:
208 //! # fn foo() -> io::Result<()> {
209 //! io::copy(&mut io::stdin(), &mut io::stdout())?;
214 //! [functions-list]: #functions-1
218 //! Last, but certainly not least, is [`io::Result`]. This type is used
219 //! as the return type of many `std::io` functions that can cause an error, and
220 //! can be returned from your own functions as well. Many of the examples in this
221 //! module use the [`?` operator]:
226 //! fn read_input() -> io::Result<()> {
227 //! let mut input = String::new();
229 //! io::stdin().read_line(&mut input)?;
231 //! println!("You typed: {}", input.trim());
237 //! The return type of `read_input()`, [`io::Result<()>`][`io::Result`], is a very
238 //! common type for functions which don't have a 'real' return value, but do want to
239 //! return errors if they happen. In this case, the only purpose of this function is
240 //! to read the line and print it, so we use `()`.
242 //! ## Platform-specific behavior
244 //! Many I/O functions throughout the standard library are documented to indicate
245 //! what various library or syscalls they are delegated to. This is done to help
246 //! applications both understand what's happening under the hood as well as investigate
247 //! any possibly unclear semantics. Note, however, that this is informative, not a binding
248 //! contract. The implementation of many of these functions are subject to change over
249 //! time and may call fewer or more syscalls/library functions.
251 //! [`Read`]: trait.Read.html
252 //! [`Write`]: trait.Write.html
253 //! [`Seek`]: trait.Seek.html
254 //! [`BufRead`]: trait.BufRead.html
255 //! [`File`]: ../fs/struct.File.html
256 //! [`TcpStream`]: ../net/struct.TcpStream.html
257 //! [`Vec<T>`]: ../vec/struct.Vec.html
258 //! [`BufReader`]: struct.BufReader.html
259 //! [`BufWriter`]: struct.BufWriter.html
260 //! [`write`]: trait.Write.html#tymethod.write
261 //! [`io::stdout`]: fn.stdout.html
262 //! [`println!`]: ../macro.println.html
263 //! [`Lines`]: struct.Lines.html
264 //! [`io::Result`]: type.Result.html
265 //! [`?` operator]: ../../book/syntax-index.html
266 //! [`read`]: trait.Read.html#tymethod.read
268 #![stable(feature = "rust1", since = "1.0.0")]
271 use core::str as core_str;
272 use error as std_error;
278 #[stable(feature = "rust1", since = "1.0.0")]
279 pub use self::buffered::{BufReader, BufWriter, LineWriter};
280 #[stable(feature = "rust1", since = "1.0.0")]
281 pub use self::buffered::IntoInnerError;
282 #[stable(feature = "rust1", since = "1.0.0")]
283 pub use self::cursor::Cursor;
284 #[stable(feature = "rust1", since = "1.0.0")]
285 pub use self::error::{Result, Error, ErrorKind};
286 #[stable(feature = "rust1", since = "1.0.0")]
287 pub use self::util::{copy, sink, Sink, empty, Empty, repeat, Repeat};
288 #[stable(feature = "rust1", since = "1.0.0")]
289 pub use self::stdio::{stdin, stdout, stderr, _print, Stdin, Stdout, Stderr};
290 #[stable(feature = "rust1", since = "1.0.0")]
291 pub use self::stdio::{StdoutLock, StderrLock, StdinLock};
292 #[unstable(feature = "libstd_io_internals", issue = "0")]
293 #[doc(no_inline, hidden)]
294 pub use self::stdio::{set_panic, set_print};
305 const DEFAULT_BUF_SIZE: usize = ::sys_common::io::DEFAULT_BUF_SIZE;
307 // A few methods below (read_to_string, read_line) will append data into a
308 // `String` buffer, but we need to be pretty careful when doing this. The
309 // implementation will just call `.as_mut_vec()` and then delegate to a
310 // byte-oriented reading method, but we must ensure that when returning we never
311 // leave `buf` in a state such that it contains invalid UTF-8 in its bounds.
313 // To this end, we use an RAII guard (to protect against panics) which updates
314 // the length of the string when it is dropped. This guard initially truncates
315 // the string to the prior length and only after we've validated that the
316 // new contents are valid UTF-8 do we allow it to set a longer length.
318 // The unsafety in this function is twofold:
320 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
322 // 2. We're passing a raw buffer to the function `f`, and it is expected that
323 // the function only *appends* bytes to the buffer. We'll get undefined
324 // behavior if existing bytes are overwritten to have non-UTF-8 data.
325 fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
326 where F: FnOnce(&mut Vec<u8>) -> Result<usize>
328 struct Guard<'a> { s: &'a mut Vec<u8>, len: usize }
329 impl<'a> Drop for Guard<'a> {
331 unsafe { self.s.set_len(self.len); }
336 let mut g = Guard { len: buf.len(), s: buf.as_mut_vec() };
338 if str::from_utf8(&g.s[g.len..]).is_err() {
340 Err(Error::new(ErrorKind::InvalidData,
341 "stream did not contain valid UTF-8"))
350 // This uses an adaptive system to extend the vector when it fills. We want to
351 // avoid paying to allocate and zero a huge chunk of memory if the reader only
352 // has 4 bytes while still making large reads if the reader does have a ton
353 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
354 // time is 4,500 times (!) slower than this if the reader has a very small
355 // amount of data to return.
356 fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
357 let start_len = buf.len();
358 let mut len = start_len;
359 let mut new_write_size = 16;
362 if len == buf.len() {
363 if new_write_size < DEFAULT_BUF_SIZE {
366 buf.resize(len + new_write_size, 0);
369 match r.read(&mut buf[len..]) {
371 ret = Ok(len - start_len);
375 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
387 /// The `Read` trait allows for reading bytes from a source.
389 /// Implementors of the `Read` trait are sometimes called 'readers'.
391 /// Readers are defined by one required method, `read()`. Each call to `read`
392 /// will attempt to pull bytes from this source into a provided buffer. A
393 /// number of other methods are implemented in terms of `read()`, giving
394 /// implementors a number of ways to read bytes while only needing to implement
397 /// Readers are intended to be composable with one another. Many implementors
398 /// throughout `std::io` take and provide types which implement the `Read`
401 /// Please note that each call to `read` may involve a system call, and
402 /// therefore, using something that implements [`BufRead`][bufread], such as
403 /// [`BufReader`][bufreader], will be more efficient.
405 /// [bufread]: trait.BufRead.html
406 /// [bufreader]: struct.BufReader.html
410 /// [`File`][file]s implement `Read`:
412 /// [file]: ../fs/struct.File.html
416 /// use std::io::prelude::*;
417 /// use std::fs::File;
419 /// # fn foo() -> io::Result<()> {
420 /// let mut f = File::open("foo.txt")?;
421 /// let mut buffer = [0; 10];
423 /// // read up to 10 bytes
424 /// f.read(&mut buffer)?;
426 /// let mut buffer = vec![0; 10];
427 /// // read the whole file
428 /// f.read_to_end(&mut buffer)?;
430 /// // read into a String, so that you don't need to do the conversion.
431 /// let mut buffer = String::new();
432 /// f.read_to_string(&mut buffer)?;
434 /// // and more! See the other methods for more details.
438 #[stable(feature = "rust1", since = "1.0.0")]
440 /// Pull some bytes from this source into the specified buffer, returning
441 /// how many bytes were read.
443 /// This function does not provide any guarantees about whether it blocks
444 /// waiting for data, but if an object needs to block for a read but cannot
445 /// it will typically signal this via an `Err` return value.
447 /// If the return value of this method is `Ok(n)`, then it must be
448 /// guaranteed that `0 <= n <= buf.len()`. A nonzero `n` value indicates
449 /// that the buffer `buf` has been filled in with `n` bytes of data from this
450 /// source. If `n` is `0`, then it can indicate one of two scenarios:
452 /// 1. This reader has reached its "end of file" and will likely no longer
453 /// be able to produce bytes. Note that this does not mean that the
454 /// reader will *always* no longer be able to produce bytes.
455 /// 2. The buffer specified was 0 bytes in length.
457 /// No guarantees are provided about the contents of `buf` when this
458 /// function is called, implementations cannot rely on any property of the
459 /// contents of `buf` being true. It is recommended that implementations
460 /// only write data to `buf` instead of reading its contents.
464 /// If this function encounters any form of I/O or other error, an error
465 /// variant will be returned. If an error is returned then it must be
466 /// guaranteed that no bytes were read.
470 /// [`File`][file]s implement `Read`:
472 /// [file]: ../fs/struct.File.html
476 /// use std::io::prelude::*;
477 /// use std::fs::File;
479 /// # fn foo() -> io::Result<()> {
480 /// let mut f = File::open("foo.txt")?;
481 /// let mut buffer = [0; 10];
484 /// f.read(&mut buffer[..])?;
488 #[stable(feature = "rust1", since = "1.0.0")]
489 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
491 /// Read all bytes until EOF in this source, placing them into `buf`.
493 /// All bytes read from this source will be appended to the specified buffer
494 /// `buf`. This function will continuously call `read` to append more data to
495 /// `buf` until `read` returns either `Ok(0)` or an error of
496 /// non-`ErrorKind::Interrupted` kind.
498 /// If successful, this function will return the total number of bytes read.
502 /// If this function encounters an error of the kind
503 /// `ErrorKind::Interrupted` then the error is ignored and the operation
506 /// If any other read error is encountered then this function immediately
507 /// returns. Any bytes which have already been read will be appended to
512 /// [`File`][file]s implement `Read`:
514 /// [file]: ../fs/struct.File.html
518 /// use std::io::prelude::*;
519 /// use std::fs::File;
521 /// # fn foo() -> io::Result<()> {
522 /// let mut f = File::open("foo.txt")?;
523 /// let mut buffer = Vec::new();
525 /// // read the whole file
526 /// f.read_to_end(&mut buffer)?;
530 #[stable(feature = "rust1", since = "1.0.0")]
531 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
532 read_to_end(self, buf)
535 /// Read all bytes until EOF in this source, placing them into `buf`.
537 /// If successful, this function returns the number of bytes which were read
538 /// and appended to `buf`.
542 /// If the data in this stream is *not* valid UTF-8 then an error is
543 /// returned and `buf` is unchanged.
545 /// See [`read_to_end`][readtoend] for other error semantics.
547 /// [readtoend]: #method.read_to_end
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 = String::new();
564 /// f.read_to_string(&mut buffer)?;
568 #[stable(feature = "rust1", since = "1.0.0")]
569 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
570 // Note that we do *not* call `.read_to_end()` here. We are passing
571 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
572 // method to fill it up. An arbitrary implementation could overwrite the
573 // entire contents of the vector, not just append to it (which is what
574 // we are expecting).
576 // To prevent extraneously checking the UTF-8-ness of the entire buffer
577 // we pass it to our hardcoded `read_to_end` implementation which we
578 // know is guaranteed to only read data into the end of the buffer.
579 append_to_string(buf, |b| read_to_end(self, b))
582 /// Read the exact number of bytes required to fill `buf`.
584 /// This function reads as many bytes as necessary to completely fill the
585 /// specified buffer `buf`.
587 /// No guarantees are provided about the contents of `buf` when this
588 /// function is called, implementations cannot rely on any property of the
589 /// contents of `buf` being true. It is recommended that implementations
590 /// only write data to `buf` instead of reading its contents.
594 /// If this function encounters an error of the kind
595 /// `ErrorKind::Interrupted` then the error is ignored and the operation
598 /// If this function encounters an "end of file" before completely filling
599 /// the buffer, it returns an error of the kind `ErrorKind::UnexpectedEof`.
600 /// The contents of `buf` are unspecified in this case.
602 /// If any other read error is encountered then this function immediately
603 /// returns. The contents of `buf` are unspecified in this case.
605 /// If this function returns an error, it is unspecified how many bytes it
606 /// has read, but it will never read more than would be necessary to
607 /// completely fill the buffer.
611 /// [`File`][file]s implement `Read`:
613 /// [file]: ../fs/struct.File.html
617 /// use std::io::prelude::*;
618 /// use std::fs::File;
620 /// # fn foo() -> io::Result<()> {
621 /// let mut f = File::open("foo.txt")?;
622 /// let mut buffer = [0; 10];
624 /// // read exactly 10 bytes
625 /// f.read_exact(&mut buffer)?;
629 #[stable(feature = "read_exact", since = "1.6.0")]
630 fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
631 while !buf.is_empty() {
632 match self.read(buf) {
634 Ok(n) => { let tmp = buf; buf = &mut tmp[n..]; }
635 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
636 Err(e) => return Err(e),
640 Err(Error::new(ErrorKind::UnexpectedEof,
641 "failed to fill whole buffer"))
647 /// Creates a "by reference" adaptor for this instance of `Read`.
649 /// The returned adaptor also implements `Read` and will simply borrow this
654 /// [`File`][file]s implement `Read`:
656 /// [file]: ../fs/struct.File.html
660 /// use std::io::Read;
661 /// use std::fs::File;
663 /// # fn foo() -> io::Result<()> {
664 /// let mut f = File::open("foo.txt")?;
665 /// let mut buffer = Vec::new();
666 /// let mut other_buffer = Vec::new();
669 /// let reference = f.by_ref();
671 /// // read at most 5 bytes
672 /// reference.take(5).read_to_end(&mut buffer)?;
674 /// } // drop our &mut reference so we can use f again
676 /// // original file still usable, read the rest
677 /// f.read_to_end(&mut other_buffer)?;
681 #[stable(feature = "rust1", since = "1.0.0")]
682 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
684 /// Transforms this `Read` instance to an `Iterator` over its bytes.
686 /// The returned type implements `Iterator` where the `Item` is `Result<u8,
687 /// R::Err>`. The yielded item is `Ok` if a byte was successfully read and
688 /// `Err` otherwise for I/O errors. EOF is mapped to returning `None` from
693 /// [`File`][file]s implement `Read`:
695 /// [file]: ../fs/struct.File.html
699 /// use std::io::prelude::*;
700 /// use std::fs::File;
702 /// # fn foo() -> io::Result<()> {
703 /// let mut f = File::open("foo.txt")?;
705 /// for byte in f.bytes() {
706 /// println!("{}", byte.unwrap());
711 #[stable(feature = "rust1", since = "1.0.0")]
712 fn bytes(self) -> Bytes<Self> where Self: Sized {
713 Bytes { inner: self }
716 /// Transforms this `Read` instance to an `Iterator` over `char`s.
718 /// This adaptor will attempt to interpret this reader as a UTF-8 encoded
719 /// sequence of characters. The returned iterator will return `None` once
720 /// EOF is reached for this reader. Otherwise each element yielded will be a
721 /// `Result<char, E>` where `E` may contain information about what I/O error
722 /// occurred or where decoding failed.
724 /// Currently this adaptor will discard intermediate data read, and should
725 /// be avoided if this is not desired.
729 /// [`File`][file]s implement `Read`:
731 /// [file]: ../fs/struct.File.html
736 /// use std::io::prelude::*;
737 /// use std::fs::File;
739 /// # fn foo() -> io::Result<()> {
740 /// let mut f = File::open("foo.txt")?;
742 /// for c in f.chars() {
743 /// println!("{}", c.unwrap());
748 #[unstable(feature = "io", reason = "the semantics of a partial read/write \
749 of where errors happen is currently \
750 unclear and may change",
752 fn chars(self) -> Chars<Self> where Self: Sized {
753 Chars { inner: self }
756 /// Creates an adaptor which will chain this stream with another.
758 /// The returned `Read` instance will first read all bytes from this object
759 /// until EOF is encountered. Afterwards the output is equivalent to the
760 /// output of `next`.
764 /// [`File`][file]s implement `Read`:
766 /// [file]: ../fs/struct.File.html
770 /// use std::io::prelude::*;
771 /// use std::fs::File;
773 /// # fn foo() -> io::Result<()> {
774 /// let mut f1 = File::open("foo.txt")?;
775 /// let mut f2 = File::open("bar.txt")?;
777 /// let mut handle = f1.chain(f2);
778 /// let mut buffer = String::new();
780 /// // read the value into a String. We could use any Read method here,
781 /// // this is just one example.
782 /// handle.read_to_string(&mut buffer)?;
786 #[stable(feature = "rust1", since = "1.0.0")]
787 fn chain<R: Read>(self, next: R) -> Chain<Self, R> where Self: Sized {
788 Chain { first: self, second: next, done_first: false }
791 /// Creates an adaptor which will read at most `limit` bytes from it.
793 /// This function returns a new instance of `Read` which will read at most
794 /// `limit` bytes, after which it will always return EOF (`Ok(0)`). Any
795 /// read errors will not count towards the number of bytes read and future
796 /// calls to `read` may succeed.
800 /// [`File`][file]s implement `Read`:
802 /// [file]: ../fs/struct.File.html
806 /// use std::io::prelude::*;
807 /// use std::fs::File;
809 /// # fn foo() -> io::Result<()> {
810 /// let mut f = File::open("foo.txt")?;
811 /// let mut buffer = [0; 5];
813 /// // read at most five bytes
814 /// let mut handle = f.take(5);
816 /// handle.read(&mut buffer)?;
820 #[stable(feature = "rust1", since = "1.0.0")]
821 fn take(self, limit: u64) -> Take<Self> where Self: Sized {
822 Take { inner: self, limit: limit }
826 /// A trait for objects which are byte-oriented sinks.
828 /// Implementors of the `Write` trait are sometimes called 'writers'.
830 /// Writers are defined by two required methods, [`write`] and [`flush`]:
832 /// * The [`write`] method will attempt to write some data into the object,
833 /// returning how many bytes were successfully written.
835 /// * The [`flush`] method is useful for adaptors and explicit buffers
836 /// themselves for ensuring that all buffered data has been pushed out to the
839 /// Writers are intended to be composable with one another. Many implementors
840 /// throughout [`std::io`] take and provide types which implement the `Write`
843 /// [`write`]: #tymethod.write
844 /// [`flush`]: #tymethod.flush
845 /// [`std::io`]: index.html
850 /// use std::io::prelude::*;
851 /// use std::fs::File;
853 /// # fn foo() -> std::io::Result<()> {
854 /// let mut buffer = File::create("foo.txt")?;
856 /// buffer.write(b"some bytes")?;
860 #[stable(feature = "rust1", since = "1.0.0")]
862 /// Write a buffer into this object, returning how many bytes were written.
864 /// This function will attempt to write the entire contents of `buf`, but
865 /// the entire write may not succeed, or the write may also generate an
866 /// error. A call to `write` represents *at most one* attempt to write to
867 /// any wrapped object.
869 /// Calls to `write` are not guaranteed to block waiting for data to be
870 /// written, and a write which would otherwise block can be indicated through
871 /// an `Err` variant.
873 /// If the return value is `Ok(n)` then it must be guaranteed that
874 /// `0 <= n <= buf.len()`. A return value of `0` typically means that the
875 /// underlying object is no longer able to accept bytes and will likely not
876 /// be able to in the future as well, or that the buffer provided is empty.
880 /// Each call to `write` may generate an I/O error indicating that the
881 /// operation could not be completed. If an error is returned then no bytes
882 /// in the buffer were written to this writer.
884 /// It is **not** considered an error if the entire buffer could not be
885 /// written to this writer.
890 /// use std::io::prelude::*;
891 /// use std::fs::File;
893 /// # fn foo() -> std::io::Result<()> {
894 /// let mut buffer = File::create("foo.txt")?;
896 /// buffer.write(b"some bytes")?;
900 #[stable(feature = "rust1", since = "1.0.0")]
901 fn write(&mut self, buf: &[u8]) -> Result<usize>;
903 /// Flush this output stream, ensuring that all intermediately buffered
904 /// contents reach their destination.
908 /// It is considered an error if not all bytes could be written due to
909 /// I/O errors or EOF being reached.
914 /// use std::io::prelude::*;
915 /// use std::io::BufWriter;
916 /// use std::fs::File;
918 /// # fn foo() -> std::io::Result<()> {
919 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
921 /// buffer.write(b"some bytes")?;
926 #[stable(feature = "rust1", since = "1.0.0")]
927 fn flush(&mut self) -> Result<()>;
929 /// Attempts to write an entire buffer into this write.
931 /// This method will continuously call `write` while there is more data to
932 /// write. This method will not return until the entire buffer has been
933 /// successfully written or an error occurs. The first error generated from
934 /// this method will be returned.
938 /// This function will return the first error that `write` returns.
943 /// use std::io::prelude::*;
944 /// use std::fs::File;
946 /// # fn foo() -> std::io::Result<()> {
947 /// let mut buffer = File::create("foo.txt")?;
949 /// buffer.write_all(b"some bytes")?;
953 #[stable(feature = "rust1", since = "1.0.0")]
954 fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
955 while !buf.is_empty() {
956 match self.write(buf) {
957 Ok(0) => return Err(Error::new(ErrorKind::WriteZero,
958 "failed to write whole buffer")),
959 Ok(n) => buf = &buf[n..],
960 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
961 Err(e) => return Err(e),
967 /// Writes a formatted string into this writer, returning any error
970 /// This method is primarily used to interface with the
971 /// [`format_args!`][formatargs] macro, but it is rare that this should
972 /// explicitly be called. The [`write!`][write] macro should be favored to
973 /// invoke this method instead.
975 /// [formatargs]: ../macro.format_args.html
976 /// [write]: ../macro.write.html
978 /// This function internally uses the [`write_all`][writeall] method on
979 /// this trait and hence will continuously write data so long as no errors
980 /// are received. This also means that partial writes are not indicated in
983 /// [writeall]: #method.write_all
987 /// This function will return any I/O error reported while formatting.
992 /// use std::io::prelude::*;
993 /// use std::fs::File;
995 /// # fn foo() -> std::io::Result<()> {
996 /// let mut buffer = File::create("foo.txt")?;
999 /// write!(buffer, "{:.*}", 2, 1.234567)?;
1000 /// // turns into this:
1001 /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1005 #[stable(feature = "rust1", since = "1.0.0")]
1006 fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()> {
1007 // Create a shim which translates a Write to a fmt::Write and saves
1008 // off I/O errors. instead of discarding them
1009 struct Adaptor<'a, T: ?Sized + 'a> {
1014 impl<'a, T: Write + ?Sized> fmt::Write for Adaptor<'a, T> {
1015 fn write_str(&mut self, s: &str) -> fmt::Result {
1016 match self.inner.write_all(s.as_bytes()) {
1019 self.error = Err(e);
1026 let mut output = Adaptor { inner: self, error: Ok(()) };
1027 match fmt::write(&mut output, fmt) {
1030 // check if the error came from the underlying `Write` or not
1031 if output.error.is_err() {
1034 Err(Error::new(ErrorKind::Other, "formatter error"))
1040 /// Creates a "by reference" adaptor for this instance of `Write`.
1042 /// The returned adaptor also implements `Write` and will simply borrow this
1048 /// use std::io::Write;
1049 /// use std::fs::File;
1051 /// # fn foo() -> std::io::Result<()> {
1052 /// let mut buffer = File::create("foo.txt")?;
1054 /// let reference = buffer.by_ref();
1056 /// // we can use reference just like our original buffer
1057 /// reference.write_all(b"some bytes")?;
1061 #[stable(feature = "rust1", since = "1.0.0")]
1062 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1065 /// The `Seek` trait provides a cursor which can be moved within a stream of
1068 /// The stream typically has a fixed size, allowing seeking relative to either
1069 /// end or the current offset.
1073 /// [`File`][file]s implement `Seek`:
1075 /// [file]: ../fs/struct.File.html
1079 /// use std::io::prelude::*;
1080 /// use std::fs::File;
1081 /// use std::io::SeekFrom;
1083 /// # fn foo() -> io::Result<()> {
1084 /// let mut f = File::open("foo.txt")?;
1086 /// // move the cursor 42 bytes from the start of the file
1087 /// f.seek(SeekFrom::Start(42))?;
1091 #[stable(feature = "rust1", since = "1.0.0")]
1093 /// Seek to an offset, in bytes, in a stream.
1095 /// A seek beyond the end of a stream is allowed, but implementation
1098 /// If the seek operation completed successfully,
1099 /// this method returns the new position from the start of the stream.
1100 /// That position can be used later with [`SeekFrom::Start`].
1104 /// Seeking to a negative offset is considered an error.
1106 /// [`SeekFrom::Start`]: enum.SeekFrom.html#variant.Start
1107 #[stable(feature = "rust1", since = "1.0.0")]
1108 fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1111 /// Enumeration of possible methods to seek within an I/O object.
1113 /// It is used by the [`Seek`] trait.
1115 /// [`Seek`]: trait.Seek.html
1116 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1117 #[stable(feature = "rust1", since = "1.0.0")]
1119 /// Set the offset to the provided number of bytes.
1120 #[stable(feature = "rust1", since = "1.0.0")]
1121 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1123 /// Set the offset to the size of this object plus the specified number of
1126 /// It is possible to seek beyond the end of an object, but it's an error to
1127 /// seek before byte 0.
1128 #[stable(feature = "rust1", since = "1.0.0")]
1129 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1131 /// Set the offset to the current position plus the specified number of
1134 /// It is possible to seek beyond the end of an object, but it's an error to
1135 /// seek before byte 0.
1136 #[stable(feature = "rust1", since = "1.0.0")]
1137 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1140 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>)
1144 let (done, used) = {
1145 let available = match r.fill_buf() {
1147 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1148 Err(e) => return Err(e)
1150 match memchr::memchr(delim, available) {
1152 buf.extend_from_slice(&available[..i + 1]);
1156 buf.extend_from_slice(available);
1157 (false, available.len())
1163 if done || used == 0 {
1169 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1170 /// to perform extra ways of reading.
1172 /// For example, reading line-by-line is inefficient without using a buffer, so
1173 /// if you want to read by line, you'll need `BufRead`, which includes a
1174 /// [`read_line`] method as well as a [`lines`] iterator.
1178 /// A locked standard input implements `BufRead`:
1182 /// use std::io::prelude::*;
1184 /// let stdin = io::stdin();
1185 /// for line in stdin.lock().lines() {
1186 /// println!("{}", line.unwrap());
1190 /// If you have something that implements [`Read`], you can use the [`BufReader`
1191 /// type][`BufReader`] to turn it into a `BufRead`.
1193 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1194 /// [`BufReader`] to the rescue!
1196 /// [`BufReader`]: struct.BufReader.html
1197 /// [`File`]: ../fs/struct.File.html
1198 /// [`read_line`]: #method.read_line
1199 /// [`lines`]: #method.lines
1200 /// [`Read`]: trait.Read.html
1203 /// use std::io::{self, BufReader};
1204 /// use std::io::prelude::*;
1205 /// use std::fs::File;
1207 /// # fn foo() -> io::Result<()> {
1208 /// let f = File::open("foo.txt")?;
1209 /// let f = BufReader::new(f);
1211 /// for line in f.lines() {
1212 /// println!("{}", line.unwrap());
1219 #[stable(feature = "rust1", since = "1.0.0")]
1220 pub trait BufRead: Read {
1221 /// Fills the internal buffer of this object, returning the buffer contents.
1223 /// This function is a lower-level call. It needs to be paired with the
1224 /// [`consume`] method to function properly. When calling this
1225 /// method, none of the contents will be "read" in the sense that later
1226 /// calling `read` may return the same contents. As such, [`consume`] must
1227 /// be called with the number of bytes that are consumed from this buffer to
1228 /// ensure that the bytes are never returned twice.
1230 /// [`consume`]: #tymethod.consume
1232 /// An empty buffer returned indicates that the stream has reached EOF.
1236 /// This function will return an I/O error if the underlying reader was
1237 /// read, but returned an error.
1241 /// A locked standard input implements `BufRead`:
1245 /// use std::io::prelude::*;
1247 /// let stdin = io::stdin();
1248 /// let mut stdin = stdin.lock();
1250 /// // we can't have two `&mut` references to `stdin`, so use a block
1251 /// // to end the borrow early.
1253 /// let buffer = stdin.fill_buf().unwrap();
1255 /// // work with buffer
1256 /// println!("{:?}", buffer);
1261 /// // ensure the bytes we worked with aren't returned again later
1262 /// stdin.consume(length);
1264 #[stable(feature = "rust1", since = "1.0.0")]
1265 fn fill_buf(&mut self) -> Result<&[u8]>;
1267 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1268 /// so they should no longer be returned in calls to `read`.
1270 /// This function is a lower-level call. It needs to be paired with the
1271 /// [`fill_buf`] method to function properly. This function does
1272 /// not perform any I/O, it simply informs this object that some amount of
1273 /// its buffer, returned from [`fill_buf`], has been consumed and should
1274 /// no longer be returned. As such, this function may do odd things if
1275 /// [`fill_buf`] isn't called before calling it.
1277 /// The `amt` must be `<=` the number of bytes in the buffer returned by
1282 /// Since `consume()` is meant to be used with [`fill_buf`],
1283 /// that method's example includes an example of `consume()`.
1285 /// [`fill_buf`]: #tymethod.fill_buf
1286 #[stable(feature = "rust1", since = "1.0.0")]
1287 fn consume(&mut self, amt: usize);
1289 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
1291 /// This function will read bytes from the underlying stream until the
1292 /// delimiter or EOF is found. Once found, all bytes up to, and including,
1293 /// the delimiter (if found) will be appended to `buf`.
1295 /// If successful, this function will return the total number of bytes read.
1299 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1300 /// will otherwise return any errors returned by [`fill_buf`].
1302 /// If an I/O error is encountered then all bytes read so far will be
1303 /// present in `buf` and its length will have been adjusted appropriately.
1305 /// [`fill_buf`]: #tymethod.fill_buf
1306 /// [`ErrorKind::Interrupted`]: enum.ErrorKind.html#variant.Interrupted
1310 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1311 /// this example, we use [`Cursor`] to read all the bytes in a byte slice
1312 /// in hyphen delimited segments:
1314 /// [`Cursor`]: struct.Cursor.html
1317 /// use std::io::{self, BufRead};
1319 /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
1320 /// let mut buf = vec![];
1322 /// // cursor is at 'l'
1323 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1324 /// .expect("reading from cursor won't fail");
1325 /// assert_eq!(num_bytes, 6);
1326 /// assert_eq!(buf, b"lorem-");
1329 /// // cursor is at 'i'
1330 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1331 /// .expect("reading from cursor won't fail");
1332 /// assert_eq!(num_bytes, 5);
1333 /// assert_eq!(buf, b"ipsum");
1336 /// // cursor is at EOF
1337 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1338 /// .expect("reading from cursor won't fail");
1339 /// assert_eq!(num_bytes, 0);
1340 /// assert_eq!(buf, b"");
1342 #[stable(feature = "rust1", since = "1.0.0")]
1343 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
1344 read_until(self, byte, buf)
1347 /// Read all bytes until a newline (the 0xA byte) is reached, and append
1348 /// them to the provided buffer.
1350 /// This function will read bytes from the underlying stream until the
1351 /// newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes
1352 /// up to, and including, the delimiter (if found) will be appended to
1355 /// If successful, this function will return the total number of bytes read.
1359 /// This function has the same error semantics as [`read_until`] and will
1360 /// also return an error if the read bytes are not valid UTF-8. If an I/O
1361 /// error is encountered then `buf` may contain some bytes already read in
1362 /// the event that all data read so far was valid UTF-8.
1366 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1367 /// this example, we use [`Cursor`] to read all the lines in a byte slice:
1369 /// [`Cursor`]: struct.Cursor.html
1372 /// use std::io::{self, BufRead};
1374 /// let mut cursor = io::Cursor::new(b"foo\nbar");
1375 /// let mut buf = String::new();
1377 /// // cursor is at 'f'
1378 /// let num_bytes = cursor.read_line(&mut buf)
1379 /// .expect("reading from cursor won't fail");
1380 /// assert_eq!(num_bytes, 4);
1381 /// assert_eq!(buf, "foo\n");
1384 /// // cursor is at 'b'
1385 /// let num_bytes = cursor.read_line(&mut buf)
1386 /// .expect("reading from cursor won't fail");
1387 /// assert_eq!(num_bytes, 3);
1388 /// assert_eq!(buf, "bar");
1391 /// // cursor is at EOF
1392 /// let num_bytes = cursor.read_line(&mut buf)
1393 /// .expect("reading from cursor won't fail");
1394 /// assert_eq!(num_bytes, 0);
1395 /// assert_eq!(buf, "");
1397 #[stable(feature = "rust1", since = "1.0.0")]
1398 fn read_line(&mut self, buf: &mut String) -> Result<usize> {
1399 // Note that we are not calling the `.read_until` method here, but
1400 // rather our hardcoded implementation. For more details as to why, see
1401 // the comments in `read_to_end`.
1402 append_to_string(buf, |b| read_until(self, b'\n', b))
1405 /// Returns an iterator over the contents of this reader split on the byte
1408 /// The iterator returned from this function will return instances of
1409 /// [`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
1410 /// the delimiter byte at the end.
1412 /// This function will yield errors whenever [`read_until`] would have
1413 /// also yielded an error.
1415 /// [`io::Result`]: type.Result.html
1416 /// [`Vec<u8>`]: ../vec/struct.Vec.html
1417 /// [`read_until`]: #method.read_until
1421 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1422 /// this example, we use [`Cursor`] to iterate over all hyphen delimited
1423 /// segments in a byte slice
1425 /// [`Cursor`]: struct.Cursor.html
1428 /// use std::io::{self, BufRead};
1430 /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
1432 /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
1433 /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
1434 /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
1435 /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
1436 /// assert_eq!(split_iter.next(), None);
1438 #[stable(feature = "rust1", since = "1.0.0")]
1439 fn split(self, byte: u8) -> Split<Self> where Self: Sized {
1440 Split { buf: self, delim: byte }
1443 /// Returns an iterator over the lines of this reader.
1445 /// The iterator returned from this function will yield instances of
1446 /// [`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline
1447 /// byte (the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.
1449 /// [`io::Result`]: type.Result.html
1450 /// [`String`]: ../string/struct.String.html
1454 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1455 /// this example, we use [`Cursor`] to iterate over all the lines in a byte
1458 /// [`Cursor`]: struct.Cursor.html
1461 /// use std::io::{self, BufRead};
1463 /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
1465 /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
1466 /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
1467 /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
1468 /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
1469 /// assert_eq!(lines_iter.next(), None);
1474 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
1476 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
1477 #[stable(feature = "rust1", since = "1.0.0")]
1478 fn lines(self) -> Lines<Self> where Self: Sized {
1483 /// Adaptor to chain together two readers.
1485 /// This struct is generally created by calling [`chain`] on a reader.
1486 /// Please see the documentation of [`chain`] for more details.
1488 /// [`chain`]: trait.Read.html#method.chain
1489 #[stable(feature = "rust1", since = "1.0.0")]
1490 pub struct Chain<T, U> {
1496 #[stable(feature = "std_debug", since = "1.16.0")]
1497 impl<T: fmt::Debug, U: fmt::Debug> fmt::Debug for Chain<T, U> {
1498 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1499 f.debug_struct("Chain")
1500 .field("t", &self.first)
1501 .field("u", &self.second)
1506 #[stable(feature = "rust1", since = "1.0.0")]
1507 impl<T: Read, U: Read> Read for Chain<T, U> {
1508 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1509 if !self.done_first {
1510 match self.first.read(buf)? {
1511 0 if buf.len() != 0 => { self.done_first = true; }
1515 self.second.read(buf)
1519 #[stable(feature = "chain_bufread", since = "1.9.0")]
1520 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
1521 fn fill_buf(&mut self) -> Result<&[u8]> {
1522 if !self.done_first {
1523 match self.first.fill_buf()? {
1524 buf if buf.len() == 0 => { self.done_first = true; }
1525 buf => return Ok(buf),
1528 self.second.fill_buf()
1531 fn consume(&mut self, amt: usize) {
1532 if !self.done_first {
1533 self.first.consume(amt)
1535 self.second.consume(amt)
1540 /// Reader adaptor which limits the bytes read from an underlying reader.
1542 /// This struct is generally created by calling [`take`] on a reader.
1543 /// Please see the documentation of [`take`] for more details.
1545 /// [`take`]: trait.Read.html#method.take
1546 #[stable(feature = "rust1", since = "1.0.0")]
1548 pub struct Take<T> {
1554 /// Returns the number of bytes that can be read before this instance will
1559 /// This instance may reach `EOF` after reading fewer bytes than indicated by
1560 /// this method if the underlying [`Read`] instance reaches EOF.
1562 /// [`Read`]: ../../std/io/trait.Read.html
1568 /// use std::io::prelude::*;
1569 /// use std::fs::File;
1571 /// # fn foo() -> io::Result<()> {
1572 /// let f = File::open("foo.txt")?;
1574 /// // read at most five bytes
1575 /// let handle = f.take(5);
1577 /// println!("limit: {}", handle.limit());
1581 #[stable(feature = "rust1", since = "1.0.0")]
1582 pub fn limit(&self) -> u64 { self.limit }
1584 /// Consumes the `Take`, returning the wrapped reader.
1590 /// use std::io::prelude::*;
1591 /// use std::fs::File;
1593 /// # fn foo() -> io::Result<()> {
1594 /// let mut file = File::open("foo.txt")?;
1596 /// let mut buffer = [0; 5];
1597 /// let mut handle = file.take(5);
1598 /// handle.read(&mut buffer)?;
1600 /// let file = handle.into_inner();
1604 #[stable(feature = "io_take_into_inner", since = "1.15.0")]
1605 pub fn into_inner(self) -> T {
1610 #[stable(feature = "rust1", since = "1.0.0")]
1611 impl<T: Read> Read for Take<T> {
1612 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1613 // Don't call into inner reader at all at EOF because it may still block
1614 if self.limit == 0 {
1618 let max = cmp::min(buf.len() as u64, self.limit) as usize;
1619 let n = self.inner.read(&mut buf[..max])?;
1620 self.limit -= n as u64;
1625 #[stable(feature = "rust1", since = "1.0.0")]
1626 impl<T: BufRead> BufRead for Take<T> {
1627 fn fill_buf(&mut self) -> Result<&[u8]> {
1628 // Don't call into inner reader at all at EOF because it may still block
1629 if self.limit == 0 {
1633 let buf = self.inner.fill_buf()?;
1634 let cap = cmp::min(buf.len() as u64, self.limit) as usize;
1638 fn consume(&mut self, amt: usize) {
1639 // Don't let callers reset the limit by passing an overlarge value
1640 let amt = cmp::min(amt as u64, self.limit) as usize;
1641 self.limit -= amt as u64;
1642 self.inner.consume(amt);
1646 fn read_one_byte(reader: &mut Read) -> Option<Result<u8>> {
1649 return match reader.read(&mut buf) {
1651 Ok(..) => Some(Ok(buf[0])),
1652 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1653 Err(e) => Some(Err(e)),
1658 /// An iterator over `u8` values of a reader.
1660 /// This struct is generally created by calling [`bytes`] on a reader.
1661 /// Please see the documentation of [`bytes`] for more details.
1663 /// [`bytes`]: trait.Read.html#method.bytes
1664 #[stable(feature = "rust1", since = "1.0.0")]
1666 pub struct Bytes<R> {
1670 #[stable(feature = "rust1", since = "1.0.0")]
1671 impl<R: Read> Iterator for Bytes<R> {
1672 type Item = Result<u8>;
1674 fn next(&mut self) -> Option<Result<u8>> {
1675 read_one_byte(&mut self.inner)
1679 /// An iterator over the `char`s of a reader.
1681 /// This struct is generally created by calling [`chars`][chars] on a reader.
1682 /// Please see the documentation of `chars()` for more details.
1684 /// [chars]: trait.Read.html#method.chars
1685 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1688 pub struct Chars<R> {
1692 /// An enumeration of possible errors that can be generated from the `Chars`
1695 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1697 pub enum CharsError {
1698 /// Variant representing that the underlying stream was read successfully
1699 /// but it did not contain valid utf8 data.
1702 /// Variant representing that an I/O error occurred.
1706 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1708 impl<R: Read> Iterator for Chars<R> {
1709 type Item = result::Result<char, CharsError>;
1711 fn next(&mut self) -> Option<result::Result<char, CharsError>> {
1712 let first_byte = match read_one_byte(&mut self.inner) {
1713 None => return None,
1715 Some(Err(e)) => return Some(Err(CharsError::Other(e))),
1717 let width = core_str::utf8_char_width(first_byte);
1718 if width == 1 { return Some(Ok(first_byte as char)) }
1719 if width == 0 { return Some(Err(CharsError::NotUtf8)) }
1720 let mut buf = [first_byte, 0, 0, 0];
1723 while start < width {
1724 match self.inner.read(&mut buf[start..width]) {
1725 Ok(0) => return Some(Err(CharsError::NotUtf8)),
1726 Ok(n) => start += n,
1727 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1728 Err(e) => return Some(Err(CharsError::Other(e))),
1732 Some(match str::from_utf8(&buf[..width]).ok() {
1733 Some(s) => Ok(s.chars().next().unwrap()),
1734 None => Err(CharsError::NotUtf8),
1739 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1741 impl std_error::Error for CharsError {
1742 fn description(&self) -> &str {
1744 CharsError::NotUtf8 => "invalid utf8 encoding",
1745 CharsError::Other(ref e) => std_error::Error::description(e),
1748 fn cause(&self) -> Option<&std_error::Error> {
1750 CharsError::NotUtf8 => None,
1751 CharsError::Other(ref e) => e.cause(),
1756 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1758 impl fmt::Display for CharsError {
1759 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1761 CharsError::NotUtf8 => {
1762 "byte stream did not contain valid utf8".fmt(f)
1764 CharsError::Other(ref e) => e.fmt(f),
1769 /// An iterator over the contents of an instance of `BufRead` split on a
1770 /// particular byte.
1772 /// This struct is generally created by calling [`split`][split] on a
1773 /// `BufRead`. Please see the documentation of `split()` for more details.
1775 /// [split]: trait.BufRead.html#method.split
1776 #[stable(feature = "rust1", since = "1.0.0")]
1778 pub struct Split<B> {
1783 #[stable(feature = "rust1", since = "1.0.0")]
1784 impl<B: BufRead> Iterator for Split<B> {
1785 type Item = Result<Vec<u8>>;
1787 fn next(&mut self) -> Option<Result<Vec<u8>>> {
1788 let mut buf = Vec::new();
1789 match self.buf.read_until(self.delim, &mut buf) {
1792 if buf[buf.len() - 1] == self.delim {
1797 Err(e) => Some(Err(e))
1802 /// An iterator over the lines of an instance of `BufRead`.
1804 /// This struct is generally created by calling [`lines`][lines] on a
1805 /// `BufRead`. Please see the documentation of `lines()` for more details.
1807 /// [lines]: trait.BufRead.html#method.lines
1808 #[stable(feature = "rust1", since = "1.0.0")]
1810 pub struct Lines<B> {
1814 #[stable(feature = "rust1", since = "1.0.0")]
1815 impl<B: BufRead> Iterator for Lines<B> {
1816 type Item = Result<String>;
1818 fn next(&mut self) -> Option<Result<String>> {
1819 let mut buf = String::new();
1820 match self.buf.read_line(&mut buf) {
1823 if buf.ends_with("\n") {
1825 if buf.ends_with("\r") {
1831 Err(e) => Some(Err(e))
1845 #[cfg_attr(target_os = "emscripten", ignore)]
1847 let mut buf = Cursor::new(&b"12"[..]);
1848 let mut v = Vec::new();
1849 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 2);
1850 assert_eq!(v, b"12");
1852 let mut buf = Cursor::new(&b"1233"[..]);
1853 let mut v = Vec::new();
1854 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 3);
1855 assert_eq!(v, b"123");
1857 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 1);
1858 assert_eq!(v, b"3");
1860 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 0);
1866 let buf = Cursor::new(&b"12"[..]);
1867 let mut s = buf.split(b'3');
1868 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
1869 assert!(s.next().is_none());
1871 let buf = Cursor::new(&b"1233"[..]);
1872 let mut s = buf.split(b'3');
1873 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
1874 assert_eq!(s.next().unwrap().unwrap(), vec![]);
1875 assert!(s.next().is_none());
1880 let mut buf = Cursor::new(&b"12"[..]);
1881 let mut v = String::new();
1882 assert_eq!(buf.read_line(&mut v).unwrap(), 2);
1883 assert_eq!(v, "12");
1885 let mut buf = Cursor::new(&b"12\n\n"[..]);
1886 let mut v = String::new();
1887 assert_eq!(buf.read_line(&mut v).unwrap(), 3);
1888 assert_eq!(v, "12\n");
1890 assert_eq!(buf.read_line(&mut v).unwrap(), 1);
1891 assert_eq!(v, "\n");
1893 assert_eq!(buf.read_line(&mut v).unwrap(), 0);
1899 let buf = Cursor::new(&b"12\r"[..]);
1900 let mut s = buf.lines();
1901 assert_eq!(s.next().unwrap().unwrap(), "12\r".to_string());
1902 assert!(s.next().is_none());
1904 let buf = Cursor::new(&b"12\r\n\n"[..]);
1905 let mut s = buf.lines();
1906 assert_eq!(s.next().unwrap().unwrap(), "12".to_string());
1907 assert_eq!(s.next().unwrap().unwrap(), "".to_string());
1908 assert!(s.next().is_none());
1913 let mut c = Cursor::new(&b""[..]);
1914 let mut v = Vec::new();
1915 assert_eq!(c.read_to_end(&mut v).unwrap(), 0);
1918 let mut c = Cursor::new(&b"1"[..]);
1919 let mut v = Vec::new();
1920 assert_eq!(c.read_to_end(&mut v).unwrap(), 1);
1921 assert_eq!(v, b"1");
1923 let cap = 1024 * 1024;
1924 let data = (0..cap).map(|i| (i / 3) as u8).collect::<Vec<_>>();
1925 let mut v = Vec::new();
1926 let (a, b) = data.split_at(data.len() / 2);
1927 assert_eq!(Cursor::new(a).read_to_end(&mut v).unwrap(), a.len());
1928 assert_eq!(Cursor::new(b).read_to_end(&mut v).unwrap(), b.len());
1929 assert_eq!(v, data);
1933 fn read_to_string() {
1934 let mut c = Cursor::new(&b""[..]);
1935 let mut v = String::new();
1936 assert_eq!(c.read_to_string(&mut v).unwrap(), 0);
1939 let mut c = Cursor::new(&b"1"[..]);
1940 let mut v = String::new();
1941 assert_eq!(c.read_to_string(&mut v).unwrap(), 1);
1944 let mut c = Cursor::new(&b"\xff"[..]);
1945 let mut v = String::new();
1946 assert!(c.read_to_string(&mut v).is_err());
1951 let mut buf = [0; 4];
1953 let mut c = Cursor::new(&b""[..]);
1954 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1955 io::ErrorKind::UnexpectedEof);
1957 let mut c = Cursor::new(&b"123"[..]).chain(Cursor::new(&b"456789"[..]));
1958 c.read_exact(&mut buf).unwrap();
1959 assert_eq!(&buf, b"1234");
1960 c.read_exact(&mut buf).unwrap();
1961 assert_eq!(&buf, b"5678");
1962 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1963 io::ErrorKind::UnexpectedEof);
1967 fn read_exact_slice() {
1968 let mut buf = [0; 4];
1970 let mut c = &b""[..];
1971 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1972 io::ErrorKind::UnexpectedEof);
1974 let mut c = &b"123"[..];
1975 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1976 io::ErrorKind::UnexpectedEof);
1977 // make sure the optimized (early returning) method is being used
1978 assert_eq!(&buf, &[0; 4]);
1980 let mut c = &b"1234"[..];
1981 c.read_exact(&mut buf).unwrap();
1982 assert_eq!(&buf, b"1234");
1984 let mut c = &b"56789"[..];
1985 c.read_exact(&mut buf).unwrap();
1986 assert_eq!(&buf, b"5678");
1987 assert_eq!(c, b"9");
1995 fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
1996 Err(io::Error::new(io::ErrorKind::Other, ""))
1999 impl BufRead for R {
2000 fn fill_buf(&mut self) -> io::Result<&[u8]> {
2001 Err(io::Error::new(io::ErrorKind::Other, ""))
2003 fn consume(&mut self, _amt: usize) { }
2006 let mut buf = [0; 1];
2007 assert_eq!(0, R.take(0).read(&mut buf).unwrap());
2008 assert_eq!(b"", R.take(0).fill_buf().unwrap());
2011 fn cmp_bufread<Br1: BufRead, Br2: BufRead>(mut br1: Br1, mut br2: Br2, exp: &[u8]) {
2012 let mut cat = Vec::new();
2015 let buf1 = br1.fill_buf().unwrap();
2016 let buf2 = br2.fill_buf().unwrap();
2017 let minlen = if buf1.len() < buf2.len() { buf1.len() } else { buf2.len() };
2018 assert_eq!(buf1[..minlen], buf2[..minlen]);
2019 cat.extend_from_slice(&buf1[..minlen]);
2025 br1.consume(consume);
2026 br2.consume(consume);
2028 assert_eq!(br1.fill_buf().unwrap().len(), 0);
2029 assert_eq!(br2.fill_buf().unwrap().len(), 0);
2030 assert_eq!(&cat[..], &exp[..])
2034 fn chain_bufread() {
2035 let testdata = b"ABCDEFGHIJKL";
2036 let chain1 = (&testdata[..3]).chain(&testdata[3..6])
2037 .chain(&testdata[6..9])
2038 .chain(&testdata[9..]);
2039 let chain2 = (&testdata[..4]).chain(&testdata[4..8])
2040 .chain(&testdata[8..]);
2041 cmp_bufread(chain1, chain2, &testdata[..]);
2045 fn chain_zero_length_read_is_not_eof() {
2048 let mut s = String::new();
2049 let mut chain = (&a[..]).chain(&b[..]);
2050 chain.read(&mut []).unwrap();
2051 chain.read_to_string(&mut s).unwrap();
2052 assert_eq!("AB", s);
2056 #[cfg_attr(target_os = "emscripten", ignore)]
2057 fn bench_read_to_end(b: &mut test::Bencher) {
2059 let mut lr = repeat(1).take(10000000);
2060 let mut vec = Vec::with_capacity(1024);
2061 super::read_to_end(&mut lr, &mut vec)