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