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