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