1 //! Traits, helpers, and type definitions for core I/O functionality.
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.
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
19 //! use std::io::prelude::*;
20 //! use std::fs::File;
22 //! fn main() -> io::Result<()> {
23 //! let mut f = File::open("foo.txt")?;
24 //! let mut buffer = [0; 10];
26 //! // read up to 10 bytes
27 //! let n = f.read(&mut buffer)?;
29 //! println!("The bytes: {:?}", &buffer[..n]);
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!
38 //! ## Seek and BufRead
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
47 //! use std::io::prelude::*;
48 //! use std::io::SeekFrom;
49 //! use std::fs::File;
51 //! fn main() -> io::Result<()> {
52 //! let mut f = File::open("foo.txt")?;
53 //! let mut buffer = [0; 10];
55 //! // skip to the last 10 bytes of the file
56 //! f.seek(SeekFrom::End(-10))?;
58 //! // read up to 10 bytes
59 //! let n = f.read(&mut buffer)?;
61 //! println!("The bytes: {:?}", &buffer[..n]);
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!
69 //! ## BufReader and BufWriter
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.
77 //! For example, [`BufReader`] works with the [`BufRead`] trait to add extra
78 //! methods to any reader:
82 //! use std::io::prelude::*;
83 //! use std::io::BufReader;
84 //! use std::fs::File;
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();
91 //! // read a line into buffer
92 //! reader.read_line(&mut buffer)?;
94 //! println!("{}", buffer);
99 //! [`BufWriter`] doesn't add any new ways of writing; it just buffers every call
100 //! to [`write`][`Write::write`]:
104 //! use std::io::prelude::*;
105 //! use std::io::BufWriter;
106 //! use std::fs::File;
108 //! fn main() -> io::Result<()> {
109 //! let f = File::create("foo.txt")?;
111 //! let mut writer = BufWriter::new(f);
113 //! // write a byte to the buffer
114 //! writer.write(&[42])?;
116 //! } // the buffer is flushed once writer goes out of scope
122 //! ## Standard input and output
124 //! A very common source of input is standard input:
129 //! fn main() -> io::Result<()> {
130 //! let mut input = String::new();
132 //! io::stdin().read_line(&mut input)?;
134 //! println!("You typed: {}", input.trim());
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:
146 //! let mut input = String::new();
148 //! io::stdin().read_line(&mut input).unwrap();
151 //! And a very common source of output is standard output:
155 //! use std::io::prelude::*;
157 //! fn main() -> io::Result<()> {
158 //! io::stdout().write(&[42])?;
163 //! Of course, using [`io::stdout`] directly is less common than something like
166 //! ## Iterator types
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
174 //! use std::io::prelude::*;
175 //! use std::io::BufReader;
176 //! use std::fs::File;
178 //! fn main() -> io::Result<()> {
179 //! let f = File::open("foo.txt")?;
180 //! let reader = BufReader::new(f);
182 //! for line in reader.lines() {
183 //! println!("{}", line?);
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:
198 //! fn main() -> io::Result<()> {
199 //! io::copy(&mut io::stdin(), &mut io::stdout())?;
204 //! [functions-list]: #functions-1
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]:
216 //! fn read_input() -> io::Result<()> {
217 //! let mut input = String::new();
219 //! io::stdin().read_line(&mut input)?;
221 //! println!("You typed: {}", input.trim());
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 `()`.
232 //! ## Platform-specific behavior
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.
241 //! [`File`]: crate::fs::File
242 //! [`TcpStream`]: crate::net::TcpStream
243 //! [`Vec<T>`]: crate::vec::Vec
244 //! [`io::stdout`]: stdout
245 //! [`io::Result`]: crate::io::Result
246 //! [`?` operator]: ../../book/appendix-02-operators.html
247 //! [`Result`]: crate::result::Result
248 //! [`.unwrap()`]: crate::result::Result::unwrap
250 #![stable(feature = "rust1", since = "1.0.0")]
255 use crate::ops::{Deref, DerefMut};
261 #[stable(feature = "rust1", since = "1.0.0")]
262 pub use self::buffered::IntoInnerError;
263 #[stable(feature = "rust1", since = "1.0.0")]
264 pub use self::buffered::{BufReader, BufWriter, LineWriter};
265 #[stable(feature = "rust1", since = "1.0.0")]
266 pub use self::cursor::Cursor;
267 #[stable(feature = "rust1", since = "1.0.0")]
268 pub use self::error::{Error, ErrorKind, Result};
269 #[stable(feature = "rust1", since = "1.0.0")]
270 pub use self::stdio::{stderr, stdin, stdout, Stderr, Stdin, Stdout};
271 #[stable(feature = "rust1", since = "1.0.0")]
272 pub use self::stdio::{StderrLock, StdinLock, StdoutLock};
273 #[unstable(feature = "print_internals", issue = "none")]
274 pub use self::stdio::{_eprint, _print};
275 #[unstable(feature = "libstd_io_internals", issue = "42788")]
276 #[doc(no_inline, hidden)]
277 pub use self::stdio::{set_panic, set_print};
278 #[stable(feature = "rust1", since = "1.0.0")]
279 pub use self::util::{copy, empty, repeat, sink, Empty, Repeat, Sink};
290 const DEFAULT_BUF_SIZE: usize = crate::sys_common::io::DEFAULT_BUF_SIZE;
293 buf: &'a mut Vec<u8>,
297 impl Drop for Guard<'_> {
300 self.buf.set_len(self.len);
305 // A few methods below (read_to_string, read_line) will append data into a
306 // `String` buffer, but we need to be pretty careful when doing this. The
307 // implementation will just call `.as_mut_vec()` and then delegate to a
308 // byte-oriented reading method, but we must ensure that when returning we never
309 // leave `buf` in a state such that it contains invalid UTF-8 in its bounds.
311 // To this end, we use an RAII guard (to protect against panics) which updates
312 // the length of the string when it is dropped. This guard initially truncates
313 // the string to the prior length and only after we've validated that the
314 // new contents are valid UTF-8 do we allow it to set a longer length.
316 // The unsafety in this function is twofold:
318 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
320 // 2. We're passing a raw buffer to the function `f`, and it is expected that
321 // the function only *appends* bytes to the buffer. We'll get undefined
322 // behavior if existing bytes are overwritten to have non-UTF-8 data.
323 fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
325 F: FnOnce(&mut Vec<u8>) -> Result<usize>,
328 let mut g = Guard { len: buf.len(), buf: buf.as_mut_vec() };
330 if str::from_utf8(&g.buf[g.len..]).is_err() {
332 Err(Error::new(ErrorKind::InvalidData, "stream did not contain valid UTF-8"))
341 // This uses an adaptive system to extend the vector when it fills. We want to
342 // avoid paying to allocate and zero a huge chunk of memory if the reader only
343 // has 4 bytes while still making large reads if the reader does have a ton
344 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
345 // time is 4,500 times (!) slower than a default reservation size of 32 if the
346 // reader has a very small amount of data to return.
348 // Because we're extending the buffer with uninitialized data for trusted
349 // readers, we need to make sure to truncate that if any of this panics.
350 fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
351 read_to_end_with_reservation(r, buf, |_| 32)
354 fn read_to_end_with_reservation<R, F>(
357 mut reservation_size: F,
361 F: FnMut(&R) -> usize,
363 let start_len = buf.len();
364 let mut g = Guard { len: buf.len(), buf };
367 if g.len == g.buf.len() {
369 // FIXME(danielhenrymantilla): #42788
371 // - This creates a (mut) reference to a slice of
372 // _uninitialized_ integers, which is **undefined behavior**
374 // - Only the standard library gets to soundly "ignore" this,
375 // based on its privileged knowledge of unstable rustc
377 g.buf.reserve(reservation_size(r));
378 let capacity = g.buf.capacity();
379 g.buf.set_len(capacity);
380 r.initializer().initialize(&mut g.buf[g.len..]);
384 match r.read(&mut g.buf[g.len..]) {
386 ret = Ok(g.len - start_len);
390 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
401 pub(crate) fn default_read_vectored<F>(read: F, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
403 F: FnOnce(&mut [u8]) -> Result<usize>,
405 let buf = bufs.iter_mut().find(|b| !b.is_empty()).map_or(&mut [][..], |b| &mut **b);
409 pub(crate) fn default_write_vectored<F>(write: F, bufs: &[IoSlice<'_>]) -> Result<usize>
411 F: FnOnce(&[u8]) -> Result<usize>,
413 let buf = bufs.iter().find(|b| !b.is_empty()).map_or(&[][..], |b| &**b);
417 /// The `Read` trait allows for reading bytes from a source.
419 /// Implementors of the `Read` trait are called 'readers'.
421 /// Readers are defined by one required method, [`read()`]. Each call to [`read()`]
422 /// will attempt to pull bytes from this source into a provided buffer. A
423 /// number of other methods are implemented in terms of [`read()`], giving
424 /// implementors a number of ways to read bytes while only needing to implement
427 /// Readers are intended to be composable with one another. Many implementors
428 /// throughout [`std::io`] take and provide types which implement the `Read`
431 /// Please note that each call to [`read()`] may involve a system call, and
432 /// therefore, using something that implements [`BufRead`], such as
433 /// [`BufReader`], will be more efficient.
437 /// [`File`]s implement `Read`:
441 /// use std::io::prelude::*;
442 /// use std::fs::File;
444 /// fn main() -> io::Result<()> {
445 /// let mut f = File::open("foo.txt")?;
446 /// let mut buffer = [0; 10];
448 /// // read up to 10 bytes
449 /// f.read(&mut buffer)?;
451 /// let mut buffer = Vec::new();
452 /// // read the whole file
453 /// f.read_to_end(&mut buffer)?;
455 /// // read into a String, so that you don't need to do the conversion.
456 /// let mut buffer = String::new();
457 /// f.read_to_string(&mut buffer)?;
459 /// // and more! See the other methods for more details.
464 /// Read from [`&str`] because [`&[u8]`][slice] implements `Read`:
468 /// use std::io::prelude::*;
470 /// fn main() -> io::Result<()> {
471 /// let mut b = "This string will be read".as_bytes();
472 /// let mut buffer = [0; 10];
474 /// // read up to 10 bytes
475 /// b.read(&mut buffer)?;
477 /// // etc... it works exactly as a File does!
482 /// [`read()`]: Read::read
484 /// [`std::io`]: self
485 /// [`File`]: crate::fs::File
486 /// [slice]: ../../std/primitive.slice.html
487 #[stable(feature = "rust1", since = "1.0.0")]
490 /// Pull some bytes from this source into the specified buffer, returning
491 /// how many bytes were read.
493 /// This function does not provide any guarantees about whether it blocks
494 /// waiting for data, but if an object needs to block for a read and cannot,
495 /// it will typically signal this via an [`Err`] return value.
497 /// If the return value of this method is [`Ok(n)`], then it must be
498 /// guaranteed that `0 <= n <= buf.len()`. A nonzero `n` value indicates
499 /// that the buffer `buf` has been filled in with `n` bytes of data from this
500 /// source. If `n` is `0`, then it can indicate one of two scenarios:
502 /// 1. This reader has reached its "end of file" and will likely no longer
503 /// be able to produce bytes. Note that this does not mean that the
504 /// reader will *always* no longer be able to produce bytes.
505 /// 2. The buffer specified was 0 bytes in length.
507 /// It is not an error if the returned value `n` is smaller than the buffer size,
508 /// even when the reader is not at the end of the stream yet.
509 /// This may happen for example because fewer bytes are actually available right now
510 /// (e. g. being close to end-of-file) or because read() was interrupted by a signal.
512 /// No guarantees are provided about the contents of `buf` when this
513 /// function is called, implementations cannot rely on any property of the
514 /// contents of `buf` being true. It is recommended that *implementations*
515 /// only write data to `buf` instead of reading its contents.
517 /// Correspondingly, however, *callers* of this method may not assume any guarantees
518 /// about how the implementation uses `buf`. The trait is safe to implement,
519 /// so it is possible that the code that's supposed to write to the buffer might also read
520 /// from it. It is your responsibility to make sure that `buf` is initialized
521 /// before calling `read`. Calling `read` with an uninitialized `buf` (of the kind one
522 /// obtains via [`MaybeUninit<T>`]) is not safe, and can lead to undefined behavior.
524 /// [`MaybeUninit<T>`]: crate::mem::MaybeUninit
528 /// If this function encounters any form of I/O or other error, an error
529 /// variant will be returned. If an error is returned then it must be
530 /// guaranteed that no bytes were read.
532 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
533 /// operation should be retried if there is nothing else to do.
537 /// [`File`]s implement `Read`:
540 /// [`File`]: crate::fs::File
544 /// use std::io::prelude::*;
545 /// use std::fs::File;
547 /// fn main() -> io::Result<()> {
548 /// let mut f = File::open("foo.txt")?;
549 /// let mut buffer = [0; 10];
551 /// // read up to 10 bytes
552 /// let n = f.read(&mut buffer[..])?;
554 /// println!("The bytes: {:?}", &buffer[..n]);
558 #[stable(feature = "rust1", since = "1.0.0")]
559 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
561 /// Like `read`, except that it reads into a slice of buffers.
563 /// Data is copied to fill each buffer in order, with the final buffer
564 /// written to possibly being only partially filled. This method must
565 /// behave equivalently to a single call to `read` with concatenated
568 /// The default implementation calls `read` with either the first nonempty
569 /// buffer provided, or an empty one if none exists.
570 #[stable(feature = "iovec", since = "1.36.0")]
571 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
572 default_read_vectored(|b| self.read(b), bufs)
575 /// Determines if this `Read`er has an efficient `read_vectored`
578 /// If a `Read`er does not override the default `read_vectored`
579 /// implementation, code using it may want to avoid the method all together
580 /// and coalesce writes into a single buffer for higher performance.
582 /// The default implementation returns `false`.
583 #[unstable(feature = "can_vector", issue = "69941")]
584 fn is_read_vectored(&self) -> bool {
588 /// Determines if this `Read`er can work with buffers of uninitialized
591 /// The default implementation returns an initializer which will zero
594 /// If a `Read`er guarantees that it can work properly with uninitialized
595 /// memory, it should call [`Initializer::nop()`]. See the documentation for
596 /// [`Initializer`] for details.
598 /// The behavior of this method must be independent of the state of the
599 /// `Read`er - the method only takes `&self` so that it can be used through
604 /// This method is unsafe because a `Read`er could otherwise return a
605 /// non-zeroing `Initializer` from another `Read` type without an `unsafe`
607 #[unstable(feature = "read_initializer", issue = "42788")]
609 unsafe fn initializer(&self) -> Initializer {
610 Initializer::zeroing()
613 /// Read all bytes until EOF in this source, placing them into `buf`.
615 /// All bytes read from this source will be appended to the specified buffer
616 /// `buf`. This function will continuously call [`read()`] to append more data to
617 /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of
618 /// non-[`ErrorKind::Interrupted`] kind.
620 /// If successful, this function will return the total number of bytes read.
624 /// If this function encounters an error of the kind
625 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
628 /// If any other read error is encountered then this function immediately
629 /// returns. Any bytes which have already been read will be appended to
634 /// [`File`]s implement `Read`:
636 /// [`read()`]: Read::read
638 /// [`File`]: crate::fs::File
642 /// use std::io::prelude::*;
643 /// use std::fs::File;
645 /// fn main() -> io::Result<()> {
646 /// let mut f = File::open("foo.txt")?;
647 /// let mut buffer = Vec::new();
649 /// // read the whole file
650 /// f.read_to_end(&mut buffer)?;
655 /// (See also the [`std::fs::read`] convenience function for reading from a
658 /// [`std::fs::read`]: crate::fs::read
659 #[stable(feature = "rust1", since = "1.0.0")]
660 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
661 read_to_end(self, buf)
664 /// Read all bytes until EOF in this source, appending them to `buf`.
666 /// If successful, this function returns the number of bytes which were read
667 /// and appended to `buf`.
671 /// If the data in this stream is *not* valid UTF-8 then an error is
672 /// returned and `buf` is unchanged.
674 /// See [`read_to_end`][readtoend] for other error semantics.
676 /// [readtoend]: Self::read_to_end
680 /// [`File`][file]s implement `Read`:
682 /// [file]: crate::fs::File
686 /// use std::io::prelude::*;
687 /// use std::fs::File;
689 /// fn main() -> io::Result<()> {
690 /// let mut f = File::open("foo.txt")?;
691 /// let mut buffer = String::new();
693 /// f.read_to_string(&mut buffer)?;
698 /// (See also the [`std::fs::read_to_string`] convenience function for
699 /// reading from a file.)
701 /// [`std::fs::read_to_string`]: crate::fs::read_to_string
702 #[stable(feature = "rust1", since = "1.0.0")]
703 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
704 // Note that we do *not* call `.read_to_end()` here. We are passing
705 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
706 // method to fill it up. An arbitrary implementation could overwrite the
707 // entire contents of the vector, not just append to it (which is what
708 // we are expecting).
710 // To prevent extraneously checking the UTF-8-ness of the entire buffer
711 // we pass it to our hardcoded `read_to_end` implementation which we
712 // know is guaranteed to only read data into the end of the buffer.
713 append_to_string(buf, |b| read_to_end(self, b))
716 /// Read the exact number of bytes required to fill `buf`.
718 /// This function reads as many bytes as necessary to completely fill the
719 /// specified buffer `buf`.
721 /// No guarantees are provided about the contents of `buf` when this
722 /// function is called, implementations cannot rely on any property of the
723 /// contents of `buf` being true. It is recommended that implementations
724 /// only write data to `buf` instead of reading its contents. The
725 /// documentation on [`read`] has a more detailed explanation on this
730 /// If this function encounters an error of the kind
731 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
734 /// If this function encounters an "end of file" before completely filling
735 /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
736 /// The contents of `buf` are unspecified in this case.
738 /// If any other read error is encountered then this function immediately
739 /// returns. The contents of `buf` are unspecified in this case.
741 /// If this function returns an error, it is unspecified how many bytes it
742 /// has read, but it will never read more than would be necessary to
743 /// completely fill the buffer.
747 /// [`File`]s implement `Read`:
749 /// [`read`]: Read::read
750 /// [`File`]: crate::fs::File
754 /// use std::io::prelude::*;
755 /// use std::fs::File;
757 /// fn main() -> io::Result<()> {
758 /// let mut f = File::open("foo.txt")?;
759 /// let mut buffer = [0; 10];
761 /// // read exactly 10 bytes
762 /// f.read_exact(&mut buffer)?;
766 #[stable(feature = "read_exact", since = "1.6.0")]
767 fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
768 while !buf.is_empty() {
769 match self.read(buf) {
775 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
776 Err(e) => return Err(e),
780 Err(Error::new(ErrorKind::UnexpectedEof, "failed to fill whole buffer"))
786 /// Creates a "by reference" adaptor for this instance of `Read`.
788 /// The returned adaptor also implements `Read` and will simply borrow this
793 /// [`File`][file]s implement `Read`:
795 /// [file]: crate::fs::File
799 /// use std::io::Read;
800 /// use std::fs::File;
802 /// fn main() -> io::Result<()> {
803 /// let mut f = File::open("foo.txt")?;
804 /// let mut buffer = Vec::new();
805 /// let mut other_buffer = Vec::new();
808 /// let reference = f.by_ref();
810 /// // read at most 5 bytes
811 /// reference.take(5).read_to_end(&mut buffer)?;
813 /// } // drop our &mut reference so we can use f again
815 /// // original file still usable, read the rest
816 /// f.read_to_end(&mut other_buffer)?;
820 #[stable(feature = "rust1", since = "1.0.0")]
821 fn by_ref(&mut self) -> &mut Self
828 /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
830 /// The returned type implements [`Iterator`] where the `Item` is
831 /// [`Result`]`<`[`u8`]`, `[`io::Error`]`>`.
832 /// The yielded item is [`Ok`] if a byte was successfully read and [`Err`]
833 /// otherwise. EOF is mapped to returning [`None`] from this iterator.
837 /// [`File`][file]s implement `Read`:
839 /// [file]: crate::fs::File
840 /// [`Iterator`]: crate::iter::Iterator
841 /// [`Result`]: crate::result::Result
842 /// [`io::Error`]: self::Error
846 /// use std::io::prelude::*;
847 /// use std::fs::File;
849 /// fn main() -> io::Result<()> {
850 /// let mut f = File::open("foo.txt")?;
852 /// for byte in f.bytes() {
853 /// println!("{}", byte.unwrap());
858 #[stable(feature = "rust1", since = "1.0.0")]
859 fn bytes(self) -> Bytes<Self>
863 Bytes { inner: self }
866 /// Creates an adaptor which will chain this stream with another.
868 /// The returned `Read` instance will first read all bytes from this object
869 /// until EOF is encountered. Afterwards the output is equivalent to the
870 /// output of `next`.
874 /// [`File`][file]s implement `Read`:
876 /// [file]: crate::fs::File
880 /// use std::io::prelude::*;
881 /// use std::fs::File;
883 /// fn main() -> io::Result<()> {
884 /// let mut f1 = File::open("foo.txt")?;
885 /// let mut f2 = File::open("bar.txt")?;
887 /// let mut handle = f1.chain(f2);
888 /// let mut buffer = String::new();
890 /// // read the value into a String. We could use any Read method here,
891 /// // this is just one example.
892 /// handle.read_to_string(&mut buffer)?;
896 #[stable(feature = "rust1", since = "1.0.0")]
897 fn chain<R: Read>(self, next: R) -> Chain<Self, R>
901 Chain { first: self, second: next, done_first: false }
904 /// Creates an adaptor which will read at most `limit` bytes from it.
906 /// This function returns a new instance of `Read` which will read at most
907 /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
908 /// read errors will not count towards the number of bytes read and future
909 /// calls to [`read()`] may succeed.
913 /// [`File`]s implement `Read`:
915 /// [`File`]: crate::fs::File
917 /// [`read()`]: Read::read
921 /// use std::io::prelude::*;
922 /// use std::fs::File;
924 /// fn main() -> io::Result<()> {
925 /// let mut f = File::open("foo.txt")?;
926 /// let mut buffer = [0; 5];
928 /// // read at most five bytes
929 /// let mut handle = f.take(5);
931 /// handle.read(&mut buffer)?;
935 #[stable(feature = "rust1", since = "1.0.0")]
936 fn take(self, limit: u64) -> Take<Self>
940 Take { inner: self, limit }
944 /// A buffer type used with `Read::read_vectored`.
946 /// It is semantically a wrapper around an `&mut [u8]`, but is guaranteed to be
947 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
949 #[stable(feature = "iovec", since = "1.36.0")]
951 pub struct IoSliceMut<'a>(sys::io::IoSliceMut<'a>);
953 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
954 unsafe impl<'a> Send for IoSliceMut<'a> {}
956 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
957 unsafe impl<'a> Sync for IoSliceMut<'a> {}
959 #[stable(feature = "iovec", since = "1.36.0")]
960 impl<'a> fmt::Debug for IoSliceMut<'a> {
961 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
962 fmt::Debug::fmt(self.0.as_slice(), fmt)
966 impl<'a> IoSliceMut<'a> {
967 /// Creates a new `IoSliceMut` wrapping a byte slice.
971 /// Panics on Windows if the slice is larger than 4GB.
972 #[stable(feature = "iovec", since = "1.36.0")]
974 pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> {
975 IoSliceMut(sys::io::IoSliceMut::new(buf))
978 /// Advance the internal cursor of the slice.
982 /// Elements in the slice may be modified if the cursor is not advanced to
983 /// the end of the slice. For example if we have a slice of buffers with 2
984 /// `IoSliceMut`s, both of length 8, and we advance the cursor by 10 bytes
985 /// the first `IoSliceMut` will be untouched however the second will be
986 /// modified to remove the first 2 bytes (10 - 8).
991 /// #![feature(io_slice_advance)]
993 /// use std::io::IoSliceMut;
994 /// use std::ops::Deref;
996 /// let mut buf1 = [1; 8];
997 /// let mut buf2 = [2; 16];
998 /// let mut buf3 = [3; 8];
999 /// let mut bufs = &mut [
1000 /// IoSliceMut::new(&mut buf1),
1001 /// IoSliceMut::new(&mut buf2),
1002 /// IoSliceMut::new(&mut buf3),
1005 /// // Mark 10 bytes as read.
1006 /// bufs = IoSliceMut::advance(bufs, 10);
1007 /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1008 /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1010 #[unstable(feature = "io_slice_advance", issue = "62726")]
1012 pub fn advance<'b>(bufs: &'b mut [IoSliceMut<'a>], n: usize) -> &'b mut [IoSliceMut<'a>] {
1013 // Number of buffers to remove.
1015 // Total length of all the to be removed buffers.
1016 let mut accumulated_len = 0;
1017 for buf in bufs.iter() {
1018 if accumulated_len + buf.len() > n {
1021 accumulated_len += buf.len();
1026 let bufs = &mut bufs[remove..];
1027 if !bufs.is_empty() {
1028 bufs[0].0.advance(n - accumulated_len)
1034 #[stable(feature = "iovec", since = "1.36.0")]
1035 impl<'a> Deref for IoSliceMut<'a> {
1039 fn deref(&self) -> &[u8] {
1044 #[stable(feature = "iovec", since = "1.36.0")]
1045 impl<'a> DerefMut for IoSliceMut<'a> {
1047 fn deref_mut(&mut self) -> &mut [u8] {
1048 self.0.as_mut_slice()
1052 /// A buffer type used with `Write::write_vectored`.
1054 /// It is semantically a wrapper around an `&[u8]`, but is guaranteed to be
1055 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
1057 #[stable(feature = "iovec", since = "1.36.0")]
1058 #[derive(Copy, Clone)]
1059 #[repr(transparent)]
1060 pub struct IoSlice<'a>(sys::io::IoSlice<'a>);
1062 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1063 unsafe impl<'a> Send for IoSlice<'a> {}
1065 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1066 unsafe impl<'a> Sync for IoSlice<'a> {}
1068 #[stable(feature = "iovec", since = "1.36.0")]
1069 impl<'a> fmt::Debug for IoSlice<'a> {
1070 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1071 fmt::Debug::fmt(self.0.as_slice(), fmt)
1075 impl<'a> IoSlice<'a> {
1076 /// Creates a new `IoSlice` wrapping a byte slice.
1080 /// Panics on Windows if the slice is larger than 4GB.
1081 #[stable(feature = "iovec", since = "1.36.0")]
1083 pub fn new(buf: &'a [u8]) -> IoSlice<'a> {
1084 IoSlice(sys::io::IoSlice::new(buf))
1087 /// Advance the internal cursor of the slice.
1091 /// Elements in the slice may be modified if the cursor is not advanced to
1092 /// the end of the slice. For example if we have a slice of buffers with 2
1093 /// `IoSlice`s, both of length 8, and we advance the cursor by 10 bytes the
1094 /// first `IoSlice` will be untouched however the second will be modified to
1095 /// remove the first 2 bytes (10 - 8).
1100 /// #![feature(io_slice_advance)]
1102 /// use std::io::IoSlice;
1103 /// use std::ops::Deref;
1105 /// let buf1 = [1; 8];
1106 /// let buf2 = [2; 16];
1107 /// let buf3 = [3; 8];
1108 /// let mut bufs = &mut [
1109 /// IoSlice::new(&buf1),
1110 /// IoSlice::new(&buf2),
1111 /// IoSlice::new(&buf3),
1114 /// // Mark 10 bytes as written.
1115 /// bufs = IoSlice::advance(bufs, 10);
1116 /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1117 /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1118 #[unstable(feature = "io_slice_advance", issue = "62726")]
1120 pub fn advance<'b>(bufs: &'b mut [IoSlice<'a>], n: usize) -> &'b mut [IoSlice<'a>] {
1121 // Number of buffers to remove.
1123 // Total length of all the to be removed buffers.
1124 let mut accumulated_len = 0;
1125 for buf in bufs.iter() {
1126 if accumulated_len + buf.len() > n {
1129 accumulated_len += buf.len();
1134 let bufs = &mut bufs[remove..];
1135 if !bufs.is_empty() {
1136 bufs[0].0.advance(n - accumulated_len)
1142 #[stable(feature = "iovec", since = "1.36.0")]
1143 impl<'a> Deref for IoSlice<'a> {
1147 fn deref(&self) -> &[u8] {
1152 /// A type used to conditionally initialize buffers passed to `Read` methods.
1153 #[unstable(feature = "read_initializer", issue = "42788")]
1155 pub struct Initializer(bool);
1158 /// Returns a new `Initializer` which will zero out buffers.
1159 #[unstable(feature = "read_initializer", issue = "42788")]
1161 pub fn zeroing() -> Initializer {
1165 /// Returns a new `Initializer` which will not zero out buffers.
1169 /// This may only be called by `Read`ers which guarantee that they will not
1170 /// read from buffers passed to `Read` methods, and that the return value of
1171 /// the method accurately reflects the number of bytes that have been
1172 /// written to the head of the buffer.
1173 #[unstable(feature = "read_initializer", issue = "42788")]
1175 pub unsafe fn nop() -> Initializer {
1179 /// Indicates if a buffer should be initialized.
1180 #[unstable(feature = "read_initializer", issue = "42788")]
1182 pub fn should_initialize(&self) -> bool {
1186 /// Initializes a buffer if necessary.
1187 #[unstable(feature = "read_initializer", issue = "42788")]
1189 pub fn initialize(&self, buf: &mut [u8]) {
1190 if self.should_initialize() {
1191 unsafe { ptr::write_bytes(buf.as_mut_ptr(), 0, buf.len()) }
1196 /// A trait for objects which are byte-oriented sinks.
1198 /// Implementors of the `Write` trait are sometimes called 'writers'.
1200 /// Writers are defined by two required methods, [`write`] and [`flush`]:
1202 /// * The [`write`] method will attempt to write some data into the object,
1203 /// returning how many bytes were successfully written.
1205 /// * The [`flush`] method is useful for adaptors and explicit buffers
1206 /// themselves for ensuring that all buffered data has been pushed out to the
1209 /// Writers are intended to be composable with one another. Many implementors
1210 /// throughout [`std::io`] take and provide types which implement the `Write`
1213 /// [`write`]: Self::write
1214 /// [`flush`]: Self::flush
1215 /// [`std::io`]: index.html
1220 /// use std::io::prelude::*;
1221 /// use std::fs::File;
1223 /// fn main() -> std::io::Result<()> {
1224 /// let data = b"some bytes";
1226 /// let mut pos = 0;
1227 /// let mut buffer = File::create("foo.txt")?;
1229 /// while pos < data.len() {
1230 /// let bytes_written = buffer.write(&data[pos..])?;
1231 /// pos += bytes_written;
1237 /// The trait also provides convenience methods like [`write_all`], which calls
1238 /// `write` in a loop until its entire input has been written.
1240 /// [`write_all`]: Self::write_all
1241 #[stable(feature = "rust1", since = "1.0.0")]
1244 /// Write a buffer into this writer, returning how many bytes were written.
1246 /// This function will attempt to write the entire contents of `buf`, but
1247 /// the entire write may not succeed, or the write may also generate an
1248 /// error. A call to `write` represents *at most one* attempt to write to
1249 /// any wrapped object.
1251 /// Calls to `write` are not guaranteed to block waiting for data to be
1252 /// written, and a write which would otherwise block can be indicated through
1253 /// an [`Err`] variant.
1255 /// If the return value is [`Ok(n)`] then it must be guaranteed that
1256 /// `n <= buf.len()`. A return value of `0` typically means that the
1257 /// underlying object is no longer able to accept bytes and will likely not
1258 /// be able to in the future as well, or that the buffer provided is empty.
1262 /// Each call to `write` may generate an I/O error indicating that the
1263 /// operation could not be completed. If an error is returned then no bytes
1264 /// in the buffer were written to this writer.
1266 /// It is **not** considered an error if the entire buffer could not be
1267 /// written to this writer.
1269 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the
1270 /// write operation should be retried if there is nothing else to do.
1275 /// use std::io::prelude::*;
1276 /// use std::fs::File;
1278 /// fn main() -> std::io::Result<()> {
1279 /// let mut buffer = File::create("foo.txt")?;
1281 /// // Writes some prefix of the byte string, not necessarily all of it.
1282 /// buffer.write(b"some bytes")?;
1286 #[stable(feature = "rust1", since = "1.0.0")]
1287 fn write(&mut self, buf: &[u8]) -> Result<usize>;
1289 /// Like `write`, except that it writes from a slice of buffers.
1291 /// Data is copied from each buffer in order, with the final buffer
1292 /// read from possibly being only partially consumed. This method must
1293 /// behave as a call to `write` with the buffers concatenated would.
1295 /// The default implementation calls `write` with either the first nonempty
1296 /// buffer provided, or an empty one if none exists.
1297 #[stable(feature = "iovec", since = "1.36.0")]
1298 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize> {
1299 default_write_vectored(|b| self.write(b), bufs)
1302 /// Determines if this `Write`er has an efficient `write_vectored`
1305 /// If a `Write`er does not override the default `write_vectored`
1306 /// implementation, code using it may want to avoid the method all together
1307 /// and coalesce writes into a single buffer for higher performance.
1309 /// The default implementation returns `false`.
1310 #[unstable(feature = "can_vector", issue = "69941")]
1311 fn is_write_vectored(&self) -> bool {
1315 /// Flush this output stream, ensuring that all intermediately buffered
1316 /// contents reach their destination.
1320 /// It is considered an error if not all bytes could be written due to
1321 /// I/O errors or EOF being reached.
1326 /// use std::io::prelude::*;
1327 /// use std::io::BufWriter;
1328 /// use std::fs::File;
1330 /// fn main() -> std::io::Result<()> {
1331 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
1333 /// buffer.write_all(b"some bytes")?;
1334 /// buffer.flush()?;
1338 #[stable(feature = "rust1", since = "1.0.0")]
1339 fn flush(&mut self) -> Result<()>;
1341 /// Attempts to write an entire buffer into this writer.
1343 /// This method will continuously call [`write`] until there is no more data
1344 /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is
1345 /// returned. This method will not return until the entire buffer has been
1346 /// successfully written or such an error occurs. The first error that is
1347 /// not of [`ErrorKind::Interrupted`] kind generated from this method will be
1350 /// If the buffer contains no data, this will never call [`write`].
1354 /// This function will return the first error of
1355 /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns.
1357 /// [`write`]: Self::write
1362 /// use std::io::prelude::*;
1363 /// use std::fs::File;
1365 /// fn main() -> std::io::Result<()> {
1366 /// let mut buffer = File::create("foo.txt")?;
1368 /// buffer.write_all(b"some bytes")?;
1372 #[stable(feature = "rust1", since = "1.0.0")]
1373 fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
1374 while !buf.is_empty() {
1375 match self.write(buf) {
1377 return Err(Error::new(ErrorKind::WriteZero, "failed to write whole buffer"));
1379 Ok(n) => buf = &buf[n..],
1380 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1381 Err(e) => return Err(e),
1387 /// Attempts to write multiple buffers into this writer.
1389 /// This method will continuously call [`write_vectored`] until there is no
1390 /// more data to be written or an error of non-[`ErrorKind::Interrupted`]
1391 /// kind is returned. This method will not return until all buffers have
1392 /// been successfully written or such an error occurs. The first error that
1393 /// is not of [`ErrorKind::Interrupted`] kind generated from this method
1394 /// will be returned.
1396 /// If the buffer contains no data, this will never call [`write_vectored`].
1398 /// [`write_vectored`]: Self::write_vectored
1403 /// Unlike `io::Write::write_vectored`, this takes a *mutable* reference to
1404 /// a slice of `IoSlice`s, not an immutable one. That's because we need to
1405 /// modify the slice to keep track of the bytes already written.
1407 /// Once this function returns, the contents of `bufs` are unspecified, as
1408 /// this depends on how many calls to `write_vectored` were necessary. It is
1409 /// best to understand this function as taking ownership of `bufs` and to
1410 /// not use `bufs` afterwards. The underlying buffers, to which the
1411 /// `IoSlice`s point (but not the `IoSlice`s themselves), are unchanged and
1417 /// #![feature(write_all_vectored)]
1418 /// # fn main() -> std::io::Result<()> {
1420 /// use std::io::{Write, IoSlice};
1422 /// let mut writer = Vec::new();
1423 /// let bufs = &mut [
1424 /// IoSlice::new(&[1]),
1425 /// IoSlice::new(&[2, 3]),
1426 /// IoSlice::new(&[4, 5, 6]),
1429 /// writer.write_all_vectored(bufs)?;
1430 /// // Note: the contents of `bufs` is now undefined, see the Notes section.
1432 /// assert_eq!(writer, &[1, 2, 3, 4, 5, 6]);
1435 #[unstable(feature = "write_all_vectored", issue = "70436")]
1436 fn write_all_vectored(&mut self, mut bufs: &mut [IoSlice<'_>]) -> Result<()> {
1437 // Guarantee that bufs is empty if it contains no data,
1438 // to avoid calling write_vectored if there is no data to be written.
1439 bufs = IoSlice::advance(bufs, 0);
1440 while !bufs.is_empty() {
1441 match self.write_vectored(bufs) {
1443 return Err(Error::new(ErrorKind::WriteZero, "failed to write whole buffer"));
1445 Ok(n) => bufs = IoSlice::advance(bufs, n),
1446 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1447 Err(e) => return Err(e),
1453 /// Writes a formatted string into this writer, returning any error
1456 /// This method is primarily used to interface with the
1457 /// [`format_args!()`] macro, but it is rare that this should
1458 /// explicitly be called. The [`write!()`] macro should be favored to
1459 /// invoke this method instead.
1461 /// This function internally uses the [`write_all`][writeall] method on
1462 /// this trait and hence will continuously write data so long as no errors
1463 /// are received. This also means that partial writes are not indicated in
1466 /// [writeall]: Self::write_all
1470 /// This function will return any I/O error reported while formatting.
1475 /// use std::io::prelude::*;
1476 /// use std::fs::File;
1478 /// fn main() -> std::io::Result<()> {
1479 /// let mut buffer = File::create("foo.txt")?;
1482 /// write!(buffer, "{:.*}", 2, 1.234567)?;
1483 /// // turns into this:
1484 /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1488 #[stable(feature = "rust1", since = "1.0.0")]
1489 fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> Result<()> {
1490 // Create a shim which translates a Write to a fmt::Write and saves
1491 // off I/O errors. instead of discarding them
1492 struct Adaptor<'a, T: ?Sized + 'a> {
1497 impl<T: Write + ?Sized> fmt::Write for Adaptor<'_, T> {
1498 fn write_str(&mut self, s: &str) -> fmt::Result {
1499 match self.inner.write_all(s.as_bytes()) {
1502 self.error = Err(e);
1509 let mut output = Adaptor { inner: self, error: Ok(()) };
1510 match fmt::write(&mut output, fmt) {
1513 // check if the error came from the underlying `Write` or not
1514 if output.error.is_err() {
1517 Err(Error::new(ErrorKind::Other, "formatter error"))
1523 /// Creates a "by reference" adaptor for this instance of `Write`.
1525 /// The returned adaptor also implements `Write` and will simply borrow this
1531 /// use std::io::Write;
1532 /// use std::fs::File;
1534 /// fn main() -> std::io::Result<()> {
1535 /// let mut buffer = File::create("foo.txt")?;
1537 /// let reference = buffer.by_ref();
1539 /// // we can use reference just like our original buffer
1540 /// reference.write_all(b"some bytes")?;
1544 #[stable(feature = "rust1", since = "1.0.0")]
1545 fn by_ref(&mut self) -> &mut Self
1553 /// The `Seek` trait provides a cursor which can be moved within a stream of
1556 /// The stream typically has a fixed size, allowing seeking relative to either
1557 /// end or the current offset.
1561 /// [`File`][file]s implement `Seek`:
1563 /// [file]: crate::fs::File
1567 /// use std::io::prelude::*;
1568 /// use std::fs::File;
1569 /// use std::io::SeekFrom;
1571 /// fn main() -> io::Result<()> {
1572 /// let mut f = File::open("foo.txt")?;
1574 /// // move the cursor 42 bytes from the start of the file
1575 /// f.seek(SeekFrom::Start(42))?;
1579 #[stable(feature = "rust1", since = "1.0.0")]
1581 /// Seek to an offset, in bytes, in a stream.
1583 /// A seek beyond the end of a stream is allowed, but behavior is defined
1584 /// by the implementation.
1586 /// If the seek operation completed successfully,
1587 /// this method returns the new position from the start of the stream.
1588 /// That position can be used later with [`SeekFrom::Start`].
1592 /// Seeking to a negative offset is considered an error.
1594 /// [`SeekFrom::Start`]: enum.SeekFrom.html#variant.Start
1595 #[stable(feature = "rust1", since = "1.0.0")]
1596 fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1598 /// Returns the length of this stream (in bytes).
1600 /// This method is implemented using up to three seek operations. If this
1601 /// method returns successfully, the seek position is unchanged (i.e. the
1602 /// position before calling this method is the same as afterwards).
1603 /// However, if this method returns an error, the seek position is
1606 /// If you need to obtain the length of *many* streams and you don't care
1607 /// about the seek position afterwards, you can reduce the number of seek
1608 /// operations by simply calling `seek(SeekFrom::End(0))` and using its
1609 /// return value (it is also the stream length).
1611 /// Note that length of a stream can change over time (for example, when
1612 /// data is appended to a file). So calling this method multiple times does
1613 /// not necessarily return the same length each time.
1619 /// #![feature(seek_convenience)]
1621 /// io::{self, Seek},
1625 /// fn main() -> io::Result<()> {
1626 /// let mut f = File::open("foo.txt")?;
1628 /// let len = f.stream_len()?;
1629 /// println!("The file is currently {} bytes long", len);
1633 #[unstable(feature = "seek_convenience", issue = "59359")]
1634 fn stream_len(&mut self) -> Result<u64> {
1635 let old_pos = self.stream_position()?;
1636 let len = self.seek(SeekFrom::End(0))?;
1638 // Avoid seeking a third time when we were already at the end of the
1639 // stream. The branch is usually way cheaper than a seek operation.
1641 self.seek(SeekFrom::Start(old_pos))?;
1647 /// Returns the current seek position from the start of the stream.
1649 /// This is equivalent to `self.seek(SeekFrom::Current(0))`.
1655 /// #![feature(seek_convenience)]
1657 /// io::{self, BufRead, BufReader, Seek},
1661 /// fn main() -> io::Result<()> {
1662 /// let mut f = BufReader::new(File::open("foo.txt")?);
1664 /// let before = f.stream_position()?;
1665 /// f.read_line(&mut String::new())?;
1666 /// let after = f.stream_position()?;
1668 /// println!("The first line was {} bytes long", after - before);
1672 #[unstable(feature = "seek_convenience", issue = "59359")]
1673 fn stream_position(&mut self) -> Result<u64> {
1674 self.seek(SeekFrom::Current(0))
1678 /// Enumeration of possible methods to seek within an I/O object.
1680 /// It is used by the [`Seek`] trait.
1682 /// [`Seek`]: trait.Seek.html
1683 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1684 #[stable(feature = "rust1", since = "1.0.0")]
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),
1690 /// Sets the offset to the size of this object plus the specified number of
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),
1698 /// Sets the offset to the current position plus the specified number of
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),
1707 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>) -> Result<usize> {
1710 let (done, used) = {
1711 let available = match r.fill_buf() {
1713 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1714 Err(e) => return Err(e),
1716 match memchr::memchr(delim, available) {
1718 buf.extend_from_slice(&available[..=i]);
1722 buf.extend_from_slice(available);
1723 (false, available.len())
1729 if done || used == 0 {
1735 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1736 /// to perform extra ways of reading.
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.
1744 /// A locked standard input implements `BufRead`:
1748 /// use std::io::prelude::*;
1750 /// let stdin = io::stdin();
1751 /// for line in stdin.lock().lines() {
1752 /// println!("{}", line.unwrap());
1756 /// If you have something that implements [`Read`], you can use the [`BufReader`
1757 /// type][`BufReader`] to turn it into a `BufRead`.
1759 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1760 /// [`BufReader`] to the rescue!
1762 /// [`BufReader`]: struct.BufReader.html
1763 /// [`File`]: crate::fs::File
1764 /// [`read_line`]: Self::read_line
1765 /// [`lines`]: Self::lines
1766 /// [`Read`]: trait.Read.html
1769 /// use std::io::{self, BufReader};
1770 /// use std::io::prelude::*;
1771 /// use std::fs::File;
1773 /// fn main() -> io::Result<()> {
1774 /// let f = File::open("foo.txt")?;
1775 /// let f = BufReader::new(f);
1777 /// for line in f.lines() {
1778 /// println!("{}", line.unwrap());
1785 #[stable(feature = "rust1", since = "1.0.0")]
1786 pub trait BufRead: Read {
1787 /// Returns the contents of the internal buffer, filling it with more data
1788 /// from the inner reader if it is empty.
1790 /// This function is a lower-level call. It needs to be paired with the
1791 /// [`consume`] method to function properly. When calling this
1792 /// method, none of the contents will be "read" in the sense that later
1793 /// calling `read` may return the same contents. As such, [`consume`] must
1794 /// be called with the number of bytes that are consumed from this buffer to
1795 /// ensure that the bytes are never returned twice.
1797 /// [`consume`]: Self::consume
1799 /// An empty buffer returned indicates that the stream has reached EOF.
1803 /// This function will return an I/O error if the underlying reader was
1804 /// read, but returned an error.
1808 /// A locked standard input implements `BufRead`:
1812 /// use std::io::prelude::*;
1814 /// let stdin = io::stdin();
1815 /// let mut stdin = stdin.lock();
1817 /// let buffer = stdin.fill_buf().unwrap();
1819 /// // work with buffer
1820 /// println!("{:?}", buffer);
1822 /// // ensure the bytes we worked with aren't returned again later
1823 /// let length = buffer.len();
1824 /// stdin.consume(length);
1826 #[stable(feature = "rust1", since = "1.0.0")]
1827 fn fill_buf(&mut self) -> Result<&[u8]>;
1829 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1830 /// so they should no longer be returned in calls to `read`.
1832 /// This function is a lower-level call. It needs to be paired with the
1833 /// [`fill_buf`] method to function properly. This function does
1834 /// not perform any I/O, it simply informs this object that some amount of
1835 /// its buffer, returned from [`fill_buf`], has been consumed and should
1836 /// no longer be returned. As such, this function may do odd things if
1837 /// [`fill_buf`] isn't called before calling it.
1839 /// The `amt` must be `<=` the number of bytes in the buffer returned by
1844 /// Since `consume()` is meant to be used with [`fill_buf`],
1845 /// that method's example includes an example of `consume()`.
1847 /// [`fill_buf`]: Self::fill_buf
1848 #[stable(feature = "rust1", since = "1.0.0")]
1849 fn consume(&mut self, amt: usize);
1851 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
1853 /// This function will read bytes from the underlying stream until the
1854 /// delimiter or EOF is found. Once found, all bytes up to, and including,
1855 /// the delimiter (if found) will be appended to `buf`.
1857 /// If successful, this function will return the total number of bytes read.
1859 /// This function is blocking and should be used carefully: it is possible for
1860 /// an attacker to continuously send bytes without ever sending the delimiter
1865 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1866 /// will otherwise return any errors returned by [`fill_buf`].
1868 /// If an I/O error is encountered then all bytes read so far will be
1869 /// present in `buf` and its length will have been adjusted appropriately.
1871 /// [`fill_buf`]: Self::fill_buf
1872 /// [`ErrorKind::Interrupted`]: enum.ErrorKind.html#variant.Interrupted
1876 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1877 /// this example, we use [`Cursor`] to read all the bytes in a byte slice
1878 /// in hyphen delimited segments:
1880 /// [`Cursor`]: struct.Cursor.html
1883 /// use std::io::{self, BufRead};
1885 /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
1886 /// let mut buf = vec![];
1888 /// // cursor is at 'l'
1889 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1890 /// .expect("reading from cursor won't fail");
1891 /// assert_eq!(num_bytes, 6);
1892 /// assert_eq!(buf, b"lorem-");
1895 /// // cursor is at 'i'
1896 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1897 /// .expect("reading from cursor won't fail");
1898 /// assert_eq!(num_bytes, 5);
1899 /// assert_eq!(buf, b"ipsum");
1902 /// // cursor is at EOF
1903 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1904 /// .expect("reading from cursor won't fail");
1905 /// assert_eq!(num_bytes, 0);
1906 /// assert_eq!(buf, b"");
1908 #[stable(feature = "rust1", since = "1.0.0")]
1909 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
1910 read_until(self, byte, buf)
1913 /// Read all bytes until a newline (the 0xA byte) is reached, and append
1914 /// them to the provided buffer.
1916 /// This function will read bytes from the underlying stream until the
1917 /// newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes
1918 /// up to, and including, the delimiter (if found) will be appended to
1921 /// If successful, this function will return the total number of bytes read.
1923 /// If this function returns `Ok(0)`, the stream has reached EOF.
1925 /// This function is blocking and should be used carefully: it is possible for
1926 /// an attacker to continuously send bytes without ever sending a newline
1931 /// This function has the same error semantics as [`read_until`] and will
1932 /// also return an error if the read bytes are not valid UTF-8. If an I/O
1933 /// error is encountered then `buf` may contain some bytes already read in
1934 /// the event that all data read so far was valid UTF-8.
1936 /// [`read_until`]: Self::read_until
1940 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1941 /// this example, we use [`Cursor`] to read all the lines in a byte slice:
1943 /// [`Cursor`]: struct.Cursor.html
1946 /// use std::io::{self, BufRead};
1948 /// let mut cursor = io::Cursor::new(b"foo\nbar");
1949 /// let mut buf = String::new();
1951 /// // cursor is at 'f'
1952 /// let num_bytes = cursor.read_line(&mut buf)
1953 /// .expect("reading from cursor won't fail");
1954 /// assert_eq!(num_bytes, 4);
1955 /// assert_eq!(buf, "foo\n");
1958 /// // cursor is at 'b'
1959 /// let num_bytes = cursor.read_line(&mut buf)
1960 /// .expect("reading from cursor won't fail");
1961 /// assert_eq!(num_bytes, 3);
1962 /// assert_eq!(buf, "bar");
1965 /// // cursor is at EOF
1966 /// let num_bytes = cursor.read_line(&mut buf)
1967 /// .expect("reading from cursor won't fail");
1968 /// assert_eq!(num_bytes, 0);
1969 /// assert_eq!(buf, "");
1971 #[stable(feature = "rust1", since = "1.0.0")]
1972 fn read_line(&mut self, buf: &mut String) -> Result<usize> {
1973 // Note that we are not calling the `.read_until` method here, but
1974 // rather our hardcoded implementation. For more details as to why, see
1975 // the comments in `read_to_end`.
1976 append_to_string(buf, |b| read_until(self, b'\n', b))
1979 /// Returns an iterator over the contents of this reader split on the byte
1982 /// The iterator returned from this function will return instances of
1983 /// [`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
1984 /// the delimiter byte at the end.
1986 /// This function will yield errors whenever [`read_until`] would have
1987 /// also yielded an error.
1989 /// [`io::Result`]: self::Result
1990 /// [`Vec<u8>`]: crate::vec::Vec
1991 /// [`read_until`]: Self::read_until
1995 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1996 /// this example, we use [`Cursor`] to iterate over all hyphen delimited
1997 /// segments in a byte slice
1999 /// [`Cursor`]: struct.Cursor.html
2002 /// use std::io::{self, BufRead};
2004 /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
2006 /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
2007 /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
2008 /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
2009 /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
2010 /// assert_eq!(split_iter.next(), None);
2012 #[stable(feature = "rust1", since = "1.0.0")]
2013 fn split(self, byte: u8) -> Split<Self>
2017 Split { buf: self, delim: byte }
2020 /// Returns an iterator over the lines of this reader.
2022 /// The iterator returned from this function will yield instances of
2023 /// [`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline
2024 /// byte (the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.
2026 /// [`io::Result`]: self::Result
2030 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2031 /// this example, we use [`Cursor`] to iterate over all the lines in a byte
2035 /// use std::io::{self, BufRead};
2037 /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
2039 /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
2040 /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
2041 /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
2042 /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
2043 /// assert_eq!(lines_iter.next(), None);
2048 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
2050 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
2051 #[stable(feature = "rust1", since = "1.0.0")]
2052 fn lines(self) -> Lines<Self>
2060 /// Adaptor to chain together two readers.
2062 /// This struct is generally created by calling [`chain`] on a reader.
2063 /// Please see the documentation of [`chain`] for more details.
2065 /// [`chain`]: trait.Read.html#method.chain
2066 #[stable(feature = "rust1", since = "1.0.0")]
2067 pub struct Chain<T, U> {
2073 impl<T, U> Chain<T, U> {
2074 /// Consumes the `Chain`, returning the wrapped readers.
2080 /// use std::io::prelude::*;
2081 /// use std::fs::File;
2083 /// fn main() -> io::Result<()> {
2084 /// let mut foo_file = File::open("foo.txt")?;
2085 /// let mut bar_file = File::open("bar.txt")?;
2087 /// let chain = foo_file.chain(bar_file);
2088 /// let (foo_file, bar_file) = chain.into_inner();
2092 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2093 pub fn into_inner(self) -> (T, U) {
2094 (self.first, self.second)
2097 /// Gets references to the underlying readers in this `Chain`.
2103 /// use std::io::prelude::*;
2104 /// use std::fs::File;
2106 /// fn main() -> io::Result<()> {
2107 /// let mut foo_file = File::open("foo.txt")?;
2108 /// let mut bar_file = File::open("bar.txt")?;
2110 /// let chain = foo_file.chain(bar_file);
2111 /// let (foo_file, bar_file) = chain.get_ref();
2115 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2116 pub fn get_ref(&self) -> (&T, &U) {
2117 (&self.first, &self.second)
2120 /// Gets mutable references to the underlying readers in this `Chain`.
2122 /// Care should be taken to avoid modifying the internal I/O state of the
2123 /// underlying readers as doing so may corrupt the internal state of this
2130 /// use std::io::prelude::*;
2131 /// use std::fs::File;
2133 /// fn main() -> io::Result<()> {
2134 /// let mut foo_file = File::open("foo.txt")?;
2135 /// let mut bar_file = File::open("bar.txt")?;
2137 /// let mut chain = foo_file.chain(bar_file);
2138 /// let (foo_file, bar_file) = chain.get_mut();
2142 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2143 pub fn get_mut(&mut self) -> (&mut T, &mut U) {
2144 (&mut self.first, &mut self.second)
2148 #[stable(feature = "std_debug", since = "1.16.0")]
2149 impl<T: fmt::Debug, U: fmt::Debug> fmt::Debug for Chain<T, U> {
2150 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2151 f.debug_struct("Chain").field("t", &self.first).field("u", &self.second).finish()
2155 #[stable(feature = "rust1", since = "1.0.0")]
2156 impl<T: Read, U: Read> Read for Chain<T, U> {
2157 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2158 if !self.done_first {
2159 match self.first.read(buf)? {
2160 0 if !buf.is_empty() => self.done_first = true,
2164 self.second.read(buf)
2167 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
2168 if !self.done_first {
2169 match self.first.read_vectored(bufs)? {
2170 0 if bufs.iter().any(|b| !b.is_empty()) => self.done_first = true,
2174 self.second.read_vectored(bufs)
2177 unsafe fn initializer(&self) -> Initializer {
2178 let initializer = self.first.initializer();
2179 if initializer.should_initialize() { initializer } else { self.second.initializer() }
2183 #[stable(feature = "chain_bufread", since = "1.9.0")]
2184 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
2185 fn fill_buf(&mut self) -> Result<&[u8]> {
2186 if !self.done_first {
2187 match self.first.fill_buf()? {
2188 buf if buf.is_empty() => {
2189 self.done_first = true;
2191 buf => return Ok(buf),
2194 self.second.fill_buf()
2197 fn consume(&mut self, amt: usize) {
2198 if !self.done_first { self.first.consume(amt) } else { self.second.consume(amt) }
2202 /// Reader adaptor which limits the bytes read from an underlying reader.
2204 /// This struct is generally created by calling [`take`] on a reader.
2205 /// Please see the documentation of [`take`] for more details.
2207 /// [`take`]: trait.Read.html#method.take
2208 #[stable(feature = "rust1", since = "1.0.0")]
2210 pub struct Take<T> {
2216 /// Returns the number of bytes that can be read before this instance will
2221 /// This instance may reach `EOF` after reading fewer bytes than indicated by
2222 /// this method if the underlying [`Read`] instance reaches EOF.
2228 /// use std::io::prelude::*;
2229 /// use std::fs::File;
2231 /// fn main() -> io::Result<()> {
2232 /// let f = File::open("foo.txt")?;
2234 /// // read at most five bytes
2235 /// let handle = f.take(5);
2237 /// println!("limit: {}", handle.limit());
2241 #[stable(feature = "rust1", since = "1.0.0")]
2242 pub fn limit(&self) -> u64 {
2246 /// Sets the number of bytes that can be read before this instance will
2247 /// return EOF. This is the same as constructing a new `Take` instance, so
2248 /// the amount of bytes read and the previous limit value don't matter when
2249 /// calling this method.
2255 /// use std::io::prelude::*;
2256 /// use std::fs::File;
2258 /// fn main() -> io::Result<()> {
2259 /// let f = File::open("foo.txt")?;
2261 /// // read at most five bytes
2262 /// let mut handle = f.take(5);
2263 /// handle.set_limit(10);
2265 /// assert_eq!(handle.limit(), 10);
2269 #[stable(feature = "take_set_limit", since = "1.27.0")]
2270 pub fn set_limit(&mut self, limit: u64) {
2274 /// Consumes the `Take`, returning the wrapped reader.
2280 /// use std::io::prelude::*;
2281 /// use std::fs::File;
2283 /// fn main() -> io::Result<()> {
2284 /// let mut file = File::open("foo.txt")?;
2286 /// let mut buffer = [0; 5];
2287 /// let mut handle = file.take(5);
2288 /// handle.read(&mut buffer)?;
2290 /// let file = handle.into_inner();
2294 #[stable(feature = "io_take_into_inner", since = "1.15.0")]
2295 pub fn into_inner(self) -> T {
2299 /// Gets a reference to the underlying reader.
2305 /// use std::io::prelude::*;
2306 /// use std::fs::File;
2308 /// fn main() -> io::Result<()> {
2309 /// let mut file = File::open("foo.txt")?;
2311 /// let mut buffer = [0; 5];
2312 /// let mut handle = file.take(5);
2313 /// handle.read(&mut buffer)?;
2315 /// let file = handle.get_ref();
2319 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2320 pub fn get_ref(&self) -> &T {
2324 /// Gets a mutable reference to the underlying reader.
2326 /// Care should be taken to avoid modifying the internal I/O state of the
2327 /// underlying reader as doing so may corrupt the internal limit of this
2334 /// use std::io::prelude::*;
2335 /// use std::fs::File;
2337 /// fn main() -> io::Result<()> {
2338 /// let mut file = File::open("foo.txt")?;
2340 /// let mut buffer = [0; 5];
2341 /// let mut handle = file.take(5);
2342 /// handle.read(&mut buffer)?;
2344 /// let file = handle.get_mut();
2348 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2349 pub fn get_mut(&mut self) -> &mut T {
2354 #[stable(feature = "rust1", since = "1.0.0")]
2355 impl<T: Read> Read for Take<T> {
2356 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2357 // Don't call into inner reader at all at EOF because it may still block
2358 if self.limit == 0 {
2362 let max = cmp::min(buf.len() as u64, self.limit) as usize;
2363 let n = self.inner.read(&mut buf[..max])?;
2364 self.limit -= n as u64;
2368 unsafe fn initializer(&self) -> Initializer {
2369 self.inner.initializer()
2372 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
2373 // Pass in a reservation_size closure that respects the current value
2374 // of limit for each read. If we hit the read limit, this prevents the
2375 // final zero-byte read from allocating again.
2376 read_to_end_with_reservation(self, buf, |self_| cmp::min(self_.limit, 32) as usize)
2380 #[stable(feature = "rust1", since = "1.0.0")]
2381 impl<T: BufRead> BufRead for Take<T> {
2382 fn fill_buf(&mut self) -> Result<&[u8]> {
2383 // Don't call into inner reader at all at EOF because it may still block
2384 if self.limit == 0 {
2388 let buf = self.inner.fill_buf()?;
2389 let cap = cmp::min(buf.len() as u64, self.limit) as usize;
2393 fn consume(&mut self, amt: usize) {
2394 // Don't let callers reset the limit by passing an overlarge value
2395 let amt = cmp::min(amt as u64, self.limit) as usize;
2396 self.limit -= amt as u64;
2397 self.inner.consume(amt);
2401 /// An iterator over `u8` values of a reader.
2403 /// This struct is generally created by calling [`bytes`] on a reader.
2404 /// Please see the documentation of [`bytes`] for more details.
2406 /// [`bytes`]: trait.Read.html#method.bytes
2407 #[stable(feature = "rust1", since = "1.0.0")]
2409 pub struct Bytes<R> {
2413 #[stable(feature = "rust1", since = "1.0.0")]
2414 impl<R: Read> Iterator for Bytes<R> {
2415 type Item = Result<u8>;
2417 fn next(&mut self) -> Option<Result<u8>> {
2420 return match self.inner.read(slice::from_mut(&mut byte)) {
2422 Ok(..) => Some(Ok(byte)),
2423 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
2424 Err(e) => Some(Err(e)),
2430 /// An iterator over the contents of an instance of `BufRead` split on a
2431 /// particular byte.
2433 /// This struct is generally created by calling [`split`] on a `BufRead`.
2434 /// Please see the documentation of [`split`] for more details.
2436 /// [`split`]: trait.BufRead.html#method.split
2437 #[stable(feature = "rust1", since = "1.0.0")]
2439 pub struct Split<B> {
2444 #[stable(feature = "rust1", since = "1.0.0")]
2445 impl<B: BufRead> Iterator for Split<B> {
2446 type Item = Result<Vec<u8>>;
2448 fn next(&mut self) -> Option<Result<Vec<u8>>> {
2449 let mut buf = Vec::new();
2450 match self.buf.read_until(self.delim, &mut buf) {
2453 if buf[buf.len() - 1] == self.delim {
2458 Err(e) => Some(Err(e)),
2463 /// An iterator over the lines of an instance of `BufRead`.
2465 /// This struct is generally created by calling [`lines`] on a `BufRead`.
2466 /// Please see the documentation of [`lines`] for more details.
2468 /// [`lines`]: trait.BufRead.html#method.lines
2469 #[stable(feature = "rust1", since = "1.0.0")]
2471 pub struct Lines<B> {
2475 #[stable(feature = "rust1", since = "1.0.0")]
2476 impl<B: BufRead> Iterator for Lines<B> {
2477 type Item = Result<String>;
2479 fn next(&mut self) -> Option<Result<String>> {
2480 let mut buf = String::new();
2481 match self.buf.read_line(&mut buf) {
2484 if buf.ends_with('\n') {
2486 if buf.ends_with('\r') {
2492 Err(e) => Some(Err(e)),
2499 use super::{repeat, Cursor, SeekFrom};
2500 use crate::cmp::{self, min};
2501 use crate::io::prelude::*;
2502 use crate::io::{self, IoSlice, IoSliceMut};
2503 use crate::ops::Deref;
2506 #[cfg_attr(target_os = "emscripten", ignore)]
2508 let mut buf = Cursor::new(&b"12"[..]);
2509 let mut v = Vec::new();
2510 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 2);
2511 assert_eq!(v, b"12");
2513 let mut buf = Cursor::new(&b"1233"[..]);
2514 let mut v = Vec::new();
2515 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 3);
2516 assert_eq!(v, b"123");
2518 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 1);
2519 assert_eq!(v, b"3");
2521 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 0);
2527 let buf = Cursor::new(&b"12"[..]);
2528 let mut s = buf.split(b'3');
2529 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2530 assert!(s.next().is_none());
2532 let buf = Cursor::new(&b"1233"[..]);
2533 let mut s = buf.split(b'3');
2534 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2535 assert_eq!(s.next().unwrap().unwrap(), vec![]);
2536 assert!(s.next().is_none());
2541 let mut buf = Cursor::new(&b"12"[..]);
2542 let mut v = String::new();
2543 assert_eq!(buf.read_line(&mut v).unwrap(), 2);
2544 assert_eq!(v, "12");
2546 let mut buf = Cursor::new(&b"12\n\n"[..]);
2547 let mut v = String::new();
2548 assert_eq!(buf.read_line(&mut v).unwrap(), 3);
2549 assert_eq!(v, "12\n");
2551 assert_eq!(buf.read_line(&mut v).unwrap(), 1);
2552 assert_eq!(v, "\n");
2554 assert_eq!(buf.read_line(&mut v).unwrap(), 0);
2560 let buf = Cursor::new(&b"12\r"[..]);
2561 let mut s = buf.lines();
2562 assert_eq!(s.next().unwrap().unwrap(), "12\r".to_string());
2563 assert!(s.next().is_none());
2565 let buf = Cursor::new(&b"12\r\n\n"[..]);
2566 let mut s = buf.lines();
2567 assert_eq!(s.next().unwrap().unwrap(), "12".to_string());
2568 assert_eq!(s.next().unwrap().unwrap(), "".to_string());
2569 assert!(s.next().is_none());
2574 let mut c = Cursor::new(&b""[..]);
2575 let mut v = Vec::new();
2576 assert_eq!(c.read_to_end(&mut v).unwrap(), 0);
2579 let mut c = Cursor::new(&b"1"[..]);
2580 let mut v = Vec::new();
2581 assert_eq!(c.read_to_end(&mut v).unwrap(), 1);
2582 assert_eq!(v, b"1");
2584 let cap = 1024 * 1024;
2585 let data = (0..cap).map(|i| (i / 3) as u8).collect::<Vec<_>>();
2586 let mut v = Vec::new();
2587 let (a, b) = data.split_at(data.len() / 2);
2588 assert_eq!(Cursor::new(a).read_to_end(&mut v).unwrap(), a.len());
2589 assert_eq!(Cursor::new(b).read_to_end(&mut v).unwrap(), b.len());
2590 assert_eq!(v, data);
2594 fn read_to_string() {
2595 let mut c = Cursor::new(&b""[..]);
2596 let mut v = String::new();
2597 assert_eq!(c.read_to_string(&mut v).unwrap(), 0);
2600 let mut c = Cursor::new(&b"1"[..]);
2601 let mut v = String::new();
2602 assert_eq!(c.read_to_string(&mut v).unwrap(), 1);
2605 let mut c = Cursor::new(&b"\xff"[..]);
2606 let mut v = String::new();
2607 assert!(c.read_to_string(&mut v).is_err());
2612 let mut buf = [0; 4];
2614 let mut c = Cursor::new(&b""[..]);
2615 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
2617 let mut c = Cursor::new(&b"123"[..]).chain(Cursor::new(&b"456789"[..]));
2618 c.read_exact(&mut buf).unwrap();
2619 assert_eq!(&buf, b"1234");
2620 c.read_exact(&mut buf).unwrap();
2621 assert_eq!(&buf, b"5678");
2622 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
2626 fn read_exact_slice() {
2627 let mut buf = [0; 4];
2629 let mut c = &b""[..];
2630 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
2632 let mut c = &b"123"[..];
2633 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
2634 // make sure the optimized (early returning) method is being used
2635 assert_eq!(&buf, &[0; 4]);
2637 let mut c = &b"1234"[..];
2638 c.read_exact(&mut buf).unwrap();
2639 assert_eq!(&buf, b"1234");
2641 let mut c = &b"56789"[..];
2642 c.read_exact(&mut buf).unwrap();
2643 assert_eq!(&buf, b"5678");
2644 assert_eq!(c, b"9");
2652 fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
2653 Err(io::Error::new(io::ErrorKind::Other, ""))
2656 impl BufRead for R {
2657 fn fill_buf(&mut self) -> io::Result<&[u8]> {
2658 Err(io::Error::new(io::ErrorKind::Other, ""))
2660 fn consume(&mut self, _amt: usize) {}
2663 let mut buf = [0; 1];
2664 assert_eq!(0, R.take(0).read(&mut buf).unwrap());
2665 assert_eq!(b"", R.take(0).fill_buf().unwrap());
2668 fn cmp_bufread<Br1: BufRead, Br2: BufRead>(mut br1: Br1, mut br2: Br2, exp: &[u8]) {
2669 let mut cat = Vec::new();
2672 let buf1 = br1.fill_buf().unwrap();
2673 let buf2 = br2.fill_buf().unwrap();
2674 let minlen = if buf1.len() < buf2.len() { buf1.len() } else { buf2.len() };
2675 assert_eq!(buf1[..minlen], buf2[..minlen]);
2676 cat.extend_from_slice(&buf1[..minlen]);
2682 br1.consume(consume);
2683 br2.consume(consume);
2685 assert_eq!(br1.fill_buf().unwrap().len(), 0);
2686 assert_eq!(br2.fill_buf().unwrap().len(), 0);
2687 assert_eq!(&cat[..], &exp[..])
2691 fn chain_bufread() {
2692 let testdata = b"ABCDEFGHIJKL";
2694 (&testdata[..3]).chain(&testdata[3..6]).chain(&testdata[6..9]).chain(&testdata[9..]);
2695 let chain2 = (&testdata[..4]).chain(&testdata[4..8]).chain(&testdata[8..]);
2696 cmp_bufread(chain1, chain2, &testdata[..]);
2700 fn chain_zero_length_read_is_not_eof() {
2703 let mut s = String::new();
2704 let mut chain = (&a[..]).chain(&b[..]);
2705 chain.read(&mut []).unwrap();
2706 chain.read_to_string(&mut s).unwrap();
2707 assert_eq!("AB", s);
2711 #[cfg_attr(target_os = "emscripten", ignore)]
2712 fn bench_read_to_end(b: &mut test::Bencher) {
2714 let mut lr = repeat(1).take(10000000);
2715 let mut vec = Vec::with_capacity(1024);
2716 super::read_to_end(&mut lr, &mut vec)
2721 fn seek_len() -> io::Result<()> {
2722 let mut c = Cursor::new(vec![0; 15]);
2723 assert_eq!(c.stream_len()?, 15);
2725 c.seek(SeekFrom::End(0))?;
2726 let old_pos = c.stream_position()?;
2727 assert_eq!(c.stream_len()?, 15);
2728 assert_eq!(c.stream_position()?, old_pos);
2730 c.seek(SeekFrom::Start(7))?;
2731 c.seek(SeekFrom::Current(2))?;
2732 let old_pos = c.stream_position()?;
2733 assert_eq!(c.stream_len()?, 15);
2734 assert_eq!(c.stream_position()?, old_pos);
2740 fn seek_position() -> io::Result<()> {
2741 // All `asserts` are duplicated here to make sure the method does not
2742 // change anything about the seek state.
2743 let mut c = Cursor::new(vec![0; 15]);
2744 assert_eq!(c.stream_position()?, 0);
2745 assert_eq!(c.stream_position()?, 0);
2747 c.seek(SeekFrom::End(0))?;
2748 assert_eq!(c.stream_position()?, 15);
2749 assert_eq!(c.stream_position()?, 15);
2751 c.seek(SeekFrom::Start(7))?;
2752 c.seek(SeekFrom::Current(2))?;
2753 assert_eq!(c.stream_position()?, 9);
2754 assert_eq!(c.stream_position()?, 9);
2756 c.seek(SeekFrom::End(-3))?;
2757 c.seek(SeekFrom::Current(1))?;
2758 c.seek(SeekFrom::Current(-5))?;
2759 assert_eq!(c.stream_position()?, 8);
2760 assert_eq!(c.stream_position()?, 8);
2765 // A simple example reader which uses the default implementation of
2767 struct ExampleSliceReader<'a> {
2771 impl<'a> Read for ExampleSliceReader<'a> {
2772 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
2773 let len = cmp::min(self.slice.len(), buf.len());
2774 buf[..len].copy_from_slice(&self.slice[..len]);
2775 self.slice = &self.slice[len..];
2781 fn test_read_to_end_capacity() -> io::Result<()> {
2782 let input = &b"foo"[..];
2784 // read_to_end() generally needs to over-allocate, both for efficiency
2785 // and so that it can distinguish EOF. Assert that this is the case
2786 // with this simple ExampleSliceReader struct, which uses the default
2787 // implementation of read_to_end. Even though vec1 is allocated with
2788 // exactly enough capacity for the read, read_to_end will allocate more
2790 let mut vec1 = Vec::with_capacity(input.len());
2791 ExampleSliceReader { slice: input }.read_to_end(&mut vec1)?;
2792 assert_eq!(vec1.len(), input.len());
2793 assert!(vec1.capacity() > input.len(), "allocated more");
2795 // However, std::io::Take includes an implementation of read_to_end
2796 // that will not allocate when the limit has already been reached. In
2797 // this case, vec2 never grows.
2798 let mut vec2 = Vec::with_capacity(input.len());
2799 ExampleSliceReader { slice: input }.take(input.len() as u64).read_to_end(&mut vec2)?;
2800 assert_eq!(vec2.len(), input.len());
2801 assert_eq!(vec2.capacity(), input.len(), "did not allocate more");
2807 fn io_slice_mut_advance() {
2808 let mut buf1 = [1; 8];
2809 let mut buf2 = [2; 16];
2810 let mut buf3 = [3; 8];
2811 let mut bufs = &mut [
2812 IoSliceMut::new(&mut buf1),
2813 IoSliceMut::new(&mut buf2),
2814 IoSliceMut::new(&mut buf3),
2817 // Only in a single buffer..
2818 bufs = IoSliceMut::advance(bufs, 1);
2819 assert_eq!(bufs[0].deref(), [1; 7].as_ref());
2820 assert_eq!(bufs[1].deref(), [2; 16].as_ref());
2821 assert_eq!(bufs[2].deref(), [3; 8].as_ref());
2823 // Removing a buffer, leaving others as is.
2824 bufs = IoSliceMut::advance(bufs, 7);
2825 assert_eq!(bufs[0].deref(), [2; 16].as_ref());
2826 assert_eq!(bufs[1].deref(), [3; 8].as_ref());
2828 // Removing a buffer and removing from the next buffer.
2829 bufs = IoSliceMut::advance(bufs, 18);
2830 assert_eq!(bufs[0].deref(), [3; 6].as_ref());
2834 fn io_slice_mut_advance_empty_slice() {
2835 let empty_bufs = &mut [][..];
2837 IoSliceMut::advance(empty_bufs, 1);
2841 fn io_slice_mut_advance_beyond_total_length() {
2842 let mut buf1 = [1; 8];
2843 let mut bufs = &mut [IoSliceMut::new(&mut buf1)][..];
2845 // Going beyond the total length should be ok.
2846 bufs = IoSliceMut::advance(bufs, 9);
2847 assert!(bufs.is_empty());
2851 fn io_slice_advance() {
2855 let mut bufs = &mut [IoSlice::new(&buf1), IoSlice::new(&buf2), IoSlice::new(&buf3)][..];
2857 // Only in a single buffer..
2858 bufs = IoSlice::advance(bufs, 1);
2859 assert_eq!(bufs[0].deref(), [1; 7].as_ref());
2860 assert_eq!(bufs[1].deref(), [2; 16].as_ref());
2861 assert_eq!(bufs[2].deref(), [3; 8].as_ref());
2863 // Removing a buffer, leaving others as is.
2864 bufs = IoSlice::advance(bufs, 7);
2865 assert_eq!(bufs[0].deref(), [2; 16].as_ref());
2866 assert_eq!(bufs[1].deref(), [3; 8].as_ref());
2868 // Removing a buffer and removing from the next buffer.
2869 bufs = IoSlice::advance(bufs, 18);
2870 assert_eq!(bufs[0].deref(), [3; 6].as_ref());
2874 fn io_slice_advance_empty_slice() {
2875 let empty_bufs = &mut [][..];
2877 IoSlice::advance(empty_bufs, 1);
2881 fn io_slice_advance_beyond_total_length() {
2883 let mut bufs = &mut [IoSlice::new(&buf1)][..];
2885 // Going beyond the total length should be ok.
2886 bufs = IoSlice::advance(bufs, 9);
2887 assert!(bufs.is_empty());
2890 /// Create a new writer that reads from at most `n_bufs` and reads
2891 /// `per_call` bytes (in total) per call to write.
2892 fn test_writer(n_bufs: usize, per_call: usize) -> TestWriter {
2893 TestWriter { n_bufs, per_call, written: Vec::new() }
2902 impl Write for TestWriter {
2903 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
2904 self.write_vectored(&[IoSlice::new(buf)])
2907 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
2908 let mut left = self.per_call;
2909 let mut written = 0;
2910 for buf in bufs.iter().take(self.n_bufs) {
2911 let n = min(left, buf.len());
2912 self.written.extend_from_slice(&buf[0..n]);
2919 fn flush(&mut self) -> io::Result<()> {
2925 fn test_writer_read_from_one_buf() {
2926 let mut writer = test_writer(1, 2);
2928 assert_eq!(writer.write(&[]).unwrap(), 0);
2929 assert_eq!(writer.write_vectored(&[]).unwrap(), 0);
2931 // Read at most 2 bytes.
2932 assert_eq!(writer.write(&[1, 1, 1]).unwrap(), 2);
2933 let bufs = &[IoSlice::new(&[2, 2, 2])];
2934 assert_eq!(writer.write_vectored(bufs).unwrap(), 2);
2936 // Only read from first buf.
2937 let bufs = &[IoSlice::new(&[3]), IoSlice::new(&[4, 4])];
2938 assert_eq!(writer.write_vectored(bufs).unwrap(), 1);
2940 assert_eq!(writer.written, &[1, 1, 2, 2, 3]);
2944 fn test_writer_read_from_multiple_bufs() {
2945 let mut writer = test_writer(3, 3);
2947 // Read at most 3 bytes from two buffers.
2948 let bufs = &[IoSlice::new(&[1]), IoSlice::new(&[2, 2, 2])];
2949 assert_eq!(writer.write_vectored(bufs).unwrap(), 3);
2951 // Read at most 3 bytes from three buffers.
2952 let bufs = &[IoSlice::new(&[3]), IoSlice::new(&[4]), IoSlice::new(&[5, 5])];
2953 assert_eq!(writer.write_vectored(bufs).unwrap(), 3);
2955 assert_eq!(writer.written, &[1, 2, 2, 3, 4, 5]);
2959 fn test_write_all_vectored() {
2960 #[rustfmt::skip] // Becomes unreadable otherwise.
2961 let tests: Vec<(_, &'static [u8])> = vec![
2963 (vec![IoSlice::new(&[]), IoSlice::new(&[])], &[]),
2964 (vec![IoSlice::new(&[1])], &[1]),
2965 (vec![IoSlice::new(&[1, 2])], &[1, 2]),
2966 (vec![IoSlice::new(&[1, 2, 3])], &[1, 2, 3]),
2967 (vec![IoSlice::new(&[1, 2, 3, 4])], &[1, 2, 3, 4]),
2968 (vec![IoSlice::new(&[1, 2, 3, 4, 5])], &[1, 2, 3, 4, 5]),
2969 (vec![IoSlice::new(&[1]), IoSlice::new(&[2])], &[1, 2]),
2970 (vec![IoSlice::new(&[1]), IoSlice::new(&[2, 2])], &[1, 2, 2]),
2971 (vec![IoSlice::new(&[1, 1]), IoSlice::new(&[2, 2])], &[1, 1, 2, 2]),
2972 (vec![IoSlice::new(&[1, 1]), IoSlice::new(&[2, 2, 2])], &[1, 1, 2, 2, 2]),
2973 (vec![IoSlice::new(&[1, 1]), IoSlice::new(&[2, 2, 2])], &[1, 1, 2, 2, 2]),
2974 (vec![IoSlice::new(&[1, 1, 1]), IoSlice::new(&[2, 2, 2])], &[1, 1, 1, 2, 2, 2]),
2975 (vec![IoSlice::new(&[1, 1, 1]), IoSlice::new(&[2, 2, 2, 2])], &[1, 1, 1, 2, 2, 2, 2]),
2976 (vec![IoSlice::new(&[1, 1, 1, 1]), IoSlice::new(&[2, 2, 2, 2])], &[1, 1, 1, 1, 2, 2, 2, 2]),
2977 (vec![IoSlice::new(&[1]), IoSlice::new(&[2]), IoSlice::new(&[3])], &[1, 2, 3]),
2978 (vec![IoSlice::new(&[1, 1]), IoSlice::new(&[2, 2]), IoSlice::new(&[3, 3])], &[1, 1, 2, 2, 3, 3]),
2979 (vec![IoSlice::new(&[1]), IoSlice::new(&[2, 2]), IoSlice::new(&[3, 3, 3])], &[1, 2, 2, 3, 3, 3]),
2980 (vec![IoSlice::new(&[1, 1, 1]), IoSlice::new(&[2, 2, 2]), IoSlice::new(&[3, 3, 3])], &[1, 1, 1, 2, 2, 2, 3, 3, 3]),
2983 let writer_configs = &[(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)];
2985 for (n_bufs, per_call) in writer_configs.iter().copied() {
2986 for (mut input, wanted) in tests.clone().into_iter() {
2987 let mut writer = test_writer(n_bufs, per_call);
2988 assert!(writer.write_all_vectored(&mut *input).is_ok());
2989 assert_eq!(&*writer.written, &*wanted);