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