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