]> git.lizzy.rs Git - rust.git/blob - src/libstd/io/mod.rs
newline for breathing room
[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 a `Result<T, E>` (e.g. `main`).
149 //! Instead, you can `match` on the return value to catch any possible errors:
150 //! 
151 //! ```
152 //! let mut input = String::new();
153 //! 
154 //! match io::stdin().read_line(&mut input) {
155 //!     Err(why) => panic!("Failed to read input: {}", why.description()),
156 //!     Ok(_) => println!("You typed: {}", input.trim()),
157 //! }
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     /// # Examples
1306     ///
1307     /// A locked standard input implements `BufRead`. In this example, we'll
1308     /// read from standard input until we see an `a` byte.
1309     ///
1310     /// [`fill_buf`]: #tymethod.fill_buf
1311     /// [`ErrorKind::Interrupted`]: enum.ErrorKind.html#variant.Interrupted
1312     ///
1313     /// ```
1314     /// use std::io;
1315     /// use std::io::prelude::*;
1316     ///
1317     /// fn foo() -> io::Result<()> {
1318     /// let stdin = io::stdin();
1319     /// let mut stdin = stdin.lock();
1320     /// let mut buffer = Vec::new();
1321     ///
1322     /// stdin.read_until(b'a', &mut buffer)?;
1323     ///
1324     /// println!("{:?}", buffer);
1325     /// # Ok(())
1326     /// # }
1327     /// ```
1328     #[stable(feature = "rust1", since = "1.0.0")]
1329     fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
1330         read_until(self, byte, buf)
1331     }
1332
1333     /// Read all bytes until a newline (the 0xA byte) is reached, and append
1334     /// them to the provided buffer.
1335     ///
1336     /// This function will read bytes from the underlying stream until the
1337     /// newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes
1338     /// up to, and including, the delimiter (if found) will be appended to
1339     /// `buf`.
1340     ///
1341     /// If successful, this function will return the total number of bytes read.
1342     ///
1343     /// # Errors
1344     ///
1345     /// This function has the same error semantics as [`read_until`] and will
1346     /// also return an error if the read bytes are not valid UTF-8. If an I/O
1347     /// error is encountered then `buf` may contain some bytes already read in
1348     /// the event that all data read so far was valid UTF-8.
1349     ///
1350     /// # Examples
1351     ///
1352     /// A locked standard input implements `BufRead`. In this example, we'll
1353     /// read all of the lines from standard input. If we were to do this in
1354     /// an actual project, the [`lines`] method would be easier, of
1355     /// course.
1356     ///
1357     /// [`lines`]: #method.lines
1358     /// [`read_until`]: #method.read_until
1359     ///
1360     /// ```
1361     /// use std::io;
1362     /// use std::io::prelude::*;
1363     ///
1364     /// let stdin = io::stdin();
1365     /// let mut stdin = stdin.lock();
1366     /// let mut buffer = String::new();
1367     ///
1368     /// while stdin.read_line(&mut buffer).unwrap() > 0 {
1369     ///     // work with buffer
1370     ///     println!("{:?}", buffer);
1371     ///
1372     ///     buffer.clear();
1373     /// }
1374     /// ```
1375     #[stable(feature = "rust1", since = "1.0.0")]
1376     fn read_line(&mut self, buf: &mut String) -> Result<usize> {
1377         // Note that we are not calling the `.read_until` method here, but
1378         // rather our hardcoded implementation. For more details as to why, see
1379         // the comments in `read_to_end`.
1380         append_to_string(buf, |b| read_until(self, b'\n', b))
1381     }
1382
1383     /// Returns an iterator over the contents of this reader split on the byte
1384     /// `byte`.
1385     ///
1386     /// The iterator returned from this function will return instances of
1387     /// [`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
1388     /// the delimiter byte at the end.
1389     ///
1390     /// This function will yield errors whenever [`read_until`] would have
1391     /// also yielded an error.
1392     ///
1393     /// # Examples
1394     ///
1395     /// A locked standard input implements `BufRead`. In this example, we'll
1396     /// read some input from standard input, splitting on commas.
1397     ///
1398     /// [`io::Result`]: type.Result.html
1399     /// [`Vec<u8>`]: ../vec/struct.Vec.html
1400     /// [`read_until`]: #method.read_until
1401     ///
1402     /// ```
1403     /// use std::io;
1404     /// use std::io::prelude::*;
1405     ///
1406     /// let stdin = io::stdin();
1407     ///
1408     /// for content in stdin.lock().split(b',') {
1409     ///     println!("{:?}", content.unwrap());
1410     /// }
1411     /// ```
1412     #[stable(feature = "rust1", since = "1.0.0")]
1413     fn split(self, byte: u8) -> Split<Self> where Self: Sized {
1414         Split { buf: self, delim: byte }
1415     }
1416
1417     /// Returns an iterator over the lines of this reader.
1418     ///
1419     /// The iterator returned from this function will yield instances of
1420     /// [`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline
1421     /// byte (the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.
1422     ///
1423     /// [`io::Result`]: type.Result.html
1424     /// [`String`]: ../string/struct.String.html
1425     ///
1426     /// # Examples
1427     ///
1428     /// A locked standard input implements `BufRead`:
1429     ///
1430     /// ```
1431     /// use std::io;
1432     /// use std::io::prelude::*;
1433     ///
1434     /// let stdin = io::stdin();
1435     ///
1436     /// for line in stdin.lock().lines() {
1437     ///     println!("{}", line.unwrap());
1438     /// }
1439     /// ```
1440     ///
1441     /// # Errors
1442     ///
1443     /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
1444     ///
1445     /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
1446     #[stable(feature = "rust1", since = "1.0.0")]
1447     fn lines(self) -> Lines<Self> where Self: Sized {
1448         Lines { buf: self }
1449     }
1450 }
1451
1452 /// Adaptor to chain together two readers.
1453 ///
1454 /// This struct is generally created by calling [`chain`] on a reader.
1455 /// Please see the documentation of [`chain`] for more details.
1456 ///
1457 /// [`chain`]: trait.Read.html#method.chain
1458 #[stable(feature = "rust1", since = "1.0.0")]
1459 pub struct Chain<T, U> {
1460     first: T,
1461     second: U,
1462     done_first: bool,
1463 }
1464
1465 #[stable(feature = "std_debug", since = "1.16.0")]
1466 impl<T: fmt::Debug, U: fmt::Debug> fmt::Debug for Chain<T, U> {
1467     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1468         f.debug_struct("Chain")
1469             .field("t", &self.first)
1470             .field("u", &self.second)
1471             .finish()
1472     }
1473 }
1474
1475 #[stable(feature = "rust1", since = "1.0.0")]
1476 impl<T: Read, U: Read> Read for Chain<T, U> {
1477     fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1478         if !self.done_first {
1479             match self.first.read(buf)? {
1480                 0 if buf.len() != 0 => { self.done_first = true; }
1481                 n => return Ok(n),
1482             }
1483         }
1484         self.second.read(buf)
1485     }
1486 }
1487
1488 #[stable(feature = "chain_bufread", since = "1.9.0")]
1489 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
1490     fn fill_buf(&mut self) -> Result<&[u8]> {
1491         if !self.done_first {
1492             match self.first.fill_buf()? {
1493                 buf if buf.len() == 0 => { self.done_first = true; }
1494                 buf => return Ok(buf),
1495             }
1496         }
1497         self.second.fill_buf()
1498     }
1499
1500     fn consume(&mut self, amt: usize) {
1501         if !self.done_first {
1502             self.first.consume(amt)
1503         } else {
1504             self.second.consume(amt)
1505         }
1506     }
1507 }
1508
1509 /// Reader adaptor which limits the bytes read from an underlying reader.
1510 ///
1511 /// This struct is generally created by calling [`take`] on a reader.
1512 /// Please see the documentation of [`take`] for more details.
1513 ///
1514 /// [`take`]: trait.Read.html#method.take
1515 #[stable(feature = "rust1", since = "1.0.0")]
1516 #[derive(Debug)]
1517 pub struct Take<T> {
1518     inner: T,
1519     limit: u64,
1520 }
1521
1522 impl<T> Take<T> {
1523     /// Returns the number of bytes that can be read before this instance will
1524     /// return EOF.
1525     ///
1526     /// # Note
1527     ///
1528     /// This instance may reach `EOF` after reading fewer bytes than indicated by
1529     /// this method if the underlying [`Read`] instance reaches EOF.
1530     ///
1531     /// [`Read`]: ../../std/io/trait.Read.html
1532     ///
1533     /// # Examples
1534     ///
1535     /// ```
1536     /// use std::io;
1537     /// use std::io::prelude::*;
1538     /// use std::fs::File;
1539     ///
1540     /// # fn foo() -> io::Result<()> {
1541     /// let f = File::open("foo.txt")?;
1542     ///
1543     /// // read at most five bytes
1544     /// let handle = f.take(5);
1545     ///
1546     /// println!("limit: {}", handle.limit());
1547     /// # Ok(())
1548     /// # }
1549     /// ```
1550     #[stable(feature = "rust1", since = "1.0.0")]
1551     pub fn limit(&self) -> u64 { self.limit }
1552
1553     /// Consumes the `Take`, returning the wrapped reader.
1554     ///
1555     /// # Examples
1556     ///
1557     /// ```
1558     /// use std::io;
1559     /// use std::io::prelude::*;
1560     /// use std::fs::File;
1561     ///
1562     /// # fn foo() -> io::Result<()> {
1563     /// let mut file = File::open("foo.txt")?;
1564     ///
1565     /// let mut buffer = [0; 5];
1566     /// let mut handle = file.take(5);
1567     /// handle.read(&mut buffer)?;
1568     ///
1569     /// let file = handle.into_inner();
1570     /// # Ok(())
1571     /// # }
1572     /// ```
1573     #[stable(feature = "io_take_into_inner", since = "1.15.0")]
1574     pub fn into_inner(self) -> T {
1575         self.inner
1576     }
1577 }
1578
1579 #[stable(feature = "rust1", since = "1.0.0")]
1580 impl<T: Read> Read for Take<T> {
1581     fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1582         // Don't call into inner reader at all at EOF because it may still block
1583         if self.limit == 0 {
1584             return Ok(0);
1585         }
1586
1587         let max = cmp::min(buf.len() as u64, self.limit) as usize;
1588         let n = self.inner.read(&mut buf[..max])?;
1589         self.limit -= n as u64;
1590         Ok(n)
1591     }
1592 }
1593
1594 #[stable(feature = "rust1", since = "1.0.0")]
1595 impl<T: BufRead> BufRead for Take<T> {
1596     fn fill_buf(&mut self) -> Result<&[u8]> {
1597         // Don't call into inner reader at all at EOF because it may still block
1598         if self.limit == 0 {
1599             return Ok(&[]);
1600         }
1601
1602         let buf = self.inner.fill_buf()?;
1603         let cap = cmp::min(buf.len() as u64, self.limit) as usize;
1604         Ok(&buf[..cap])
1605     }
1606
1607     fn consume(&mut self, amt: usize) {
1608         // Don't let callers reset the limit by passing an overlarge value
1609         let amt = cmp::min(amt as u64, self.limit) as usize;
1610         self.limit -= amt as u64;
1611         self.inner.consume(amt);
1612     }
1613 }
1614
1615 fn read_one_byte(reader: &mut Read) -> Option<Result<u8>> {
1616     let mut buf = [0];
1617     loop {
1618         return match reader.read(&mut buf) {
1619             Ok(0) => None,
1620             Ok(..) => Some(Ok(buf[0])),
1621             Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1622             Err(e) => Some(Err(e)),
1623         };
1624     }
1625 }
1626
1627 /// An iterator over `u8` values of a reader.
1628 ///
1629 /// This struct is generally created by calling [`bytes`] on a reader.
1630 /// Please see the documentation of [`bytes`] for more details.
1631 ///
1632 /// [`bytes`]: trait.Read.html#method.bytes
1633 #[stable(feature = "rust1", since = "1.0.0")]
1634 #[derive(Debug)]
1635 pub struct Bytes<R> {
1636     inner: R,
1637 }
1638
1639 #[stable(feature = "rust1", since = "1.0.0")]
1640 impl<R: Read> Iterator for Bytes<R> {
1641     type Item = Result<u8>;
1642
1643     fn next(&mut self) -> Option<Result<u8>> {
1644         read_one_byte(&mut self.inner)
1645     }
1646 }
1647
1648 /// An iterator over the `char`s of a reader.
1649 ///
1650 /// This struct is generally created by calling [`chars`][chars] on a reader.
1651 /// Please see the documentation of `chars()` for more details.
1652 ///
1653 /// [chars]: trait.Read.html#method.chars
1654 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1655            issue = "27802")]
1656 #[derive(Debug)]
1657 pub struct Chars<R> {
1658     inner: R,
1659 }
1660
1661 /// An enumeration of possible errors that can be generated from the `Chars`
1662 /// adapter.
1663 #[derive(Debug)]
1664 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1665            issue = "27802")]
1666 pub enum CharsError {
1667     /// Variant representing that the underlying stream was read successfully
1668     /// but it did not contain valid utf8 data.
1669     NotUtf8,
1670
1671     /// Variant representing that an I/O error occurred.
1672     Other(Error),
1673 }
1674
1675 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1676            issue = "27802")]
1677 impl<R: Read> Iterator for Chars<R> {
1678     type Item = result::Result<char, CharsError>;
1679
1680     fn next(&mut self) -> Option<result::Result<char, CharsError>> {
1681         let first_byte = match read_one_byte(&mut self.inner) {
1682             None => return None,
1683             Some(Ok(b)) => b,
1684             Some(Err(e)) => return Some(Err(CharsError::Other(e))),
1685         };
1686         let width = core_str::utf8_char_width(first_byte);
1687         if width == 1 { return Some(Ok(first_byte as char)) }
1688         if width == 0 { return Some(Err(CharsError::NotUtf8)) }
1689         let mut buf = [first_byte, 0, 0, 0];
1690         {
1691             let mut start = 1;
1692             while start < width {
1693                 match self.inner.read(&mut buf[start..width]) {
1694                     Ok(0) => return Some(Err(CharsError::NotUtf8)),
1695                     Ok(n) => start += n,
1696                     Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1697                     Err(e) => return Some(Err(CharsError::Other(e))),
1698                 }
1699             }
1700         }
1701         Some(match str::from_utf8(&buf[..width]).ok() {
1702             Some(s) => Ok(s.chars().next().unwrap()),
1703             None => Err(CharsError::NotUtf8),
1704         })
1705     }
1706 }
1707
1708 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1709            issue = "27802")]
1710 impl std_error::Error for CharsError {
1711     fn description(&self) -> &str {
1712         match *self {
1713             CharsError::NotUtf8 => "invalid utf8 encoding",
1714             CharsError::Other(ref e) => std_error::Error::description(e),
1715         }
1716     }
1717     fn cause(&self) -> Option<&std_error::Error> {
1718         match *self {
1719             CharsError::NotUtf8 => None,
1720             CharsError::Other(ref e) => e.cause(),
1721         }
1722     }
1723 }
1724
1725 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1726            issue = "27802")]
1727 impl fmt::Display for CharsError {
1728     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1729         match *self {
1730             CharsError::NotUtf8 => {
1731                 "byte stream did not contain valid utf8".fmt(f)
1732             }
1733             CharsError::Other(ref e) => e.fmt(f),
1734         }
1735     }
1736 }
1737
1738 /// An iterator over the contents of an instance of `BufRead` split on a
1739 /// particular byte.
1740 ///
1741 /// This struct is generally created by calling [`split`][split] on a
1742 /// `BufRead`. Please see the documentation of `split()` for more details.
1743 ///
1744 /// [split]: trait.BufRead.html#method.split
1745 #[stable(feature = "rust1", since = "1.0.0")]
1746 #[derive(Debug)]
1747 pub struct Split<B> {
1748     buf: B,
1749     delim: u8,
1750 }
1751
1752 #[stable(feature = "rust1", since = "1.0.0")]
1753 impl<B: BufRead> Iterator for Split<B> {
1754     type Item = Result<Vec<u8>>;
1755
1756     fn next(&mut self) -> Option<Result<Vec<u8>>> {
1757         let mut buf = Vec::new();
1758         match self.buf.read_until(self.delim, &mut buf) {
1759             Ok(0) => None,
1760             Ok(_n) => {
1761                 if buf[buf.len() - 1] == self.delim {
1762                     buf.pop();
1763                 }
1764                 Some(Ok(buf))
1765             }
1766             Err(e) => Some(Err(e))
1767         }
1768     }
1769 }
1770
1771 /// An iterator over the lines of an instance of `BufRead`.
1772 ///
1773 /// This struct is generally created by calling [`lines`][lines] on a
1774 /// `BufRead`. Please see the documentation of `lines()` for more details.
1775 ///
1776 /// [lines]: trait.BufRead.html#method.lines
1777 #[stable(feature = "rust1", since = "1.0.0")]
1778 #[derive(Debug)]
1779 pub struct Lines<B> {
1780     buf: B,
1781 }
1782
1783 #[stable(feature = "rust1", since = "1.0.0")]
1784 impl<B: BufRead> Iterator for Lines<B> {
1785     type Item = Result<String>;
1786
1787     fn next(&mut self) -> Option<Result<String>> {
1788         let mut buf = String::new();
1789         match self.buf.read_line(&mut buf) {
1790             Ok(0) => None,
1791             Ok(_n) => {
1792                 if buf.ends_with("\n") {
1793                     buf.pop();
1794                     if buf.ends_with("\r") {
1795                         buf.pop();
1796                     }
1797                 }
1798                 Some(Ok(buf))
1799             }
1800             Err(e) => Some(Err(e))
1801         }
1802     }
1803 }
1804
1805 #[cfg(test)]
1806 mod tests {
1807     use io::prelude::*;
1808     use io;
1809     use super::Cursor;
1810     use test;
1811     use super::repeat;
1812
1813     #[test]
1814     #[cfg_attr(target_os = "emscripten", ignore)]
1815     fn read_until() {
1816         let mut buf = Cursor::new(&b"12"[..]);
1817         let mut v = Vec::new();
1818         assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 2);
1819         assert_eq!(v, b"12");
1820
1821         let mut buf = Cursor::new(&b"1233"[..]);
1822         let mut v = Vec::new();
1823         assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 3);
1824         assert_eq!(v, b"123");
1825         v.truncate(0);
1826         assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 1);
1827         assert_eq!(v, b"3");
1828         v.truncate(0);
1829         assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 0);
1830         assert_eq!(v, []);
1831     }
1832
1833     #[test]
1834     fn split() {
1835         let buf = Cursor::new(&b"12"[..]);
1836         let mut s = buf.split(b'3');
1837         assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
1838         assert!(s.next().is_none());
1839
1840         let buf = Cursor::new(&b"1233"[..]);
1841         let mut s = buf.split(b'3');
1842         assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
1843         assert_eq!(s.next().unwrap().unwrap(), vec![]);
1844         assert!(s.next().is_none());
1845     }
1846
1847     #[test]
1848     fn read_line() {
1849         let mut buf = Cursor::new(&b"12"[..]);
1850         let mut v = String::new();
1851         assert_eq!(buf.read_line(&mut v).unwrap(), 2);
1852         assert_eq!(v, "12");
1853
1854         let mut buf = Cursor::new(&b"12\n\n"[..]);
1855         let mut v = String::new();
1856         assert_eq!(buf.read_line(&mut v).unwrap(), 3);
1857         assert_eq!(v, "12\n");
1858         v.truncate(0);
1859         assert_eq!(buf.read_line(&mut v).unwrap(), 1);
1860         assert_eq!(v, "\n");
1861         v.truncate(0);
1862         assert_eq!(buf.read_line(&mut v).unwrap(), 0);
1863         assert_eq!(v, "");
1864     }
1865
1866     #[test]
1867     fn lines() {
1868         let buf = Cursor::new(&b"12\r"[..]);
1869         let mut s = buf.lines();
1870         assert_eq!(s.next().unwrap().unwrap(), "12\r".to_string());
1871         assert!(s.next().is_none());
1872
1873         let buf = Cursor::new(&b"12\r\n\n"[..]);
1874         let mut s = buf.lines();
1875         assert_eq!(s.next().unwrap().unwrap(), "12".to_string());
1876         assert_eq!(s.next().unwrap().unwrap(), "".to_string());
1877         assert!(s.next().is_none());
1878     }
1879
1880     #[test]
1881     fn read_to_end() {
1882         let mut c = Cursor::new(&b""[..]);
1883         let mut v = Vec::new();
1884         assert_eq!(c.read_to_end(&mut v).unwrap(), 0);
1885         assert_eq!(v, []);
1886
1887         let mut c = Cursor::new(&b"1"[..]);
1888         let mut v = Vec::new();
1889         assert_eq!(c.read_to_end(&mut v).unwrap(), 1);
1890         assert_eq!(v, b"1");
1891
1892         let cap = 1024 * 1024;
1893         let data = (0..cap).map(|i| (i / 3) as u8).collect::<Vec<_>>();
1894         let mut v = Vec::new();
1895         let (a, b) = data.split_at(data.len() / 2);
1896         assert_eq!(Cursor::new(a).read_to_end(&mut v).unwrap(), a.len());
1897         assert_eq!(Cursor::new(b).read_to_end(&mut v).unwrap(), b.len());
1898         assert_eq!(v, data);
1899     }
1900
1901     #[test]
1902     fn read_to_string() {
1903         let mut c = Cursor::new(&b""[..]);
1904         let mut v = String::new();
1905         assert_eq!(c.read_to_string(&mut v).unwrap(), 0);
1906         assert_eq!(v, "");
1907
1908         let mut c = Cursor::new(&b"1"[..]);
1909         let mut v = String::new();
1910         assert_eq!(c.read_to_string(&mut v).unwrap(), 1);
1911         assert_eq!(v, "1");
1912
1913         let mut c = Cursor::new(&b"\xff"[..]);
1914         let mut v = String::new();
1915         assert!(c.read_to_string(&mut v).is_err());
1916     }
1917
1918     #[test]
1919     fn read_exact() {
1920         let mut buf = [0; 4];
1921
1922         let mut c = Cursor::new(&b""[..]);
1923         assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1924                    io::ErrorKind::UnexpectedEof);
1925
1926         let mut c = Cursor::new(&b"123"[..]).chain(Cursor::new(&b"456789"[..]));
1927         c.read_exact(&mut buf).unwrap();
1928         assert_eq!(&buf, b"1234");
1929         c.read_exact(&mut buf).unwrap();
1930         assert_eq!(&buf, b"5678");
1931         assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1932                    io::ErrorKind::UnexpectedEof);
1933     }
1934
1935     #[test]
1936     fn read_exact_slice() {
1937         let mut buf = [0; 4];
1938
1939         let mut c = &b""[..];
1940         assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1941                    io::ErrorKind::UnexpectedEof);
1942
1943         let mut c = &b"123"[..];
1944         assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1945                    io::ErrorKind::UnexpectedEof);
1946         // make sure the optimized (early returning) method is being used
1947         assert_eq!(&buf, &[0; 4]);
1948
1949         let mut c = &b"1234"[..];
1950         c.read_exact(&mut buf).unwrap();
1951         assert_eq!(&buf, b"1234");
1952
1953         let mut c = &b"56789"[..];
1954         c.read_exact(&mut buf).unwrap();
1955         assert_eq!(&buf, b"5678");
1956         assert_eq!(c, b"9");
1957     }
1958
1959     #[test]
1960     fn take_eof() {
1961         struct R;
1962
1963         impl Read for R {
1964             fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
1965                 Err(io::Error::new(io::ErrorKind::Other, ""))
1966             }
1967         }
1968         impl BufRead for R {
1969             fn fill_buf(&mut self) -> io::Result<&[u8]> {
1970                 Err(io::Error::new(io::ErrorKind::Other, ""))
1971             }
1972             fn consume(&mut self, _amt: usize) { }
1973         }
1974
1975         let mut buf = [0; 1];
1976         assert_eq!(0, R.take(0).read(&mut buf).unwrap());
1977         assert_eq!(b"", R.take(0).fill_buf().unwrap());
1978     }
1979
1980     fn cmp_bufread<Br1: BufRead, Br2: BufRead>(mut br1: Br1, mut br2: Br2, exp: &[u8]) {
1981         let mut cat = Vec::new();
1982         loop {
1983             let consume = {
1984                 let buf1 = br1.fill_buf().unwrap();
1985                 let buf2 = br2.fill_buf().unwrap();
1986                 let minlen = if buf1.len() < buf2.len() { buf1.len() } else { buf2.len() };
1987                 assert_eq!(buf1[..minlen], buf2[..minlen]);
1988                 cat.extend_from_slice(&buf1[..minlen]);
1989                 minlen
1990             };
1991             if consume == 0 {
1992                 break;
1993             }
1994             br1.consume(consume);
1995             br2.consume(consume);
1996         }
1997         assert_eq!(br1.fill_buf().unwrap().len(), 0);
1998         assert_eq!(br2.fill_buf().unwrap().len(), 0);
1999         assert_eq!(&cat[..], &exp[..])
2000     }
2001
2002     #[test]
2003     fn chain_bufread() {
2004         let testdata = b"ABCDEFGHIJKL";
2005         let chain1 = (&testdata[..3]).chain(&testdata[3..6])
2006                                      .chain(&testdata[6..9])
2007                                      .chain(&testdata[9..]);
2008         let chain2 = (&testdata[..4]).chain(&testdata[4..8])
2009                                      .chain(&testdata[8..]);
2010         cmp_bufread(chain1, chain2, &testdata[..]);
2011     }
2012
2013     #[test]
2014     fn chain_zero_length_read_is_not_eof() {
2015         let a = b"A";
2016         let b = b"B";
2017         let mut s = String::new();
2018         let mut chain = (&a[..]).chain(&b[..]);
2019         chain.read(&mut []).unwrap();
2020         chain.read_to_string(&mut s).unwrap();
2021         assert_eq!("AB", s);
2022     }
2023
2024     #[bench]
2025     #[cfg_attr(target_os = "emscripten", ignore)]
2026     fn bench_read_to_end(b: &mut test::Bencher) {
2027         b.iter(|| {
2028             let mut lr = repeat(1).take(10000000);
2029             let mut vec = Vec::with_capacity(1024);
2030             super::read_to_end(&mut lr, &mut vec)
2031         });
2032     }
2033 }