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