]> git.proxmox.com Git - rustc.git/blob - library/std/src/io/mod.rs
New upstream version 1.52.0~beta.3+dfsg1
[rustc.git] / library / std / src / io / mod.rs
1 //! Traits, helpers, and type definitions for core I/O functionality.
2 //!
3 //! The `std::io` module contains a number of common things you'll need
4 //! when doing input and output. The most core part of this module is
5 //! the [`Read`] and [`Write`] traits, which provide the
6 //! most general interface for reading and writing input and output.
7 //!
8 //! # Read and Write
9 //!
10 //! Because they are traits, [`Read`] and [`Write`] are implemented by a number
11 //! of other types, and you can implement them for your types too. As such,
12 //! you'll see a few different types of I/O throughout the documentation in
13 //! this module: [`File`]s, [`TcpStream`]s, and sometimes even [`Vec<T>`]s. For
14 //! example, [`Read`] adds a [`read`][`Read::read`] method, which we can use on
15 //! [`File`]s:
16 //!
17 //! ```no_run
18 //! use std::io;
19 //! use std::io::prelude::*;
20 //! use std::fs::File;
21 //!
22 //! fn main() -> io::Result<()> {
23 //! let mut f = File::open("foo.txt")?;
24 //! let mut buffer = [0; 10];
25 //!
26 //! // read up to 10 bytes
27 //! let n = f.read(&mut buffer)?;
28 //!
29 //! println!("The bytes: {:?}", &buffer[..n]);
30 //! Ok(())
31 //! }
32 //! ```
33 //!
34 //! [`Read`] and [`Write`] are so important, implementors of the two traits have a
35 //! nickname: readers and writers. So you'll sometimes see 'a reader' instead
36 //! of 'a type that implements the [`Read`] trait'. Much easier!
37 //!
38 //! ## Seek and BufRead
39 //!
40 //! Beyond that, there are two important traits that are provided: [`Seek`]
41 //! and [`BufRead`]. Both of these build on top of a reader to control
42 //! how the reading happens. [`Seek`] lets you control where the next byte is
43 //! coming from:
44 //!
45 //! ```no_run
46 //! use std::io;
47 //! use std::io::prelude::*;
48 //! use std::io::SeekFrom;
49 //! use std::fs::File;
50 //!
51 //! fn main() -> io::Result<()> {
52 //! let mut f = File::open("foo.txt")?;
53 //! let mut buffer = [0; 10];
54 //!
55 //! // skip to the last 10 bytes of the file
56 //! f.seek(SeekFrom::End(-10))?;
57 //!
58 //! // read up to 10 bytes
59 //! let n = f.read(&mut buffer)?;
60 //!
61 //! println!("The bytes: {:?}", &buffer[..n]);
62 //! Ok(())
63 //! }
64 //! ```
65 //!
66 //! [`BufRead`] uses an internal buffer to provide a number of other ways to read, but
67 //! to show it off, we'll need to talk about buffers in general. Keep reading!
68 //!
69 //! ## BufReader and BufWriter
70 //!
71 //! Byte-based interfaces are unwieldy and can be inefficient, as we'd need to be
72 //! making near-constant calls to the operating system. To help with this,
73 //! `std::io` comes with two structs, [`BufReader`] and [`BufWriter`], which wrap
74 //! readers and writers. The wrapper uses a buffer, reducing the number of
75 //! calls and providing nicer methods for accessing exactly what you want.
76 //!
77 //! For example, [`BufReader`] works with the [`BufRead`] trait to add extra
78 //! methods to any reader:
79 //!
80 //! ```no_run
81 //! use std::io;
82 //! use std::io::prelude::*;
83 //! use std::io::BufReader;
84 //! use std::fs::File;
85 //!
86 //! fn main() -> io::Result<()> {
87 //! let f = File::open("foo.txt")?;
88 //! let mut reader = BufReader::new(f);
89 //! let mut buffer = String::new();
90 //!
91 //! // read a line into buffer
92 //! reader.read_line(&mut buffer)?;
93 //!
94 //! println!("{}", buffer);
95 //! Ok(())
96 //! }
97 //! ```
98 //!
99 //! [`BufWriter`] doesn't add any new ways of writing; it just buffers every call
100 //! to [`write`][`Write::write`]:
101 //!
102 //! ```no_run
103 //! use std::io;
104 //! use std::io::prelude::*;
105 //! use std::io::BufWriter;
106 //! use std::fs::File;
107 //!
108 //! fn main() -> io::Result<()> {
109 //! let f = File::create("foo.txt")?;
110 //! {
111 //! let mut writer = BufWriter::new(f);
112 //!
113 //! // write a byte to the buffer
114 //! writer.write(&[42])?;
115 //!
116 //! } // the buffer is flushed once writer goes out of scope
117 //!
118 //! Ok(())
119 //! }
120 //! ```
121 //!
122 //! ## Standard input and output
123 //!
124 //! A very common source of input is standard input:
125 //!
126 //! ```no_run
127 //! use std::io;
128 //!
129 //! fn main() -> io::Result<()> {
130 //! let mut input = String::new();
131 //!
132 //! io::stdin().read_line(&mut input)?;
133 //!
134 //! println!("You typed: {}", input.trim());
135 //! Ok(())
136 //! }
137 //! ```
138 //!
139 //! Note that you cannot use the [`?` operator] in functions that do not return
140 //! a [`Result<T, E>`][`Result`]. Instead, you can call [`.unwrap()`]
141 //! or `match` on the return value to catch any possible errors:
142 //!
143 //! ```no_run
144 //! use std::io;
145 //!
146 //! let mut input = String::new();
147 //!
148 //! io::stdin().read_line(&mut input).unwrap();
149 //! ```
150 //!
151 //! And a very common source of output is standard output:
152 //!
153 //! ```no_run
154 //! use std::io;
155 //! use std::io::prelude::*;
156 //!
157 //! fn main() -> io::Result<()> {
158 //! io::stdout().write(&[42])?;
159 //! Ok(())
160 //! }
161 //! ```
162 //!
163 //! Of course, using [`io::stdout`] directly is less common than something like
164 //! [`println!`].
165 //!
166 //! ## Iterator types
167 //!
168 //! A large number of the structures provided by `std::io` are for various
169 //! ways of iterating over I/O. For example, [`Lines`] is used to split over
170 //! lines:
171 //!
172 //! ```no_run
173 //! use std::io;
174 //! use std::io::prelude::*;
175 //! use std::io::BufReader;
176 //! use std::fs::File;
177 //!
178 //! fn main() -> io::Result<()> {
179 //! let f = File::open("foo.txt")?;
180 //! let reader = BufReader::new(f);
181 //!
182 //! for line in reader.lines() {
183 //! println!("{}", line?);
184 //! }
185 //! Ok(())
186 //! }
187 //! ```
188 //!
189 //! ## Functions
190 //!
191 //! There are a number of [functions][functions-list] that offer access to various
192 //! features. For example, we can use three of these functions to copy everything
193 //! from standard input to standard output:
194 //!
195 //! ```no_run
196 //! use std::io;
197 //!
198 //! fn main() -> io::Result<()> {
199 //! io::copy(&mut io::stdin(), &mut io::stdout())?;
200 //! Ok(())
201 //! }
202 //! ```
203 //!
204 //! [functions-list]: #functions-1
205 //!
206 //! ## io::Result
207 //!
208 //! Last, but certainly not least, is [`io::Result`]. This type is used
209 //! as the return type of many `std::io` functions that can cause an error, and
210 //! can be returned from your own functions as well. Many of the examples in this
211 //! module use the [`?` operator]:
212 //!
213 //! ```
214 //! use std::io;
215 //!
216 //! fn read_input() -> io::Result<()> {
217 //! let mut input = String::new();
218 //!
219 //! io::stdin().read_line(&mut input)?;
220 //!
221 //! println!("You typed: {}", input.trim());
222 //!
223 //! Ok(())
224 //! }
225 //! ```
226 //!
227 //! The return type of `read_input()`, [`io::Result<()>`][`io::Result`], is a very
228 //! common type for functions which don't have a 'real' return value, but do want to
229 //! return errors if they happen. In this case, the only purpose of this function is
230 //! to read the line and print it, so we use `()`.
231 //!
232 //! ## Platform-specific behavior
233 //!
234 //! Many I/O functions throughout the standard library are documented to indicate
235 //! what various library or syscalls they are delegated to. This is done to help
236 //! applications both understand what's happening under the hood as well as investigate
237 //! any possibly unclear semantics. Note, however, that this is informative, not a binding
238 //! contract. The implementation of many of these functions are subject to change over
239 //! time and may call fewer or more syscalls/library functions.
240 //!
241 //! [`File`]: crate::fs::File
242 //! [`TcpStream`]: crate::net::TcpStream
243 //! [`io::stdout`]: stdout
244 //! [`io::Result`]: self::Result
245 //! [`?` operator]: ../../book/appendix-02-operators.html
246 //! [`Result`]: crate::result::Result
247 //! [`.unwrap()`]: crate::result::Result::unwrap
248
249 #![stable(feature = "rust1", since = "1.0.0")]
250
251 #[cfg(test)]
252 mod tests;
253
254 use crate::cmp;
255 use crate::fmt;
256 use crate::memchr;
257 use crate::ops::{Deref, DerefMut};
258 use crate::ptr;
259 use crate::slice;
260 use crate::str;
261 use crate::sys;
262
263 #[stable(feature = "rust1", since = "1.0.0")]
264 pub use self::buffered::IntoInnerError;
265 #[stable(feature = "rust1", since = "1.0.0")]
266 pub use self::buffered::{BufReader, BufWriter, LineWriter};
267 #[stable(feature = "rust1", since = "1.0.0")]
268 pub use self::copy::copy;
269 #[stable(feature = "rust1", since = "1.0.0")]
270 pub use self::cursor::Cursor;
271 #[stable(feature = "rust1", since = "1.0.0")]
272 pub use self::error::{Error, ErrorKind, Result};
273 #[unstable(feature = "internal_output_capture", issue = "none")]
274 #[doc(no_inline, hidden)]
275 pub use self::stdio::set_output_capture;
276 #[stable(feature = "rust1", since = "1.0.0")]
277 pub use self::stdio::{stderr, stdin, stdout, Stderr, Stdin, Stdout};
278 #[stable(feature = "rust1", since = "1.0.0")]
279 pub use self::stdio::{StderrLock, StdinLock, StdoutLock};
280 #[unstable(feature = "print_internals", issue = "none")]
281 pub use self::stdio::{_eprint, _print};
282 #[stable(feature = "rust1", since = "1.0.0")]
283 pub use self::util::{empty, repeat, sink, Empty, Repeat, Sink};
284
285 mod buffered;
286 pub(crate) mod copy;
287 mod cursor;
288 mod error;
289 mod impls;
290 pub mod prelude;
291 mod stdio;
292 mod util;
293
294 const DEFAULT_BUF_SIZE: usize = crate::sys_common::io::DEFAULT_BUF_SIZE;
295
296 struct Guard<'a> {
297 buf: &'a mut Vec<u8>,
298 len: usize,
299 }
300
301 impl Drop for Guard<'_> {
302 fn drop(&mut self) {
303 unsafe {
304 self.buf.set_len(self.len);
305 }
306 }
307 }
308
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.
327 fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
328 where
329 F: FnOnce(&mut Vec<u8>) -> Result<usize>,
330 {
331 unsafe {
332 let mut g = Guard { len: buf.len(), buf: buf.as_mut_vec() };
333 let ret = f(g.buf);
334 if str::from_utf8(&g.buf[g.len..]).is_err() {
335 ret.and_then(|_| {
336 Err(Error::new(ErrorKind::InvalidData, "stream did not contain valid UTF-8"))
337 })
338 } else {
339 g.len = g.buf.len();
340 ret
341 }
342 }
343 }
344
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
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.
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.
354 fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
355 read_to_end_with_reservation(r, buf, |_| 32)
356 }
357
358 fn read_to_end_with_reservation<R, F>(
359 r: &mut R,
360 buf: &mut Vec<u8>,
361 mut reservation_size: F,
362 ) -> Result<usize>
363 where
364 R: Read + ?Sized,
365 F: FnMut(&R) -> usize,
366 {
367 let start_len = buf.len();
368 let mut g = Guard { len: buf.len(), buf };
369 loop {
370 if g.len == g.buf.len() {
371 unsafe {
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));
381 let capacity = g.buf.capacity();
382 g.buf.set_len(capacity);
383 r.initializer().initialize(&mut g.buf[g.len..]);
384 }
385 }
386
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;
396 }
397 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
398 Err(e) => return Err(e),
399 }
400 }
401 }
402
403 pub(crate) fn default_read_vectored<F>(read: F, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
404 where
405 F: FnOnce(&mut [u8]) -> Result<usize>,
406 {
407 let buf = bufs.iter_mut().find(|b| !b.is_empty()).map_or(&mut [][..], |b| &mut **b);
408 read(buf)
409 }
410
411 pub(crate) fn default_write_vectored<F>(write: F, bufs: &[IoSlice<'_>]) -> Result<usize>
412 where
413 F: FnOnce(&[u8]) -> Result<usize>,
414 {
415 let buf = bufs.iter().find(|b| !b.is_empty()).map_or(&[][..], |b| &**b);
416 write(buf)
417 }
418
419 pub(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
438 /// The `Read` trait allows for reading bytes from a source.
439 ///
440 /// Implementors of the `Read` trait are called 'readers'.
441 ///
442 /// Readers are defined by one required method, [`read()`]. Each call to [`read()`]
443 /// will attempt to pull bytes from this source into a provided buffer. A
444 /// number of other methods are implemented in terms of [`read()`], giving
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
449 /// throughout [`std::io`] take and provide types which implement the `Read`
450 /// trait.
451 ///
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.
455 ///
456 /// # Examples
457 ///
458 /// [`File`]s implement `Read`:
459 ///
460 /// ```no_run
461 /// use std::io;
462 /// use std::io::prelude::*;
463 /// use std::fs::File;
464 ///
465 /// fn main() -> io::Result<()> {
466 /// let mut f = File::open("foo.txt")?;
467 /// let mut buffer = [0; 10];
468 ///
469 /// // read up to 10 bytes
470 /// f.read(&mut buffer)?;
471 ///
472 /// let mut buffer = Vec::new();
473 /// // read the whole file
474 /// f.read_to_end(&mut buffer)?;
475 ///
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)?;
479 ///
480 /// // and more! See the other methods for more details.
481 /// Ok(())
482 /// }
483 /// ```
484 ///
485 /// Read from [`&str`] because [`&[u8]`][prim@slice] implements `Read`:
486 ///
487 /// ```no_run
488 /// # use std::io;
489 /// use std::io::prelude::*;
490 ///
491 /// fn main() -> io::Result<()> {
492 /// let mut b = "This string will be read".as_bytes();
493 /// let mut buffer = [0; 10];
494 ///
495 /// // read up to 10 bytes
496 /// b.read(&mut buffer)?;
497 ///
498 /// // etc... it works exactly as a File does!
499 /// Ok(())
500 /// }
501 /// ```
502 ///
503 /// [`read()`]: Read::read
504 /// [`&str`]: prim@str
505 /// [`std::io`]: self
506 /// [`File`]: crate::fs::File
507 #[stable(feature = "rust1", since = "1.0.0")]
508 #[doc(spotlight)]
509 pub 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
514 /// waiting for data, but if an object needs to block for a read and cannot,
515 /// it will typically signal this via an [`Err`] return value.
516 ///
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
519 /// that the buffer `buf` has been filled in with `n` bytes of data from this
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 ///
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 ///
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 ///
537 /// No guarantees are provided about the contents of `buf` when this
538 /// function is called, implementations cannot rely on any property of the
539 /// contents of `buf` being true. It is recommended that *implementations*
540 /// only write data to `buf` instead of reading its contents.
541 ///
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,
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
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 ///
549 /// [`MaybeUninit<T>`]: crate::mem::MaybeUninit
550 ///
551 /// # Errors
552 ///
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.
556 ///
557 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
558 /// operation should be retried if there is nothing else to do.
559 ///
560 /// # Examples
561 ///
562 /// [`File`]s implement `Read`:
563 ///
564 /// [`Ok(n)`]: Ok
565 /// [`File`]: crate::fs::File
566 ///
567 /// ```no_run
568 /// use std::io;
569 /// use std::io::prelude::*;
570 /// use std::fs::File;
571 ///
572 /// fn main() -> io::Result<()> {
573 /// let mut f = File::open("foo.txt")?;
574 /// let mut buffer = [0; 10];
575 ///
576 /// // read up to 10 bytes
577 /// let n = f.read(&mut buffer[..])?;
578 ///
579 /// println!("The bytes: {:?}", &buffer[..n]);
580 /// Ok(())
581 /// }
582 /// ```
583 #[stable(feature = "rust1", since = "1.0.0")]
584 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
585
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
589 /// written to possibly being only partially filled. This method must
590 /// behave equivalently to a single call to `read` with concatenated
591 /// buffers.
592 ///
593 /// The default implementation calls `read` with either the first nonempty
594 /// buffer provided, or an empty one if none exists.
595 #[stable(feature = "iovec", since = "1.36.0")]
596 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
597 default_read_vectored(|b| self.read(b), bufs)
598 }
599
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
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
620 /// memory, it should call [`Initializer::nop()`]. See the documentation for
621 /// [`Initializer`] for details.
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 ///
627 /// # Safety
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
638 /// Read all bytes until EOF in this source, placing them into `buf`.
639 ///
640 /// All bytes read from this source will be appended to the specified buffer
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.
644 ///
645 /// If successful, this function will return the total number of bytes read.
646 ///
647 /// # Errors
648 ///
649 /// If this function encounters an error of the kind
650 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
651 /// will continue.
652 ///
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`.
656 ///
657 /// # Examples
658 ///
659 /// [`File`]s implement `Read`:
660 ///
661 /// [`read()`]: Read::read
662 /// [`Ok(0)`]: Ok
663 /// [`File`]: crate::fs::File
664 ///
665 /// ```no_run
666 /// use std::io;
667 /// use std::io::prelude::*;
668 /// use std::fs::File;
669 ///
670 /// fn main() -> io::Result<()> {
671 /// let mut f = File::open("foo.txt")?;
672 /// let mut buffer = Vec::new();
673 ///
674 /// // read the whole file
675 /// f.read_to_end(&mut buffer)?;
676 /// Ok(())
677 /// }
678 /// ```
679 ///
680 /// (See also the [`std::fs::read`] convenience function for reading from a
681 /// file.)
682 ///
683 /// [`std::fs::read`]: crate::fs::read
684 #[stable(feature = "rust1", since = "1.0.0")]
685 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
686 read_to_end(self, buf)
687 }
688
689 /// Read all bytes until EOF in this source, appending them to `buf`.
690 ///
691 /// If successful, this function returns the number of bytes which were read
692 /// and appended to `buf`.
693 ///
694 /// # Errors
695 ///
696 /// If the data in this stream is *not* valid UTF-8 then an error is
697 /// returned and `buf` is unchanged.
698 ///
699 /// See [`read_to_end`] for other error semantics.
700 ///
701 /// [`read_to_end`]: Read::read_to_end
702 ///
703 /// # Examples
704 ///
705 /// [`File`]s implement `Read`:
706 ///
707 /// [`File`]: crate::fs::File
708 ///
709 /// ```no_run
710 /// use std::io;
711 /// use std::io::prelude::*;
712 /// use std::fs::File;
713 ///
714 /// fn main() -> io::Result<()> {
715 /// let mut f = File::open("foo.txt")?;
716 /// let mut buffer = String::new();
717 ///
718 /// f.read_to_string(&mut buffer)?;
719 /// Ok(())
720 /// }
721 /// ```
722 ///
723 /// (See also the [`std::fs::read_to_string`] convenience function for
724 /// reading from a file.)
725 ///
726 /// [`std::fs::read_to_string`]: crate::fs::read_to_string
727 #[stable(feature = "rust1", since = "1.0.0")]
728 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
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))
739 }
740
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
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.
752 ///
753 /// # Errors
754 ///
755 /// If this function encounters an error of the kind
756 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
757 /// will continue.
758 ///
759 /// If this function encounters an "end of file" before completely filling
760 /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
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 ///
772 /// [`File`]s implement `Read`:
773 ///
774 /// [`read`]: Read::read
775 /// [`File`]: crate::fs::File
776 ///
777 /// ```no_run
778 /// use std::io;
779 /// use std::io::prelude::*;
780 /// use std::fs::File;
781 ///
782 /// fn main() -> io::Result<()> {
783 /// let mut f = File::open("foo.txt")?;
784 /// let mut buffer = [0; 10];
785 ///
786 /// // read exactly 10 bytes
787 /// f.read_exact(&mut buffer)?;
788 /// Ok(())
789 /// }
790 /// ```
791 #[stable(feature = "read_exact", since = "1.6.0")]
792 fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
793 default_read_exact(self, buf)
794 }
795
796 /// Creates a "by reference" adaptor for this instance of `Read`.
797 ///
798 /// The returned adaptor also implements `Read` and will simply borrow this
799 /// current reader.
800 ///
801 /// # Examples
802 ///
803 /// [`File`]s implement `Read`:
804 ///
805 /// [`File`]: crate::fs::File
806 ///
807 /// ```no_run
808 /// use std::io;
809 /// use std::io::Read;
810 /// use std::fs::File;
811 ///
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();
816 ///
817 /// {
818 /// let reference = f.by_ref();
819 ///
820 /// // read at most 5 bytes
821 /// reference.take(5).read_to_end(&mut buffer)?;
822 ///
823 /// } // drop our &mut reference so we can use f again
824 ///
825 /// // original file still usable, read the rest
826 /// f.read_to_end(&mut other_buffer)?;
827 /// Ok(())
828 /// }
829 /// ```
830 #[stable(feature = "rust1", since = "1.0.0")]
831 fn by_ref(&mut self) -> &mut Self
832 where
833 Self: Sized,
834 {
835 self
836 }
837
838 /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
839 ///
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.
844 ///
845 /// # Examples
846 ///
847 /// [`File`]s implement `Read`:
848 ///
849 /// [`File`]: crate::fs::File
850 /// [`Result`]: crate::result::Result
851 /// [`io::Error`]: self::Error
852 ///
853 /// ```no_run
854 /// use std::io;
855 /// use std::io::prelude::*;
856 /// use std::fs::File;
857 ///
858 /// fn main() -> io::Result<()> {
859 /// let mut f = File::open("foo.txt")?;
860 ///
861 /// for byte in f.bytes() {
862 /// println!("{}", byte.unwrap());
863 /// }
864 /// Ok(())
865 /// }
866 /// ```
867 #[stable(feature = "rust1", since = "1.0.0")]
868 fn bytes(self) -> Bytes<Self>
869 where
870 Self: Sized,
871 {
872 Bytes { inner: self }
873 }
874
875 /// Creates an adaptor which will chain this stream with another.
876 ///
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`.
880 ///
881 /// # Examples
882 ///
883 /// [`File`]s implement `Read`:
884 ///
885 /// [`File`]: crate::fs::File
886 ///
887 /// ```no_run
888 /// use std::io;
889 /// use std::io::prelude::*;
890 /// use std::fs::File;
891 ///
892 /// fn main() -> io::Result<()> {
893 /// let mut f1 = File::open("foo.txt")?;
894 /// let mut f2 = File::open("bar.txt")?;
895 ///
896 /// let mut handle = f1.chain(f2);
897 /// let mut buffer = String::new();
898 ///
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 /// }
904 /// ```
905 #[stable(feature = "rust1", since = "1.0.0")]
906 fn chain<R: Read>(self, next: R) -> Chain<Self, R>
907 where
908 Self: Sized,
909 {
910 Chain { first: self, second: next, done_first: false }
911 }
912
913 /// Creates an adaptor which will read at most `limit` bytes from it.
914 ///
915 /// This function returns a new instance of `Read` which will read at most
916 /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
917 /// read errors will not count towards the number of bytes read and future
918 /// calls to [`read()`] may succeed.
919 ///
920 /// # Examples
921 ///
922 /// [`File`]s implement `Read`:
923 ///
924 /// [`File`]: crate::fs::File
925 /// [`Ok(0)`]: Ok
926 /// [`read()`]: Read::read
927 ///
928 /// ```no_run
929 /// use std::io;
930 /// use std::io::prelude::*;
931 /// use std::fs::File;
932 ///
933 /// fn main() -> io::Result<()> {
934 /// let mut f = File::open("foo.txt")?;
935 /// let mut buffer = [0; 5];
936 ///
937 /// // read at most five bytes
938 /// let mut handle = f.take(5);
939 ///
940 /// handle.read(&mut buffer)?;
941 /// Ok(())
942 /// }
943 /// ```
944 #[stable(feature = "rust1", since = "1.0.0")]
945 fn take(self, limit: u64) -> Take<Self>
946 where
947 Self: Sized,
948 {
949 Take { inner: self, limit }
950 }
951 }
952
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")]
995 pub 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
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.
1006 #[stable(feature = "iovec", since = "1.36.0")]
1007 #[repr(transparent)]
1008 pub struct IoSliceMut<'a>(sys::io::IoSliceMut<'a>);
1009
1010 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1011 unsafe impl<'a> Send for IoSliceMut<'a> {}
1012
1013 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1014 unsafe impl<'a> Sync for IoSliceMut<'a> {}
1015
1016 #[stable(feature = "iovec", since = "1.36.0")]
1017 impl<'a> fmt::Debug for IoSliceMut<'a> {
1018 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1019 fmt::Debug::fmt(self.0.as_slice(), fmt)
1020 }
1021 }
1022
1023 impl<'a> IoSliceMut<'a> {
1024 /// Creates a new `IoSliceMut` wrapping a byte slice.
1025 ///
1026 /// # Panics
1027 ///
1028 /// Panics on Windows if the slice is larger than 4GB.
1029 #[stable(feature = "iovec", since = "1.36.0")]
1030 #[inline]
1031 pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> {
1032 IoSliceMut(sys::io::IoSliceMut::new(buf))
1033 }
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;
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.
1063 /// bufs = IoSliceMut::advance(bufs, 10);
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 }
1089 }
1090
1091 #[stable(feature = "iovec", since = "1.36.0")]
1092 impl<'a> Deref for IoSliceMut<'a> {
1093 type Target = [u8];
1094
1095 #[inline]
1096 fn deref(&self) -> &[u8] {
1097 self.0.as_slice()
1098 }
1099 }
1100
1101 #[stable(feature = "iovec", since = "1.36.0")]
1102 impl<'a> DerefMut for IoSliceMut<'a> {
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.
1114 #[stable(feature = "iovec", since = "1.36.0")]
1115 #[derive(Copy, Clone)]
1116 #[repr(transparent)]
1117 pub struct IoSlice<'a>(sys::io::IoSlice<'a>);
1118
1119 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1120 unsafe impl<'a> Send for IoSlice<'a> {}
1121
1122 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1123 unsafe impl<'a> Sync for IoSlice<'a> {}
1124
1125 #[stable(feature = "iovec", since = "1.36.0")]
1126 impl<'a> fmt::Debug for IoSlice<'a> {
1127 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1128 fmt::Debug::fmt(self.0.as_slice(), fmt)
1129 }
1130 }
1131
1132 impl<'a> IoSlice<'a> {
1133 /// Creates a new `IoSlice` wrapping a byte slice.
1134 ///
1135 /// # Panics
1136 ///
1137 /// Panics on Windows if the slice is larger than 4GB.
1138 #[stable(feature = "iovec", since = "1.36.0")]
1139 #[inline]
1140 pub fn new(buf: &'a [u8]) -> IoSlice<'a> {
1141 IoSlice(sys::io::IoSlice::new(buf))
1142 }
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;
1160 /// use std::ops::Deref;
1161 ///
1162 /// let buf1 = [1; 8];
1163 /// let buf2 = [2; 16];
1164 /// let buf3 = [3; 8];
1165 /// let mut bufs = &mut [
1166 /// IoSlice::new(&buf1),
1167 /// IoSlice::new(&buf2),
1168 /// IoSlice::new(&buf3),
1169 /// ][..];
1170 ///
1171 /// // Mark 10 bytes as written.
1172 /// bufs = IoSlice::advance(bufs, 10);
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 }
1197 }
1198
1199 #[stable(feature = "iovec", since = "1.36.0")]
1200 impl<'a> Deref for IoSlice<'a> {
1201 type Target = [u8];
1202
1203 #[inline]
1204 fn deref(&self) -> &[u8] {
1205 self.0.as_slice()
1206 }
1207 }
1208
1209 /// A type used to conditionally initialize buffers passed to `Read` methods.
1210 #[unstable(feature = "read_initializer", issue = "42788")]
1211 #[derive(Debug)]
1212 pub struct Initializer(bool);
1213
1214 impl 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 ///
1224 /// # Safety
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
1253 /// A trait for objects which are byte-oriented sinks.
1254 ///
1255 /// Implementors of the `Write` trait are sometimes called 'writers'.
1256 ///
1257 /// Writers are defined by two required methods, [`write`] and [`flush`]:
1258 ///
1259 /// * The [`write`] method will attempt to write some data into the object,
1260 /// returning how many bytes were successfully written.
1261 ///
1262 /// * The [`flush`] method is useful for adaptors and explicit buffers
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
1267 /// throughout [`std::io`] take and provide types which implement the `Write`
1268 /// trait.
1269 ///
1270 /// [`write`]: Write::write
1271 /// [`flush`]: Write::flush
1272 /// [`std::io`]: self
1273 ///
1274 /// # Examples
1275 ///
1276 /// ```no_run
1277 /// use std::io::prelude::*;
1278 /// use std::fs::File;
1279 ///
1280 /// fn main() -> std::io::Result<()> {
1281 /// let data = b"some bytes";
1282 ///
1283 /// let mut pos = 0;
1284 /// let mut buffer = File::create("foo.txt")?;
1285 ///
1286 /// while pos < data.len() {
1287 /// let bytes_written = buffer.write(&data[pos..])?;
1288 /// pos += bytes_written;
1289 /// }
1290 /// Ok(())
1291 /// }
1292 /// ```
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 ///
1297 /// [`write_all`]: Write::write_all
1298 #[stable(feature = "rust1", since = "1.0.0")]
1299 #[doc(spotlight)]
1300 pub trait Write {
1301 /// Write a buffer into this writer, returning how many bytes were written.
1302 ///
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.
1307 ///
1308 /// Calls to `write` are not guaranteed to block waiting for data to be
1309 /// written, and a write which would otherwise block can be indicated through
1310 /// an [`Err`] variant.
1311 ///
1312 /// If the return value is [`Ok(n)`] then it must be guaranteed that
1313 /// `n <= buf.len()`. A return value of `0` typically means that the
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.
1316 ///
1317 /// # Errors
1318 ///
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.
1322 ///
1323 /// It is **not** considered an error if the entire buffer could not be
1324 /// written to this writer.
1325 ///
1326 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the
1327 /// write operation should be retried if there is nothing else to do.
1328 ///
1329 /// # Examples
1330 ///
1331 /// ```no_run
1332 /// use std::io::prelude::*;
1333 /// use std::fs::File;
1334 ///
1335 /// fn main() -> std::io::Result<()> {
1336 /// let mut buffer = File::create("foo.txt")?;
1337 ///
1338 /// // Writes some prefix of the byte string, not necessarily all of it.
1339 /// buffer.write(b"some bytes")?;
1340 /// Ok(())
1341 /// }
1342 /// ```
1343 ///
1344 /// [`Ok(n)`]: Ok
1345 #[stable(feature = "rust1", since = "1.0.0")]
1346 fn write(&mut self, buf: &[u8]) -> Result<usize>;
1347
1348 /// Like [`write`], except that it writes from a slice of buffers.
1349 ///
1350 /// Data is copied from each buffer in order, with the final buffer
1351 /// read from possibly being only partially consumed. This method must
1352 /// behave as a call to [`write`] with the buffers concatenated would.
1353 ///
1354 /// The default implementation calls [`write`] with either the first nonempty
1355 /// buffer provided, or an empty one if none exists.
1356 ///
1357 /// [`write`]: Write::write
1358 #[stable(feature = "iovec", since = "1.36.0")]
1359 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize> {
1360 default_write_vectored(|b| self.write(b), bufs)
1361 }
1362
1363 /// Determines if this `Write`r has an efficient [`write_vectored`]
1364 /// implementation.
1365 ///
1366 /// If a `Write`r does not override the default [`write_vectored`]
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`.
1371 ///
1372 /// [`write_vectored`]: Write::write_vectored
1373 #[unstable(feature = "can_vector", issue = "69941")]
1374 fn is_write_vectored(&self) -> bool {
1375 false
1376 }
1377
1378 /// Flush this output stream, ensuring that all intermediately buffered
1379 /// contents reach their destination.
1380 ///
1381 /// # Errors
1382 ///
1383 /// It is considered an error if not all bytes could be written due to
1384 /// I/O errors or EOF being reached.
1385 ///
1386 /// # Examples
1387 ///
1388 /// ```no_run
1389 /// use std::io::prelude::*;
1390 /// use std::io::BufWriter;
1391 /// use std::fs::File;
1392 ///
1393 /// fn main() -> std::io::Result<()> {
1394 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
1395 ///
1396 /// buffer.write_all(b"some bytes")?;
1397 /// buffer.flush()?;
1398 /// Ok(())
1399 /// }
1400 /// ```
1401 #[stable(feature = "rust1", since = "1.0.0")]
1402 fn flush(&mut self) -> Result<()>;
1403
1404 /// Attempts to write an entire buffer into this writer.
1405 ///
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
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
1410 /// not of [`ErrorKind::Interrupted`] kind generated from this method will be
1411 /// returned.
1412 ///
1413 /// If the buffer contains no data, this will never call [`write`].
1414 ///
1415 /// # Errors
1416 ///
1417 /// This function will return the first error of
1418 /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns.
1419 ///
1420 /// [`write`]: Write::write
1421 ///
1422 /// # Examples
1423 ///
1424 /// ```no_run
1425 /// use std::io::prelude::*;
1426 /// use std::fs::File;
1427 ///
1428 /// fn main() -> std::io::Result<()> {
1429 /// let mut buffer = File::create("foo.txt")?;
1430 ///
1431 /// buffer.write_all(b"some bytes")?;
1432 /// Ok(())
1433 /// }
1434 /// ```
1435 #[stable(feature = "rust1", since = "1.0.0")]
1436 fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
1437 while !buf.is_empty() {
1438 match self.write(buf) {
1439 Ok(0) => {
1440 return Err(Error::new(ErrorKind::WriteZero, "failed to write whole buffer"));
1441 }
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 }
1449
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 ///
1461 /// # Notes
1462 ///
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
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
1468 /// this depends on how many calls to [`write_vectored`] were necessary. It is
1469 /// best to understand this function as taking ownership of `bufs` and to
1470 /// not use `bufs` afterwards. The underlying buffers, to which the
1471 /// [`IoSlice`]s point (but not the [`IoSlice`]s themselves), are unchanged and
1472 /// can be reused.
1473 ///
1474 /// [`write_vectored`]: Write::write_vectored
1475 ///
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<()> {
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);
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 }
1507 Ok(n) => bufs = IoSlice::advance(bufs, n),
1508 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1509 Err(e) => return Err(e),
1510 }
1511 }
1512 Ok(())
1513 }
1514
1515 /// Writes a formatted string into this writer, returning any error
1516 /// encountered.
1517 ///
1518 /// This method is primarily used to interface with the
1519 /// [`format_args!()`] macro, but it is rare that this should
1520 /// explicitly be called. The [`write!()`] macro should be favored to
1521 /// invoke this method instead.
1522 ///
1523 /// This function internally uses the [`write_all`] method on
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 ///
1528 /// [`write_all`]: Write::write_all
1529 ///
1530 /// # Errors
1531 ///
1532 /// This function will return any I/O error reported while formatting.
1533 ///
1534 /// # Examples
1535 ///
1536 /// ```no_run
1537 /// use std::io::prelude::*;
1538 /// use std::fs::File;
1539 ///
1540 /// fn main() -> std::io::Result<()> {
1541 /// let mut buffer = File::create("foo.txt")?;
1542 ///
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 /// }
1549 /// ```
1550 #[stable(feature = "rust1", since = "1.0.0")]
1551 fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> Result<()> {
1552 // Create a shim which translates a Write to a fmt::Write and saves
1553 // off I/O errors. instead of discarding them
1554 struct Adaptor<'a, T: ?Sized + 'a> {
1555 inner: &'a mut T,
1556 error: Result<()>,
1557 }
1558
1559 impl<T: Write + ?Sized> fmt::Write for Adaptor<'_, T> {
1560 fn write_str(&mut self, s: &str) -> fmt::Result {
1561 match self.inner.write_all(s.as_bytes()) {
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(()),
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 }
1582 }
1583 }
1584
1585 /// Creates a "by reference" adaptor for this instance of `Write`.
1586 ///
1587 /// The returned adaptor also implements `Write` and will simply borrow this
1588 /// current writer.
1589 ///
1590 /// # Examples
1591 ///
1592 /// ```no_run
1593 /// use std::io::Write;
1594 /// use std::fs::File;
1595 ///
1596 /// fn main() -> std::io::Result<()> {
1597 /// let mut buffer = File::create("foo.txt")?;
1598 ///
1599 /// let reference = buffer.by_ref();
1600 ///
1601 /// // we can use reference just like our original buffer
1602 /// reference.write_all(b"some bytes")?;
1603 /// Ok(())
1604 /// }
1605 /// ```
1606 #[stable(feature = "rust1", since = "1.0.0")]
1607 fn by_ref(&mut self) -> &mut Self
1608 where
1609 Self: Sized,
1610 {
1611 self
1612 }
1613 }
1614
1615 /// The `Seek` trait provides a cursor which can be moved within a stream of
1616 /// bytes.
1617 ///
1618 /// The stream typically has a fixed size, allowing seeking relative to either
1619 /// end or the current offset.
1620 ///
1621 /// # Examples
1622 ///
1623 /// [`File`]s implement `Seek`:
1624 ///
1625 /// [`File`]: crate::fs::File
1626 ///
1627 /// ```no_run
1628 /// use std::io;
1629 /// use std::io::prelude::*;
1630 /// use std::fs::File;
1631 /// use std::io::SeekFrom;
1632 ///
1633 /// fn main() -> io::Result<()> {
1634 /// let mut f = File::open("foo.txt")?;
1635 ///
1636 /// // move the cursor 42 bytes from the start of the file
1637 /// f.seek(SeekFrom::Start(42))?;
1638 /// Ok(())
1639 /// }
1640 /// ```
1641 #[stable(feature = "rust1", since = "1.0.0")]
1642 pub trait Seek {
1643 /// Seek to an offset, in bytes, in a stream.
1644 ///
1645 /// A seek beyond the end of a stream is allowed, but behavior is defined
1646 /// by the implementation.
1647 ///
1648 /// If the seek operation completed successfully,
1649 /// this method returns the new position from the start of the stream.
1650 /// That position can be used later with [`SeekFrom::Start`].
1651 ///
1652 /// # Errors
1653 ///
1654 /// Seeking to a negative offset is considered an error.
1655 #[stable(feature = "rust1", since = "1.0.0")]
1656 fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
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 ///
1675 /// # Example
1676 ///
1677 /// ```no_run
1678 /// #![feature(seek_stream_len)]
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 /// ```
1692 #[unstable(feature = "seek_stream_len", issue = "59359")]
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 ///
1710 /// # Example
1711 ///
1712 /// ```no_run
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 /// ```
1729 #[stable(feature = "seek_convenience", since = "1.51.0")]
1730 fn stream_position(&mut self) -> Result<u64> {
1731 self.seek(SeekFrom::Current(0))
1732 }
1733 }
1734
1735 /// Enumeration of possible methods to seek within an I/O object.
1736 ///
1737 /// It is used by the [`Seek`] trait.
1738 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1739 #[stable(feature = "rust1", since = "1.0.0")]
1740 pub enum SeekFrom {
1741 /// Sets the offset to the provided number of bytes.
1742 #[stable(feature = "rust1", since = "1.0.0")]
1743 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1744
1745 /// Sets the offset to the size of this object plus the specified number of
1746 /// bytes.
1747 ///
1748 /// It is possible to seek beyond the end of an object, but it's an error to
1749 /// seek before byte 0.
1750 #[stable(feature = "rust1", since = "1.0.0")]
1751 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1752
1753 /// Sets the offset to the current position plus the specified number of
1754 /// bytes.
1755 ///
1756 /// It is possible to seek beyond the end of an object, but it's an error to
1757 /// seek before byte 0.
1758 #[stable(feature = "rust1", since = "1.0.0")]
1759 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1760 }
1761
1762 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>) -> Result<usize> {
1763 let mut read = 0;
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,
1769 Err(e) => return Err(e),
1770 };
1771 match memchr::memchr(delim, available) {
1772 Some(i) => {
1773 buf.extend_from_slice(&available[..=i]);
1774 (true, i + 1)
1775 }
1776 None => {
1777 buf.extend_from_slice(available);
1778 (false, available.len())
1779 }
1780 }
1781 };
1782 r.consume(used);
1783 read += used;
1784 if done || used == 0 {
1785 return Ok(read);
1786 }
1787 }
1788 }
1789
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
1795 /// [`read_line`] method as well as a [`lines`] iterator.
1796 ///
1797 /// # Examples
1798 ///
1799 /// A locked standard input implements `BufRead`:
1800 ///
1801 /// ```no_run
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 ///
1811 /// If you have something that implements [`Read`], you can use the [`BufReader`
1812 /// type][`BufReader`] to turn it into a `BufRead`.
1813 ///
1814 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1815 /// [`BufReader`] to the rescue!
1816 ///
1817 /// [`File`]: crate::fs::File
1818 /// [`read_line`]: BufRead::read_line
1819 /// [`lines`]: BufRead::lines
1820 ///
1821 /// ```no_run
1822 /// use std::io::{self, BufReader};
1823 /// use std::io::prelude::*;
1824 /// use std::fs::File;
1825 ///
1826 /// fn main() -> io::Result<()> {
1827 /// let f = File::open("foo.txt")?;
1828 /// let f = BufReader::new(f);
1829 ///
1830 /// for line in f.lines() {
1831 /// println!("{}", line.unwrap());
1832 /// }
1833 ///
1834 /// Ok(())
1835 /// }
1836 /// ```
1837 #[stable(feature = "rust1", since = "1.0.0")]
1838 pub trait BufRead: Read {
1839 /// Returns the contents of the internal buffer, filling it with more data
1840 /// from the inner reader if it is empty.
1841 ///
1842 /// This function is a lower-level call. It needs to be paired with the
1843 /// [`consume`] method to function properly. When calling this
1844 /// method, none of the contents will be "read" in the sense that later
1845 /// calling `read` may return the same contents. As such, [`consume`] must
1846 /// be called with the number of bytes that are consumed from this buffer to
1847 /// ensure that the bytes are never returned twice.
1848 ///
1849 /// [`consume`]: BufRead::consume
1850 ///
1851 /// An empty buffer returned indicates that the stream has reached EOF.
1852 ///
1853 /// # Errors
1854 ///
1855 /// This function will return an I/O error if the underlying reader was
1856 /// read, but returned an error.
1857 ///
1858 /// # Examples
1859 ///
1860 /// A locked standard input implements `BufRead`:
1861 ///
1862 /// ```no_run
1863 /// use std::io;
1864 /// use std::io::prelude::*;
1865 ///
1866 /// let stdin = io::stdin();
1867 /// let mut stdin = stdin.lock();
1868 ///
1869 /// let buffer = stdin.fill_buf().unwrap();
1870 ///
1871 /// // work with buffer
1872 /// println!("{:?}", buffer);
1873 ///
1874 /// // ensure the bytes we worked with aren't returned again later
1875 /// let length = buffer.len();
1876 /// stdin.consume(length);
1877 /// ```
1878 #[stable(feature = "rust1", since = "1.0.0")]
1879 fn fill_buf(&mut self) -> Result<&[u8]>;
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`.
1883 ///
1884 /// This function is a lower-level call. It needs to be paired with the
1885 /// [`fill_buf`] method to function properly. This function does
1886 /// not perform any I/O, it simply informs this object that some amount of
1887 /// its buffer, returned from [`fill_buf`], has been consumed and should
1888 /// no longer be returned. As such, this function may do odd things if
1889 /// [`fill_buf`] isn't called before calling it.
1890 ///
1891 /// The `amt` must be `<=` the number of bytes in the buffer returned by
1892 /// [`fill_buf`].
1893 ///
1894 /// # Examples
1895 ///
1896 /// Since `consume()` is meant to be used with [`fill_buf`],
1897 /// that method's example includes an example of `consume()`.
1898 ///
1899 /// [`fill_buf`]: BufRead::fill_buf
1900 #[stable(feature = "rust1", since = "1.0.0")]
1901 fn consume(&mut self, amt: usize);
1902
1903 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
1904 ///
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`.
1908 ///
1909 /// If successful, this function will return the total number of bytes read.
1910 ///
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 ///
1915 /// # Errors
1916 ///
1917 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1918 /// will otherwise return any errors returned by [`fill_buf`].
1919 ///
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.
1922 ///
1923 /// [`fill_buf`]: BufRead::fill_buf
1924 ///
1925 /// # Examples
1926 ///
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:
1930 ///
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"");
1956 /// ```
1957 #[stable(feature = "rust1", since = "1.0.0")]
1958 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
1959 read_until(self, byte, buf)
1960 }
1961
1962 /// Read all bytes until a newline (the `0xA` byte) is reached, and append
1963 /// them to the provided buffer.
1964 ///
1965 /// This function will read bytes from the underlying stream until the
1966 /// newline delimiter (the `0xA` byte) or EOF is found. Once found, all bytes
1967 /// up to, and including, the delimiter (if found) will be appended to
1968 /// `buf`.
1969 ///
1970 /// If successful, this function will return the total number of bytes read.
1971 ///
1972 /// If this function returns [`Ok(0)`], the stream has reached EOF.
1973 ///
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 ///
1978 /// [`Ok(0)`]: Ok
1979 ///
1980 /// # Errors
1981 ///
1982 /// This function has the same error semantics as [`read_until`] and will
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.
1986 ///
1987 /// [`read_until`]: BufRead::read_until
1988 ///
1989 /// # Examples
1990 ///
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:
1993 ///
1994 /// ```
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, "");
2019 /// ```
2020 #[stable(feature = "rust1", since = "1.0.0")]
2021 fn read_line(&mut self, buf: &mut String) -> Result<usize> {
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))
2026 }
2027
2028 /// Returns an iterator over the contents of this reader split on the byte
2029 /// `byte`.
2030 ///
2031 /// The iterator returned from this function will return instances of
2032 /// [`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
2033 /// the delimiter byte at the end.
2034 ///
2035 /// This function will yield errors whenever [`read_until`] would have
2036 /// also yielded an error.
2037 ///
2038 /// [`io::Result`]: self::Result
2039 /// [`read_until`]: BufRead::read_until
2040 ///
2041 /// # Examples
2042 ///
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
2046 ///
2047 /// ```
2048 /// use std::io::{self, BufRead};
2049 ///
2050 /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
2051 ///
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);
2057 /// ```
2058 #[stable(feature = "rust1", since = "1.0.0")]
2059 fn split(self, byte: u8) -> Split<Self>
2060 where
2061 Self: Sized,
2062 {
2063 Split { buf: self, delim: byte }
2064 }
2065
2066 /// Returns an iterator over the lines of this reader.
2067 ///
2068 /// The iterator returned from this function will yield instances of
2069 /// [`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline
2070 /// byte (the `0xA` byte) or `CRLF` (`0xD`, `0xA` bytes) at the end.
2071 ///
2072 /// [`io::Result`]: self::Result
2073 ///
2074 /// # Examples
2075 ///
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 ///
2080 /// ```
2081 /// use std::io::{self, BufRead};
2082 ///
2083 /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
2084 ///
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);
2090 /// ```
2091 ///
2092 /// # Errors
2093 ///
2094 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
2095 #[stable(feature = "rust1", since = "1.0.0")]
2096 fn lines(self) -> Lines<Self>
2097 where
2098 Self: Sized,
2099 {
2100 Lines { buf: self }
2101 }
2102 }
2103
2104 /// Adaptor to chain together two readers.
2105 ///
2106 /// This struct is generally created by calling [`chain`] on a reader.
2107 /// Please see the documentation of [`chain`] for more details.
2108 ///
2109 /// [`chain`]: Read::chain
2110 #[stable(feature = "rust1", since = "1.0.0")]
2111 pub struct Chain<T, U> {
2112 first: T,
2113 second: U,
2114 done_first: bool,
2115 }
2116
2117 impl<T, U> Chain<T, U> {
2118 /// Consumes the `Chain`, returning the wrapped readers.
2119 ///
2120 /// # Examples
2121 ///
2122 /// ```no_run
2123 /// use std::io;
2124 /// use std::io::prelude::*;
2125 /// use std::fs::File;
2126 ///
2127 /// fn main() -> io::Result<()> {
2128 /// let mut foo_file = File::open("foo.txt")?;
2129 /// let mut bar_file = File::open("bar.txt")?;
2130 ///
2131 /// let chain = foo_file.chain(bar_file);
2132 /// let (foo_file, bar_file) = chain.into_inner();
2133 /// Ok(())
2134 /// }
2135 /// ```
2136 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
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 ///
2145 /// ```no_run
2146 /// use std::io;
2147 /// use std::io::prelude::*;
2148 /// use std::fs::File;
2149 ///
2150 /// fn main() -> io::Result<()> {
2151 /// let mut foo_file = File::open("foo.txt")?;
2152 /// let mut bar_file = File::open("bar.txt")?;
2153 ///
2154 /// let chain = foo_file.chain(bar_file);
2155 /// let (foo_file, bar_file) = chain.get_ref();
2156 /// Ok(())
2157 /// }
2158 /// ```
2159 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
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 ///
2172 /// ```no_run
2173 /// use std::io;
2174 /// use std::io::prelude::*;
2175 /// use std::fs::File;
2176 ///
2177 /// fn main() -> io::Result<()> {
2178 /// let mut foo_file = File::open("foo.txt")?;
2179 /// let mut bar_file = File::open("bar.txt")?;
2180 ///
2181 /// let mut chain = foo_file.chain(bar_file);
2182 /// let (foo_file, bar_file) = chain.get_mut();
2183 /// Ok(())
2184 /// }
2185 /// ```
2186 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2187 pub fn get_mut(&mut self) -> (&mut T, &mut U) {
2188 (&mut self.first, &mut self.second)
2189 }
2190 }
2191
2192 #[stable(feature = "std_debug", since = "1.16.0")]
2193 impl<T: fmt::Debug, U: fmt::Debug> fmt::Debug for Chain<T, U> {
2194 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2195 f.debug_struct("Chain").field("t", &self.first).field("u", &self.second).finish()
2196 }
2197 }
2198
2199 #[stable(feature = "rust1", since = "1.0.0")]
2200 impl<T: Read, U: Read> Read for Chain<T, U> {
2201 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2202 if !self.done_first {
2203 match self.first.read(buf)? {
2204 0 if !buf.is_empty() => self.done_first = true,
2205 n => return Ok(n),
2206 }
2207 }
2208 self.second.read(buf)
2209 }
2210
2211 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
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
2221 unsafe fn initializer(&self) -> Initializer {
2222 let initializer = self.first.initializer();
2223 if initializer.should_initialize() { initializer } else { self.second.initializer() }
2224 }
2225 }
2226
2227 #[stable(feature = "chain_bufread", since = "1.9.0")]
2228 impl<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()? {
2232 buf if buf.is_empty() => {
2233 self.done_first = true;
2234 }
2235 buf => return Ok(buf),
2236 }
2237 }
2238 self.second.fill_buf()
2239 }
2240
2241 fn consume(&mut self, amt: usize) {
2242 if !self.done_first { self.first.consume(amt) } else { self.second.consume(amt) }
2243 }
2244 }
2245
2246 impl<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
2259 /// Reader adaptor which limits the bytes read from an underlying reader.
2260 ///
2261 /// This struct is generally created by calling [`take`] on a reader.
2262 /// Please see the documentation of [`take`] for more details.
2263 ///
2264 /// [`take`]: Read::take
2265 #[stable(feature = "rust1", since = "1.0.0")]
2266 #[derive(Debug)]
2267 pub struct Take<T> {
2268 inner: T,
2269 limit: u64,
2270 }
2271
2272 impl<T> Take<T> {
2273 /// Returns the number of bytes that can be read before this instance will
2274 /// return EOF.
2275 ///
2276 /// # Note
2277 ///
2278 /// This instance may reach `EOF` after reading fewer bytes than indicated by
2279 /// this method if the underlying [`Read`] instance reaches EOF.
2280 ///
2281 /// # Examples
2282 ///
2283 /// ```no_run
2284 /// use std::io;
2285 /// use std::io::prelude::*;
2286 /// use std::fs::File;
2287 ///
2288 /// fn main() -> io::Result<()> {
2289 /// let f = File::open("foo.txt")?;
2290 ///
2291 /// // read at most five bytes
2292 /// let handle = f.take(5);
2293 ///
2294 /// println!("limit: {}", handle.limit());
2295 /// Ok(())
2296 /// }
2297 /// ```
2298 #[stable(feature = "rust1", since = "1.0.0")]
2299 pub fn limit(&self) -> u64 {
2300 self.limit
2301 }
2302
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 ///
2310 /// ```no_run
2311 /// use std::io;
2312 /// use std::io::prelude::*;
2313 /// use std::fs::File;
2314 ///
2315 /// fn main() -> io::Result<()> {
2316 /// let f = File::open("foo.txt")?;
2317 ///
2318 /// // read at most five bytes
2319 /// let mut handle = f.take(5);
2320 /// handle.set_limit(10);
2321 ///
2322 /// assert_eq!(handle.limit(), 10);
2323 /// Ok(())
2324 /// }
2325 /// ```
2326 #[stable(feature = "take_set_limit", since = "1.27.0")]
2327 pub fn set_limit(&mut self, limit: u64) {
2328 self.limit = limit;
2329 }
2330
2331 /// Consumes the `Take`, returning the wrapped reader.
2332 ///
2333 /// # Examples
2334 ///
2335 /// ```no_run
2336 /// use std::io;
2337 /// use std::io::prelude::*;
2338 /// use std::fs::File;
2339 ///
2340 /// fn main() -> io::Result<()> {
2341 /// let mut file = File::open("foo.txt")?;
2342 ///
2343 /// let mut buffer = [0; 5];
2344 /// let mut handle = file.take(5);
2345 /// handle.read(&mut buffer)?;
2346 ///
2347 /// let file = handle.into_inner();
2348 /// Ok(())
2349 /// }
2350 /// ```
2351 #[stable(feature = "io_take_into_inner", since = "1.15.0")]
2352 pub fn into_inner(self) -> T {
2353 self.inner
2354 }
2355
2356 /// Gets a reference to the underlying reader.
2357 ///
2358 /// # Examples
2359 ///
2360 /// ```no_run
2361 /// use std::io;
2362 /// use std::io::prelude::*;
2363 /// use std::fs::File;
2364 ///
2365 /// fn main() -> io::Result<()> {
2366 /// let mut file = File::open("foo.txt")?;
2367 ///
2368 /// let mut buffer = [0; 5];
2369 /// let mut handle = file.take(5);
2370 /// handle.read(&mut buffer)?;
2371 ///
2372 /// let file = handle.get_ref();
2373 /// Ok(())
2374 /// }
2375 /// ```
2376 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
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 ///
2389 /// ```no_run
2390 /// use std::io;
2391 /// use std::io::prelude::*;
2392 /// use std::fs::File;
2393 ///
2394 /// fn main() -> io::Result<()> {
2395 /// let mut file = File::open("foo.txt")?;
2396 ///
2397 /// let mut buffer = [0; 5];
2398 /// let mut handle = file.take(5);
2399 /// handle.read(&mut buffer)?;
2400 ///
2401 /// let file = handle.get_mut();
2402 /// Ok(())
2403 /// }
2404 /// ```
2405 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2406 pub fn get_mut(&mut self) -> &mut T {
2407 &mut self.inner
2408 }
2409 }
2410
2411 #[stable(feature = "rust1", since = "1.0.0")]
2412 impl<T: Read> Read for Take<T> {
2413 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
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
2419 let max = cmp::min(buf.len() as u64, self.limit) as usize;
2420 let n = self.inner.read(&mut buf[..max])?;
2421 self.limit -= n as u64;
2422 Ok(n)
2423 }
2424
2425 unsafe fn initializer(&self) -> Initializer {
2426 self.inner.initializer()
2427 }
2428
2429 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
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)
2434 }
2435 }
2436
2437 #[stable(feature = "rust1", since = "1.0.0")]
2438 impl<T: BufRead> BufRead for Take<T> {
2439 fn fill_buf(&mut self) -> Result<&[u8]> {
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
2445 let buf = self.inner.fill_buf()?;
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
2458 /// An iterator over `u8` values of a reader.
2459 ///
2460 /// This struct is generally created by calling [`bytes`] on a reader.
2461 /// Please see the documentation of [`bytes`] for more details.
2462 ///
2463 /// [`bytes`]: Read::bytes
2464 #[stable(feature = "rust1", since = "1.0.0")]
2465 #[derive(Debug)]
2466 pub struct Bytes<R> {
2467 inner: R,
2468 }
2469
2470 #[stable(feature = "rust1", since = "1.0.0")]
2471 impl<R: Read> Iterator for Bytes<R> {
2472 type Item = Result<u8>;
2473
2474 fn next(&mut self) -> Option<Result<u8>> {
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 }
2484 }
2485
2486 fn size_hint(&self) -> (usize, Option<usize>) {
2487 SizeHint::size_hint(&self.inner)
2488 }
2489 }
2490
2491 trait 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
2501 impl<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 }
2509 }
2510
2511 /// An iterator over the contents of an instance of `BufRead` split on a
2512 /// particular byte.
2513 ///
2514 /// This struct is generally created by calling [`split`] on a `BufRead`.
2515 /// Please see the documentation of [`split`] for more details.
2516 ///
2517 /// [`split`]: BufRead::split
2518 #[stable(feature = "rust1", since = "1.0.0")]
2519 #[derive(Debug)]
2520 pub struct Split<B> {
2521 buf: B,
2522 delim: u8,
2523 }
2524
2525 #[stable(feature = "rust1", since = "1.0.0")]
2526 impl<B: BufRead> Iterator for Split<B> {
2527 type Item = Result<Vec<u8>>;
2528
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) {
2532 Ok(0) => None,
2533 Ok(_n) => {
2534 if buf[buf.len() - 1] == self.delim {
2535 buf.pop();
2536 }
2537 Some(Ok(buf))
2538 }
2539 Err(e) => Some(Err(e)),
2540 }
2541 }
2542 }
2543
2544 /// An iterator over the lines of an instance of `BufRead`.
2545 ///
2546 /// This struct is generally created by calling [`lines`] on a `BufRead`.
2547 /// Please see the documentation of [`lines`] for more details.
2548 ///
2549 /// [`lines`]: BufRead::lines
2550 #[stable(feature = "rust1", since = "1.0.0")]
2551 #[derive(Debug)]
2552 pub struct Lines<B> {
2553 buf: B,
2554 }
2555
2556 #[stable(feature = "rust1", since = "1.0.0")]
2557 impl<B: BufRead> Iterator for Lines<B> {
2558 type Item = Result<String>;
2559
2560 fn next(&mut self) -> Option<Result<String>> {
2561 let mut buf = String::new();
2562 match self.buf.read_line(&mut buf) {
2563 Ok(0) => None,
2564 Ok(_n) => {
2565 if buf.ends_with('\n') {
2566 buf.pop();
2567 if buf.ends_with('\r') {
2568 buf.pop();
2569 }
2570 }
2571 Some(Ok(buf))
2572 }
2573 Err(e) => Some(Err(e)),
2574 }
2575 }
2576 }