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