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