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