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