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