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