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