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