]> git.lizzy.rs Git - rust.git/blob - src/libstd/io/mod.rs
Fix Markdown issues in the docs
[rust.git] / src / libstd / io / mod.rs
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.
4 //
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.
10
11 //! Traits, helpers, and type definitions for core I/O functionality.
12 //!
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.
17 //!
18 //! # Read and Write
19 //!
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
25 //! `File`s:
26 //!
27 //! ```
28 //! use std::io;
29 //! use std::io::prelude::*;
30 //! use std::fs::File;
31 //!
32 //! # fn foo() -> io::Result<()> {
33 //! let mut f = File::open("foo.txt")?;
34 //! let mut buffer = [0; 10];
35 //!
36 //! // read up to 10 bytes
37 //! f.read(&mut buffer)?;
38 //!
39 //! println!("The bytes: {:?}", buffer);
40 //! # Ok(())
41 //! # }
42 //! ```
43 //!
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!
47 //!
48 //! ## Seek and BufRead
49 //!
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
53 //! coming from:
54 //!
55 //! ```
56 //! use std::io;
57 //! use std::io::prelude::*;
58 //! use std::io::SeekFrom;
59 //! use std::fs::File;
60 //!
61 //! # fn foo() -> io::Result<()> {
62 //! let mut f = File::open("foo.txt")?;
63 //! let mut buffer = [0; 10];
64 //!
65 //! // skip to the last 10 bytes of the file
66 //! f.seek(SeekFrom::End(-10))?;
67 //!
68 //! // read up to 10 bytes
69 //! f.read(&mut buffer)?;
70 //!
71 //! println!("The bytes: {:?}", buffer);
72 //! # Ok(())
73 //! # }
74 //! ```
75 //!
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!
78 //!
79 //! ## BufReader and BufWriter
80 //!
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.
86 //!
87 //! For example, [`BufReader`] works with the [`BufRead`] trait to add extra
88 //! methods to any reader:
89 //!
90 //! ```
91 //! use std::io;
92 //! use std::io::prelude::*;
93 //! use std::io::BufReader;
94 //! use std::fs::File;
95 //!
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();
100 //!
101 //! // read a line into buffer
102 //! reader.read_line(&mut buffer)?;
103 //!
104 //! println!("{}", buffer);
105 //! # Ok(())
106 //! # }
107 //! ```
108 //!
109 //! [`BufWriter`] doesn't add any new ways of writing; it just buffers every call
110 //! to [`write`][`Write::write`]:
111 //!
112 //! ```
113 //! use std::io;
114 //! use std::io::prelude::*;
115 //! use std::io::BufWriter;
116 //! use std::fs::File;
117 //!
118 //! # fn foo() -> io::Result<()> {
119 //! let f = File::create("foo.txt")?;
120 //! {
121 //!     let mut writer = BufWriter::new(f);
122 //!
123 //!     // write a byte to the buffer
124 //!     writer.write(&[42])?;
125 //!
126 //! } // the buffer is flushed once writer goes out of scope
127 //!
128 //! # Ok(())
129 //! # }
130 //! ```
131 //!
132 //! ## Standard input and output
133 //!
134 //! A very common source of input is standard input:
135 //!
136 //! ```
137 //! use std::io;
138 //!
139 //! # fn foo() -> io::Result<()> {
140 //! let mut input = String::new();
141 //!
142 //! io::stdin().read_line(&mut input)?;
143 //!
144 //! println!("You typed: {}", input.trim());
145 //! # Ok(())
146 //! # }
147 //! ```
148 //!
149 //! Note that you cannot use the `?` operator in functions that do not return
150 //! a `Result<T, E>` (e.g. `main`). Instead, you can call `.unwrap()` or `match`
151 //! on the return value to catch any possible errors:
152 //!
153 //! ```
154 //! use std::io;
155 //!
156 //! let mut input = String::new();
157 //!
158 //! io::stdin().read_line(&mut input).unwrap();
159 //! ```
160 //!
161 //! And a very common source of output is standard output:
162 //!
163 //! ```
164 //! use std::io;
165 //! use std::io::prelude::*;
166 //!
167 //! # fn foo() -> io::Result<()> {
168 //! io::stdout().write(&[42])?;
169 //! # Ok(())
170 //! # }
171 //! ```
172 //!
173 //! Of course, using [`io::stdout`] directly is less common than something like
174 //! [`println!`].
175 //!
176 //! ## Iterator types
177 //!
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
180 //! lines:
181 //!
182 //! ```
183 //! use std::io;
184 //! use std::io::prelude::*;
185 //! use std::io::BufReader;
186 //! use std::fs::File;
187 //!
188 //! # fn foo() -> io::Result<()> {
189 //! let f = File::open("foo.txt")?;
190 //! let reader = BufReader::new(f);
191 //!
192 //! for line in reader.lines() {
193 //!     println!("{}", line?);
194 //! }
195 //!
196 //! # Ok(())
197 //! # }
198 //! ```
199 //!
200 //! ## Functions
201 //!
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:
205 //!
206 //! ```
207 //! use std::io;
208 //!
209 //! # fn foo() -> io::Result<()> {
210 //! io::copy(&mut io::stdin(), &mut io::stdout())?;
211 //! # Ok(())
212 //! # }
213 //! ```
214 //!
215 //! [functions-list]: #functions-1
216 //!
217 //! ## io::Result
218 //!
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]:
223 //!
224 //! ```
225 //! use std::io;
226 //!
227 //! fn read_input() -> io::Result<()> {
228 //!     let mut input = String::new();
229 //!
230 //!     io::stdin().read_line(&mut input)?;
231 //!
232 //!     println!("You typed: {}", input.trim());
233 //!
234 //!     Ok(())
235 //! }
236 //! ```
237 //!
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 `()`.
242 //!
243 //! ## Platform-specific behavior
244 //!
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.
251 //!
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/syntax-index.html
267 //! [`Read::read`]: trait.Read.html#tymethod.read
268
269 #![stable(feature = "rust1", since = "1.0.0")]
270
271 use cmp;
272 use core::str as core_str;
273 use error as std_error;
274 use fmt;
275 use result;
276 use str;
277 use memchr;
278
279 #[stable(feature = "rust1", since = "1.0.0")]
280 pub use self::buffered::{BufReader, BufWriter, LineWriter};
281 #[stable(feature = "rust1", since = "1.0.0")]
282 pub use self::buffered::IntoInnerError;
283 #[stable(feature = "rust1", since = "1.0.0")]
284 pub use self::cursor::Cursor;
285 #[stable(feature = "rust1", since = "1.0.0")]
286 pub use self::error::{Result, Error, ErrorKind};
287 #[stable(feature = "rust1", since = "1.0.0")]
288 pub use self::util::{copy, sink, Sink, empty, Empty, repeat, Repeat};
289 #[stable(feature = "rust1", since = "1.0.0")]
290 pub use self::stdio::{stdin, stdout, stderr, _print, Stdin, Stdout, Stderr};
291 #[stable(feature = "rust1", since = "1.0.0")]
292 pub use self::stdio::{StdoutLock, StderrLock, StdinLock};
293 #[unstable(feature = "libstd_io_internals", issue = "0")]
294 #[doc(no_inline, hidden)]
295 pub use self::stdio::{set_panic, set_print};
296
297 pub mod prelude;
298 mod buffered;
299 mod cursor;
300 mod error;
301 mod impls;
302 mod lazy;
303 mod util;
304 mod stdio;
305
306 const DEFAULT_BUF_SIZE: usize = ::sys_common::io::DEFAULT_BUF_SIZE;
307
308 // A few methods below (read_to_string, read_line) will append data into a
309 // `String` buffer, but we need to be pretty careful when doing this. The
310 // implementation will just call `.as_mut_vec()` and then delegate to a
311 // byte-oriented reading method, but we must ensure that when returning we never
312 // leave `buf` in a state such that it contains invalid UTF-8 in its bounds.
313 //
314 // To this end, we use an RAII guard (to protect against panics) which updates
315 // the length of the string when it is dropped. This guard initially truncates
316 // the string to the prior length and only after we've validated that the
317 // new contents are valid UTF-8 do we allow it to set a longer length.
318 //
319 // The unsafety in this function is twofold:
320 //
321 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
322 //    checks.
323 // 2. We're passing a raw buffer to the function `f`, and it is expected that
324 //    the function only *appends* bytes to the buffer. We'll get undefined
325 //    behavior if existing bytes are overwritten to have non-UTF-8 data.
326 fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
327     where F: FnOnce(&mut Vec<u8>) -> Result<usize>
328 {
329     struct Guard<'a> { s: &'a mut Vec<u8>, len: usize }
330         impl<'a> Drop for Guard<'a> {
331         fn drop(&mut self) {
332             unsafe { self.s.set_len(self.len); }
333         }
334     }
335
336     unsafe {
337         let mut g = Guard { len: buf.len(), s: buf.as_mut_vec() };
338         let ret = f(g.s);
339         if str::from_utf8(&g.s[g.len..]).is_err() {
340             ret.and_then(|_| {
341                 Err(Error::new(ErrorKind::InvalidData,
342                                "stream did not contain valid UTF-8"))
343             })
344         } else {
345             g.len = g.s.len();
346             ret
347         }
348     }
349 }
350
351 // This uses an adaptive system to extend the vector when it fills. We want to
352 // avoid paying to allocate and zero a huge chunk of memory if the reader only
353 // has 4 bytes while still making large reads if the reader does have a ton
354 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
355 // time is 4,500 times (!) slower than this if the reader has a very small
356 // amount of data to return.
357 fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
358     let start_len = buf.len();
359     let mut len = start_len;
360     let mut new_write_size = 16;
361     let ret;
362     loop {
363         if len == buf.len() {
364             if new_write_size < DEFAULT_BUF_SIZE {
365                 new_write_size *= 2;
366             }
367             buf.resize(len + new_write_size, 0);
368         }
369
370         match r.read(&mut buf[len..]) {
371             Ok(0) => {
372                 ret = Ok(len - start_len);
373                 break;
374             }
375             Ok(n) => len += n,
376             Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
377             Err(e) => {
378                 ret = Err(e);
379                 break;
380             }
381         }
382     }
383
384     buf.truncate(len);
385     ret
386 }
387
388 /// The `Read` trait allows for reading bytes from a source.
389 ///
390 /// Implementors of the `Read` trait are sometimes called 'readers'.
391 ///
392 /// Readers are defined by one required method, `read()`. Each call to `read`
393 /// will attempt to pull bytes from this source into a provided buffer. A
394 /// number of other methods are implemented in terms of `read()`, giving
395 /// implementors a number of ways to read bytes while only needing to implement
396 /// a single method.
397 ///
398 /// Readers are intended to be composable with one another. Many implementors
399 /// throughout `std::io` take and provide types which implement the `Read`
400 /// trait.
401 ///
402 /// Please note that each call to `read` may involve a system call, and
403 /// therefore, using something that implements [`BufRead`][bufread], such as
404 /// [`BufReader`][bufreader], will be more efficient.
405 ///
406 /// [bufread]: trait.BufRead.html
407 /// [bufreader]: struct.BufReader.html
408 ///
409 /// # Examples
410 ///
411 /// [`File`][file]s implement `Read`:
412 ///
413 /// [file]: ../fs/struct.File.html
414 ///
415 /// ```
416 /// use std::io;
417 /// use std::io::prelude::*;
418 /// use std::fs::File;
419 ///
420 /// # fn foo() -> io::Result<()> {
421 /// let mut f = File::open("foo.txt")?;
422 /// let mut buffer = [0; 10];
423 ///
424 /// // read up to 10 bytes
425 /// f.read(&mut buffer)?;
426 ///
427 /// let mut buffer = vec![0; 10];
428 /// // read the whole file
429 /// f.read_to_end(&mut buffer)?;
430 ///
431 /// // read into a String, so that you don't need to do the conversion.
432 /// let mut buffer = String::new();
433 /// f.read_to_string(&mut buffer)?;
434 ///
435 /// // and more! See the other methods for more details.
436 /// # Ok(())
437 /// # }
438 /// ```
439 #[stable(feature = "rust1", since = "1.0.0")]
440 pub trait Read {
441     /// Pull some bytes from this source into the specified buffer, returning
442     /// how many bytes were read.
443     ///
444     /// This function does not provide any guarantees about whether it blocks
445     /// waiting for data, but if an object needs to block for a read but cannot
446     /// it will typically signal this via an `Err` return value.
447     ///
448     /// If the return value of this method is `Ok(n)`, then it must be
449     /// guaranteed that `0 <= n <= buf.len()`. A nonzero `n` value indicates
450     /// that the buffer `buf` has been filled in with `n` bytes of data from this
451     /// source. If `n` is `0`, then it can indicate one of two scenarios:
452     ///
453     /// 1. This reader has reached its "end of file" and will likely no longer
454     ///    be able to produce bytes. Note that this does not mean that the
455     ///    reader will *always* no longer be able to produce bytes.
456     /// 2. The buffer specified was 0 bytes in length.
457     ///
458     /// No guarantees are provided about the contents of `buf` when this
459     /// function is called, implementations cannot rely on any property of the
460     /// contents of `buf` being true. It is recommended that implementations
461     /// only write data to `buf` instead of reading its contents.
462     ///
463     /// # Errors
464     ///
465     /// If this function encounters any form of I/O or other error, an error
466     /// variant will be returned. If an error is returned then it must be
467     /// guaranteed that no bytes were read.
468     ///
469     /// # Examples
470     ///
471     /// [`File`][file]s implement `Read`:
472     ///
473     /// [file]: ../fs/struct.File.html
474     ///
475     /// ```
476     /// use std::io;
477     /// use std::io::prelude::*;
478     /// use std::fs::File;
479     ///
480     /// # fn foo() -> io::Result<()> {
481     /// let mut f = File::open("foo.txt")?;
482     /// let mut buffer = [0; 10];
483     ///
484     /// // read 10 bytes
485     /// f.read(&mut buffer[..])?;
486     /// # Ok(())
487     /// # }
488     /// ```
489     #[stable(feature = "rust1", since = "1.0.0")]
490     fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
491
492     /// Read all bytes until EOF in this source, placing them into `buf`.
493     ///
494     /// All bytes read from this source will be appended to the specified buffer
495     /// `buf`. This function will continuously call `read` to append more data to
496     /// `buf` until `read` returns either `Ok(0)` or an error of
497     /// non-`ErrorKind::Interrupted` kind.
498     ///
499     /// If successful, this function will return the total number of bytes read.
500     ///
501     /// # Errors
502     ///
503     /// If this function encounters an error of the kind
504     /// `ErrorKind::Interrupted` then the error is ignored and the operation
505     /// will continue.
506     ///
507     /// If any other read error is encountered then this function immediately
508     /// returns. Any bytes which have already been read will be appended to
509     /// `buf`.
510     ///
511     /// # Examples
512     ///
513     /// [`File`][file]s implement `Read`:
514     ///
515     /// [file]: ../fs/struct.File.html
516     ///
517     /// ```
518     /// use std::io;
519     /// use std::io::prelude::*;
520     /// use std::fs::File;
521     ///
522     /// # fn foo() -> io::Result<()> {
523     /// let mut f = File::open("foo.txt")?;
524     /// let mut buffer = Vec::new();
525     ///
526     /// // read the whole file
527     /// f.read_to_end(&mut buffer)?;
528     /// # Ok(())
529     /// # }
530     /// ```
531     #[stable(feature = "rust1", since = "1.0.0")]
532     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
533         read_to_end(self, buf)
534     }
535
536     /// Read all bytes until EOF in this source, placing them into `buf`.
537     ///
538     /// If successful, this function returns the number of bytes which were read
539     /// and appended to `buf`.
540     ///
541     /// # Errors
542     ///
543     /// If the data in this stream is *not* valid UTF-8 then an error is
544     /// returned and `buf` is unchanged.
545     ///
546     /// See [`read_to_end`][readtoend] for other error semantics.
547     ///
548     /// [readtoend]: #method.read_to_end
549     ///
550     /// # Examples
551     ///
552     /// [`File`][file]s implement `Read`:
553     ///
554     /// [file]: ../fs/struct.File.html
555     ///
556     /// ```
557     /// use std::io;
558     /// use std::io::prelude::*;
559     /// use std::fs::File;
560     ///
561     /// # fn foo() -> io::Result<()> {
562     /// let mut f = File::open("foo.txt")?;
563     /// let mut buffer = String::new();
564     ///
565     /// f.read_to_string(&mut buffer)?;
566     /// # Ok(())
567     /// # }
568     /// ```
569     #[stable(feature = "rust1", since = "1.0.0")]
570     fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
571         // Note that we do *not* call `.read_to_end()` here. We are passing
572         // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
573         // method to fill it up. An arbitrary implementation could overwrite the
574         // entire contents of the vector, not just append to it (which is what
575         // we are expecting).
576         //
577         // To prevent extraneously checking the UTF-8-ness of the entire buffer
578         // we pass it to our hardcoded `read_to_end` implementation which we
579         // know is guaranteed to only read data into the end of the buffer.
580         append_to_string(buf, |b| read_to_end(self, b))
581     }
582
583     /// Read the exact number of bytes required to fill `buf`.
584     ///
585     /// This function reads as many bytes as necessary to completely fill the
586     /// specified buffer `buf`.
587     ///
588     /// No guarantees are provided about the contents of `buf` when this
589     /// function is called, implementations cannot rely on any property of the
590     /// contents of `buf` being true. It is recommended that implementations
591     /// only write data to `buf` instead of reading its contents.
592     ///
593     /// # Errors
594     ///
595     /// If this function encounters an error of the kind
596     /// `ErrorKind::Interrupted` then the error is ignored and the operation
597     /// will continue.
598     ///
599     /// If this function encounters an "end of file" before completely filling
600     /// the buffer, it returns an error of the kind `ErrorKind::UnexpectedEof`.
601     /// The contents of `buf` are unspecified in this case.
602     ///
603     /// If any other read error is encountered then this function immediately
604     /// returns. The contents of `buf` are unspecified in this case.
605     ///
606     /// If this function returns an error, it is unspecified how many bytes it
607     /// has read, but it will never read more than would be necessary to
608     /// completely fill the buffer.
609     ///
610     /// # Examples
611     ///
612     /// [`File`][file]s implement `Read`:
613     ///
614     /// [file]: ../fs/struct.File.html
615     ///
616     /// ```
617     /// use std::io;
618     /// use std::io::prelude::*;
619     /// use std::fs::File;
620     ///
621     /// # fn foo() -> io::Result<()> {
622     /// let mut f = File::open("foo.txt")?;
623     /// let mut buffer = [0; 10];
624     ///
625     /// // read exactly 10 bytes
626     /// f.read_exact(&mut buffer)?;
627     /// # Ok(())
628     /// # }
629     /// ```
630     #[stable(feature = "read_exact", since = "1.6.0")]
631     fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
632         while !buf.is_empty() {
633             match self.read(buf) {
634                 Ok(0) => break,
635                 Ok(n) => { let tmp = buf; buf = &mut tmp[n..]; }
636                 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
637                 Err(e) => return Err(e),
638             }
639         }
640         if !buf.is_empty() {
641             Err(Error::new(ErrorKind::UnexpectedEof,
642                            "failed to fill whole buffer"))
643         } else {
644             Ok(())
645         }
646     }
647
648     /// Creates a "by reference" adaptor for this instance of `Read`.
649     ///
650     /// The returned adaptor also implements `Read` and will simply borrow this
651     /// current reader.
652     ///
653     /// # Examples
654     ///
655     /// [`File`][file]s implement `Read`:
656     ///
657     /// [file]: ../fs/struct.File.html
658     ///
659     /// ```
660     /// use std::io;
661     /// use std::io::Read;
662     /// use std::fs::File;
663     ///
664     /// # fn foo() -> io::Result<()> {
665     /// let mut f = File::open("foo.txt")?;
666     /// let mut buffer = Vec::new();
667     /// let mut other_buffer = Vec::new();
668     ///
669     /// {
670     ///     let reference = f.by_ref();
671     ///
672     ///     // read at most 5 bytes
673     ///     reference.take(5).read_to_end(&mut buffer)?;
674     ///
675     /// } // drop our &mut reference so we can use f again
676     ///
677     /// // original file still usable, read the rest
678     /// f.read_to_end(&mut other_buffer)?;
679     /// # Ok(())
680     /// # }
681     /// ```
682     #[stable(feature = "rust1", since = "1.0.0")]
683     fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
684
685     /// Transforms this `Read` instance to an `Iterator` over its bytes.
686     ///
687     /// The returned type implements `Iterator` where the `Item` is `Result<u8,
688     /// R::Err>`.  The yielded item is `Ok` if a byte was successfully read and
689     /// `Err` otherwise for I/O errors. EOF is mapped to returning `None` from
690     /// this iterator.
691     ///
692     /// # Examples
693     ///
694     /// [`File`][file]s implement `Read`:
695     ///
696     /// [file]: ../fs/struct.File.html
697     ///
698     /// ```
699     /// use std::io;
700     /// use std::io::prelude::*;
701     /// use std::fs::File;
702     ///
703     /// # fn foo() -> io::Result<()> {
704     /// let mut f = File::open("foo.txt")?;
705     ///
706     /// for byte in f.bytes() {
707     ///     println!("{}", byte.unwrap());
708     /// }
709     /// # Ok(())
710     /// # }
711     /// ```
712     #[stable(feature = "rust1", since = "1.0.0")]
713     fn bytes(self) -> Bytes<Self> where Self: Sized {
714         Bytes { inner: self }
715     }
716
717     /// Transforms this `Read` instance to an `Iterator` over `char`s.
718     ///
719     /// This adaptor will attempt to interpret this reader as a UTF-8 encoded
720     /// sequence of characters. The returned iterator will return `None` once
721     /// EOF is reached for this reader. Otherwise each element yielded will be a
722     /// `Result<char, E>` where `E` may contain information about what I/O error
723     /// occurred or where decoding failed.
724     ///
725     /// Currently this adaptor will discard intermediate data read, and should
726     /// be avoided if this is not desired.
727     ///
728     /// # Examples
729     ///
730     /// [`File`][file]s implement `Read`:
731     ///
732     /// [file]: ../fs/struct.File.html
733     ///
734     /// ```
735     /// #![feature(io)]
736     /// use std::io;
737     /// use std::io::prelude::*;
738     /// use std::fs::File;
739     ///
740     /// # fn foo() -> io::Result<()> {
741     /// let mut f = File::open("foo.txt")?;
742     ///
743     /// for c in f.chars() {
744     ///     println!("{}", c.unwrap());
745     /// }
746     /// # Ok(())
747     /// # }
748     /// ```
749     #[unstable(feature = "io", reason = "the semantics of a partial read/write \
750                                          of where errors happen is currently \
751                                          unclear and may change",
752                issue = "27802")]
753     fn chars(self) -> Chars<Self> where Self: Sized {
754         Chars { inner: self }
755     }
756
757     /// Creates an adaptor which will chain this stream with another.
758     ///
759     /// The returned `Read` instance will first read all bytes from this object
760     /// until EOF is encountered. Afterwards the output is equivalent to the
761     /// output of `next`.
762     ///
763     /// # Examples
764     ///
765     /// [`File`][file]s implement `Read`:
766     ///
767     /// [file]: ../fs/struct.File.html
768     ///
769     /// ```
770     /// use std::io;
771     /// use std::io::prelude::*;
772     /// use std::fs::File;
773     ///
774     /// # fn foo() -> io::Result<()> {
775     /// let mut f1 = File::open("foo.txt")?;
776     /// let mut f2 = File::open("bar.txt")?;
777     ///
778     /// let mut handle = f1.chain(f2);
779     /// let mut buffer = String::new();
780     ///
781     /// // read the value into a String. We could use any Read method here,
782     /// // this is just one example.
783     /// handle.read_to_string(&mut buffer)?;
784     /// # Ok(())
785     /// # }
786     /// ```
787     #[stable(feature = "rust1", since = "1.0.0")]
788     fn chain<R: Read>(self, next: R) -> Chain<Self, R> where Self: Sized {
789         Chain { first: self, second: next, done_first: false }
790     }
791
792     /// Creates an adaptor which will read at most `limit` bytes from it.
793     ///
794     /// This function returns a new instance of `Read` which will read at most
795     /// `limit` bytes, after which it will always return EOF (`Ok(0)`). Any
796     /// read errors will not count towards the number of bytes read and future
797     /// calls to `read` may succeed.
798     ///
799     /// # Examples
800     ///
801     /// [`File`][file]s implement `Read`:
802     ///
803     /// [file]: ../fs/struct.File.html
804     ///
805     /// ```
806     /// use std::io;
807     /// use std::io::prelude::*;
808     /// use std::fs::File;
809     ///
810     /// # fn foo() -> io::Result<()> {
811     /// let mut f = File::open("foo.txt")?;
812     /// let mut buffer = [0; 5];
813     ///
814     /// // read at most five bytes
815     /// let mut handle = f.take(5);
816     ///
817     /// handle.read(&mut buffer)?;
818     /// # Ok(())
819     /// # }
820     /// ```
821     #[stable(feature = "rust1", since = "1.0.0")]
822     fn take(self, limit: u64) -> Take<Self> where Self: Sized {
823         Take { inner: self, limit: limit }
824     }
825 }
826
827 /// A trait for objects which are byte-oriented sinks.
828 ///
829 /// Implementors of the `Write` trait are sometimes called 'writers'.
830 ///
831 /// Writers are defined by two required methods, [`write`] and [`flush`]:
832 ///
833 /// * The [`write`] method will attempt to write some data into the object,
834 ///   returning how many bytes were successfully written.
835 ///
836 /// * The [`flush`] method is useful for adaptors and explicit buffers
837 ///   themselves for ensuring that all buffered data has been pushed out to the
838 ///   'true sink'.
839 ///
840 /// Writers are intended to be composable with one another. Many implementors
841 /// throughout [`std::io`] take and provide types which implement the `Write`
842 /// trait.
843 ///
844 /// [`write`]: #tymethod.write
845 /// [`flush`]: #tymethod.flush
846 /// [`std::io`]: index.html
847 ///
848 /// # Examples
849 ///
850 /// ```
851 /// use std::io::prelude::*;
852 /// use std::fs::File;
853 ///
854 /// # fn foo() -> std::io::Result<()> {
855 /// let mut buffer = File::create("foo.txt")?;
856 ///
857 /// buffer.write(b"some bytes")?;
858 /// # Ok(())
859 /// # }
860 /// ```
861 #[stable(feature = "rust1", since = "1.0.0")]
862 pub trait Write {
863     /// Write a buffer into this object, returning how many bytes were written.
864     ///
865     /// This function will attempt to write the entire contents of `buf`, but
866     /// the entire write may not succeed, or the write may also generate an
867     /// error. A call to `write` represents *at most one* attempt to write to
868     /// any wrapped object.
869     ///
870     /// Calls to `write` are not guaranteed to block waiting for data to be
871     /// written, and a write which would otherwise block can be indicated through
872     /// an `Err` variant.
873     ///
874     /// If the return value is `Ok(n)` then it must be guaranteed that
875     /// `0 <= n <= buf.len()`. A return value of `0` typically means that the
876     /// underlying object is no longer able to accept bytes and will likely not
877     /// be able to in the future as well, or that the buffer provided is empty.
878     ///
879     /// # Errors
880     ///
881     /// Each call to `write` may generate an I/O error indicating that the
882     /// operation could not be completed. If an error is returned then no bytes
883     /// in the buffer were written to this writer.
884     ///
885     /// It is **not** considered an error if the entire buffer could not be
886     /// written to this writer.
887     ///
888     /// # Examples
889     ///
890     /// ```
891     /// use std::io::prelude::*;
892     /// use std::fs::File;
893     ///
894     /// # fn foo() -> std::io::Result<()> {
895     /// let mut buffer = File::create("foo.txt")?;
896     ///
897     /// buffer.write(b"some bytes")?;
898     /// # Ok(())
899     /// # }
900     /// ```
901     #[stable(feature = "rust1", since = "1.0.0")]
902     fn write(&mut self, buf: &[u8]) -> Result<usize>;
903
904     /// Flush this output stream, ensuring that all intermediately buffered
905     /// contents reach their destination.
906     ///
907     /// # Errors
908     ///
909     /// It is considered an error if not all bytes could be written due to
910     /// I/O errors or EOF being reached.
911     ///
912     /// # Examples
913     ///
914     /// ```
915     /// use std::io::prelude::*;
916     /// use std::io::BufWriter;
917     /// use std::fs::File;
918     ///
919     /// # fn foo() -> std::io::Result<()> {
920     /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
921     ///
922     /// buffer.write(b"some bytes")?;
923     /// buffer.flush()?;
924     /// # Ok(())
925     /// # }
926     /// ```
927     #[stable(feature = "rust1", since = "1.0.0")]
928     fn flush(&mut self) -> Result<()>;
929
930     /// Attempts to write an entire buffer into this write.
931     ///
932     /// This method will continuously call `write` while there is more data to
933     /// write. This method will not return until the entire buffer has been
934     /// successfully written or an error occurs. The first error generated from
935     /// this method will be returned.
936     ///
937     /// # Errors
938     ///
939     /// This function will return the first error that `write` returns.
940     ///
941     /// # Examples
942     ///
943     /// ```
944     /// use std::io::prelude::*;
945     /// use std::fs::File;
946     ///
947     /// # fn foo() -> std::io::Result<()> {
948     /// let mut buffer = File::create("foo.txt")?;
949     ///
950     /// buffer.write_all(b"some bytes")?;
951     /// # Ok(())
952     /// # }
953     /// ```
954     #[stable(feature = "rust1", since = "1.0.0")]
955     fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
956         while !buf.is_empty() {
957             match self.write(buf) {
958                 Ok(0) => return Err(Error::new(ErrorKind::WriteZero,
959                                                "failed to write whole buffer")),
960                 Ok(n) => buf = &buf[n..],
961                 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
962                 Err(e) => return Err(e),
963             }
964         }
965         Ok(())
966     }
967
968     /// Writes a formatted string into this writer, returning any error
969     /// encountered.
970     ///
971     /// This method is primarily used to interface with the
972     /// [`format_args!`][formatargs] macro, but it is rare that this should
973     /// explicitly be called. The [`write!`][write] macro should be favored to
974     /// invoke this method instead.
975     ///
976     /// [formatargs]: ../macro.format_args.html
977     /// [write]: ../macro.write.html
978     ///
979     /// This function internally uses the [`write_all`][writeall] method on
980     /// this trait and hence will continuously write data so long as no errors
981     /// are received. This also means that partial writes are not indicated in
982     /// this signature.
983     ///
984     /// [writeall]: #method.write_all
985     ///
986     /// # Errors
987     ///
988     /// This function will return any I/O error reported while formatting.
989     ///
990     /// # Examples
991     ///
992     /// ```
993     /// use std::io::prelude::*;
994     /// use std::fs::File;
995     ///
996     /// # fn foo() -> std::io::Result<()> {
997     /// let mut buffer = File::create("foo.txt")?;
998     ///
999     /// // this call
1000     /// write!(buffer, "{:.*}", 2, 1.234567)?;
1001     /// // turns into this:
1002     /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1003     /// # Ok(())
1004     /// # }
1005     /// ```
1006     #[stable(feature = "rust1", since = "1.0.0")]
1007     fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()> {
1008         // Create a shim which translates a Write to a fmt::Write and saves
1009         // off I/O errors. instead of discarding them
1010         struct Adaptor<'a, T: ?Sized + 'a> {
1011             inner: &'a mut T,
1012             error: Result<()>,
1013         }
1014
1015         impl<'a, T: Write + ?Sized> fmt::Write for Adaptor<'a, T> {
1016             fn write_str(&mut self, s: &str) -> fmt::Result {
1017                 match self.inner.write_all(s.as_bytes()) {
1018                     Ok(()) => Ok(()),
1019                     Err(e) => {
1020                         self.error = Err(e);
1021                         Err(fmt::Error)
1022                     }
1023                 }
1024             }
1025         }
1026
1027         let mut output = Adaptor { inner: self, error: Ok(()) };
1028         match fmt::write(&mut output, fmt) {
1029             Ok(()) => Ok(()),
1030             Err(..) => {
1031                 // check if the error came from the underlying `Write` or not
1032                 if output.error.is_err() {
1033                     output.error
1034                 } else {
1035                     Err(Error::new(ErrorKind::Other, "formatter error"))
1036                 }
1037             }
1038         }
1039     }
1040
1041     /// Creates a "by reference" adaptor for this instance of `Write`.
1042     ///
1043     /// The returned adaptor also implements `Write` and will simply borrow this
1044     /// current writer.
1045     ///
1046     /// # Examples
1047     ///
1048     /// ```
1049     /// use std::io::Write;
1050     /// use std::fs::File;
1051     ///
1052     /// # fn foo() -> std::io::Result<()> {
1053     /// let mut buffer = File::create("foo.txt")?;
1054     ///
1055     /// let reference = buffer.by_ref();
1056     ///
1057     /// // we can use reference just like our original buffer
1058     /// reference.write_all(b"some bytes")?;
1059     /// # Ok(())
1060     /// # }
1061     /// ```
1062     #[stable(feature = "rust1", since = "1.0.0")]
1063     fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1064 }
1065
1066 /// The `Seek` trait provides a cursor which can be moved within a stream of
1067 /// bytes.
1068 ///
1069 /// The stream typically has a fixed size, allowing seeking relative to either
1070 /// end or the current offset.
1071 ///
1072 /// # Examples
1073 ///
1074 /// [`File`][file]s implement `Seek`:
1075 ///
1076 /// [file]: ../fs/struct.File.html
1077 ///
1078 /// ```
1079 /// use std::io;
1080 /// use std::io::prelude::*;
1081 /// use std::fs::File;
1082 /// use std::io::SeekFrom;
1083 ///
1084 /// # fn foo() -> io::Result<()> {
1085 /// let mut f = File::open("foo.txt")?;
1086 ///
1087 /// // move the cursor 42 bytes from the start of the file
1088 /// f.seek(SeekFrom::Start(42))?;
1089 /// # Ok(())
1090 /// # }
1091 /// ```
1092 #[stable(feature = "rust1", since = "1.0.0")]
1093 pub trait Seek {
1094     /// Seek to an offset, in bytes, in a stream.
1095     ///
1096     /// A seek beyond the end of a stream is allowed, but implementation
1097     /// defined.
1098     ///
1099     /// If the seek operation completed successfully,
1100     /// this method returns the new position from the start of the stream.
1101     /// That position can be used later with [`SeekFrom::Start`].
1102     ///
1103     /// # Errors
1104     ///
1105     /// Seeking to a negative offset is considered an error.
1106     ///
1107     /// [`SeekFrom::Start`]: enum.SeekFrom.html#variant.Start
1108     #[stable(feature = "rust1", since = "1.0.0")]
1109     fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1110 }
1111
1112 /// Enumeration of possible methods to seek within an I/O object.
1113 ///
1114 /// It is used by the [`Seek`] trait.
1115 ///
1116 /// [`Seek`]: trait.Seek.html
1117 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1118 #[stable(feature = "rust1", since = "1.0.0")]
1119 pub enum SeekFrom {
1120     /// Set the offset to the provided number of bytes.
1121     #[stable(feature = "rust1", since = "1.0.0")]
1122     Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1123
1124     /// Set the offset to the size of this object plus the specified number of
1125     /// bytes.
1126     ///
1127     /// It is possible to seek beyond the end of an object, but it's an error to
1128     /// seek before byte 0.
1129     #[stable(feature = "rust1", since = "1.0.0")]
1130     End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1131
1132     /// Set the offset to the current position plus the specified number of
1133     /// bytes.
1134     ///
1135     /// It is possible to seek beyond the end of an object, but it's an error to
1136     /// seek before byte 0.
1137     #[stable(feature = "rust1", since = "1.0.0")]
1138     Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1139 }
1140
1141 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>)
1142                                    -> Result<usize> {
1143     let mut read = 0;
1144     loop {
1145         let (done, used) = {
1146             let available = match r.fill_buf() {
1147                 Ok(n) => n,
1148                 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1149                 Err(e) => return Err(e)
1150             };
1151             match memchr::memchr(delim, available) {
1152                 Some(i) => {
1153                     buf.extend_from_slice(&available[..i + 1]);
1154                     (true, i + 1)
1155                 }
1156                 None => {
1157                     buf.extend_from_slice(available);
1158                     (false, available.len())
1159                 }
1160             }
1161         };
1162         r.consume(used);
1163         read += used;
1164         if done || used == 0 {
1165             return Ok(read);
1166         }
1167     }
1168 }
1169
1170 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1171 /// to perform extra ways of reading.
1172 ///
1173 /// For example, reading line-by-line is inefficient without using a buffer, so
1174 /// if you want to read by line, you'll need `BufRead`, which includes a
1175 /// [`read_line`] method as well as a [`lines`] iterator.
1176 ///
1177 /// # Examples
1178 ///
1179 /// A locked standard input implements `BufRead`:
1180 ///
1181 /// ```
1182 /// use std::io;
1183 /// use std::io::prelude::*;
1184 ///
1185 /// let stdin = io::stdin();
1186 /// for line in stdin.lock().lines() {
1187 ///     println!("{}", line.unwrap());
1188 /// }
1189 /// ```
1190 ///
1191 /// If you have something that implements [`Read`], you can use the [`BufReader`
1192 /// type][`BufReader`] to turn it into a `BufRead`.
1193 ///
1194 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1195 /// [`BufReader`] to the rescue!
1196 ///
1197 /// [`BufReader`]: struct.BufReader.html
1198 /// [`File`]: ../fs/struct.File.html
1199 /// [`read_line`]: #method.read_line
1200 /// [`lines`]: #method.lines
1201 /// [`Read`]: trait.Read.html
1202 ///
1203 /// ```
1204 /// use std::io::{self, BufReader};
1205 /// use std::io::prelude::*;
1206 /// use std::fs::File;
1207 ///
1208 /// # fn foo() -> io::Result<()> {
1209 /// let f = File::open("foo.txt")?;
1210 /// let f = BufReader::new(f);
1211 ///
1212 /// for line in f.lines() {
1213 ///     println!("{}", line.unwrap());
1214 /// }
1215 ///
1216 /// # Ok(())
1217 /// # }
1218 /// ```
1219 ///
1220 #[stable(feature = "rust1", since = "1.0.0")]
1221 pub trait BufRead: Read {
1222     /// Fills the internal buffer of this object, returning the buffer contents.
1223     ///
1224     /// This function is a lower-level call. It needs to be paired with the
1225     /// [`consume`] method to function properly. When calling this
1226     /// method, none of the contents will be "read" in the sense that later
1227     /// calling `read` may return the same contents. As such, [`consume`] must
1228     /// be called with the number of bytes that are consumed from this buffer to
1229     /// ensure that the bytes are never returned twice.
1230     ///
1231     /// [`consume`]: #tymethod.consume
1232     ///
1233     /// An empty buffer returned indicates that the stream has reached EOF.
1234     ///
1235     /// # Errors
1236     ///
1237     /// This function will return an I/O error if the underlying reader was
1238     /// read, but returned an error.
1239     ///
1240     /// # Examples
1241     ///
1242     /// A locked standard input implements `BufRead`:
1243     ///
1244     /// ```
1245     /// use std::io;
1246     /// use std::io::prelude::*;
1247     ///
1248     /// let stdin = io::stdin();
1249     /// let mut stdin = stdin.lock();
1250     ///
1251     /// // we can't have two `&mut` references to `stdin`, so use a block
1252     /// // to end the borrow early.
1253     /// let length = {
1254     ///     let buffer = stdin.fill_buf().unwrap();
1255     ///
1256     ///     // work with buffer
1257     ///     println!("{:?}", buffer);
1258     ///
1259     ///     buffer.len()
1260     /// };
1261     ///
1262     /// // ensure the bytes we worked with aren't returned again later
1263     /// stdin.consume(length);
1264     /// ```
1265     #[stable(feature = "rust1", since = "1.0.0")]
1266     fn fill_buf(&mut self) -> Result<&[u8]>;
1267
1268     /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1269     /// so they should no longer be returned in calls to `read`.
1270     ///
1271     /// This function is a lower-level call. It needs to be paired with the
1272     /// [`fill_buf`] method to function properly. This function does
1273     /// not perform any I/O, it simply informs this object that some amount of
1274     /// its buffer, returned from [`fill_buf`], has been consumed and should
1275     /// no longer be returned. As such, this function may do odd things if
1276     /// [`fill_buf`] isn't called before calling it.
1277     ///
1278     /// The `amt` must be `<=` the number of bytes in the buffer returned by
1279     /// [`fill_buf`].
1280     ///
1281     /// # Examples
1282     ///
1283     /// Since `consume()` is meant to be used with [`fill_buf`],
1284     /// that method's example includes an example of `consume()`.
1285     ///
1286     /// [`fill_buf`]: #tymethod.fill_buf
1287     #[stable(feature = "rust1", since = "1.0.0")]
1288     fn consume(&mut self, amt: usize);
1289
1290     /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
1291     ///
1292     /// This function will read bytes from the underlying stream until the
1293     /// delimiter or EOF is found. Once found, all bytes up to, and including,
1294     /// the delimiter (if found) will be appended to `buf`.
1295     ///
1296     /// If successful, this function will return the total number of bytes read.
1297     ///
1298     /// # Errors
1299     ///
1300     /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1301     /// will otherwise return any errors returned by [`fill_buf`].
1302     ///
1303     /// If an I/O error is encountered then all bytes read so far will be
1304     /// present in `buf` and its length will have been adjusted appropriately.
1305     ///
1306     /// [`fill_buf`]: #tymethod.fill_buf
1307     /// [`ErrorKind::Interrupted`]: enum.ErrorKind.html#variant.Interrupted
1308     ///
1309     /// # Examples
1310     ///
1311     /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1312     /// this example, we use [`Cursor`] to read all the bytes in a byte slice
1313     /// in hyphen delimited segments:
1314     ///
1315     /// [`Cursor`]: struct.Cursor.html
1316     ///
1317     /// ```
1318     /// use std::io::{self, BufRead};
1319     ///
1320     /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
1321     /// let mut buf = vec![];
1322     ///
1323     /// // cursor is at 'l'
1324     /// let num_bytes = cursor.read_until(b'-', &mut buf)
1325     ///     .expect("reading from cursor won't fail");
1326     /// assert_eq!(num_bytes, 6);
1327     /// assert_eq!(buf, b"lorem-");
1328     /// buf.clear();
1329     ///
1330     /// // cursor is at 'i'
1331     /// let num_bytes = cursor.read_until(b'-', &mut buf)
1332     ///     .expect("reading from cursor won't fail");
1333     /// assert_eq!(num_bytes, 5);
1334     /// assert_eq!(buf, b"ipsum");
1335     /// buf.clear();
1336     ///
1337     /// // cursor is at EOF
1338     /// let num_bytes = cursor.read_until(b'-', &mut buf)
1339     ///     .expect("reading from cursor won't fail");
1340     /// assert_eq!(num_bytes, 0);
1341     /// assert_eq!(buf, b"");
1342     /// ```
1343     #[stable(feature = "rust1", since = "1.0.0")]
1344     fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
1345         read_until(self, byte, buf)
1346     }
1347
1348     /// Read all bytes until a newline (the 0xA byte) is reached, and append
1349     /// them to the provided buffer.
1350     ///
1351     /// This function will read bytes from the underlying stream until the
1352     /// newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes
1353     /// up to, and including, the delimiter (if found) will be appended to
1354     /// `buf`.
1355     ///
1356     /// If successful, this function will return the total number of bytes read.
1357     ///
1358     /// # Errors
1359     ///
1360     /// This function has the same error semantics as [`read_until`] and will
1361     /// also return an error if the read bytes are not valid UTF-8. If an I/O
1362     /// error is encountered then `buf` may contain some bytes already read in
1363     /// the event that all data read so far was valid UTF-8.
1364     ///
1365     /// # Examples
1366     ///
1367     /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1368     /// this example, we use [`Cursor`] to read all the lines in a byte slice:
1369     ///
1370     /// [`Cursor`]: struct.Cursor.html
1371     ///
1372     /// ```
1373     /// use std::io::{self, BufRead};
1374     ///
1375     /// let mut cursor = io::Cursor::new(b"foo\nbar");
1376     /// let mut buf = String::new();
1377     ///
1378     /// // cursor is at 'f'
1379     /// let num_bytes = cursor.read_line(&mut buf)
1380     ///     .expect("reading from cursor won't fail");
1381     /// assert_eq!(num_bytes, 4);
1382     /// assert_eq!(buf, "foo\n");
1383     /// buf.clear();
1384     ///
1385     /// // cursor is at 'b'
1386     /// let num_bytes = cursor.read_line(&mut buf)
1387     ///     .expect("reading from cursor won't fail");
1388     /// assert_eq!(num_bytes, 3);
1389     /// assert_eq!(buf, "bar");
1390     /// buf.clear();
1391     ///
1392     /// // cursor is at EOF
1393     /// let num_bytes = cursor.read_line(&mut buf)
1394     ///     .expect("reading from cursor won't fail");
1395     /// assert_eq!(num_bytes, 0);
1396     /// assert_eq!(buf, "");
1397     /// ```
1398     #[stable(feature = "rust1", since = "1.0.0")]
1399     fn read_line(&mut self, buf: &mut String) -> Result<usize> {
1400         // Note that we are not calling the `.read_until` method here, but
1401         // rather our hardcoded implementation. For more details as to why, see
1402         // the comments in `read_to_end`.
1403         append_to_string(buf, |b| read_until(self, b'\n', b))
1404     }
1405
1406     /// Returns an iterator over the contents of this reader split on the byte
1407     /// `byte`.
1408     ///
1409     /// The iterator returned from this function will return instances of
1410     /// [`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
1411     /// the delimiter byte at the end.
1412     ///
1413     /// This function will yield errors whenever [`read_until`] would have
1414     /// also yielded an error.
1415     ///
1416     /// [`io::Result`]: type.Result.html
1417     /// [`Vec<u8>`]: ../vec/struct.Vec.html
1418     /// [`read_until`]: #method.read_until
1419     ///
1420     /// # Examples
1421     ///
1422     /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1423     /// this example, we use [`Cursor`] to iterate over all hyphen delimited
1424     /// segments in a byte slice
1425     ///
1426     /// [`Cursor`]: struct.Cursor.html
1427     ///
1428     /// ```
1429     /// use std::io::{self, BufRead};
1430     ///
1431     /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
1432     ///
1433     /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
1434     /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
1435     /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
1436     /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
1437     /// assert_eq!(split_iter.next(), None);
1438     /// ```
1439     #[stable(feature = "rust1", since = "1.0.0")]
1440     fn split(self, byte: u8) -> Split<Self> where Self: Sized {
1441         Split { buf: self, delim: byte }
1442     }
1443
1444     /// Returns an iterator over the lines of this reader.
1445     ///
1446     /// The iterator returned from this function will yield instances of
1447     /// [`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline
1448     /// byte (the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.
1449     ///
1450     /// [`io::Result`]: type.Result.html
1451     /// [`String`]: ../string/struct.String.html
1452     ///
1453     /// # Examples
1454     ///
1455     /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1456     /// this example, we use [`Cursor`] to iterate over all the lines in a byte
1457     /// slice.
1458     ///
1459     /// [`Cursor`]: struct.Cursor.html
1460     ///
1461     /// ```
1462     /// use std::io::{self, BufRead};
1463     ///
1464     /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
1465     ///
1466     /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
1467     /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
1468     /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
1469     /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
1470     /// assert_eq!(lines_iter.next(), None);
1471     /// ```
1472     ///
1473     /// # Errors
1474     ///
1475     /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
1476     ///
1477     /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
1478     #[stable(feature = "rust1", since = "1.0.0")]
1479     fn lines(self) -> Lines<Self> where Self: Sized {
1480         Lines { buf: self }
1481     }
1482 }
1483
1484 /// Adaptor to chain together two readers.
1485 ///
1486 /// This struct is generally created by calling [`chain`] on a reader.
1487 /// Please see the documentation of [`chain`] for more details.
1488 ///
1489 /// [`chain`]: trait.Read.html#method.chain
1490 #[stable(feature = "rust1", since = "1.0.0")]
1491 pub struct Chain<T, U> {
1492     first: T,
1493     second: U,
1494     done_first: bool,
1495 }
1496
1497 #[stable(feature = "std_debug", since = "1.16.0")]
1498 impl<T: fmt::Debug, U: fmt::Debug> fmt::Debug for Chain<T, U> {
1499     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1500         f.debug_struct("Chain")
1501             .field("t", &self.first)
1502             .field("u", &self.second)
1503             .finish()
1504     }
1505 }
1506
1507 #[stable(feature = "rust1", since = "1.0.0")]
1508 impl<T: Read, U: Read> Read for Chain<T, U> {
1509     fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1510         if !self.done_first {
1511             match self.first.read(buf)? {
1512                 0 if buf.len() != 0 => { self.done_first = true; }
1513                 n => return Ok(n),
1514             }
1515         }
1516         self.second.read(buf)
1517     }
1518 }
1519
1520 #[stable(feature = "chain_bufread", since = "1.9.0")]
1521 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
1522     fn fill_buf(&mut self) -> Result<&[u8]> {
1523         if !self.done_first {
1524             match self.first.fill_buf()? {
1525                 buf if buf.len() == 0 => { self.done_first = true; }
1526                 buf => return Ok(buf),
1527             }
1528         }
1529         self.second.fill_buf()
1530     }
1531
1532     fn consume(&mut self, amt: usize) {
1533         if !self.done_first {
1534             self.first.consume(amt)
1535         } else {
1536             self.second.consume(amt)
1537         }
1538     }
1539 }
1540
1541 /// Reader adaptor which limits the bytes read from an underlying reader.
1542 ///
1543 /// This struct is generally created by calling [`take`] on a reader.
1544 /// Please see the documentation of [`take`] for more details.
1545 ///
1546 /// [`take`]: trait.Read.html#method.take
1547 #[stable(feature = "rust1", since = "1.0.0")]
1548 #[derive(Debug)]
1549 pub struct Take<T> {
1550     inner: T,
1551     limit: u64,
1552 }
1553
1554 impl<T> Take<T> {
1555     /// Returns the number of bytes that can be read before this instance will
1556     /// return EOF.
1557     ///
1558     /// # Note
1559     ///
1560     /// This instance may reach `EOF` after reading fewer bytes than indicated by
1561     /// this method if the underlying [`Read`] instance reaches EOF.
1562     ///
1563     /// [`Read`]: ../../std/io/trait.Read.html
1564     ///
1565     /// # Examples
1566     ///
1567     /// ```
1568     /// use std::io;
1569     /// use std::io::prelude::*;
1570     /// use std::fs::File;
1571     ///
1572     /// # fn foo() -> io::Result<()> {
1573     /// let f = File::open("foo.txt")?;
1574     ///
1575     /// // read at most five bytes
1576     /// let handle = f.take(5);
1577     ///
1578     /// println!("limit: {}", handle.limit());
1579     /// # Ok(())
1580     /// # }
1581     /// ```
1582     #[stable(feature = "rust1", since = "1.0.0")]
1583     pub fn limit(&self) -> u64 { self.limit }
1584
1585     /// Consumes the `Take`, returning the wrapped reader.
1586     ///
1587     /// # Examples
1588     ///
1589     /// ```
1590     /// use std::io;
1591     /// use std::io::prelude::*;
1592     /// use std::fs::File;
1593     ///
1594     /// # fn foo() -> io::Result<()> {
1595     /// let mut file = File::open("foo.txt")?;
1596     ///
1597     /// let mut buffer = [0; 5];
1598     /// let mut handle = file.take(5);
1599     /// handle.read(&mut buffer)?;
1600     ///
1601     /// let file = handle.into_inner();
1602     /// # Ok(())
1603     /// # }
1604     /// ```
1605     #[stable(feature = "io_take_into_inner", since = "1.15.0")]
1606     pub fn into_inner(self) -> T {
1607         self.inner
1608     }
1609 }
1610
1611 #[stable(feature = "rust1", since = "1.0.0")]
1612 impl<T: Read> Read for Take<T> {
1613     fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1614         // Don't call into inner reader at all at EOF because it may still block
1615         if self.limit == 0 {
1616             return Ok(0);
1617         }
1618
1619         let max = cmp::min(buf.len() as u64, self.limit) as usize;
1620         let n = self.inner.read(&mut buf[..max])?;
1621         self.limit -= n as u64;
1622         Ok(n)
1623     }
1624 }
1625
1626 #[stable(feature = "rust1", since = "1.0.0")]
1627 impl<T: BufRead> BufRead for Take<T> {
1628     fn fill_buf(&mut self) -> Result<&[u8]> {
1629         // Don't call into inner reader at all at EOF because it may still block
1630         if self.limit == 0 {
1631             return Ok(&[]);
1632         }
1633
1634         let buf = self.inner.fill_buf()?;
1635         let cap = cmp::min(buf.len() as u64, self.limit) as usize;
1636         Ok(&buf[..cap])
1637     }
1638
1639     fn consume(&mut self, amt: usize) {
1640         // Don't let callers reset the limit by passing an overlarge value
1641         let amt = cmp::min(amt as u64, self.limit) as usize;
1642         self.limit -= amt as u64;
1643         self.inner.consume(amt);
1644     }
1645 }
1646
1647 fn read_one_byte(reader: &mut Read) -> Option<Result<u8>> {
1648     let mut buf = [0];
1649     loop {
1650         return match reader.read(&mut buf) {
1651             Ok(0) => None,
1652             Ok(..) => Some(Ok(buf[0])),
1653             Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1654             Err(e) => Some(Err(e)),
1655         };
1656     }
1657 }
1658
1659 /// An iterator over `u8` values of a reader.
1660 ///
1661 /// This struct is generally created by calling [`bytes`] on a reader.
1662 /// Please see the documentation of [`bytes`] for more details.
1663 ///
1664 /// [`bytes`]: trait.Read.html#method.bytes
1665 #[stable(feature = "rust1", since = "1.0.0")]
1666 #[derive(Debug)]
1667 pub struct Bytes<R> {
1668     inner: R,
1669 }
1670
1671 #[stable(feature = "rust1", since = "1.0.0")]
1672 impl<R: Read> Iterator for Bytes<R> {
1673     type Item = Result<u8>;
1674
1675     fn next(&mut self) -> Option<Result<u8>> {
1676         read_one_byte(&mut self.inner)
1677     }
1678 }
1679
1680 /// An iterator over the `char`s of a reader.
1681 ///
1682 /// This struct is generally created by calling [`chars`][chars] on a reader.
1683 /// Please see the documentation of `chars()` for more details.
1684 ///
1685 /// [chars]: trait.Read.html#method.chars
1686 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1687            issue = "27802")]
1688 #[derive(Debug)]
1689 pub struct Chars<R> {
1690     inner: R,
1691 }
1692
1693 /// An enumeration of possible errors that can be generated from the `Chars`
1694 /// adapter.
1695 #[derive(Debug)]
1696 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1697            issue = "27802")]
1698 pub enum CharsError {
1699     /// Variant representing that the underlying stream was read successfully
1700     /// but it did not contain valid utf8 data.
1701     NotUtf8,
1702
1703     /// Variant representing that an I/O error occurred.
1704     Other(Error),
1705 }
1706
1707 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1708            issue = "27802")]
1709 impl<R: Read> Iterator for Chars<R> {
1710     type Item = result::Result<char, CharsError>;
1711
1712     fn next(&mut self) -> Option<result::Result<char, CharsError>> {
1713         let first_byte = match read_one_byte(&mut self.inner) {
1714             None => return None,
1715             Some(Ok(b)) => b,
1716             Some(Err(e)) => return Some(Err(CharsError::Other(e))),
1717         };
1718         let width = core_str::utf8_char_width(first_byte);
1719         if width == 1 { return Some(Ok(first_byte as char)) }
1720         if width == 0 { return Some(Err(CharsError::NotUtf8)) }
1721         let mut buf = [first_byte, 0, 0, 0];
1722         {
1723             let mut start = 1;
1724             while start < width {
1725                 match self.inner.read(&mut buf[start..width]) {
1726                     Ok(0) => return Some(Err(CharsError::NotUtf8)),
1727                     Ok(n) => start += n,
1728                     Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1729                     Err(e) => return Some(Err(CharsError::Other(e))),
1730                 }
1731             }
1732         }
1733         Some(match str::from_utf8(&buf[..width]).ok() {
1734             Some(s) => Ok(s.chars().next().unwrap()),
1735             None => Err(CharsError::NotUtf8),
1736         })
1737     }
1738 }
1739
1740 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1741            issue = "27802")]
1742 impl std_error::Error for CharsError {
1743     fn description(&self) -> &str {
1744         match *self {
1745             CharsError::NotUtf8 => "invalid utf8 encoding",
1746             CharsError::Other(ref e) => std_error::Error::description(e),
1747         }
1748     }
1749     fn cause(&self) -> Option<&std_error::Error> {
1750         match *self {
1751             CharsError::NotUtf8 => None,
1752             CharsError::Other(ref e) => e.cause(),
1753         }
1754     }
1755 }
1756
1757 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1758            issue = "27802")]
1759 impl fmt::Display for CharsError {
1760     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1761         match *self {
1762             CharsError::NotUtf8 => {
1763                 "byte stream did not contain valid utf8".fmt(f)
1764             }
1765             CharsError::Other(ref e) => e.fmt(f),
1766         }
1767     }
1768 }
1769
1770 /// An iterator over the contents of an instance of `BufRead` split on a
1771 /// particular byte.
1772 ///
1773 /// This struct is generally created by calling [`split`][split] on a
1774 /// `BufRead`. Please see the documentation of `split()` for more details.
1775 ///
1776 /// [split]: trait.BufRead.html#method.split
1777 #[stable(feature = "rust1", since = "1.0.0")]
1778 #[derive(Debug)]
1779 pub struct Split<B> {
1780     buf: B,
1781     delim: u8,
1782 }
1783
1784 #[stable(feature = "rust1", since = "1.0.0")]
1785 impl<B: BufRead> Iterator for Split<B> {
1786     type Item = Result<Vec<u8>>;
1787
1788     fn next(&mut self) -> Option<Result<Vec<u8>>> {
1789         let mut buf = Vec::new();
1790         match self.buf.read_until(self.delim, &mut buf) {
1791             Ok(0) => None,
1792             Ok(_n) => {
1793                 if buf[buf.len() - 1] == self.delim {
1794                     buf.pop();
1795                 }
1796                 Some(Ok(buf))
1797             }
1798             Err(e) => Some(Err(e))
1799         }
1800     }
1801 }
1802
1803 /// An iterator over the lines of an instance of `BufRead`.
1804 ///
1805 /// This struct is generally created by calling [`lines`][lines] on a
1806 /// `BufRead`. Please see the documentation of `lines()` for more details.
1807 ///
1808 /// [lines]: trait.BufRead.html#method.lines
1809 #[stable(feature = "rust1", since = "1.0.0")]
1810 #[derive(Debug)]
1811 pub struct Lines<B> {
1812     buf: B,
1813 }
1814
1815 #[stable(feature = "rust1", since = "1.0.0")]
1816 impl<B: BufRead> Iterator for Lines<B> {
1817     type Item = Result<String>;
1818
1819     fn next(&mut self) -> Option<Result<String>> {
1820         let mut buf = String::new();
1821         match self.buf.read_line(&mut buf) {
1822             Ok(0) => None,
1823             Ok(_n) => {
1824                 if buf.ends_with("\n") {
1825                     buf.pop();
1826                     if buf.ends_with("\r") {
1827                         buf.pop();
1828                     }
1829                 }
1830                 Some(Ok(buf))
1831             }
1832             Err(e) => Some(Err(e))
1833         }
1834     }
1835 }
1836
1837 #[cfg(test)]
1838 mod tests {
1839     use io::prelude::*;
1840     use io;
1841     use super::Cursor;
1842     use test;
1843     use super::repeat;
1844
1845     #[test]
1846     #[cfg_attr(target_os = "emscripten", ignore)]
1847     fn read_until() {
1848         let mut buf = Cursor::new(&b"12"[..]);
1849         let mut v = Vec::new();
1850         assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 2);
1851         assert_eq!(v, b"12");
1852
1853         let mut buf = Cursor::new(&b"1233"[..]);
1854         let mut v = Vec::new();
1855         assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 3);
1856         assert_eq!(v, b"123");
1857         v.truncate(0);
1858         assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 1);
1859         assert_eq!(v, b"3");
1860         v.truncate(0);
1861         assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 0);
1862         assert_eq!(v, []);
1863     }
1864
1865     #[test]
1866     fn split() {
1867         let buf = Cursor::new(&b"12"[..]);
1868         let mut s = buf.split(b'3');
1869         assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
1870         assert!(s.next().is_none());
1871
1872         let buf = Cursor::new(&b"1233"[..]);
1873         let mut s = buf.split(b'3');
1874         assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
1875         assert_eq!(s.next().unwrap().unwrap(), vec![]);
1876         assert!(s.next().is_none());
1877     }
1878
1879     #[test]
1880     fn read_line() {
1881         let mut buf = Cursor::new(&b"12"[..]);
1882         let mut v = String::new();
1883         assert_eq!(buf.read_line(&mut v).unwrap(), 2);
1884         assert_eq!(v, "12");
1885
1886         let mut buf = Cursor::new(&b"12\n\n"[..]);
1887         let mut v = String::new();
1888         assert_eq!(buf.read_line(&mut v).unwrap(), 3);
1889         assert_eq!(v, "12\n");
1890         v.truncate(0);
1891         assert_eq!(buf.read_line(&mut v).unwrap(), 1);
1892         assert_eq!(v, "\n");
1893         v.truncate(0);
1894         assert_eq!(buf.read_line(&mut v).unwrap(), 0);
1895         assert_eq!(v, "");
1896     }
1897
1898     #[test]
1899     fn lines() {
1900         let buf = Cursor::new(&b"12\r"[..]);
1901         let mut s = buf.lines();
1902         assert_eq!(s.next().unwrap().unwrap(), "12\r".to_string());
1903         assert!(s.next().is_none());
1904
1905         let buf = Cursor::new(&b"12\r\n\n"[..]);
1906         let mut s = buf.lines();
1907         assert_eq!(s.next().unwrap().unwrap(), "12".to_string());
1908         assert_eq!(s.next().unwrap().unwrap(), "".to_string());
1909         assert!(s.next().is_none());
1910     }
1911
1912     #[test]
1913     fn read_to_end() {
1914         let mut c = Cursor::new(&b""[..]);
1915         let mut v = Vec::new();
1916         assert_eq!(c.read_to_end(&mut v).unwrap(), 0);
1917         assert_eq!(v, []);
1918
1919         let mut c = Cursor::new(&b"1"[..]);
1920         let mut v = Vec::new();
1921         assert_eq!(c.read_to_end(&mut v).unwrap(), 1);
1922         assert_eq!(v, b"1");
1923
1924         let cap = 1024 * 1024;
1925         let data = (0..cap).map(|i| (i / 3) as u8).collect::<Vec<_>>();
1926         let mut v = Vec::new();
1927         let (a, b) = data.split_at(data.len() / 2);
1928         assert_eq!(Cursor::new(a).read_to_end(&mut v).unwrap(), a.len());
1929         assert_eq!(Cursor::new(b).read_to_end(&mut v).unwrap(), b.len());
1930         assert_eq!(v, data);
1931     }
1932
1933     #[test]
1934     fn read_to_string() {
1935         let mut c = Cursor::new(&b""[..]);
1936         let mut v = String::new();
1937         assert_eq!(c.read_to_string(&mut v).unwrap(), 0);
1938         assert_eq!(v, "");
1939
1940         let mut c = Cursor::new(&b"1"[..]);
1941         let mut v = String::new();
1942         assert_eq!(c.read_to_string(&mut v).unwrap(), 1);
1943         assert_eq!(v, "1");
1944
1945         let mut c = Cursor::new(&b"\xff"[..]);
1946         let mut v = String::new();
1947         assert!(c.read_to_string(&mut v).is_err());
1948     }
1949
1950     #[test]
1951     fn read_exact() {
1952         let mut buf = [0; 4];
1953
1954         let mut c = Cursor::new(&b""[..]);
1955         assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1956                    io::ErrorKind::UnexpectedEof);
1957
1958         let mut c = Cursor::new(&b"123"[..]).chain(Cursor::new(&b"456789"[..]));
1959         c.read_exact(&mut buf).unwrap();
1960         assert_eq!(&buf, b"1234");
1961         c.read_exact(&mut buf).unwrap();
1962         assert_eq!(&buf, b"5678");
1963         assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1964                    io::ErrorKind::UnexpectedEof);
1965     }
1966
1967     #[test]
1968     fn read_exact_slice() {
1969         let mut buf = [0; 4];
1970
1971         let mut c = &b""[..];
1972         assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1973                    io::ErrorKind::UnexpectedEof);
1974
1975         let mut c = &b"123"[..];
1976         assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1977                    io::ErrorKind::UnexpectedEof);
1978         // make sure the optimized (early returning) method is being used
1979         assert_eq!(&buf, &[0; 4]);
1980
1981         let mut c = &b"1234"[..];
1982         c.read_exact(&mut buf).unwrap();
1983         assert_eq!(&buf, b"1234");
1984
1985         let mut c = &b"56789"[..];
1986         c.read_exact(&mut buf).unwrap();
1987         assert_eq!(&buf, b"5678");
1988         assert_eq!(c, b"9");
1989     }
1990
1991     #[test]
1992     fn take_eof() {
1993         struct R;
1994
1995         impl Read for R {
1996             fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
1997                 Err(io::Error::new(io::ErrorKind::Other, ""))
1998             }
1999         }
2000         impl BufRead for R {
2001             fn fill_buf(&mut self) -> io::Result<&[u8]> {
2002                 Err(io::Error::new(io::ErrorKind::Other, ""))
2003             }
2004             fn consume(&mut self, _amt: usize) { }
2005         }
2006
2007         let mut buf = [0; 1];
2008         assert_eq!(0, R.take(0).read(&mut buf).unwrap());
2009         assert_eq!(b"", R.take(0).fill_buf().unwrap());
2010     }
2011
2012     fn cmp_bufread<Br1: BufRead, Br2: BufRead>(mut br1: Br1, mut br2: Br2, exp: &[u8]) {
2013         let mut cat = Vec::new();
2014         loop {
2015             let consume = {
2016                 let buf1 = br1.fill_buf().unwrap();
2017                 let buf2 = br2.fill_buf().unwrap();
2018                 let minlen = if buf1.len() < buf2.len() { buf1.len() } else { buf2.len() };
2019                 assert_eq!(buf1[..minlen], buf2[..minlen]);
2020                 cat.extend_from_slice(&buf1[..minlen]);
2021                 minlen
2022             };
2023             if consume == 0 {
2024                 break;
2025             }
2026             br1.consume(consume);
2027             br2.consume(consume);
2028         }
2029         assert_eq!(br1.fill_buf().unwrap().len(), 0);
2030         assert_eq!(br2.fill_buf().unwrap().len(), 0);
2031         assert_eq!(&cat[..], &exp[..])
2032     }
2033
2034     #[test]
2035     fn chain_bufread() {
2036         let testdata = b"ABCDEFGHIJKL";
2037         let chain1 = (&testdata[..3]).chain(&testdata[3..6])
2038                                      .chain(&testdata[6..9])
2039                                      .chain(&testdata[9..]);
2040         let chain2 = (&testdata[..4]).chain(&testdata[4..8])
2041                                      .chain(&testdata[8..]);
2042         cmp_bufread(chain1, chain2, &testdata[..]);
2043     }
2044
2045     #[test]
2046     fn chain_zero_length_read_is_not_eof() {
2047         let a = b"A";
2048         let b = b"B";
2049         let mut s = String::new();
2050         let mut chain = (&a[..]).chain(&b[..]);
2051         chain.read(&mut []).unwrap();
2052         chain.read_to_string(&mut s).unwrap();
2053         assert_eq!("AB", s);
2054     }
2055
2056     #[bench]
2057     #[cfg_attr(target_os = "emscripten", ignore)]
2058     fn bench_read_to_end(b: &mut test::Bencher) {
2059         b.iter(|| {
2060             let mut lr = repeat(1).take(10000000);
2061             let mut vec = Vec::with_capacity(1024);
2062             super::read_to_end(&mut lr, &mut vec)
2063         });
2064     }
2065 }