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