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