]> git.lizzy.rs Git - rust.git/blob - src/libstd/io/mod.rs
Rollup merge of #63055 - Mark-Simulacrum:save-analysis-clean-2, r=Xanewok
[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 //!     let n = f.read(&mut buffer)?;
28 //!
29 //!     println!("The bytes: {:?}", &buffer[..n]);
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 //!     let n = f.read(&mut buffer)?;
60 //!
61 //!     println!("The bytes: {:?}", &buffer[..n]);
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 [IoSliceMut<'_>]) -> 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: &[IoSlice<'_>]) -> 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     /// Correspondingly, however, *callers* of this method may not assume any guarantees
513     /// about how the implementation uses `buf`. The trait is safe to implement,
514     /// so it is possible that the code that's supposed to write to the buffer might also read
515     /// from it. It is your responsibility to make sure that `buf` is initialized
516     /// before calling `read`. Calling `read` with an uninitialized `buf` (of the kind one
517     /// obtains via [`MaybeUninit<T>`]) is not safe, and can lead to undefined behavior.
518     ///
519     /// [`MaybeUninit<T>`]: ../mem/union.MaybeUninit.html
520     ///
521     /// # Errors
522     ///
523     /// If this function encounters any form of I/O or other error, an error
524     /// variant will be returned. If an error is returned then it must be
525     /// guaranteed that no bytes were read.
526     ///
527     /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
528     /// operation should be retried if there is nothing else to do.
529     ///
530     /// # Examples
531     ///
532     /// [`File`]s implement `Read`:
533     ///
534     /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
535     /// [`Ok(n)`]: ../../std/result/enum.Result.html#variant.Ok
536     /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
537     /// [`File`]: ../fs/struct.File.html
538     ///
539     /// ```no_run
540     /// use std::io;
541     /// use std::io::prelude::*;
542     /// use std::fs::File;
543     ///
544     /// fn main() -> io::Result<()> {
545     ///     let mut f = File::open("foo.txt")?;
546     ///     let mut buffer = [0; 10];
547     ///
548     ///     // read up to 10 bytes
549     ///     let n = f.read(&mut buffer[..])?;
550     ///
551     ///     println!("The bytes: {:?}", &buffer[..n]);
552     ///     Ok(())
553     /// }
554     /// ```
555     #[stable(feature = "rust1", since = "1.0.0")]
556     fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
557
558     /// Like `read`, except that it reads into a slice of buffers.
559     ///
560     /// Data is copied to fill each buffer in order, with the final buffer
561     /// written to possibly being only partially filled. This method must behave
562     /// as a single call to `read` with the buffers concatenated would.
563     ///
564     /// The default implementation calls `read` with either the first nonempty
565     /// buffer provided, or an empty one if none exists.
566     #[stable(feature = "iovec", since = "1.36.0")]
567     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
568         default_read_vectored(|b| self.read(b), bufs)
569     }
570
571     /// Determines if this `Read`er can work with buffers of uninitialized
572     /// memory.
573     ///
574     /// The default implementation returns an initializer which will zero
575     /// buffers.
576     ///
577     /// If a `Read`er guarantees that it can work properly with uninitialized
578     /// memory, it should call [`Initializer::nop()`]. See the documentation for
579     /// [`Initializer`] for details.
580     ///
581     /// The behavior of this method must be independent of the state of the
582     /// `Read`er - the method only takes `&self` so that it can be used through
583     /// trait objects.
584     ///
585     /// # Safety
586     ///
587     /// This method is unsafe because a `Read`er could otherwise return a
588     /// non-zeroing `Initializer` from another `Read` type without an `unsafe`
589     /// block.
590     ///
591     /// [`Initializer::nop()`]: ../../std/io/struct.Initializer.html#method.nop
592     /// [`Initializer`]: ../../std/io/struct.Initializer.html
593     #[unstable(feature = "read_initializer", issue = "42788")]
594     #[inline]
595     unsafe fn initializer(&self) -> Initializer {
596         Initializer::zeroing()
597     }
598
599     /// Read all bytes until EOF in this source, placing them into `buf`.
600     ///
601     /// All bytes read from this source will be appended to the specified buffer
602     /// `buf`. This function will continuously call [`read()`] to append more data to
603     /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of
604     /// non-[`ErrorKind::Interrupted`] kind.
605     ///
606     /// If successful, this function will return the total number of bytes read.
607     ///
608     /// # Errors
609     ///
610     /// If this function encounters an error of the kind
611     /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
612     /// will continue.
613     ///
614     /// If any other read error is encountered then this function immediately
615     /// returns. Any bytes which have already been read will be appended to
616     /// `buf`.
617     ///
618     /// # Examples
619     ///
620     /// [`File`]s implement `Read`:
621     ///
622     /// [`read()`]: trait.Read.html#tymethod.read
623     /// [`Ok(0)`]: ../../std/result/enum.Result.html#variant.Ok
624     /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
625     /// [`File`]: ../fs/struct.File.html
626     ///
627     /// ```no_run
628     /// use std::io;
629     /// use std::io::prelude::*;
630     /// use std::fs::File;
631     ///
632     /// fn main() -> io::Result<()> {
633     ///     let mut f = File::open("foo.txt")?;
634     ///     let mut buffer = Vec::new();
635     ///
636     ///     // read the whole file
637     ///     f.read_to_end(&mut buffer)?;
638     ///     Ok(())
639     /// }
640     /// ```
641     ///
642     /// (See also the [`std::fs::read`] convenience function for reading from a
643     /// file.)
644     ///
645     /// [`std::fs::read`]: ../fs/fn.read.html
646     #[stable(feature = "rust1", since = "1.0.0")]
647     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
648         read_to_end(self, buf)
649     }
650
651     /// Read all bytes until EOF in this source, appending them to `buf`.
652     ///
653     /// If successful, this function returns the number of bytes which were read
654     /// and appended to `buf`.
655     ///
656     /// # Errors
657     ///
658     /// If the data in this stream is *not* valid UTF-8 then an error is
659     /// returned and `buf` is unchanged.
660     ///
661     /// See [`read_to_end`][readtoend] for other error semantics.
662     ///
663     /// [readtoend]: #method.read_to_end
664     ///
665     /// # Examples
666     ///
667     /// [`File`][file]s implement `Read`:
668     ///
669     /// [file]: ../fs/struct.File.html
670     ///
671     /// ```no_run
672     /// use std::io;
673     /// use std::io::prelude::*;
674     /// use std::fs::File;
675     ///
676     /// fn main() -> io::Result<()> {
677     ///     let mut f = File::open("foo.txt")?;
678     ///     let mut buffer = String::new();
679     ///
680     ///     f.read_to_string(&mut buffer)?;
681     ///     Ok(())
682     /// }
683     /// ```
684     ///
685     /// (See also the [`std::fs::read_to_string`] convenience function for
686     /// reading from a file.)
687     ///
688     /// [`std::fs::read_to_string`]: ../fs/fn.read_to_string.html
689     #[stable(feature = "rust1", since = "1.0.0")]
690     fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
691         // Note that we do *not* call `.read_to_end()` here. We are passing
692         // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
693         // method to fill it up. An arbitrary implementation could overwrite the
694         // entire contents of the vector, not just append to it (which is what
695         // we are expecting).
696         //
697         // To prevent extraneously checking the UTF-8-ness of the entire buffer
698         // we pass it to our hardcoded `read_to_end` implementation which we
699         // know is guaranteed to only read data into the end of the buffer.
700         append_to_string(buf, |b| read_to_end(self, b))
701     }
702
703     /// Read the exact number of bytes required to fill `buf`.
704     ///
705     /// This function reads as many bytes as necessary to completely fill the
706     /// specified buffer `buf`.
707     ///
708     /// No guarantees are provided about the contents of `buf` when this
709     /// function is called, implementations cannot rely on any property of the
710     /// contents of `buf` being true. It is recommended that implementations
711     /// only write data to `buf` instead of reading its contents.
712     ///
713     /// # Errors
714     ///
715     /// If this function encounters an error of the kind
716     /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
717     /// will continue.
718     ///
719     /// If this function encounters an "end of file" before completely filling
720     /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
721     /// The contents of `buf` are unspecified in this case.
722     ///
723     /// If any other read error is encountered then this function immediately
724     /// returns. The contents of `buf` are unspecified in this case.
725     ///
726     /// If this function returns an error, it is unspecified how many bytes it
727     /// has read, but it will never read more than would be necessary to
728     /// completely fill the buffer.
729     ///
730     /// # Examples
731     ///
732     /// [`File`]s implement `Read`:
733     ///
734     /// [`File`]: ../fs/struct.File.html
735     /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
736     /// [`ErrorKind::UnexpectedEof`]: ../../std/io/enum.ErrorKind.html#variant.UnexpectedEof
737     ///
738     /// ```no_run
739     /// use std::io;
740     /// use std::io::prelude::*;
741     /// use std::fs::File;
742     ///
743     /// fn main() -> io::Result<()> {
744     ///     let mut f = File::open("foo.txt")?;
745     ///     let mut buffer = [0; 10];
746     ///
747     ///     // read exactly 10 bytes
748     ///     f.read_exact(&mut buffer)?;
749     ///     Ok(())
750     /// }
751     /// ```
752     #[stable(feature = "read_exact", since = "1.6.0")]
753     fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
754         while !buf.is_empty() {
755             match self.read(buf) {
756                 Ok(0) => break,
757                 Ok(n) => { let tmp = buf; buf = &mut tmp[n..]; }
758                 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
759                 Err(e) => return Err(e),
760             }
761         }
762         if !buf.is_empty() {
763             Err(Error::new(ErrorKind::UnexpectedEof,
764                            "failed to fill whole buffer"))
765         } else {
766             Ok(())
767         }
768     }
769
770     /// Creates a "by reference" adaptor for this instance of `Read`.
771     ///
772     /// The returned adaptor also implements `Read` and will simply borrow this
773     /// current reader.
774     ///
775     /// # Examples
776     ///
777     /// [`File`][file]s implement `Read`:
778     ///
779     /// [file]: ../fs/struct.File.html
780     ///
781     /// ```no_run
782     /// use std::io;
783     /// use std::io::Read;
784     /// use std::fs::File;
785     ///
786     /// fn main() -> io::Result<()> {
787     ///     let mut f = File::open("foo.txt")?;
788     ///     let mut buffer = Vec::new();
789     ///     let mut other_buffer = Vec::new();
790     ///
791     ///     {
792     ///         let reference = f.by_ref();
793     ///
794     ///         // read at most 5 bytes
795     ///         reference.take(5).read_to_end(&mut buffer)?;
796     ///
797     ///     } // drop our &mut reference so we can use f again
798     ///
799     ///     // original file still usable, read the rest
800     ///     f.read_to_end(&mut other_buffer)?;
801     ///     Ok(())
802     /// }
803     /// ```
804     #[stable(feature = "rust1", since = "1.0.0")]
805     fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
806
807     /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
808     ///
809     /// The returned type implements [`Iterator`] where the `Item` is
810     /// [`Result`]`<`[`u8`]`, `[`io::Error`]`>`.
811     /// The yielded item is [`Ok`] if a byte was successfully read and [`Err`]
812     /// otherwise. EOF is mapped to returning [`None`] from this iterator.
813     ///
814     /// # Examples
815     ///
816     /// [`File`][file]s implement `Read`:
817     ///
818     /// [file]: ../fs/struct.File.html
819     /// [`Iterator`]: ../../std/iter/trait.Iterator.html
820     /// [`Result`]: ../../std/result/enum.Result.html
821     /// [`io::Error`]: ../../std/io/struct.Error.html
822     /// [`u8`]: ../../std/primitive.u8.html
823     /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
824     /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
825     /// [`None`]: ../../std/option/enum.Option.html#variant.None
826     ///
827     /// ```no_run
828     /// use std::io;
829     /// use std::io::prelude::*;
830     /// use std::fs::File;
831     ///
832     /// fn main() -> io::Result<()> {
833     ///     let mut f = File::open("foo.txt")?;
834     ///
835     ///     for byte in f.bytes() {
836     ///         println!("{}", byte.unwrap());
837     ///     }
838     ///     Ok(())
839     /// }
840     /// ```
841     #[stable(feature = "rust1", since = "1.0.0")]
842     fn bytes(self) -> Bytes<Self> where Self: Sized {
843         Bytes { inner: self }
844     }
845
846     /// Creates an adaptor which will chain this stream with another.
847     ///
848     /// The returned `Read` instance will first read all bytes from this object
849     /// until EOF is encountered. Afterwards the output is equivalent to the
850     /// output of `next`.
851     ///
852     /// # Examples
853     ///
854     /// [`File`][file]s implement `Read`:
855     ///
856     /// [file]: ../fs/struct.File.html
857     ///
858     /// ```no_run
859     /// use std::io;
860     /// use std::io::prelude::*;
861     /// use std::fs::File;
862     ///
863     /// fn main() -> io::Result<()> {
864     ///     let mut f1 = File::open("foo.txt")?;
865     ///     let mut f2 = File::open("bar.txt")?;
866     ///
867     ///     let mut handle = f1.chain(f2);
868     ///     let mut buffer = String::new();
869     ///
870     ///     // read the value into a String. We could use any Read method here,
871     ///     // this is just one example.
872     ///     handle.read_to_string(&mut buffer)?;
873     ///     Ok(())
874     /// }
875     /// ```
876     #[stable(feature = "rust1", since = "1.0.0")]
877     fn chain<R: Read>(self, next: R) -> Chain<Self, R> where Self: Sized {
878         Chain { first: self, second: next, done_first: false }
879     }
880
881     /// Creates an adaptor which will read at most `limit` bytes from it.
882     ///
883     /// This function returns a new instance of `Read` which will read at most
884     /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
885     /// read errors will not count towards the number of bytes read and future
886     /// calls to [`read()`] may succeed.
887     ///
888     /// # Examples
889     ///
890     /// [`File`]s implement `Read`:
891     ///
892     /// [`File`]: ../fs/struct.File.html
893     /// [`Ok(0)`]: ../../std/result/enum.Result.html#variant.Ok
894     /// [`read()`]: trait.Read.html#tymethod.read
895     ///
896     /// ```no_run
897     /// use std::io;
898     /// use std::io::prelude::*;
899     /// use std::fs::File;
900     ///
901     /// fn main() -> io::Result<()> {
902     ///     let mut f = File::open("foo.txt")?;
903     ///     let mut buffer = [0; 5];
904     ///
905     ///     // read at most five bytes
906     ///     let mut handle = f.take(5);
907     ///
908     ///     handle.read(&mut buffer)?;
909     ///     Ok(())
910     /// }
911     /// ```
912     #[stable(feature = "rust1", since = "1.0.0")]
913     fn take(self, limit: u64) -> Take<Self> where Self: Sized {
914         Take { inner: self, limit: limit }
915     }
916 }
917
918 /// A buffer type used with `Read::read_vectored`.
919 ///
920 /// It is semantically a wrapper around an `&mut [u8]`, but is guaranteed to be
921 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
922 /// Windows.
923 #[stable(feature = "iovec", since = "1.36.0")]
924 #[repr(transparent)]
925 pub struct IoSliceMut<'a>(sys::io::IoSliceMut<'a>);
926
927 #[stable(feature = "iovec", since = "1.36.0")]
928 impl<'a> fmt::Debug for IoSliceMut<'a> {
929     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
930         fmt::Debug::fmt(self.0.as_slice(), fmt)
931     }
932 }
933
934 impl<'a> IoSliceMut<'a> {
935     /// Creates a new `IoSliceMut` wrapping a byte slice.
936     ///
937     /// # Panics
938     ///
939     /// Panics on Windows if the slice is larger than 4GB.
940     #[stable(feature = "iovec", since = "1.36.0")]
941     #[inline]
942     pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> {
943         IoSliceMut(sys::io::IoSliceMut::new(buf))
944     }
945 }
946
947 #[stable(feature = "iovec", since = "1.36.0")]
948 impl<'a> Deref for IoSliceMut<'a> {
949     type Target = [u8];
950
951     #[inline]
952     fn deref(&self) -> &[u8] {
953         self.0.as_slice()
954     }
955 }
956
957 #[stable(feature = "iovec", since = "1.36.0")]
958 impl<'a> DerefMut for IoSliceMut<'a> {
959     #[inline]
960     fn deref_mut(&mut self) -> &mut [u8] {
961         self.0.as_mut_slice()
962     }
963 }
964
965 /// A buffer type used with `Write::write_vectored`.
966 ///
967 /// It is semantically a wrapper around an `&[u8]`, but is guaranteed to be
968 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
969 /// Windows.
970 #[stable(feature = "iovec", since = "1.36.0")]
971 #[repr(transparent)]
972 pub struct IoSlice<'a>(sys::io::IoSlice<'a>);
973
974 #[stable(feature = "iovec", since = "1.36.0")]
975 impl<'a> fmt::Debug for IoSlice<'a> {
976     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
977         fmt::Debug::fmt(self.0.as_slice(), fmt)
978     }
979 }
980
981 impl<'a> IoSlice<'a> {
982     /// Creates a new `IoSlice` wrapping a byte slice.
983     ///
984     /// # Panics
985     ///
986     /// Panics on Windows if the slice is larger than 4GB.
987     #[stable(feature = "iovec", since = "1.36.0")]
988     #[inline]
989     pub fn new(buf: &'a [u8]) -> IoSlice<'a> {
990         IoSlice(sys::io::IoSlice::new(buf))
991     }
992 }
993
994 #[stable(feature = "iovec", since = "1.36.0")]
995 impl<'a> Deref for IoSlice<'a> {
996     type Target = [u8];
997
998     #[inline]
999     fn deref(&self) -> &[u8] {
1000         self.0.as_slice()
1001     }
1002 }
1003
1004 /// A type used to conditionally initialize buffers passed to `Read` methods.
1005 #[unstable(feature = "read_initializer", issue = "42788")]
1006 #[derive(Debug)]
1007 pub struct Initializer(bool);
1008
1009 impl Initializer {
1010     /// Returns a new `Initializer` which will zero out buffers.
1011     #[unstable(feature = "read_initializer", issue = "42788")]
1012     #[inline]
1013     pub fn zeroing() -> Initializer {
1014         Initializer(true)
1015     }
1016
1017     /// Returns a new `Initializer` which will not zero out buffers.
1018     ///
1019     /// # Safety
1020     ///
1021     /// This may only be called by `Read`ers which guarantee that they will not
1022     /// read from buffers passed to `Read` methods, and that the return value of
1023     /// the method accurately reflects the number of bytes that have been
1024     /// written to the head of the buffer.
1025     #[unstable(feature = "read_initializer", issue = "42788")]
1026     #[inline]
1027     pub unsafe fn nop() -> Initializer {
1028         Initializer(false)
1029     }
1030
1031     /// Indicates if a buffer should be initialized.
1032     #[unstable(feature = "read_initializer", issue = "42788")]
1033     #[inline]
1034     pub fn should_initialize(&self) -> bool {
1035         self.0
1036     }
1037
1038     /// Initializes a buffer if necessary.
1039     #[unstable(feature = "read_initializer", issue = "42788")]
1040     #[inline]
1041     pub fn initialize(&self, buf: &mut [u8]) {
1042         if self.should_initialize() {
1043             unsafe { ptr::write_bytes(buf.as_mut_ptr(), 0, buf.len()) }
1044         }
1045     }
1046 }
1047
1048 /// A trait for objects which are byte-oriented sinks.
1049 ///
1050 /// Implementors of the `Write` trait are sometimes called 'writers'.
1051 ///
1052 /// Writers are defined by two required methods, [`write`] and [`flush`]:
1053 ///
1054 /// * The [`write`] method will attempt to write some data into the object,
1055 ///   returning how many bytes were successfully written.
1056 ///
1057 /// * The [`flush`] method is useful for adaptors and explicit buffers
1058 ///   themselves for ensuring that all buffered data has been pushed out to the
1059 ///   'true sink'.
1060 ///
1061 /// Writers are intended to be composable with one another. Many implementors
1062 /// throughout [`std::io`] take and provide types which implement the `Write`
1063 /// trait.
1064 ///
1065 /// [`write`]: #tymethod.write
1066 /// [`flush`]: #tymethod.flush
1067 /// [`std::io`]: index.html
1068 ///
1069 /// # Examples
1070 ///
1071 /// ```no_run
1072 /// use std::io::prelude::*;
1073 /// use std::fs::File;
1074 ///
1075 /// fn main() -> std::io::Result<()> {
1076 ///     let data = b"some bytes";
1077 ///
1078 ///     let mut pos = 0;
1079 ///     let mut buffer = File::create("foo.txt")?;
1080 ///
1081 ///     while pos < data.len() {
1082 ///         let bytes_written = buffer.write(&data[pos..])?;
1083 ///         pos += bytes_written;
1084 ///     }
1085 ///     Ok(())
1086 /// }
1087 /// ```
1088 ///
1089 /// The trait also provides convenience methods like [`write_all`], which calls
1090 /// `write` in a loop until its entire input has been written.
1091 ///
1092 /// [`write_all`]: #method.write_all
1093 #[stable(feature = "rust1", since = "1.0.0")]
1094 #[doc(spotlight)]
1095 pub trait Write {
1096     /// Write a buffer into this writer, returning how many bytes were written.
1097     ///
1098     /// This function will attempt to write the entire contents of `buf`, but
1099     /// the entire write may not succeed, or the write may also generate an
1100     /// error. A call to `write` represents *at most one* attempt to write to
1101     /// any wrapped object.
1102     ///
1103     /// Calls to `write` are not guaranteed to block waiting for data to be
1104     /// written, and a write which would otherwise block can be indicated through
1105     /// an [`Err`] variant.
1106     ///
1107     /// If the return value is [`Ok(n)`] then it must be guaranteed that
1108     /// `0 <= n <= buf.len()`. A return value of `0` typically means that the
1109     /// underlying object is no longer able to accept bytes and will likely not
1110     /// be able to in the future as well, or that the buffer provided is empty.
1111     ///
1112     /// # Errors
1113     ///
1114     /// Each call to `write` may generate an I/O error indicating that the
1115     /// operation could not be completed. If an error is returned then no bytes
1116     /// in the buffer were written to this writer.
1117     ///
1118     /// It is **not** considered an error if the entire buffer could not be
1119     /// written to this writer.
1120     ///
1121     /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the
1122     /// write operation should be retried if there is nothing else to do.
1123     ///
1124     /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
1125     /// [`Ok(n)`]:  ../../std/result/enum.Result.html#variant.Ok
1126     /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
1127     ///
1128     /// # Examples
1129     ///
1130     /// ```no_run
1131     /// use std::io::prelude::*;
1132     /// use std::fs::File;
1133     ///
1134     /// fn main() -> std::io::Result<()> {
1135     ///     let mut buffer = File::create("foo.txt")?;
1136     ///
1137     ///     // Writes some prefix of the byte string, not necessarily all of it.
1138     ///     buffer.write(b"some bytes")?;
1139     ///     Ok(())
1140     /// }
1141     /// ```
1142     #[stable(feature = "rust1", since = "1.0.0")]
1143     fn write(&mut self, buf: &[u8]) -> Result<usize>;
1144
1145     /// Like `write`, except that it writes from a slice of buffers.
1146     ///
1147     /// Data is copied from each buffer in order, with the final buffer
1148     /// read from possibly being only partially consumed. This method must
1149     /// behave as a call to `write` with the buffers concatenated would.
1150     ///
1151     /// The default implementation calls `write` with either the first nonempty
1152     /// buffer provided, or an empty one if none exists.
1153     #[stable(feature = "iovec", since = "1.36.0")]
1154     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize> {
1155         default_write_vectored(|b| self.write(b), bufs)
1156     }
1157
1158     /// Flush this output stream, ensuring that all intermediately buffered
1159     /// contents reach their destination.
1160     ///
1161     /// # Errors
1162     ///
1163     /// It is considered an error if not all bytes could be written due to
1164     /// I/O errors or EOF being reached.
1165     ///
1166     /// # Examples
1167     ///
1168     /// ```no_run
1169     /// use std::io::prelude::*;
1170     /// use std::io::BufWriter;
1171     /// use std::fs::File;
1172     ///
1173     /// fn main() -> std::io::Result<()> {
1174     ///     let mut buffer = BufWriter::new(File::create("foo.txt")?);
1175     ///
1176     ///     buffer.write_all(b"some bytes")?;
1177     ///     buffer.flush()?;
1178     ///     Ok(())
1179     /// }
1180     /// ```
1181     #[stable(feature = "rust1", since = "1.0.0")]
1182     fn flush(&mut self) -> Result<()>;
1183
1184     /// Attempts to write an entire buffer into this writer.
1185     ///
1186     /// This method will continuously call [`write`] until there is no more data
1187     /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is
1188     /// returned. This method will not return until the entire buffer has been
1189     /// successfully written or such an error occurs. The first error that is
1190     /// not of [`ErrorKind::Interrupted`] kind generated from this method will be
1191     /// returned.
1192     ///
1193     /// # Errors
1194     ///
1195     /// This function will return the first error of
1196     /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns.
1197     ///
1198     /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
1199     /// [`write`]: #tymethod.write
1200     ///
1201     /// # Examples
1202     ///
1203     /// ```no_run
1204     /// use std::io::prelude::*;
1205     /// use std::fs::File;
1206     ///
1207     /// fn main() -> std::io::Result<()> {
1208     ///     let mut buffer = File::create("foo.txt")?;
1209     ///
1210     ///     buffer.write_all(b"some bytes")?;
1211     ///     Ok(())
1212     /// }
1213     /// ```
1214     #[stable(feature = "rust1", since = "1.0.0")]
1215     fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
1216         while !buf.is_empty() {
1217             match self.write(buf) {
1218                 Ok(0) => return Err(Error::new(ErrorKind::WriteZero,
1219                                                "failed to write whole buffer")),
1220                 Ok(n) => buf = &buf[n..],
1221                 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1222                 Err(e) => return Err(e),
1223             }
1224         }
1225         Ok(())
1226     }
1227
1228     /// Writes a formatted string into this writer, returning any error
1229     /// encountered.
1230     ///
1231     /// This method is primarily used to interface with the
1232     /// [`format_args!`][formatargs] macro, but it is rare that this should
1233     /// explicitly be called. The [`write!`][write] macro should be favored to
1234     /// invoke this method instead.
1235     ///
1236     /// [formatargs]: ../macro.format_args.html
1237     /// [write]: ../macro.write.html
1238     ///
1239     /// This function internally uses the [`write_all`][writeall] method on
1240     /// this trait and hence will continuously write data so long as no errors
1241     /// are received. This also means that partial writes are not indicated in
1242     /// this signature.
1243     ///
1244     /// [writeall]: #method.write_all
1245     ///
1246     /// # Errors
1247     ///
1248     /// This function will return any I/O error reported while formatting.
1249     ///
1250     /// # Examples
1251     ///
1252     /// ```no_run
1253     /// use std::io::prelude::*;
1254     /// use std::fs::File;
1255     ///
1256     /// fn main() -> std::io::Result<()> {
1257     ///     let mut buffer = File::create("foo.txt")?;
1258     ///
1259     ///     // this call
1260     ///     write!(buffer, "{:.*}", 2, 1.234567)?;
1261     ///     // turns into this:
1262     ///     buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1263     ///     Ok(())
1264     /// }
1265     /// ```
1266     #[stable(feature = "rust1", since = "1.0.0")]
1267     fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> Result<()> {
1268         // Create a shim which translates a Write to a fmt::Write and saves
1269         // off I/O errors. instead of discarding them
1270         struct Adaptor<'a, T: ?Sized + 'a> {
1271             inner: &'a mut T,
1272             error: Result<()>,
1273         }
1274
1275         impl<T: Write + ?Sized> fmt::Write for Adaptor<'_, T> {
1276             fn write_str(&mut self, s: &str) -> fmt::Result {
1277                 match self.inner.write_all(s.as_bytes()) {
1278                     Ok(()) => Ok(()),
1279                     Err(e) => {
1280                         self.error = Err(e);
1281                         Err(fmt::Error)
1282                     }
1283                 }
1284             }
1285         }
1286
1287         let mut output = Adaptor { inner: self, error: Ok(()) };
1288         match fmt::write(&mut output, fmt) {
1289             Ok(()) => Ok(()),
1290             Err(..) => {
1291                 // check if the error came from the underlying `Write` or not
1292                 if output.error.is_err() {
1293                     output.error
1294                 } else {
1295                     Err(Error::new(ErrorKind::Other, "formatter error"))
1296                 }
1297             }
1298         }
1299     }
1300
1301     /// Creates a "by reference" adaptor for this instance of `Write`.
1302     ///
1303     /// The returned adaptor also implements `Write` and will simply borrow this
1304     /// current writer.
1305     ///
1306     /// # Examples
1307     ///
1308     /// ```no_run
1309     /// use std::io::Write;
1310     /// use std::fs::File;
1311     ///
1312     /// fn main() -> std::io::Result<()> {
1313     ///     let mut buffer = File::create("foo.txt")?;
1314     ///
1315     ///     let reference = buffer.by_ref();
1316     ///
1317     ///     // we can use reference just like our original buffer
1318     ///     reference.write_all(b"some bytes")?;
1319     ///     Ok(())
1320     /// }
1321     /// ```
1322     #[stable(feature = "rust1", since = "1.0.0")]
1323     fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1324 }
1325
1326 /// The `Seek` trait provides a cursor which can be moved within a stream of
1327 /// bytes.
1328 ///
1329 /// The stream typically has a fixed size, allowing seeking relative to either
1330 /// end or the current offset.
1331 ///
1332 /// # Examples
1333 ///
1334 /// [`File`][file]s implement `Seek`:
1335 ///
1336 /// [file]: ../fs/struct.File.html
1337 ///
1338 /// ```no_run
1339 /// use std::io;
1340 /// use std::io::prelude::*;
1341 /// use std::fs::File;
1342 /// use std::io::SeekFrom;
1343 ///
1344 /// fn main() -> io::Result<()> {
1345 ///     let mut f = File::open("foo.txt")?;
1346 ///
1347 ///     // move the cursor 42 bytes from the start of the file
1348 ///     f.seek(SeekFrom::Start(42))?;
1349 ///     Ok(())
1350 /// }
1351 /// ```
1352 #[stable(feature = "rust1", since = "1.0.0")]
1353 pub trait Seek {
1354     /// Seek to an offset, in bytes, in a stream.
1355     ///
1356     /// A seek beyond the end of a stream is allowed, but behavior is defined
1357     /// by the implementation.
1358     ///
1359     /// If the seek operation completed successfully,
1360     /// this method returns the new position from the start of the stream.
1361     /// That position can be used later with [`SeekFrom::Start`].
1362     ///
1363     /// # Errors
1364     ///
1365     /// Seeking to a negative offset is considered an error.
1366     ///
1367     /// [`SeekFrom::Start`]: enum.SeekFrom.html#variant.Start
1368     #[stable(feature = "rust1", since = "1.0.0")]
1369     fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1370
1371     /// Returns the length of this stream (in bytes).
1372     ///
1373     /// This method is implemented using up to three seek operations. If this
1374     /// method returns successfully, the seek position is unchanged (i.e. the
1375     /// position before calling this method is the same as afterwards).
1376     /// However, if this method returns an error, the seek position is
1377     /// unspecified.
1378     ///
1379     /// If you need to obtain the length of *many* streams and you don't care
1380     /// about the seek position afterwards, you can reduce the number of seek
1381     /// operations by simply calling `seek(SeekFrom::End(0))` and using its
1382     /// return value (it is also the stream length).
1383     ///
1384     /// Note that length of a stream can change over time (for example, when
1385     /// data is appended to a file). So calling this method multiple times does
1386     /// not necessarily return the same length each time.
1387     ///
1388     ///
1389     /// # Example
1390     ///
1391     /// ```no_run
1392     /// #![feature(seek_convenience)]
1393     /// use std::{
1394     ///     io::{self, Seek},
1395     ///     fs::File,
1396     /// };
1397     ///
1398     /// fn main() -> io::Result<()> {
1399     ///     let mut f = File::open("foo.txt")?;
1400     ///
1401     ///     let len = f.stream_len()?;
1402     ///     println!("The file is currently {} bytes long", len);
1403     ///     Ok(())
1404     /// }
1405     /// ```
1406     #[unstable(feature = "seek_convenience", issue = "59359")]
1407     fn stream_len(&mut self) -> Result<u64> {
1408         let old_pos = self.stream_position()?;
1409         let len = self.seek(SeekFrom::End(0))?;
1410
1411         // Avoid seeking a third time when we were already at the end of the
1412         // stream. The branch is usually way cheaper than a seek operation.
1413         if old_pos != len {
1414             self.seek(SeekFrom::Start(old_pos))?;
1415         }
1416
1417         Ok(len)
1418     }
1419
1420     /// Returns the current seek position from the start of the stream.
1421     ///
1422     /// This is equivalent to `self.seek(SeekFrom::Current(0))`.
1423     ///
1424     ///
1425     /// # Example
1426     ///
1427     /// ```no_run
1428     /// #![feature(seek_convenience)]
1429     /// use std::{
1430     ///     io::{self, BufRead, BufReader, Seek},
1431     ///     fs::File,
1432     /// };
1433     ///
1434     /// fn main() -> io::Result<()> {
1435     ///     let mut f = BufReader::new(File::open("foo.txt")?);
1436     ///
1437     ///     let before = f.stream_position()?;
1438     ///     f.read_line(&mut String::new())?;
1439     ///     let after = f.stream_position()?;
1440     ///
1441     ///     println!("The first line was {} bytes long", after - before);
1442     ///     Ok(())
1443     /// }
1444     /// ```
1445     #[unstable(feature = "seek_convenience", issue = "59359")]
1446     fn stream_position(&mut self) -> Result<u64> {
1447         self.seek(SeekFrom::Current(0))
1448     }
1449 }
1450
1451 /// Enumeration of possible methods to seek within an I/O object.
1452 ///
1453 /// It is used by the [`Seek`] trait.
1454 ///
1455 /// [`Seek`]: trait.Seek.html
1456 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1457 #[stable(feature = "rust1", since = "1.0.0")]
1458 pub enum SeekFrom {
1459     /// Sets the offset to the provided number of bytes.
1460     #[stable(feature = "rust1", since = "1.0.0")]
1461     Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1462
1463     /// Sets the offset to the size of this object plus the specified number of
1464     /// bytes.
1465     ///
1466     /// It is possible to seek beyond the end of an object, but it's an error to
1467     /// seek before byte 0.
1468     #[stable(feature = "rust1", since = "1.0.0")]
1469     End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1470
1471     /// Sets the offset to the current position plus the specified number of
1472     /// bytes.
1473     ///
1474     /// It is possible to seek beyond the end of an object, but it's an error to
1475     /// seek before byte 0.
1476     #[stable(feature = "rust1", since = "1.0.0")]
1477     Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1478 }
1479
1480 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>)
1481                                    -> Result<usize> {
1482     let mut read = 0;
1483     loop {
1484         let (done, used) = {
1485             let available = match r.fill_buf() {
1486                 Ok(n) => n,
1487                 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1488                 Err(e) => return Err(e)
1489             };
1490             match memchr::memchr(delim, available) {
1491                 Some(i) => {
1492                     buf.extend_from_slice(&available[..=i]);
1493                     (true, i + 1)
1494                 }
1495                 None => {
1496                     buf.extend_from_slice(available);
1497                     (false, available.len())
1498                 }
1499             }
1500         };
1501         r.consume(used);
1502         read += used;
1503         if done || used == 0 {
1504             return Ok(read);
1505         }
1506     }
1507 }
1508
1509 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1510 /// to perform extra ways of reading.
1511 ///
1512 /// For example, reading line-by-line is inefficient without using a buffer, so
1513 /// if you want to read by line, you'll need `BufRead`, which includes a
1514 /// [`read_line`] method as well as a [`lines`] iterator.
1515 ///
1516 /// # Examples
1517 ///
1518 /// A locked standard input implements `BufRead`:
1519 ///
1520 /// ```no_run
1521 /// use std::io;
1522 /// use std::io::prelude::*;
1523 ///
1524 /// let stdin = io::stdin();
1525 /// for line in stdin.lock().lines() {
1526 ///     println!("{}", line.unwrap());
1527 /// }
1528 /// ```
1529 ///
1530 /// If you have something that implements [`Read`], you can use the [`BufReader`
1531 /// type][`BufReader`] to turn it into a `BufRead`.
1532 ///
1533 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1534 /// [`BufReader`] to the rescue!
1535 ///
1536 /// [`BufReader`]: struct.BufReader.html
1537 /// [`File`]: ../fs/struct.File.html
1538 /// [`read_line`]: #method.read_line
1539 /// [`lines`]: #method.lines
1540 /// [`Read`]: trait.Read.html
1541 ///
1542 /// ```no_run
1543 /// use std::io::{self, BufReader};
1544 /// use std::io::prelude::*;
1545 /// use std::fs::File;
1546 ///
1547 /// fn main() -> io::Result<()> {
1548 ///     let f = File::open("foo.txt")?;
1549 ///     let f = BufReader::new(f);
1550 ///
1551 ///     for line in f.lines() {
1552 ///         println!("{}", line.unwrap());
1553 ///     }
1554 ///
1555 ///     Ok(())
1556 /// }
1557 /// ```
1558 ///
1559 #[stable(feature = "rust1", since = "1.0.0")]
1560 pub trait BufRead: Read {
1561     /// Returns the contents of the internal buffer, filling it with more data
1562     /// from the inner reader if it is empty.
1563     ///
1564     /// This function is a lower-level call. It needs to be paired with the
1565     /// [`consume`] method to function properly. When calling this
1566     /// method, none of the contents will be "read" in the sense that later
1567     /// calling `read` may return the same contents. As such, [`consume`] must
1568     /// be called with the number of bytes that are consumed from this buffer to
1569     /// ensure that the bytes are never returned twice.
1570     ///
1571     /// [`consume`]: #tymethod.consume
1572     ///
1573     /// An empty buffer returned indicates that the stream has reached EOF.
1574     ///
1575     /// # Errors
1576     ///
1577     /// This function will return an I/O error if the underlying reader was
1578     /// read, but returned an error.
1579     ///
1580     /// # Examples
1581     ///
1582     /// A locked standard input implements `BufRead`:
1583     ///
1584     /// ```no_run
1585     /// use std::io;
1586     /// use std::io::prelude::*;
1587     ///
1588     /// let stdin = io::stdin();
1589     /// let mut stdin = stdin.lock();
1590     ///
1591     /// let buffer = stdin.fill_buf().unwrap();
1592     ///
1593     /// // work with buffer
1594     /// println!("{:?}", buffer);
1595     ///
1596     /// // ensure the bytes we worked with aren't returned again later
1597     /// let length = buffer.len();
1598     /// stdin.consume(length);
1599     /// ```
1600     #[stable(feature = "rust1", since = "1.0.0")]
1601     fn fill_buf(&mut self) -> Result<&[u8]>;
1602
1603     /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1604     /// so they should no longer be returned in calls to `read`.
1605     ///
1606     /// This function is a lower-level call. It needs to be paired with the
1607     /// [`fill_buf`] method to function properly. This function does
1608     /// not perform any I/O, it simply informs this object that some amount of
1609     /// its buffer, returned from [`fill_buf`], has been consumed and should
1610     /// no longer be returned. As such, this function may do odd things if
1611     /// [`fill_buf`] isn't called before calling it.
1612     ///
1613     /// The `amt` must be `<=` the number of bytes in the buffer returned by
1614     /// [`fill_buf`].
1615     ///
1616     /// # Examples
1617     ///
1618     /// Since `consume()` is meant to be used with [`fill_buf`],
1619     /// that method's example includes an example of `consume()`.
1620     ///
1621     /// [`fill_buf`]: #tymethod.fill_buf
1622     #[stable(feature = "rust1", since = "1.0.0")]
1623     fn consume(&mut self, amt: usize);
1624
1625     /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
1626     ///
1627     /// This function will read bytes from the underlying stream until the
1628     /// delimiter or EOF is found. Once found, all bytes up to, and including,
1629     /// the delimiter (if found) will be appended to `buf`.
1630     ///
1631     /// If successful, this function will return the total number of bytes read.
1632     ///
1633     /// # Errors
1634     ///
1635     /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1636     /// will otherwise return any errors returned by [`fill_buf`].
1637     ///
1638     /// If an I/O error is encountered then all bytes read so far will be
1639     /// present in `buf` and its length will have been adjusted appropriately.
1640     ///
1641     /// [`fill_buf`]: #tymethod.fill_buf
1642     /// [`ErrorKind::Interrupted`]: enum.ErrorKind.html#variant.Interrupted
1643     ///
1644     /// # Examples
1645     ///
1646     /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1647     /// this example, we use [`Cursor`] to read all the bytes in a byte slice
1648     /// in hyphen delimited segments:
1649     ///
1650     /// [`Cursor`]: struct.Cursor.html
1651     ///
1652     /// ```
1653     /// use std::io::{self, BufRead};
1654     ///
1655     /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
1656     /// let mut buf = vec![];
1657     ///
1658     /// // cursor is at 'l'
1659     /// let num_bytes = cursor.read_until(b'-', &mut buf)
1660     ///     .expect("reading from cursor won't fail");
1661     /// assert_eq!(num_bytes, 6);
1662     /// assert_eq!(buf, b"lorem-");
1663     /// buf.clear();
1664     ///
1665     /// // cursor is at 'i'
1666     /// let num_bytes = cursor.read_until(b'-', &mut buf)
1667     ///     .expect("reading from cursor won't fail");
1668     /// assert_eq!(num_bytes, 5);
1669     /// assert_eq!(buf, b"ipsum");
1670     /// buf.clear();
1671     ///
1672     /// // cursor is at EOF
1673     /// let num_bytes = cursor.read_until(b'-', &mut buf)
1674     ///     .expect("reading from cursor won't fail");
1675     /// assert_eq!(num_bytes, 0);
1676     /// assert_eq!(buf, b"");
1677     /// ```
1678     #[stable(feature = "rust1", since = "1.0.0")]
1679     fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
1680         read_until(self, byte, buf)
1681     }
1682
1683     /// Read all bytes until a newline (the 0xA byte) is reached, and append
1684     /// them to the provided buffer.
1685     ///
1686     /// This function will read bytes from the underlying stream until the
1687     /// newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes
1688     /// up to, and including, the delimiter (if found) will be appended to
1689     /// `buf`.
1690     ///
1691     /// If successful, this function will return the total number of bytes read.
1692     ///
1693     /// If this function returns `Ok(0)`, the stream has reached EOF.
1694     ///
1695     /// # Errors
1696     ///
1697     /// This function has the same error semantics as [`read_until`] and will
1698     /// also return an error if the read bytes are not valid UTF-8. If an I/O
1699     /// error is encountered then `buf` may contain some bytes already read in
1700     /// the event that all data read so far was valid UTF-8.
1701     ///
1702     /// [`read_until`]: #method.read_until
1703     ///
1704     /// # Examples
1705     ///
1706     /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1707     /// this example, we use [`Cursor`] to read all the lines in a byte slice:
1708     ///
1709     /// [`Cursor`]: struct.Cursor.html
1710     ///
1711     /// ```
1712     /// use std::io::{self, BufRead};
1713     ///
1714     /// let mut cursor = io::Cursor::new(b"foo\nbar");
1715     /// let mut buf = String::new();
1716     ///
1717     /// // cursor is at 'f'
1718     /// let num_bytes = cursor.read_line(&mut buf)
1719     ///     .expect("reading from cursor won't fail");
1720     /// assert_eq!(num_bytes, 4);
1721     /// assert_eq!(buf, "foo\n");
1722     /// buf.clear();
1723     ///
1724     /// // cursor is at 'b'
1725     /// let num_bytes = cursor.read_line(&mut buf)
1726     ///     .expect("reading from cursor won't fail");
1727     /// assert_eq!(num_bytes, 3);
1728     /// assert_eq!(buf, "bar");
1729     /// buf.clear();
1730     ///
1731     /// // cursor is at EOF
1732     /// let num_bytes = cursor.read_line(&mut buf)
1733     ///     .expect("reading from cursor won't fail");
1734     /// assert_eq!(num_bytes, 0);
1735     /// assert_eq!(buf, "");
1736     /// ```
1737     #[stable(feature = "rust1", since = "1.0.0")]
1738     fn read_line(&mut self, buf: &mut String) -> Result<usize> {
1739         // Note that we are not calling the `.read_until` method here, but
1740         // rather our hardcoded implementation. For more details as to why, see
1741         // the comments in `read_to_end`.
1742         append_to_string(buf, |b| read_until(self, b'\n', b))
1743     }
1744
1745     /// Returns an iterator over the contents of this reader split on the byte
1746     /// `byte`.
1747     ///
1748     /// The iterator returned from this function will return instances of
1749     /// [`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
1750     /// the delimiter byte at the end.
1751     ///
1752     /// This function will yield errors whenever [`read_until`] would have
1753     /// also yielded an error.
1754     ///
1755     /// [`io::Result`]: type.Result.html
1756     /// [`Vec<u8>`]: ../vec/struct.Vec.html
1757     /// [`read_until`]: #method.read_until
1758     ///
1759     /// # Examples
1760     ///
1761     /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1762     /// this example, we use [`Cursor`] to iterate over all hyphen delimited
1763     /// segments in a byte slice
1764     ///
1765     /// [`Cursor`]: struct.Cursor.html
1766     ///
1767     /// ```
1768     /// use std::io::{self, BufRead};
1769     ///
1770     /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
1771     ///
1772     /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
1773     /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
1774     /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
1775     /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
1776     /// assert_eq!(split_iter.next(), None);
1777     /// ```
1778     #[stable(feature = "rust1", since = "1.0.0")]
1779     fn split(self, byte: u8) -> Split<Self> where Self: Sized {
1780         Split { buf: self, delim: byte }
1781     }
1782
1783     /// Returns an iterator over the lines of this reader.
1784     ///
1785     /// The iterator returned from this function will yield instances of
1786     /// [`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline
1787     /// byte (the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.
1788     ///
1789     /// [`io::Result`]: type.Result.html
1790     /// [`String`]: ../string/struct.String.html
1791     ///
1792     /// # Examples
1793     ///
1794     /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1795     /// this example, we use [`Cursor`] to iterate over all the lines in a byte
1796     /// slice.
1797     ///
1798     /// [`Cursor`]: struct.Cursor.html
1799     ///
1800     /// ```
1801     /// use std::io::{self, BufRead};
1802     ///
1803     /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
1804     ///
1805     /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
1806     /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
1807     /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
1808     /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
1809     /// assert_eq!(lines_iter.next(), None);
1810     /// ```
1811     ///
1812     /// # Errors
1813     ///
1814     /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
1815     ///
1816     /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
1817     #[stable(feature = "rust1", since = "1.0.0")]
1818     fn lines(self) -> Lines<Self> where Self: Sized {
1819         Lines { buf: self }
1820     }
1821 }
1822
1823 /// Adaptor to chain together two readers.
1824 ///
1825 /// This struct is generally created by calling [`chain`] on a reader.
1826 /// Please see the documentation of [`chain`] for more details.
1827 ///
1828 /// [`chain`]: trait.Read.html#method.chain
1829 #[stable(feature = "rust1", since = "1.0.0")]
1830 pub struct Chain<T, U> {
1831     first: T,
1832     second: U,
1833     done_first: bool,
1834 }
1835
1836 impl<T, U> Chain<T, U> {
1837     /// Consumes the `Chain`, returning the wrapped readers.
1838     ///
1839     /// # Examples
1840     ///
1841     /// ```no_run
1842     /// use std::io;
1843     /// use std::io::prelude::*;
1844     /// use std::fs::File;
1845     ///
1846     /// fn main() -> io::Result<()> {
1847     ///     let mut foo_file = File::open("foo.txt")?;
1848     ///     let mut bar_file = File::open("bar.txt")?;
1849     ///
1850     ///     let chain = foo_file.chain(bar_file);
1851     ///     let (foo_file, bar_file) = chain.into_inner();
1852     ///     Ok(())
1853     /// }
1854     /// ```
1855     #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1856     pub fn into_inner(self) -> (T, U) {
1857         (self.first, self.second)
1858     }
1859
1860     /// Gets references to the underlying readers in this `Chain`.
1861     ///
1862     /// # Examples
1863     ///
1864     /// ```no_run
1865     /// use std::io;
1866     /// use std::io::prelude::*;
1867     /// use std::fs::File;
1868     ///
1869     /// fn main() -> io::Result<()> {
1870     ///     let mut foo_file = File::open("foo.txt")?;
1871     ///     let mut bar_file = File::open("bar.txt")?;
1872     ///
1873     ///     let chain = foo_file.chain(bar_file);
1874     ///     let (foo_file, bar_file) = chain.get_ref();
1875     ///     Ok(())
1876     /// }
1877     /// ```
1878     #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1879     pub fn get_ref(&self) -> (&T, &U) {
1880         (&self.first, &self.second)
1881     }
1882
1883     /// Gets mutable references to the underlying readers in this `Chain`.
1884     ///
1885     /// Care should be taken to avoid modifying the internal I/O state of the
1886     /// underlying readers as doing so may corrupt the internal state of this
1887     /// `Chain`.
1888     ///
1889     /// # Examples
1890     ///
1891     /// ```no_run
1892     /// use std::io;
1893     /// use std::io::prelude::*;
1894     /// use std::fs::File;
1895     ///
1896     /// fn main() -> io::Result<()> {
1897     ///     let mut foo_file = File::open("foo.txt")?;
1898     ///     let mut bar_file = File::open("bar.txt")?;
1899     ///
1900     ///     let mut chain = foo_file.chain(bar_file);
1901     ///     let (foo_file, bar_file) = chain.get_mut();
1902     ///     Ok(())
1903     /// }
1904     /// ```
1905     #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1906     pub fn get_mut(&mut self) -> (&mut T, &mut U) {
1907         (&mut self.first, &mut self.second)
1908     }
1909 }
1910
1911 #[stable(feature = "std_debug", since = "1.16.0")]
1912 impl<T: fmt::Debug, U: fmt::Debug> fmt::Debug for Chain<T, U> {
1913     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1914         f.debug_struct("Chain")
1915             .field("t", &self.first)
1916             .field("u", &self.second)
1917             .finish()
1918     }
1919 }
1920
1921 #[stable(feature = "rust1", since = "1.0.0")]
1922 impl<T: Read, U: Read> Read for Chain<T, U> {
1923     fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1924         if !self.done_first {
1925             match self.first.read(buf)? {
1926                 0 if !buf.is_empty() => self.done_first = true,
1927                 n => return Ok(n),
1928             }
1929         }
1930         self.second.read(buf)
1931     }
1932
1933     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
1934         if !self.done_first {
1935             match self.first.read_vectored(bufs)? {
1936                 0 if bufs.iter().any(|b| !b.is_empty()) => self.done_first = true,
1937                 n => return Ok(n),
1938             }
1939         }
1940         self.second.read_vectored(bufs)
1941     }
1942
1943     unsafe fn initializer(&self) -> Initializer {
1944         let initializer = self.first.initializer();
1945         if initializer.should_initialize() {
1946             initializer
1947         } else {
1948             self.second.initializer()
1949         }
1950     }
1951 }
1952
1953 #[stable(feature = "chain_bufread", since = "1.9.0")]
1954 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
1955     fn fill_buf(&mut self) -> Result<&[u8]> {
1956         if !self.done_first {
1957             match self.first.fill_buf()? {
1958                 buf if buf.is_empty() => { self.done_first = true; }
1959                 buf => return Ok(buf),
1960             }
1961         }
1962         self.second.fill_buf()
1963     }
1964
1965     fn consume(&mut self, amt: usize) {
1966         if !self.done_first {
1967             self.first.consume(amt)
1968         } else {
1969             self.second.consume(amt)
1970         }
1971     }
1972 }
1973
1974 /// Reader adaptor which limits the bytes read from an underlying reader.
1975 ///
1976 /// This struct is generally created by calling [`take`] on a reader.
1977 /// Please see the documentation of [`take`] for more details.
1978 ///
1979 /// [`take`]: trait.Read.html#method.take
1980 #[stable(feature = "rust1", since = "1.0.0")]
1981 #[derive(Debug)]
1982 pub struct Take<T> {
1983     inner: T,
1984     limit: u64,
1985 }
1986
1987 impl<T> Take<T> {
1988     /// Returns the number of bytes that can be read before this instance will
1989     /// return EOF.
1990     ///
1991     /// # Note
1992     ///
1993     /// This instance may reach `EOF` after reading fewer bytes than indicated by
1994     /// this method if the underlying [`Read`] instance reaches EOF.
1995     ///
1996     /// [`Read`]: ../../std/io/trait.Read.html
1997     ///
1998     /// # Examples
1999     ///
2000     /// ```no_run
2001     /// use std::io;
2002     /// use std::io::prelude::*;
2003     /// use std::fs::File;
2004     ///
2005     /// fn main() -> io::Result<()> {
2006     ///     let f = File::open("foo.txt")?;
2007     ///
2008     ///     // read at most five bytes
2009     ///     let handle = f.take(5);
2010     ///
2011     ///     println!("limit: {}", handle.limit());
2012     ///     Ok(())
2013     /// }
2014     /// ```
2015     #[stable(feature = "rust1", since = "1.0.0")]
2016     pub fn limit(&self) -> u64 { self.limit }
2017
2018     /// Sets the number of bytes that can be read before this instance will
2019     /// return EOF. This is the same as constructing a new `Take` instance, so
2020     /// the amount of bytes read and the previous limit value don't matter when
2021     /// calling this method.
2022     ///
2023     /// # Examples
2024     ///
2025     /// ```no_run
2026     /// use std::io;
2027     /// use std::io::prelude::*;
2028     /// use std::fs::File;
2029     ///
2030     /// fn main() -> io::Result<()> {
2031     ///     let f = File::open("foo.txt")?;
2032     ///
2033     ///     // read at most five bytes
2034     ///     let mut handle = f.take(5);
2035     ///     handle.set_limit(10);
2036     ///
2037     ///     assert_eq!(handle.limit(), 10);
2038     ///     Ok(())
2039     /// }
2040     /// ```
2041     #[stable(feature = "take_set_limit", since = "1.27.0")]
2042     pub fn set_limit(&mut self, limit: u64) {
2043         self.limit = limit;
2044     }
2045
2046     /// Consumes the `Take`, returning the wrapped reader.
2047     ///
2048     /// # Examples
2049     ///
2050     /// ```no_run
2051     /// use std::io;
2052     /// use std::io::prelude::*;
2053     /// use std::fs::File;
2054     ///
2055     /// fn main() -> io::Result<()> {
2056     ///     let mut file = File::open("foo.txt")?;
2057     ///
2058     ///     let mut buffer = [0; 5];
2059     ///     let mut handle = file.take(5);
2060     ///     handle.read(&mut buffer)?;
2061     ///
2062     ///     let file = handle.into_inner();
2063     ///     Ok(())
2064     /// }
2065     /// ```
2066     #[stable(feature = "io_take_into_inner", since = "1.15.0")]
2067     pub fn into_inner(self) -> T {
2068         self.inner
2069     }
2070
2071     /// Gets a reference to the underlying reader.
2072     ///
2073     /// # Examples
2074     ///
2075     /// ```no_run
2076     /// use std::io;
2077     /// use std::io::prelude::*;
2078     /// use std::fs::File;
2079     ///
2080     /// fn main() -> io::Result<()> {
2081     ///     let mut file = File::open("foo.txt")?;
2082     ///
2083     ///     let mut buffer = [0; 5];
2084     ///     let mut handle = file.take(5);
2085     ///     handle.read(&mut buffer)?;
2086     ///
2087     ///     let file = handle.get_ref();
2088     ///     Ok(())
2089     /// }
2090     /// ```
2091     #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2092     pub fn get_ref(&self) -> &T {
2093         &self.inner
2094     }
2095
2096     /// Gets a mutable reference to the underlying reader.
2097     ///
2098     /// Care should be taken to avoid modifying the internal I/O state of the
2099     /// underlying reader as doing so may corrupt the internal limit of this
2100     /// `Take`.
2101     ///
2102     /// # Examples
2103     ///
2104     /// ```no_run
2105     /// use std::io;
2106     /// use std::io::prelude::*;
2107     /// use std::fs::File;
2108     ///
2109     /// fn main() -> io::Result<()> {
2110     ///     let mut file = File::open("foo.txt")?;
2111     ///
2112     ///     let mut buffer = [0; 5];
2113     ///     let mut handle = file.take(5);
2114     ///     handle.read(&mut buffer)?;
2115     ///
2116     ///     let file = handle.get_mut();
2117     ///     Ok(())
2118     /// }
2119     /// ```
2120     #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2121     pub fn get_mut(&mut self) -> &mut T {
2122         &mut self.inner
2123     }
2124 }
2125
2126 #[stable(feature = "rust1", since = "1.0.0")]
2127 impl<T: Read> Read for Take<T> {
2128     fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2129         // Don't call into inner reader at all at EOF because it may still block
2130         if self.limit == 0 {
2131             return Ok(0);
2132         }
2133
2134         let max = cmp::min(buf.len() as u64, self.limit) as usize;
2135         let n = self.inner.read(&mut buf[..max])?;
2136         self.limit -= n as u64;
2137         Ok(n)
2138     }
2139
2140     unsafe fn initializer(&self) -> Initializer {
2141         self.inner.initializer()
2142     }
2143
2144     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
2145         let reservation_size = cmp::min(self.limit, 32) as usize;
2146
2147         read_to_end_with_reservation(self, buf, reservation_size)
2148     }
2149 }
2150
2151 #[stable(feature = "rust1", since = "1.0.0")]
2152 impl<T: BufRead> BufRead for Take<T> {
2153     fn fill_buf(&mut self) -> Result<&[u8]> {
2154         // Don't call into inner reader at all at EOF because it may still block
2155         if self.limit == 0 {
2156             return Ok(&[]);
2157         }
2158
2159         let buf = self.inner.fill_buf()?;
2160         let cap = cmp::min(buf.len() as u64, self.limit) as usize;
2161         Ok(&buf[..cap])
2162     }
2163
2164     fn consume(&mut self, amt: usize) {
2165         // Don't let callers reset the limit by passing an overlarge value
2166         let amt = cmp::min(amt as u64, self.limit) as usize;
2167         self.limit -= amt as u64;
2168         self.inner.consume(amt);
2169     }
2170 }
2171
2172 /// An iterator over `u8` values of a reader.
2173 ///
2174 /// This struct is generally created by calling [`bytes`] on a reader.
2175 /// Please see the documentation of [`bytes`] for more details.
2176 ///
2177 /// [`bytes`]: trait.Read.html#method.bytes
2178 #[stable(feature = "rust1", since = "1.0.0")]
2179 #[derive(Debug)]
2180 pub struct Bytes<R> {
2181     inner: R,
2182 }
2183
2184 #[stable(feature = "rust1", since = "1.0.0")]
2185 impl<R: Read> Iterator for Bytes<R> {
2186     type Item = Result<u8>;
2187
2188     fn next(&mut self) -> Option<Result<u8>> {
2189         let mut byte = 0;
2190         loop {
2191             return match self.inner.read(slice::from_mut(&mut byte)) {
2192                 Ok(0) => None,
2193                 Ok(..) => Some(Ok(byte)),
2194                 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
2195                 Err(e) => Some(Err(e)),
2196             };
2197         }
2198     }
2199 }
2200
2201 /// An iterator over the contents of an instance of `BufRead` split on a
2202 /// particular byte.
2203 ///
2204 /// This struct is generally created by calling [`split`][split] on a
2205 /// `BufRead`. Please see the documentation of `split()` for more details.
2206 ///
2207 /// [split]: trait.BufRead.html#method.split
2208 #[stable(feature = "rust1", since = "1.0.0")]
2209 #[derive(Debug)]
2210 pub struct Split<B> {
2211     buf: B,
2212     delim: u8,
2213 }
2214
2215 #[stable(feature = "rust1", since = "1.0.0")]
2216 impl<B: BufRead> Iterator for Split<B> {
2217     type Item = Result<Vec<u8>>;
2218
2219     fn next(&mut self) -> Option<Result<Vec<u8>>> {
2220         let mut buf = Vec::new();
2221         match self.buf.read_until(self.delim, &mut buf) {
2222             Ok(0) => None,
2223             Ok(_n) => {
2224                 if buf[buf.len() - 1] == self.delim {
2225                     buf.pop();
2226                 }
2227                 Some(Ok(buf))
2228             }
2229             Err(e) => Some(Err(e))
2230         }
2231     }
2232 }
2233
2234 /// An iterator over the lines of an instance of `BufRead`.
2235 ///
2236 /// This struct is generally created by calling [`lines`][lines] on a
2237 /// `BufRead`. Please see the documentation of `lines()` for more details.
2238 ///
2239 /// [lines]: trait.BufRead.html#method.lines
2240 #[stable(feature = "rust1", since = "1.0.0")]
2241 #[derive(Debug)]
2242 pub struct Lines<B> {
2243     buf: B,
2244 }
2245
2246 #[stable(feature = "rust1", since = "1.0.0")]
2247 impl<B: BufRead> Iterator for Lines<B> {
2248     type Item = Result<String>;
2249
2250     fn next(&mut self) -> Option<Result<String>> {
2251         let mut buf = String::new();
2252         match self.buf.read_line(&mut buf) {
2253             Ok(0) => None,
2254             Ok(_n) => {
2255                 if buf.ends_with("\n") {
2256                     buf.pop();
2257                     if buf.ends_with("\r") {
2258                         buf.pop();
2259                     }
2260                 }
2261                 Some(Ok(buf))
2262             }
2263             Err(e) => Some(Err(e))
2264         }
2265     }
2266 }
2267
2268 #[cfg(test)]
2269 mod tests {
2270     use crate::io::prelude::*;
2271     use crate::io;
2272     use super::{Cursor, SeekFrom, repeat};
2273
2274     #[test]
2275     #[cfg_attr(target_os = "emscripten", ignore)]
2276     fn read_until() {
2277         let mut buf = Cursor::new(&b"12"[..]);
2278         let mut v = Vec::new();
2279         assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 2);
2280         assert_eq!(v, b"12");
2281
2282         let mut buf = Cursor::new(&b"1233"[..]);
2283         let mut v = Vec::new();
2284         assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 3);
2285         assert_eq!(v, b"123");
2286         v.truncate(0);
2287         assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 1);
2288         assert_eq!(v, b"3");
2289         v.truncate(0);
2290         assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 0);
2291         assert_eq!(v, []);
2292     }
2293
2294     #[test]
2295     fn split() {
2296         let buf = Cursor::new(&b"12"[..]);
2297         let mut s = buf.split(b'3');
2298         assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2299         assert!(s.next().is_none());
2300
2301         let buf = Cursor::new(&b"1233"[..]);
2302         let mut s = buf.split(b'3');
2303         assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2304         assert_eq!(s.next().unwrap().unwrap(), vec![]);
2305         assert!(s.next().is_none());
2306     }
2307
2308     #[test]
2309     fn read_line() {
2310         let mut buf = Cursor::new(&b"12"[..]);
2311         let mut v = String::new();
2312         assert_eq!(buf.read_line(&mut v).unwrap(), 2);
2313         assert_eq!(v, "12");
2314
2315         let mut buf = Cursor::new(&b"12\n\n"[..]);
2316         let mut v = String::new();
2317         assert_eq!(buf.read_line(&mut v).unwrap(), 3);
2318         assert_eq!(v, "12\n");
2319         v.truncate(0);
2320         assert_eq!(buf.read_line(&mut v).unwrap(), 1);
2321         assert_eq!(v, "\n");
2322         v.truncate(0);
2323         assert_eq!(buf.read_line(&mut v).unwrap(), 0);
2324         assert_eq!(v, "");
2325     }
2326
2327     #[test]
2328     fn lines() {
2329         let buf = Cursor::new(&b"12\r"[..]);
2330         let mut s = buf.lines();
2331         assert_eq!(s.next().unwrap().unwrap(), "12\r".to_string());
2332         assert!(s.next().is_none());
2333
2334         let buf = Cursor::new(&b"12\r\n\n"[..]);
2335         let mut s = buf.lines();
2336         assert_eq!(s.next().unwrap().unwrap(), "12".to_string());
2337         assert_eq!(s.next().unwrap().unwrap(), "".to_string());
2338         assert!(s.next().is_none());
2339     }
2340
2341     #[test]
2342     fn read_to_end() {
2343         let mut c = Cursor::new(&b""[..]);
2344         let mut v = Vec::new();
2345         assert_eq!(c.read_to_end(&mut v).unwrap(), 0);
2346         assert_eq!(v, []);
2347
2348         let mut c = Cursor::new(&b"1"[..]);
2349         let mut v = Vec::new();
2350         assert_eq!(c.read_to_end(&mut v).unwrap(), 1);
2351         assert_eq!(v, b"1");
2352
2353         let cap = 1024 * 1024;
2354         let data = (0..cap).map(|i| (i / 3) as u8).collect::<Vec<_>>();
2355         let mut v = Vec::new();
2356         let (a, b) = data.split_at(data.len() / 2);
2357         assert_eq!(Cursor::new(a).read_to_end(&mut v).unwrap(), a.len());
2358         assert_eq!(Cursor::new(b).read_to_end(&mut v).unwrap(), b.len());
2359         assert_eq!(v, data);
2360     }
2361
2362     #[test]
2363     fn read_to_string() {
2364         let mut c = Cursor::new(&b""[..]);
2365         let mut v = String::new();
2366         assert_eq!(c.read_to_string(&mut v).unwrap(), 0);
2367         assert_eq!(v, "");
2368
2369         let mut c = Cursor::new(&b"1"[..]);
2370         let mut v = String::new();
2371         assert_eq!(c.read_to_string(&mut v).unwrap(), 1);
2372         assert_eq!(v, "1");
2373
2374         let mut c = Cursor::new(&b"\xff"[..]);
2375         let mut v = String::new();
2376         assert!(c.read_to_string(&mut v).is_err());
2377     }
2378
2379     #[test]
2380     fn read_exact() {
2381         let mut buf = [0; 4];
2382
2383         let mut c = Cursor::new(&b""[..]);
2384         assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2385                    io::ErrorKind::UnexpectedEof);
2386
2387         let mut c = Cursor::new(&b"123"[..]).chain(Cursor::new(&b"456789"[..]));
2388         c.read_exact(&mut buf).unwrap();
2389         assert_eq!(&buf, b"1234");
2390         c.read_exact(&mut buf).unwrap();
2391         assert_eq!(&buf, b"5678");
2392         assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2393                    io::ErrorKind::UnexpectedEof);
2394     }
2395
2396     #[test]
2397     fn read_exact_slice() {
2398         let mut buf = [0; 4];
2399
2400         let mut c = &b""[..];
2401         assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2402                    io::ErrorKind::UnexpectedEof);
2403
2404         let mut c = &b"123"[..];
2405         assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2406                    io::ErrorKind::UnexpectedEof);
2407         // make sure the optimized (early returning) method is being used
2408         assert_eq!(&buf, &[0; 4]);
2409
2410         let mut c = &b"1234"[..];
2411         c.read_exact(&mut buf).unwrap();
2412         assert_eq!(&buf, b"1234");
2413
2414         let mut c = &b"56789"[..];
2415         c.read_exact(&mut buf).unwrap();
2416         assert_eq!(&buf, b"5678");
2417         assert_eq!(c, b"9");
2418     }
2419
2420     #[test]
2421     fn take_eof() {
2422         struct R;
2423
2424         impl Read for R {
2425             fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
2426                 Err(io::Error::new(io::ErrorKind::Other, ""))
2427             }
2428         }
2429         impl BufRead for R {
2430             fn fill_buf(&mut self) -> io::Result<&[u8]> {
2431                 Err(io::Error::new(io::ErrorKind::Other, ""))
2432             }
2433             fn consume(&mut self, _amt: usize) { }
2434         }
2435
2436         let mut buf = [0; 1];
2437         assert_eq!(0, R.take(0).read(&mut buf).unwrap());
2438         assert_eq!(b"", R.take(0).fill_buf().unwrap());
2439     }
2440
2441     fn cmp_bufread<Br1: BufRead, Br2: BufRead>(mut br1: Br1, mut br2: Br2, exp: &[u8]) {
2442         let mut cat = Vec::new();
2443         loop {
2444             let consume = {
2445                 let buf1 = br1.fill_buf().unwrap();
2446                 let buf2 = br2.fill_buf().unwrap();
2447                 let minlen = if buf1.len() < buf2.len() { buf1.len() } else { buf2.len() };
2448                 assert_eq!(buf1[..minlen], buf2[..minlen]);
2449                 cat.extend_from_slice(&buf1[..minlen]);
2450                 minlen
2451             };
2452             if consume == 0 {
2453                 break;
2454             }
2455             br1.consume(consume);
2456             br2.consume(consume);
2457         }
2458         assert_eq!(br1.fill_buf().unwrap().len(), 0);
2459         assert_eq!(br2.fill_buf().unwrap().len(), 0);
2460         assert_eq!(&cat[..], &exp[..])
2461     }
2462
2463     #[test]
2464     fn chain_bufread() {
2465         let testdata = b"ABCDEFGHIJKL";
2466         let chain1 = (&testdata[..3]).chain(&testdata[3..6])
2467                                      .chain(&testdata[6..9])
2468                                      .chain(&testdata[9..]);
2469         let chain2 = (&testdata[..4]).chain(&testdata[4..8])
2470                                      .chain(&testdata[8..]);
2471         cmp_bufread(chain1, chain2, &testdata[..]);
2472     }
2473
2474     #[test]
2475     fn chain_zero_length_read_is_not_eof() {
2476         let a = b"A";
2477         let b = b"B";
2478         let mut s = String::new();
2479         let mut chain = (&a[..]).chain(&b[..]);
2480         chain.read(&mut []).unwrap();
2481         chain.read_to_string(&mut s).unwrap();
2482         assert_eq!("AB", s);
2483     }
2484
2485     #[bench]
2486     #[cfg_attr(target_os = "emscripten", ignore)]
2487     fn bench_read_to_end(b: &mut test::Bencher) {
2488         b.iter(|| {
2489             let mut lr = repeat(1).take(10000000);
2490             let mut vec = Vec::with_capacity(1024);
2491             super::read_to_end(&mut lr, &mut vec)
2492         });
2493     }
2494
2495     #[test]
2496     fn seek_len() -> io::Result<()> {
2497         let mut c = Cursor::new(vec![0; 15]);
2498         assert_eq!(c.stream_len()?, 15);
2499
2500         c.seek(SeekFrom::End(0))?;
2501         let old_pos = c.stream_position()?;
2502         assert_eq!(c.stream_len()?, 15);
2503         assert_eq!(c.stream_position()?, old_pos);
2504
2505         c.seek(SeekFrom::Start(7))?;
2506         c.seek(SeekFrom::Current(2))?;
2507         let old_pos = c.stream_position()?;
2508         assert_eq!(c.stream_len()?, 15);
2509         assert_eq!(c.stream_position()?, old_pos);
2510
2511         Ok(())
2512     }
2513
2514     #[test]
2515     fn seek_position() -> io::Result<()> {
2516         // All `asserts` are duplicated here to make sure the method does not
2517         // change anything about the seek state.
2518         let mut c = Cursor::new(vec![0; 15]);
2519         assert_eq!(c.stream_position()?, 0);
2520         assert_eq!(c.stream_position()?, 0);
2521
2522         c.seek(SeekFrom::End(0))?;
2523         assert_eq!(c.stream_position()?, 15);
2524         assert_eq!(c.stream_position()?, 15);
2525
2526
2527         c.seek(SeekFrom::Start(7))?;
2528         c.seek(SeekFrom::Current(2))?;
2529         assert_eq!(c.stream_position()?, 9);
2530         assert_eq!(c.stream_position()?, 9);
2531
2532         c.seek(SeekFrom::End(-3))?;
2533         c.seek(SeekFrom::Current(1))?;
2534         c.seek(SeekFrom::Current(-5))?;
2535         assert_eq!(c.stream_position()?, 8);
2536         assert_eq!(c.stream_position()?, 8);
2537
2538         Ok(())
2539     }
2540 }