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