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 //! [`Read`]: trait.Read.html
242 //! [`Write`]: trait.Write.html
243 //! [`Seek`]: trait.Seek.html
244 //! [`BufRead`]: trait.BufRead.html
245 //! [`File`]: ../fs/struct.File.html
246 //! [`TcpStream`]: ../net/struct.TcpStream.html
247 //! [`Vec<T>`]: ../vec/struct.Vec.html
248 //! [`BufReader`]: struct.BufReader.html
249 //! [`BufWriter`]: struct.BufWriter.html
250 //! [`Write::write`]: trait.Write.html#tymethod.write
251 //! [`io::stdout`]: fn.stdout.html
252 //! [`println!`]: ../macro.println.html
253 //! [`Lines`]: struct.Lines.html
254 //! [`io::Result`]: type.Result.html
255 //! [`?` operator]: ../../book/appendix-02-operators.html
256 //! [`Read::read`]: trait.Read.html#tymethod.read
257 //! [`Result`]: ../result/enum.Result.html
258 //! [`.unwrap()`]: ../result/enum.Result.html#method.unwrap
260 #![stable(feature = "rust1", since = "1.0.0")]
265 use crate::ops::{Deref, DerefMut};
271 #[stable(feature = "rust1", since = "1.0.0")]
272 pub use self::buffered::IntoInnerError;
273 #[stable(feature = "rust1", since = "1.0.0")]
274 pub use self::buffered::{BufReader, BufWriter, LineWriter};
275 #[stable(feature = "rust1", since = "1.0.0")]
276 pub use self::cursor::Cursor;
277 #[stable(feature = "rust1", since = "1.0.0")]
278 pub use self::error::{Error, ErrorKind, Result};
279 #[stable(feature = "rust1", since = "1.0.0")]
280 pub use self::stdio::{stderr, stdin, stdout, Stderr, Stdin, Stdout};
281 #[stable(feature = "rust1", since = "1.0.0")]
282 pub use self::stdio::{StderrLock, StdinLock, StdoutLock};
283 #[unstable(feature = "print_internals", issue = "none")]
284 pub use self::stdio::{_eprint, _print};
285 #[unstable(feature = "libstd_io_internals", issue = "42788")]
286 #[doc(no_inline, hidden)]
287 pub use self::stdio::{set_panic, set_print};
288 #[stable(feature = "rust1", since = "1.0.0")]
289 pub use self::util::{copy, empty, repeat, sink, Empty, Repeat, Sink};
300 const DEFAULT_BUF_SIZE: usize = crate::sys_common::io::DEFAULT_BUF_SIZE;
303 buf: &'a mut Vec<u8>,
307 impl Drop for Guard<'_> {
310 self.buf.set_len(self.len);
315 // A few methods below (read_to_string, read_line) will append data into a
316 // `String` buffer, but we need to be pretty careful when doing this. The
317 // implementation will just call `.as_mut_vec()` and then delegate to a
318 // byte-oriented reading method, but we must ensure that when returning we never
319 // leave `buf` in a state such that it contains invalid UTF-8 in its bounds.
321 // To this end, we use an RAII guard (to protect against panics) which updates
322 // the length of the string when it is dropped. This guard initially truncates
323 // the string to the prior length and only after we've validated that the
324 // new contents are valid UTF-8 do we allow it to set a longer length.
326 // The unsafety in this function is twofold:
328 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
330 // 2. We're passing a raw buffer to the function `f`, and it is expected that
331 // the function only *appends* bytes to the buffer. We'll get undefined
332 // behavior if existing bytes are overwritten to have non-UTF-8 data.
333 fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
335 F: FnOnce(&mut Vec<u8>) -> Result<usize>,
338 let mut g = Guard { len: buf.len(), buf: buf.as_mut_vec() };
340 if str::from_utf8(&g.buf[g.len..]).is_err() {
342 Err(Error::new(ErrorKind::InvalidData, "stream did not contain valid UTF-8"))
351 // This uses an adaptive system to extend the vector when it fills. We want to
352 // avoid paying to allocate and zero a huge chunk of memory if the reader only
353 // has 4 bytes while still making large reads if the reader does have a ton
354 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
355 // time is 4,500 times (!) slower than a default reservation size of 32 if the
356 // reader has a very small amount of data to return.
358 // Because we're extending the buffer with uninitialized data for trusted
359 // readers, we need to make sure to truncate that if any of this panics.
360 fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
361 read_to_end_with_reservation(r, buf, |_| 32)
364 fn read_to_end_with_reservation<R, F>(
367 mut reservation_size: F,
371 F: FnMut(&R) -> usize,
373 let start_len = buf.len();
374 let mut g = Guard { len: buf.len(), buf: buf };
377 if g.len == g.buf.len() {
379 // FIXME(danielhenrymantilla): #42788
381 // - This creates a (mut) reference to a slice of
382 // _uninitialized_ integers, which is **undefined behavior**
384 // - Only the standard library gets to soundly "ignore" this,
385 // based on its privileged knowledge of unstable rustc
387 g.buf.reserve(reservation_size(r));
388 let capacity = g.buf.capacity();
389 g.buf.set_len(capacity);
390 r.initializer().initialize(&mut g.buf[g.len..]);
394 match r.read(&mut g.buf[g.len..]) {
396 ret = Ok(g.len - start_len);
400 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
411 pub(crate) fn default_read_vectored<F>(read: F, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
413 F: FnOnce(&mut [u8]) -> Result<usize>,
415 let buf = bufs.iter_mut().find(|b| !b.is_empty()).map_or(&mut [][..], |b| &mut **b);
419 pub(crate) fn default_write_vectored<F>(write: F, bufs: &[IoSlice<'_>]) -> Result<usize>
421 F: FnOnce(&[u8]) -> Result<usize>,
423 let buf = bufs.iter().find(|b| !b.is_empty()).map_or(&[][..], |b| &**b);
427 /// The `Read` trait allows for reading bytes from a source.
429 /// Implementors of the `Read` trait are called 'readers'.
431 /// Readers are defined by one required method, [`read()`]. Each call to [`read()`]
432 /// will attempt to pull bytes from this source into a provided buffer. A
433 /// number of other methods are implemented in terms of [`read()`], giving
434 /// implementors a number of ways to read bytes while only needing to implement
437 /// Readers are intended to be composable with one another. Many implementors
438 /// throughout [`std::io`] take and provide types which implement the `Read`
441 /// Please note that each call to [`read()`] may involve a system call, and
442 /// therefore, using something that implements [`BufRead`], such as
443 /// [`BufReader`], will be more efficient.
447 /// [`File`]s implement `Read`:
451 /// use std::io::prelude::*;
452 /// use std::fs::File;
454 /// fn main() -> io::Result<()> {
455 /// let mut f = File::open("foo.txt")?;
456 /// let mut buffer = [0; 10];
458 /// // read up to 10 bytes
459 /// f.read(&mut buffer)?;
461 /// let mut buffer = Vec::new();
462 /// // read the whole file
463 /// f.read_to_end(&mut buffer)?;
465 /// // read into a String, so that you don't need to do the conversion.
466 /// let mut buffer = String::new();
467 /// f.read_to_string(&mut buffer)?;
469 /// // and more! See the other methods for more details.
474 /// Read from [`&str`] because [`&[u8]`][slice] implements `Read`:
478 /// use std::io::prelude::*;
480 /// fn main() -> io::Result<()> {
481 /// let mut b = "This string will be read".as_bytes();
482 /// let mut buffer = [0; 10];
484 /// // read up to 10 bytes
485 /// b.read(&mut buffer)?;
487 /// // etc... it works exactly as a File does!
492 /// [`read()`]: trait.Read.html#tymethod.read
493 /// [`std::io`]: ../../std/io/index.html
494 /// [`File`]: ../fs/struct.File.html
495 /// [`BufRead`]: trait.BufRead.html
496 /// [`BufReader`]: struct.BufReader.html
497 /// [`&str`]: ../../std/primitive.str.html
498 /// [slice]: ../../std/primitive.slice.html
499 #[stable(feature = "rust1", since = "1.0.0")]
502 /// Pull some bytes from this source into the specified buffer, returning
503 /// how many bytes were read.
505 /// This function does not provide any guarantees about whether it blocks
506 /// waiting for data, but if an object needs to block for a read but cannot
507 /// it will typically signal this via an [`Err`] return value.
509 /// If the return value of this method is [`Ok(n)`], then it must be
510 /// guaranteed that `0 <= n <= buf.len()`. A nonzero `n` value indicates
511 /// that the buffer `buf` has been filled in with `n` bytes of data from this
512 /// source. If `n` is `0`, then it can indicate one of two scenarios:
514 /// 1. This reader has reached its "end of file" and will likely no longer
515 /// be able to produce bytes. Note that this does not mean that the
516 /// reader will *always* no longer be able to produce bytes.
517 /// 2. The buffer specified was 0 bytes in length.
519 /// No guarantees are provided about the contents of `buf` when this
520 /// function is called, implementations cannot rely on any property of the
521 /// contents of `buf` being true. It is recommended that *implementations*
522 /// only write data to `buf` instead of reading its contents.
524 /// Correspondingly, however, *callers* of this method may not assume any guarantees
525 /// about how the implementation uses `buf`. The trait is safe to implement,
526 /// so it is possible that the code that's supposed to write to the buffer might also read
527 /// from it. It is your responsibility to make sure that `buf` is initialized
528 /// before calling `read`. Calling `read` with an uninitialized `buf` (of the kind one
529 /// obtains via [`MaybeUninit<T>`]) is not safe, and can lead to undefined behavior.
531 /// [`MaybeUninit<T>`]: ../mem/union.MaybeUninit.html
535 /// If this function encounters any form of I/O or other error, an error
536 /// variant will be returned. If an error is returned then it must be
537 /// guaranteed that no bytes were read.
539 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
540 /// operation should be retried if there is nothing else to do.
544 /// [`File`]s implement `Read`:
546 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
547 /// [`Ok(n)`]: ../../std/result/enum.Result.html#variant.Ok
548 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
549 /// [`File`]: ../fs/struct.File.html
553 /// use std::io::prelude::*;
554 /// use std::fs::File;
556 /// fn main() -> io::Result<()> {
557 /// let mut f = File::open("foo.txt")?;
558 /// let mut buffer = [0; 10];
560 /// // read up to 10 bytes
561 /// let n = f.read(&mut buffer[..])?;
563 /// println!("The bytes: {:?}", &buffer[..n]);
567 #[stable(feature = "rust1", since = "1.0.0")]
568 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
570 /// Like `read`, except that it reads into a slice of buffers.
572 /// Data is copied to fill each buffer in order, with the final buffer
573 /// written to possibly being only partially filled. This method must behave
574 /// as a single call to `read` with the buffers concatenated would.
576 /// The default implementation calls `read` with either the first nonempty
577 /// buffer provided, or an empty one if none exists.
578 #[stable(feature = "iovec", since = "1.36.0")]
579 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
580 default_read_vectored(|b| self.read(b), bufs)
583 /// Determines if this `Read`er can work with buffers of uninitialized
586 /// The default implementation returns an initializer which will zero
589 /// If a `Read`er guarantees that it can work properly with uninitialized
590 /// memory, it should call [`Initializer::nop()`]. See the documentation for
591 /// [`Initializer`] for details.
593 /// The behavior of this method must be independent of the state of the
594 /// `Read`er - the method only takes `&self` so that it can be used through
599 /// This method is unsafe because a `Read`er could otherwise return a
600 /// non-zeroing `Initializer` from another `Read` type without an `unsafe`
603 /// [`Initializer::nop()`]: ../../std/io/struct.Initializer.html#method.nop
604 /// [`Initializer`]: ../../std/io/struct.Initializer.html
605 #[unstable(feature = "read_initializer", issue = "42788")]
607 unsafe fn initializer(&self) -> Initializer {
608 Initializer::zeroing()
611 /// Read all bytes until EOF in this source, placing them into `buf`.
613 /// All bytes read from this source will be appended to the specified buffer
614 /// `buf`. This function will continuously call [`read()`] to append more data to
615 /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of
616 /// non-[`ErrorKind::Interrupted`] kind.
618 /// If successful, this function will return the total number of bytes read.
622 /// If this function encounters an error of the kind
623 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
626 /// If any other read error is encountered then this function immediately
627 /// returns. Any bytes which have already been read will be appended to
632 /// [`File`]s implement `Read`:
634 /// [`read()`]: trait.Read.html#tymethod.read
635 /// [`Ok(0)`]: ../../std/result/enum.Result.html#variant.Ok
636 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
637 /// [`File`]: ../fs/struct.File.html
641 /// use std::io::prelude::*;
642 /// use std::fs::File;
644 /// fn main() -> io::Result<()> {
645 /// let mut f = File::open("foo.txt")?;
646 /// let mut buffer = Vec::new();
648 /// // read the whole file
649 /// f.read_to_end(&mut buffer)?;
654 /// (See also the [`std::fs::read`] convenience function for reading from a
657 /// [`std::fs::read`]: ../fs/fn.read.html
658 #[stable(feature = "rust1", since = "1.0.0")]
659 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
660 read_to_end(self, buf)
663 /// Read all bytes until EOF in this source, appending them to `buf`.
665 /// If successful, this function returns the number of bytes which were read
666 /// and appended to `buf`.
670 /// If the data in this stream is *not* valid UTF-8 then an error is
671 /// returned and `buf` is unchanged.
673 /// See [`read_to_end`][readtoend] for other error semantics.
675 /// [readtoend]: #method.read_to_end
679 /// [`File`][file]s implement `Read`:
681 /// [file]: ../fs/struct.File.html
685 /// use std::io::prelude::*;
686 /// use std::fs::File;
688 /// fn main() -> io::Result<()> {
689 /// let mut f = File::open("foo.txt")?;
690 /// let mut buffer = String::new();
692 /// f.read_to_string(&mut buffer)?;
697 /// (See also the [`std::fs::read_to_string`] convenience function for
698 /// reading from a file.)
700 /// [`std::fs::read_to_string`]: ../fs/fn.read_to_string.html
701 #[stable(feature = "rust1", since = "1.0.0")]
702 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
703 // Note that we do *not* call `.read_to_end()` here. We are passing
704 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
705 // method to fill it up. An arbitrary implementation could overwrite the
706 // entire contents of the vector, not just append to it (which is what
707 // we are expecting).
709 // To prevent extraneously checking the UTF-8-ness of the entire buffer
710 // we pass it to our hardcoded `read_to_end` implementation which we
711 // know is guaranteed to only read data into the end of the buffer.
712 append_to_string(buf, |b| read_to_end(self, b))
715 /// Read the exact number of bytes required to fill `buf`.
717 /// This function reads as many bytes as necessary to completely fill the
718 /// specified buffer `buf`.
720 /// No guarantees are provided about the contents of `buf` when this
721 /// function is called, implementations cannot rely on any property of the
722 /// contents of `buf` being true. It is recommended that implementations
723 /// only write data to `buf` instead of reading its contents.
727 /// If this function encounters an error of the kind
728 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
731 /// If this function encounters an "end of file" before completely filling
732 /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
733 /// The contents of `buf` are unspecified in this case.
735 /// If any other read error is encountered then this function immediately
736 /// returns. The contents of `buf` are unspecified in this case.
738 /// If this function returns an error, it is unspecified how many bytes it
739 /// has read, but it will never read more than would be necessary to
740 /// completely fill the buffer.
744 /// [`File`]s implement `Read`:
746 /// [`File`]: ../fs/struct.File.html
747 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
748 /// [`ErrorKind::UnexpectedEof`]: ../../std/io/enum.ErrorKind.html#variant.UnexpectedEof
752 /// use std::io::prelude::*;
753 /// use std::fs::File;
755 /// fn main() -> io::Result<()> {
756 /// let mut f = File::open("foo.txt")?;
757 /// let mut buffer = [0; 10];
759 /// // read exactly 10 bytes
760 /// f.read_exact(&mut buffer)?;
764 #[stable(feature = "read_exact", since = "1.6.0")]
765 fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
766 while !buf.is_empty() {
767 match self.read(buf) {
773 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
774 Err(e) => return Err(e),
778 Err(Error::new(ErrorKind::UnexpectedEof, "failed to fill whole buffer"))
784 /// Creates a "by reference" adaptor for this instance of `Read`.
786 /// The returned adaptor also implements `Read` and will simply borrow this
791 /// [`File`][file]s implement `Read`:
793 /// [file]: ../fs/struct.File.html
797 /// use std::io::Read;
798 /// use std::fs::File;
800 /// fn main() -> io::Result<()> {
801 /// let mut f = File::open("foo.txt")?;
802 /// let mut buffer = Vec::new();
803 /// let mut other_buffer = Vec::new();
806 /// let reference = f.by_ref();
808 /// // read at most 5 bytes
809 /// reference.take(5).read_to_end(&mut buffer)?;
811 /// } // drop our &mut reference so we can use f again
813 /// // original file still usable, read the rest
814 /// f.read_to_end(&mut other_buffer)?;
818 #[stable(feature = "rust1", since = "1.0.0")]
819 fn by_ref(&mut self) -> &mut Self
826 /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
828 /// The returned type implements [`Iterator`] where the `Item` is
829 /// [`Result`]`<`[`u8`]`, `[`io::Error`]`>`.
830 /// The yielded item is [`Ok`] if a byte was successfully read and [`Err`]
831 /// otherwise. EOF is mapped to returning [`None`] from this iterator.
835 /// [`File`][file]s implement `Read`:
837 /// [file]: ../fs/struct.File.html
838 /// [`Iterator`]: ../../std/iter/trait.Iterator.html
839 /// [`Result`]: ../../std/result/enum.Result.html
840 /// [`io::Error`]: ../../std/io/struct.Error.html
841 /// [`u8`]: ../../std/primitive.u8.html
842 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
843 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
844 /// [`None`]: ../../std/option/enum.Option.html#variant.None
848 /// use std::io::prelude::*;
849 /// use std::fs::File;
851 /// fn main() -> io::Result<()> {
852 /// let mut f = File::open("foo.txt")?;
854 /// for byte in f.bytes() {
855 /// println!("{}", byte.unwrap());
860 #[stable(feature = "rust1", since = "1.0.0")]
861 fn bytes(self) -> Bytes<Self>
865 Bytes { inner: self }
868 /// Creates an adaptor which will chain this stream with another.
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`.
876 /// [`File`][file]s implement `Read`:
878 /// [file]: ../fs/struct.File.html
882 /// use std::io::prelude::*;
883 /// use std::fs::File;
885 /// fn main() -> io::Result<()> {
886 /// let mut f1 = File::open("foo.txt")?;
887 /// let mut f2 = File::open("bar.txt")?;
889 /// let mut handle = f1.chain(f2);
890 /// let mut buffer = String::new();
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)?;
898 #[stable(feature = "rust1", since = "1.0.0")]
899 fn chain<R: Read>(self, next: R) -> Chain<Self, R>
903 Chain { first: self, second: next, done_first: false }
906 /// Creates an adaptor which will read at most `limit` bytes from it.
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.
915 /// [`File`]s implement `Read`:
917 /// [`File`]: ../fs/struct.File.html
918 /// [`Ok(0)`]: ../../std/result/enum.Result.html#variant.Ok
919 /// [`read()`]: trait.Read.html#tymethod.read
923 /// use std::io::prelude::*;
924 /// use std::fs::File;
926 /// fn main() -> io::Result<()> {
927 /// let mut f = File::open("foo.txt")?;
928 /// let mut buffer = [0; 5];
930 /// // read at most five bytes
931 /// let mut handle = f.take(5);
933 /// handle.read(&mut buffer)?;
937 #[stable(feature = "rust1", since = "1.0.0")]
938 fn take(self, limit: u64) -> Take<Self>
942 Take { inner: self, limit: limit }
946 /// A buffer type used with `Read::read_vectored`.
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
951 #[stable(feature = "iovec", since = "1.36.0")]
953 pub struct IoSliceMut<'a>(sys::io::IoSliceMut<'a>);
955 #[stable(feature = "iovec", since = "1.36.0")]
956 impl<'a> fmt::Debug for IoSliceMut<'a> {
957 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
958 fmt::Debug::fmt(self.0.as_slice(), fmt)
962 impl<'a> IoSliceMut<'a> {
963 /// Creates a new `IoSliceMut` wrapping a byte slice.
967 /// Panics on Windows if the slice is larger than 4GB.
968 #[stable(feature = "iovec", since = "1.36.0")]
970 pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> {
971 IoSliceMut(sys::io::IoSliceMut::new(buf))
974 /// Advance the internal cursor of the slice.
978 /// Elements in the slice may be modified if the cursor is not advanced to
979 /// the end of the slice. For example if we have a slice of buffers with 2
980 /// `IoSliceMut`s, both of length 8, and we advance the cursor by 10 bytes
981 /// the first `IoSliceMut` will be untouched however the second will be
982 /// modified to remove the first 2 bytes (10 - 8).
987 /// #![feature(io_slice_advance)]
989 /// use std::io::IoSliceMut;
990 /// use std::ops::Deref;
992 /// let mut buf1 = [1; 8];
993 /// let mut buf2 = [2; 16];
994 /// let mut buf3 = [3; 8];
995 /// let mut bufs = &mut [
996 /// IoSliceMut::new(&mut buf1),
997 /// IoSliceMut::new(&mut buf2),
998 /// IoSliceMut::new(&mut buf3),
1001 /// // Mark 10 bytes as read.
1002 /// bufs = IoSliceMut::advance(bufs, 10);
1003 /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1004 /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1006 #[unstable(feature = "io_slice_advance", issue = "62726")]
1008 pub fn advance<'b>(bufs: &'b mut [IoSliceMut<'a>], n: usize) -> &'b mut [IoSliceMut<'a>] {
1009 // Number of buffers to remove.
1011 // Total length of all the to be removed buffers.
1012 let mut accumulated_len = 0;
1013 for buf in bufs.iter() {
1014 if accumulated_len + buf.len() > n {
1017 accumulated_len += buf.len();
1022 let bufs = &mut bufs[remove..];
1023 if !bufs.is_empty() {
1024 bufs[0].0.advance(n - accumulated_len)
1030 #[stable(feature = "iovec", since = "1.36.0")]
1031 impl<'a> Deref for IoSliceMut<'a> {
1035 fn deref(&self) -> &[u8] {
1040 #[stable(feature = "iovec", since = "1.36.0")]
1041 impl<'a> DerefMut for IoSliceMut<'a> {
1043 fn deref_mut(&mut self) -> &mut [u8] {
1044 self.0.as_mut_slice()
1048 /// A buffer type used with `Write::write_vectored`.
1050 /// It is semantically a wrapper around an `&[u8]`, but is guaranteed to be
1051 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
1053 #[stable(feature = "iovec", since = "1.36.0")]
1054 #[repr(transparent)]
1055 pub struct IoSlice<'a>(sys::io::IoSlice<'a>);
1057 #[stable(feature = "iovec", since = "1.36.0")]
1058 impl<'a> fmt::Debug for IoSlice<'a> {
1059 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1060 fmt::Debug::fmt(self.0.as_slice(), fmt)
1064 impl<'a> IoSlice<'a> {
1065 /// Creates a new `IoSlice` wrapping a byte slice.
1069 /// Panics on Windows if the slice is larger than 4GB.
1070 #[stable(feature = "iovec", since = "1.36.0")]
1072 pub fn new(buf: &'a [u8]) -> IoSlice<'a> {
1073 IoSlice(sys::io::IoSlice::new(buf))
1076 /// Advance the internal cursor of the slice.
1080 /// Elements in the slice may be modified if the cursor is not advanced to
1081 /// the end of the slice. For example if we have a slice of buffers with 2
1082 /// `IoSlice`s, both of length 8, and we advance the cursor by 10 bytes the
1083 /// first `IoSlice` will be untouched however the second will be modified to
1084 /// remove the first 2 bytes (10 - 8).
1089 /// #![feature(io_slice_advance)]
1091 /// use std::io::IoSlice;
1092 /// use std::ops::Deref;
1094 /// let buf1 = [1; 8];
1095 /// let buf2 = [2; 16];
1096 /// let buf3 = [3; 8];
1097 /// let mut bufs = &mut [
1098 /// IoSlice::new(&buf1),
1099 /// IoSlice::new(&buf2),
1100 /// IoSlice::new(&buf3),
1103 /// // Mark 10 bytes as written.
1104 /// bufs = IoSlice::advance(bufs, 10);
1105 /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1106 /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1107 #[unstable(feature = "io_slice_advance", issue = "62726")]
1109 pub fn advance<'b>(bufs: &'b mut [IoSlice<'a>], n: usize) -> &'b mut [IoSlice<'a>] {
1110 // Number of buffers to remove.
1112 // Total length of all the to be removed buffers.
1113 let mut accumulated_len = 0;
1114 for buf in bufs.iter() {
1115 if accumulated_len + buf.len() > n {
1118 accumulated_len += buf.len();
1123 let bufs = &mut bufs[remove..];
1124 if !bufs.is_empty() {
1125 bufs[0].0.advance(n - accumulated_len)
1131 #[stable(feature = "iovec", since = "1.36.0")]
1132 impl<'a> Deref for IoSlice<'a> {
1136 fn deref(&self) -> &[u8] {
1141 /// A type used to conditionally initialize buffers passed to `Read` methods.
1142 #[unstable(feature = "read_initializer", issue = "42788")]
1144 pub struct Initializer(bool);
1147 /// Returns a new `Initializer` which will zero out buffers.
1148 #[unstable(feature = "read_initializer", issue = "42788")]
1150 pub fn zeroing() -> Initializer {
1154 /// Returns a new `Initializer` which will not zero out buffers.
1158 /// This may only be called by `Read`ers which guarantee that they will not
1159 /// read from buffers passed to `Read` methods, and that the return value of
1160 /// the method accurately reflects the number of bytes that have been
1161 /// written to the head of the buffer.
1162 #[unstable(feature = "read_initializer", issue = "42788")]
1164 pub unsafe fn nop() -> Initializer {
1168 /// Indicates if a buffer should be initialized.
1169 #[unstable(feature = "read_initializer", issue = "42788")]
1171 pub fn should_initialize(&self) -> bool {
1175 /// Initializes a buffer if necessary.
1176 #[unstable(feature = "read_initializer", issue = "42788")]
1178 pub fn initialize(&self, buf: &mut [u8]) {
1179 if self.should_initialize() {
1180 unsafe { ptr::write_bytes(buf.as_mut_ptr(), 0, buf.len()) }
1185 /// A trait for objects which are byte-oriented sinks.
1187 /// Implementors of the `Write` trait are sometimes called 'writers'.
1189 /// Writers are defined by two required methods, [`write`] and [`flush`]:
1191 /// * The [`write`] method will attempt to write some data into the object,
1192 /// returning how many bytes were successfully written.
1194 /// * The [`flush`] method is useful for adaptors and explicit buffers
1195 /// themselves for ensuring that all buffered data has been pushed out to the
1198 /// Writers are intended to be composable with one another. Many implementors
1199 /// throughout [`std::io`] take and provide types which implement the `Write`
1202 /// [`write`]: #tymethod.write
1203 /// [`flush`]: #tymethod.flush
1204 /// [`std::io`]: index.html
1209 /// use std::io::prelude::*;
1210 /// use std::fs::File;
1212 /// fn main() -> std::io::Result<()> {
1213 /// let data = b"some bytes";
1215 /// let mut pos = 0;
1216 /// let mut buffer = File::create("foo.txt")?;
1218 /// while pos < data.len() {
1219 /// let bytes_written = buffer.write(&data[pos..])?;
1220 /// pos += bytes_written;
1226 /// The trait also provides convenience methods like [`write_all`], which calls
1227 /// `write` in a loop until its entire input has been written.
1229 /// [`write_all`]: #method.write_all
1230 #[stable(feature = "rust1", since = "1.0.0")]
1233 /// Write a buffer into this writer, returning how many bytes were written.
1235 /// This function will attempt to write the entire contents of `buf`, but
1236 /// the entire write may not succeed, or the write may also generate an
1237 /// error. A call to `write` represents *at most one* attempt to write to
1238 /// any wrapped object.
1240 /// Calls to `write` are not guaranteed to block waiting for data to be
1241 /// written, and a write which would otherwise block can be indicated through
1242 /// an [`Err`] variant.
1244 /// If the return value is [`Ok(n)`] then it must be guaranteed that
1245 /// `n <= buf.len()`. A return value of `0` typically means that the
1246 /// underlying object is no longer able to accept bytes and will likely not
1247 /// be able to in the future as well, or that the buffer provided is empty.
1251 /// Each call to `write` may generate an I/O error indicating that the
1252 /// operation could not be completed. If an error is returned then no bytes
1253 /// in the buffer were written to this writer.
1255 /// It is **not** considered an error if the entire buffer could not be
1256 /// written to this writer.
1258 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the
1259 /// write operation should be retried if there is nothing else to do.
1261 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
1262 /// [`Ok(n)`]: ../../std/result/enum.Result.html#variant.Ok
1263 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
1268 /// use std::io::prelude::*;
1269 /// use std::fs::File;
1271 /// fn main() -> std::io::Result<()> {
1272 /// let mut buffer = File::create("foo.txt")?;
1274 /// // Writes some prefix of the byte string, not necessarily all of it.
1275 /// buffer.write(b"some bytes")?;
1279 #[stable(feature = "rust1", since = "1.0.0")]
1280 fn write(&mut self, buf: &[u8]) -> Result<usize>;
1282 /// Like `write`, except that it writes from a slice of buffers.
1284 /// Data is copied from each buffer in order, with the final buffer
1285 /// read from possibly being only partially consumed. This method must
1286 /// behave as a call to `write` with the buffers concatenated would.
1288 /// The default implementation calls `write` with either the first nonempty
1289 /// buffer provided, or an empty one if none exists.
1290 #[stable(feature = "iovec", since = "1.36.0")]
1291 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize> {
1292 default_write_vectored(|b| self.write(b), bufs)
1295 /// Flush this output stream, ensuring that all intermediately buffered
1296 /// contents reach their destination.
1300 /// It is considered an error if not all bytes could be written due to
1301 /// I/O errors or EOF being reached.
1306 /// use std::io::prelude::*;
1307 /// use std::io::BufWriter;
1308 /// use std::fs::File;
1310 /// fn main() -> std::io::Result<()> {
1311 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
1313 /// buffer.write_all(b"some bytes")?;
1314 /// buffer.flush()?;
1318 #[stable(feature = "rust1", since = "1.0.0")]
1319 fn flush(&mut self) -> Result<()>;
1321 /// Attempts to write an entire buffer into this writer.
1323 /// This method will continuously call [`write`] until there is no more data
1324 /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is
1325 /// returned. This method will not return until the entire buffer has been
1326 /// successfully written or such an error occurs. The first error that is
1327 /// not of [`ErrorKind::Interrupted`] kind generated from this method will be
1330 /// If the buffer contains no data, this will never call [`write`].
1334 /// This function will return the first error of
1335 /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns.
1337 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
1338 /// [`write`]: #tymethod.write
1343 /// use std::io::prelude::*;
1344 /// use std::fs::File;
1346 /// fn main() -> std::io::Result<()> {
1347 /// let mut buffer = File::create("foo.txt")?;
1349 /// buffer.write_all(b"some bytes")?;
1353 #[stable(feature = "rust1", since = "1.0.0")]
1354 fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
1355 while !buf.is_empty() {
1356 match self.write(buf) {
1358 return Err(Error::new(ErrorKind::WriteZero, "failed to write whole buffer"));
1360 Ok(n) => buf = &buf[n..],
1361 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1362 Err(e) => return Err(e),
1368 /// Writes a formatted string into this writer, returning any error
1371 /// This method is primarily used to interface with the
1372 /// [`format_args!`][formatargs] macro, but it is rare that this should
1373 /// explicitly be called. The [`write!`][write] macro should be favored to
1374 /// invoke this method instead.
1376 /// [formatargs]: ../macro.format_args.html
1377 /// [write]: ../macro.write.html
1379 /// This function internally uses the [`write_all`][writeall] method on
1380 /// this trait and hence will continuously write data so long as no errors
1381 /// are received. This also means that partial writes are not indicated in
1384 /// [writeall]: #method.write_all
1388 /// This function will return any I/O error reported while formatting.
1393 /// use std::io::prelude::*;
1394 /// use std::fs::File;
1396 /// fn main() -> std::io::Result<()> {
1397 /// let mut buffer = File::create("foo.txt")?;
1400 /// write!(buffer, "{:.*}", 2, 1.234567)?;
1401 /// // turns into this:
1402 /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1406 #[stable(feature = "rust1", since = "1.0.0")]
1407 fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> Result<()> {
1408 // Create a shim which translates a Write to a fmt::Write and saves
1409 // off I/O errors. instead of discarding them
1410 struct Adaptor<'a, T: ?Sized + 'a> {
1415 impl<T: Write + ?Sized> fmt::Write for Adaptor<'_, T> {
1416 fn write_str(&mut self, s: &str) -> fmt::Result {
1417 match self.inner.write_all(s.as_bytes()) {
1420 self.error = Err(e);
1427 let mut output = Adaptor { inner: self, error: Ok(()) };
1428 match fmt::write(&mut output, fmt) {
1431 // check if the error came from the underlying `Write` or not
1432 if output.error.is_err() {
1435 Err(Error::new(ErrorKind::Other, "formatter error"))
1441 /// Creates a "by reference" adaptor for this instance of `Write`.
1443 /// The returned adaptor also implements `Write` and will simply borrow this
1449 /// use std::io::Write;
1450 /// use std::fs::File;
1452 /// fn main() -> std::io::Result<()> {
1453 /// let mut buffer = File::create("foo.txt")?;
1455 /// let reference = buffer.by_ref();
1457 /// // we can use reference just like our original buffer
1458 /// reference.write_all(b"some bytes")?;
1462 #[stable(feature = "rust1", since = "1.0.0")]
1463 fn by_ref(&mut self) -> &mut Self
1471 /// The `Seek` trait provides a cursor which can be moved within a stream of
1474 /// The stream typically has a fixed size, allowing seeking relative to either
1475 /// end or the current offset.
1479 /// [`File`][file]s implement `Seek`:
1481 /// [file]: ../fs/struct.File.html
1485 /// use std::io::prelude::*;
1486 /// use std::fs::File;
1487 /// use std::io::SeekFrom;
1489 /// fn main() -> io::Result<()> {
1490 /// let mut f = File::open("foo.txt")?;
1492 /// // move the cursor 42 bytes from the start of the file
1493 /// f.seek(SeekFrom::Start(42))?;
1497 #[stable(feature = "rust1", since = "1.0.0")]
1499 /// Seek to an offset, in bytes, in a stream.
1501 /// A seek beyond the end of a stream is allowed, but behavior is defined
1502 /// by the implementation.
1504 /// If the seek operation completed successfully,
1505 /// this method returns the new position from the start of the stream.
1506 /// That position can be used later with [`SeekFrom::Start`].
1510 /// Seeking to a negative offset is considered an error.
1512 /// [`SeekFrom::Start`]: enum.SeekFrom.html#variant.Start
1513 #[stable(feature = "rust1", since = "1.0.0")]
1514 fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1516 /// Returns the length of this stream (in bytes).
1518 /// This method is implemented using up to three seek operations. If this
1519 /// method returns successfully, the seek position is unchanged (i.e. the
1520 /// position before calling this method is the same as afterwards).
1521 /// However, if this method returns an error, the seek position is
1524 /// If you need to obtain the length of *many* streams and you don't care
1525 /// about the seek position afterwards, you can reduce the number of seek
1526 /// operations by simply calling `seek(SeekFrom::End(0))` and using its
1527 /// return value (it is also the stream length).
1529 /// Note that length of a stream can change over time (for example, when
1530 /// data is appended to a file). So calling this method multiple times does
1531 /// not necessarily return the same length each time.
1537 /// #![feature(seek_convenience)]
1539 /// io::{self, Seek},
1543 /// fn main() -> io::Result<()> {
1544 /// let mut f = File::open("foo.txt")?;
1546 /// let len = f.stream_len()?;
1547 /// println!("The file is currently {} bytes long", len);
1551 #[unstable(feature = "seek_convenience", issue = "59359")]
1552 fn stream_len(&mut self) -> Result<u64> {
1553 let old_pos = self.stream_position()?;
1554 let len = self.seek(SeekFrom::End(0))?;
1556 // Avoid seeking a third time when we were already at the end of the
1557 // stream. The branch is usually way cheaper than a seek operation.
1559 self.seek(SeekFrom::Start(old_pos))?;
1565 /// Returns the current seek position from the start of the stream.
1567 /// This is equivalent to `self.seek(SeekFrom::Current(0))`.
1573 /// #![feature(seek_convenience)]
1575 /// io::{self, BufRead, BufReader, Seek},
1579 /// fn main() -> io::Result<()> {
1580 /// let mut f = BufReader::new(File::open("foo.txt")?);
1582 /// let before = f.stream_position()?;
1583 /// f.read_line(&mut String::new())?;
1584 /// let after = f.stream_position()?;
1586 /// println!("The first line was {} bytes long", after - before);
1590 #[unstable(feature = "seek_convenience", issue = "59359")]
1591 fn stream_position(&mut self) -> Result<u64> {
1592 self.seek(SeekFrom::Current(0))
1596 /// Enumeration of possible methods to seek within an I/O object.
1598 /// It is used by the [`Seek`] trait.
1600 /// [`Seek`]: trait.Seek.html
1601 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1602 #[stable(feature = "rust1", since = "1.0.0")]
1604 /// Sets the offset to the provided number of bytes.
1605 #[stable(feature = "rust1", since = "1.0.0")]
1606 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1608 /// Sets the offset to the size of this object plus the specified number of
1611 /// It is possible to seek beyond the end of an object, but it's an error to
1612 /// seek before byte 0.
1613 #[stable(feature = "rust1", since = "1.0.0")]
1614 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1616 /// Sets the offset to the current position plus the specified number of
1619 /// It is possible to seek beyond the end of an object, but it's an error to
1620 /// seek before byte 0.
1621 #[stable(feature = "rust1", since = "1.0.0")]
1622 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1625 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>) -> Result<usize> {
1628 let (done, used) = {
1629 let available = match r.fill_buf() {
1631 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1632 Err(e) => return Err(e),
1634 match memchr::memchr(delim, available) {
1636 buf.extend_from_slice(&available[..=i]);
1640 buf.extend_from_slice(available);
1641 (false, available.len())
1647 if done || used == 0 {
1653 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1654 /// to perform extra ways of reading.
1656 /// For example, reading line-by-line is inefficient without using a buffer, so
1657 /// if you want to read by line, you'll need `BufRead`, which includes a
1658 /// [`read_line`] method as well as a [`lines`] iterator.
1662 /// A locked standard input implements `BufRead`:
1666 /// use std::io::prelude::*;
1668 /// let stdin = io::stdin();
1669 /// for line in stdin.lock().lines() {
1670 /// println!("{}", line.unwrap());
1674 /// If you have something that implements [`Read`], you can use the [`BufReader`
1675 /// type][`BufReader`] to turn it into a `BufRead`.
1677 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1678 /// [`BufReader`] to the rescue!
1680 /// [`BufReader`]: struct.BufReader.html
1681 /// [`File`]: ../fs/struct.File.html
1682 /// [`read_line`]: #method.read_line
1683 /// [`lines`]: #method.lines
1684 /// [`Read`]: trait.Read.html
1687 /// use std::io::{self, BufReader};
1688 /// use std::io::prelude::*;
1689 /// use std::fs::File;
1691 /// fn main() -> io::Result<()> {
1692 /// let f = File::open("foo.txt")?;
1693 /// let f = BufReader::new(f);
1695 /// for line in f.lines() {
1696 /// println!("{}", line.unwrap());
1703 #[stable(feature = "rust1", since = "1.0.0")]
1704 pub trait BufRead: Read {
1705 /// Returns the contents of the internal buffer, filling it with more data
1706 /// from the inner reader if it is empty.
1708 /// This function is a lower-level call. It needs to be paired with the
1709 /// [`consume`] method to function properly. When calling this
1710 /// method, none of the contents will be "read" in the sense that later
1711 /// calling `read` may return the same contents. As such, [`consume`] must
1712 /// be called with the number of bytes that are consumed from this buffer to
1713 /// ensure that the bytes are never returned twice.
1715 /// [`consume`]: #tymethod.consume
1717 /// An empty buffer returned indicates that the stream has reached EOF.
1721 /// This function will return an I/O error if the underlying reader was
1722 /// read, but returned an error.
1726 /// A locked standard input implements `BufRead`:
1730 /// use std::io::prelude::*;
1732 /// let stdin = io::stdin();
1733 /// let mut stdin = stdin.lock();
1735 /// let buffer = stdin.fill_buf().unwrap();
1737 /// // work with buffer
1738 /// println!("{:?}", buffer);
1740 /// // ensure the bytes we worked with aren't returned again later
1741 /// let length = buffer.len();
1742 /// stdin.consume(length);
1744 #[stable(feature = "rust1", since = "1.0.0")]
1745 fn fill_buf(&mut self) -> Result<&[u8]>;
1747 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1748 /// so they should no longer be returned in calls to `read`.
1750 /// This function is a lower-level call. It needs to be paired with the
1751 /// [`fill_buf`] method to function properly. This function does
1752 /// not perform any I/O, it simply informs this object that some amount of
1753 /// its buffer, returned from [`fill_buf`], has been consumed and should
1754 /// no longer be returned. As such, this function may do odd things if
1755 /// [`fill_buf`] isn't called before calling it.
1757 /// The `amt` must be `<=` the number of bytes in the buffer returned by
1762 /// Since `consume()` is meant to be used with [`fill_buf`],
1763 /// that method's example includes an example of `consume()`.
1765 /// [`fill_buf`]: #tymethod.fill_buf
1766 #[stable(feature = "rust1", since = "1.0.0")]
1767 fn consume(&mut self, amt: usize);
1769 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
1771 /// This function will read bytes from the underlying stream until the
1772 /// delimiter or EOF is found. Once found, all bytes up to, and including,
1773 /// the delimiter (if found) will be appended to `buf`.
1775 /// If successful, this function will return the total number of bytes read.
1779 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1780 /// will otherwise return any errors returned by [`fill_buf`].
1782 /// If an I/O error is encountered then all bytes read so far will be
1783 /// present in `buf` and its length will have been adjusted appropriately.
1785 /// [`fill_buf`]: #tymethod.fill_buf
1786 /// [`ErrorKind::Interrupted`]: enum.ErrorKind.html#variant.Interrupted
1790 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1791 /// this example, we use [`Cursor`] to read all the bytes in a byte slice
1792 /// in hyphen delimited segments:
1794 /// [`Cursor`]: struct.Cursor.html
1797 /// use std::io::{self, BufRead};
1799 /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
1800 /// let mut buf = vec![];
1802 /// // cursor is at 'l'
1803 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1804 /// .expect("reading from cursor won't fail");
1805 /// assert_eq!(num_bytes, 6);
1806 /// assert_eq!(buf, b"lorem-");
1809 /// // cursor is at 'i'
1810 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1811 /// .expect("reading from cursor won't fail");
1812 /// assert_eq!(num_bytes, 5);
1813 /// assert_eq!(buf, b"ipsum");
1816 /// // cursor is at EOF
1817 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1818 /// .expect("reading from cursor won't fail");
1819 /// assert_eq!(num_bytes, 0);
1820 /// assert_eq!(buf, b"");
1822 #[stable(feature = "rust1", since = "1.0.0")]
1823 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
1824 read_until(self, byte, buf)
1827 /// Read all bytes until a newline (the 0xA byte) is reached, and append
1828 /// them to the provided buffer.
1830 /// This function will read bytes from the underlying stream until the
1831 /// newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes
1832 /// up to, and including, the delimiter (if found) will be appended to
1835 /// If successful, this function will return the total number of bytes read.
1837 /// If this function returns `Ok(0)`, the stream has reached EOF.
1841 /// This function has the same error semantics as [`read_until`] and will
1842 /// also return an error if the read bytes are not valid UTF-8. If an I/O
1843 /// error is encountered then `buf` may contain some bytes already read in
1844 /// the event that all data read so far was valid UTF-8.
1846 /// [`read_until`]: #method.read_until
1850 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1851 /// this example, we use [`Cursor`] to read all the lines in a byte slice:
1853 /// [`Cursor`]: struct.Cursor.html
1856 /// use std::io::{self, BufRead};
1858 /// let mut cursor = io::Cursor::new(b"foo\nbar");
1859 /// let mut buf = String::new();
1861 /// // cursor is at 'f'
1862 /// let num_bytes = cursor.read_line(&mut buf)
1863 /// .expect("reading from cursor won't fail");
1864 /// assert_eq!(num_bytes, 4);
1865 /// assert_eq!(buf, "foo\n");
1868 /// // cursor is at 'b'
1869 /// let num_bytes = cursor.read_line(&mut buf)
1870 /// .expect("reading from cursor won't fail");
1871 /// assert_eq!(num_bytes, 3);
1872 /// assert_eq!(buf, "bar");
1875 /// // cursor is at EOF
1876 /// let num_bytes = cursor.read_line(&mut buf)
1877 /// .expect("reading from cursor won't fail");
1878 /// assert_eq!(num_bytes, 0);
1879 /// assert_eq!(buf, "");
1881 #[stable(feature = "rust1", since = "1.0.0")]
1882 fn read_line(&mut self, buf: &mut String) -> Result<usize> {
1883 // Note that we are not calling the `.read_until` method here, but
1884 // rather our hardcoded implementation. For more details as to why, see
1885 // the comments in `read_to_end`.
1886 append_to_string(buf, |b| read_until(self, b'\n', b))
1889 /// Returns an iterator over the contents of this reader split on the byte
1892 /// The iterator returned from this function will return instances of
1893 /// [`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
1894 /// the delimiter byte at the end.
1896 /// This function will yield errors whenever [`read_until`] would have
1897 /// also yielded an error.
1899 /// [`io::Result`]: type.Result.html
1900 /// [`Vec<u8>`]: ../vec/struct.Vec.html
1901 /// [`read_until`]: #method.read_until
1905 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1906 /// this example, we use [`Cursor`] to iterate over all hyphen delimited
1907 /// segments in a byte slice
1909 /// [`Cursor`]: struct.Cursor.html
1912 /// use std::io::{self, BufRead};
1914 /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
1916 /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
1917 /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
1918 /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
1919 /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
1920 /// assert_eq!(split_iter.next(), None);
1922 #[stable(feature = "rust1", since = "1.0.0")]
1923 fn split(self, byte: u8) -> Split<Self>
1927 Split { buf: self, delim: byte }
1930 /// Returns an iterator over the lines of this reader.
1932 /// The iterator returned from this function will yield instances of
1933 /// [`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline
1934 /// byte (the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.
1936 /// [`io::Result`]: type.Result.html
1937 /// [`String`]: ../string/struct.String.html
1941 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1942 /// this example, we use [`Cursor`] to iterate over all the lines in a byte
1945 /// [`Cursor`]: struct.Cursor.html
1948 /// use std::io::{self, BufRead};
1950 /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
1952 /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
1953 /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
1954 /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
1955 /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
1956 /// assert_eq!(lines_iter.next(), None);
1961 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
1963 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
1964 #[stable(feature = "rust1", since = "1.0.0")]
1965 fn lines(self) -> Lines<Self>
1973 /// Adaptor to chain together two readers.
1975 /// This struct is generally created by calling [`chain`] on a reader.
1976 /// Please see the documentation of [`chain`] for more details.
1978 /// [`chain`]: trait.Read.html#method.chain
1979 #[stable(feature = "rust1", since = "1.0.0")]
1980 pub struct Chain<T, U> {
1986 impl<T, U> Chain<T, U> {
1987 /// Consumes the `Chain`, returning the wrapped readers.
1993 /// use std::io::prelude::*;
1994 /// use std::fs::File;
1996 /// fn main() -> io::Result<()> {
1997 /// let mut foo_file = File::open("foo.txt")?;
1998 /// let mut bar_file = File::open("bar.txt")?;
2000 /// let chain = foo_file.chain(bar_file);
2001 /// let (foo_file, bar_file) = chain.into_inner();
2005 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2006 pub fn into_inner(self) -> (T, U) {
2007 (self.first, self.second)
2010 /// Gets references to the underlying readers in this `Chain`.
2016 /// use std::io::prelude::*;
2017 /// use std::fs::File;
2019 /// fn main() -> io::Result<()> {
2020 /// let mut foo_file = File::open("foo.txt")?;
2021 /// let mut bar_file = File::open("bar.txt")?;
2023 /// let chain = foo_file.chain(bar_file);
2024 /// let (foo_file, bar_file) = chain.get_ref();
2028 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2029 pub fn get_ref(&self) -> (&T, &U) {
2030 (&self.first, &self.second)
2033 /// Gets mutable references to the underlying readers in this `Chain`.
2035 /// Care should be taken to avoid modifying the internal I/O state of the
2036 /// underlying readers as doing so may corrupt the internal state of this
2043 /// use std::io::prelude::*;
2044 /// use std::fs::File;
2046 /// fn main() -> io::Result<()> {
2047 /// let mut foo_file = File::open("foo.txt")?;
2048 /// let mut bar_file = File::open("bar.txt")?;
2050 /// let mut chain = foo_file.chain(bar_file);
2051 /// let (foo_file, bar_file) = chain.get_mut();
2055 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2056 pub fn get_mut(&mut self) -> (&mut T, &mut U) {
2057 (&mut self.first, &mut self.second)
2061 #[stable(feature = "std_debug", since = "1.16.0")]
2062 impl<T: fmt::Debug, U: fmt::Debug> fmt::Debug for Chain<T, U> {
2063 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2064 f.debug_struct("Chain").field("t", &self.first).field("u", &self.second).finish()
2068 #[stable(feature = "rust1", since = "1.0.0")]
2069 impl<T: Read, U: Read> Read for Chain<T, U> {
2070 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2071 if !self.done_first {
2072 match self.first.read(buf)? {
2073 0 if !buf.is_empty() => self.done_first = true,
2077 self.second.read(buf)
2080 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
2081 if !self.done_first {
2082 match self.first.read_vectored(bufs)? {
2083 0 if bufs.iter().any(|b| !b.is_empty()) => self.done_first = true,
2087 self.second.read_vectored(bufs)
2090 unsafe fn initializer(&self) -> Initializer {
2091 let initializer = self.first.initializer();
2092 if initializer.should_initialize() { initializer } else { self.second.initializer() }
2096 #[stable(feature = "chain_bufread", since = "1.9.0")]
2097 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
2098 fn fill_buf(&mut self) -> Result<&[u8]> {
2099 if !self.done_first {
2100 match self.first.fill_buf()? {
2101 buf if buf.is_empty() => {
2102 self.done_first = true;
2104 buf => return Ok(buf),
2107 self.second.fill_buf()
2110 fn consume(&mut self, amt: usize) {
2111 if !self.done_first { self.first.consume(amt) } else { self.second.consume(amt) }
2115 /// Reader adaptor which limits the bytes read from an underlying reader.
2117 /// This struct is generally created by calling [`take`] on a reader.
2118 /// Please see the documentation of [`take`] for more details.
2120 /// [`take`]: trait.Read.html#method.take
2121 #[stable(feature = "rust1", since = "1.0.0")]
2123 pub struct Take<T> {
2129 /// Returns the number of bytes that can be read before this instance will
2134 /// This instance may reach `EOF` after reading fewer bytes than indicated by
2135 /// this method if the underlying [`Read`] instance reaches EOF.
2137 /// [`Read`]: ../../std/io/trait.Read.html
2143 /// use std::io::prelude::*;
2144 /// use std::fs::File;
2146 /// fn main() -> io::Result<()> {
2147 /// let f = File::open("foo.txt")?;
2149 /// // read at most five bytes
2150 /// let handle = f.take(5);
2152 /// println!("limit: {}", handle.limit());
2156 #[stable(feature = "rust1", since = "1.0.0")]
2157 pub fn limit(&self) -> u64 {
2161 /// Sets the number of bytes that can be read before this instance will
2162 /// return EOF. This is the same as constructing a new `Take` instance, so
2163 /// the amount of bytes read and the previous limit value don't matter when
2164 /// calling this method.
2170 /// use std::io::prelude::*;
2171 /// use std::fs::File;
2173 /// fn main() -> io::Result<()> {
2174 /// let f = File::open("foo.txt")?;
2176 /// // read at most five bytes
2177 /// let mut handle = f.take(5);
2178 /// handle.set_limit(10);
2180 /// assert_eq!(handle.limit(), 10);
2184 #[stable(feature = "take_set_limit", since = "1.27.0")]
2185 pub fn set_limit(&mut self, limit: u64) {
2189 /// Consumes the `Take`, returning the wrapped reader.
2195 /// use std::io::prelude::*;
2196 /// use std::fs::File;
2198 /// fn main() -> io::Result<()> {
2199 /// let mut file = File::open("foo.txt")?;
2201 /// let mut buffer = [0; 5];
2202 /// let mut handle = file.take(5);
2203 /// handle.read(&mut buffer)?;
2205 /// let file = handle.into_inner();
2209 #[stable(feature = "io_take_into_inner", since = "1.15.0")]
2210 pub fn into_inner(self) -> T {
2214 /// Gets a reference to the underlying reader.
2220 /// use std::io::prelude::*;
2221 /// use std::fs::File;
2223 /// fn main() -> io::Result<()> {
2224 /// let mut file = File::open("foo.txt")?;
2226 /// let mut buffer = [0; 5];
2227 /// let mut handle = file.take(5);
2228 /// handle.read(&mut buffer)?;
2230 /// let file = handle.get_ref();
2234 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2235 pub fn get_ref(&self) -> &T {
2239 /// Gets a mutable reference to the underlying reader.
2241 /// Care should be taken to avoid modifying the internal I/O state of the
2242 /// underlying reader as doing so may corrupt the internal limit of this
2249 /// use std::io::prelude::*;
2250 /// use std::fs::File;
2252 /// fn main() -> io::Result<()> {
2253 /// let mut file = File::open("foo.txt")?;
2255 /// let mut buffer = [0; 5];
2256 /// let mut handle = file.take(5);
2257 /// handle.read(&mut buffer)?;
2259 /// let file = handle.get_mut();
2263 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2264 pub fn get_mut(&mut self) -> &mut T {
2269 #[stable(feature = "rust1", since = "1.0.0")]
2270 impl<T: Read> Read for Take<T> {
2271 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2272 // Don't call into inner reader at all at EOF because it may still block
2273 if self.limit == 0 {
2277 let max = cmp::min(buf.len() as u64, self.limit) as usize;
2278 let n = self.inner.read(&mut buf[..max])?;
2279 self.limit -= n as u64;
2283 unsafe fn initializer(&self) -> Initializer {
2284 self.inner.initializer()
2287 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
2288 // Pass in a reservation_size closure that respects the current value
2289 // of limit for each read. If we hit the read limit, this prevents the
2290 // final zero-byte read from allocating again.
2291 read_to_end_with_reservation(self, buf, |self_| cmp::min(self_.limit, 32) as usize)
2295 #[stable(feature = "rust1", since = "1.0.0")]
2296 impl<T: BufRead> BufRead for Take<T> {
2297 fn fill_buf(&mut self) -> Result<&[u8]> {
2298 // Don't call into inner reader at all at EOF because it may still block
2299 if self.limit == 0 {
2303 let buf = self.inner.fill_buf()?;
2304 let cap = cmp::min(buf.len() as u64, self.limit) as usize;
2308 fn consume(&mut self, amt: usize) {
2309 // Don't let callers reset the limit by passing an overlarge value
2310 let amt = cmp::min(amt as u64, self.limit) as usize;
2311 self.limit -= amt as u64;
2312 self.inner.consume(amt);
2316 /// An iterator over `u8` values of a reader.
2318 /// This struct is generally created by calling [`bytes`] on a reader.
2319 /// Please see the documentation of [`bytes`] for more details.
2321 /// [`bytes`]: trait.Read.html#method.bytes
2322 #[stable(feature = "rust1", since = "1.0.0")]
2324 pub struct Bytes<R> {
2328 #[stable(feature = "rust1", since = "1.0.0")]
2329 impl<R: Read> Iterator for Bytes<R> {
2330 type Item = Result<u8>;
2332 fn next(&mut self) -> Option<Result<u8>> {
2335 return match self.inner.read(slice::from_mut(&mut byte)) {
2337 Ok(..) => Some(Ok(byte)),
2338 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
2339 Err(e) => Some(Err(e)),
2345 /// An iterator over the contents of an instance of `BufRead` split on a
2346 /// particular byte.
2348 /// This struct is generally created by calling [`split`] on a `BufRead`.
2349 /// Please see the documentation of [`split`] for more details.
2351 /// [`split`]: trait.BufRead.html#method.split
2352 #[stable(feature = "rust1", since = "1.0.0")]
2354 pub struct Split<B> {
2359 #[stable(feature = "rust1", since = "1.0.0")]
2360 impl<B: BufRead> Iterator for Split<B> {
2361 type Item = Result<Vec<u8>>;
2363 fn next(&mut self) -> Option<Result<Vec<u8>>> {
2364 let mut buf = Vec::new();
2365 match self.buf.read_until(self.delim, &mut buf) {
2368 if buf[buf.len() - 1] == self.delim {
2373 Err(e) => Some(Err(e)),
2378 /// An iterator over the lines of an instance of `BufRead`.
2380 /// This struct is generally created by calling [`lines`] on a `BufRead`.
2381 /// Please see the documentation of [`lines`] for more details.
2383 /// [`lines`]: trait.BufRead.html#method.lines
2384 #[stable(feature = "rust1", since = "1.0.0")]
2386 pub struct Lines<B> {
2390 #[stable(feature = "rust1", since = "1.0.0")]
2391 impl<B: BufRead> Iterator for Lines<B> {
2392 type Item = Result<String>;
2394 fn next(&mut self) -> Option<Result<String>> {
2395 let mut buf = String::new();
2396 match self.buf.read_line(&mut buf) {
2399 if buf.ends_with('\n') {
2401 if buf.ends_with('\r') {
2407 Err(e) => Some(Err(e)),
2414 use super::{repeat, Cursor, SeekFrom};
2416 use crate::io::prelude::*;
2417 use crate::io::{self, IoSlice, IoSliceMut};
2418 use crate::ops::Deref;
2421 #[cfg_attr(target_os = "emscripten", ignore)]
2423 let mut buf = Cursor::new(&b"12"[..]);
2424 let mut v = Vec::new();
2425 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 2);
2426 assert_eq!(v, b"12");
2428 let mut buf = Cursor::new(&b"1233"[..]);
2429 let mut v = Vec::new();
2430 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 3);
2431 assert_eq!(v, b"123");
2433 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 1);
2434 assert_eq!(v, b"3");
2436 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 0);
2442 let buf = Cursor::new(&b"12"[..]);
2443 let mut s = buf.split(b'3');
2444 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2445 assert!(s.next().is_none());
2447 let buf = Cursor::new(&b"1233"[..]);
2448 let mut s = buf.split(b'3');
2449 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2450 assert_eq!(s.next().unwrap().unwrap(), vec![]);
2451 assert!(s.next().is_none());
2456 let mut buf = Cursor::new(&b"12"[..]);
2457 let mut v = String::new();
2458 assert_eq!(buf.read_line(&mut v).unwrap(), 2);
2459 assert_eq!(v, "12");
2461 let mut buf = Cursor::new(&b"12\n\n"[..]);
2462 let mut v = String::new();
2463 assert_eq!(buf.read_line(&mut v).unwrap(), 3);
2464 assert_eq!(v, "12\n");
2466 assert_eq!(buf.read_line(&mut v).unwrap(), 1);
2467 assert_eq!(v, "\n");
2469 assert_eq!(buf.read_line(&mut v).unwrap(), 0);
2475 let buf = Cursor::new(&b"12\r"[..]);
2476 let mut s = buf.lines();
2477 assert_eq!(s.next().unwrap().unwrap(), "12\r".to_string());
2478 assert!(s.next().is_none());
2480 let buf = Cursor::new(&b"12\r\n\n"[..]);
2481 let mut s = buf.lines();
2482 assert_eq!(s.next().unwrap().unwrap(), "12".to_string());
2483 assert_eq!(s.next().unwrap().unwrap(), "".to_string());
2484 assert!(s.next().is_none());
2489 let mut c = Cursor::new(&b""[..]);
2490 let mut v = Vec::new();
2491 assert_eq!(c.read_to_end(&mut v).unwrap(), 0);
2494 let mut c = Cursor::new(&b"1"[..]);
2495 let mut v = Vec::new();
2496 assert_eq!(c.read_to_end(&mut v).unwrap(), 1);
2497 assert_eq!(v, b"1");
2499 let cap = 1024 * 1024;
2500 let data = (0..cap).map(|i| (i / 3) as u8).collect::<Vec<_>>();
2501 let mut v = Vec::new();
2502 let (a, b) = data.split_at(data.len() / 2);
2503 assert_eq!(Cursor::new(a).read_to_end(&mut v).unwrap(), a.len());
2504 assert_eq!(Cursor::new(b).read_to_end(&mut v).unwrap(), b.len());
2505 assert_eq!(v, data);
2509 fn read_to_string() {
2510 let mut c = Cursor::new(&b""[..]);
2511 let mut v = String::new();
2512 assert_eq!(c.read_to_string(&mut v).unwrap(), 0);
2515 let mut c = Cursor::new(&b"1"[..]);
2516 let mut v = String::new();
2517 assert_eq!(c.read_to_string(&mut v).unwrap(), 1);
2520 let mut c = Cursor::new(&b"\xff"[..]);
2521 let mut v = String::new();
2522 assert!(c.read_to_string(&mut v).is_err());
2527 let mut buf = [0; 4];
2529 let mut c = Cursor::new(&b""[..]);
2530 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
2532 let mut c = Cursor::new(&b"123"[..]).chain(Cursor::new(&b"456789"[..]));
2533 c.read_exact(&mut buf).unwrap();
2534 assert_eq!(&buf, b"1234");
2535 c.read_exact(&mut buf).unwrap();
2536 assert_eq!(&buf, b"5678");
2537 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
2541 fn read_exact_slice() {
2542 let mut buf = [0; 4];
2544 let mut c = &b""[..];
2545 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
2547 let mut c = &b"123"[..];
2548 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
2549 // make sure the optimized (early returning) method is being used
2550 assert_eq!(&buf, &[0; 4]);
2552 let mut c = &b"1234"[..];
2553 c.read_exact(&mut buf).unwrap();
2554 assert_eq!(&buf, b"1234");
2556 let mut c = &b"56789"[..];
2557 c.read_exact(&mut buf).unwrap();
2558 assert_eq!(&buf, b"5678");
2559 assert_eq!(c, b"9");
2567 fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
2568 Err(io::Error::new(io::ErrorKind::Other, ""))
2571 impl BufRead for R {
2572 fn fill_buf(&mut self) -> io::Result<&[u8]> {
2573 Err(io::Error::new(io::ErrorKind::Other, ""))
2575 fn consume(&mut self, _amt: usize) {}
2578 let mut buf = [0; 1];
2579 assert_eq!(0, R.take(0).read(&mut buf).unwrap());
2580 assert_eq!(b"", R.take(0).fill_buf().unwrap());
2583 fn cmp_bufread<Br1: BufRead, Br2: BufRead>(mut br1: Br1, mut br2: Br2, exp: &[u8]) {
2584 let mut cat = Vec::new();
2587 let buf1 = br1.fill_buf().unwrap();
2588 let buf2 = br2.fill_buf().unwrap();
2589 let minlen = if buf1.len() < buf2.len() { buf1.len() } else { buf2.len() };
2590 assert_eq!(buf1[..minlen], buf2[..minlen]);
2591 cat.extend_from_slice(&buf1[..minlen]);
2597 br1.consume(consume);
2598 br2.consume(consume);
2600 assert_eq!(br1.fill_buf().unwrap().len(), 0);
2601 assert_eq!(br2.fill_buf().unwrap().len(), 0);
2602 assert_eq!(&cat[..], &exp[..])
2606 fn chain_bufread() {
2607 let testdata = b"ABCDEFGHIJKL";
2609 (&testdata[..3]).chain(&testdata[3..6]).chain(&testdata[6..9]).chain(&testdata[9..]);
2610 let chain2 = (&testdata[..4]).chain(&testdata[4..8]).chain(&testdata[8..]);
2611 cmp_bufread(chain1, chain2, &testdata[..]);
2615 fn chain_zero_length_read_is_not_eof() {
2618 let mut s = String::new();
2619 let mut chain = (&a[..]).chain(&b[..]);
2620 chain.read(&mut []).unwrap();
2621 chain.read_to_string(&mut s).unwrap();
2622 assert_eq!("AB", s);
2626 #[cfg_attr(target_os = "emscripten", ignore)]
2627 fn bench_read_to_end(b: &mut test::Bencher) {
2629 let mut lr = repeat(1).take(10000000);
2630 let mut vec = Vec::with_capacity(1024);
2631 super::read_to_end(&mut lr, &mut vec)
2636 fn seek_len() -> io::Result<()> {
2637 let mut c = Cursor::new(vec![0; 15]);
2638 assert_eq!(c.stream_len()?, 15);
2640 c.seek(SeekFrom::End(0))?;
2641 let old_pos = c.stream_position()?;
2642 assert_eq!(c.stream_len()?, 15);
2643 assert_eq!(c.stream_position()?, old_pos);
2645 c.seek(SeekFrom::Start(7))?;
2646 c.seek(SeekFrom::Current(2))?;
2647 let old_pos = c.stream_position()?;
2648 assert_eq!(c.stream_len()?, 15);
2649 assert_eq!(c.stream_position()?, old_pos);
2655 fn seek_position() -> io::Result<()> {
2656 // All `asserts` are duplicated here to make sure the method does not
2657 // change anything about the seek state.
2658 let mut c = Cursor::new(vec![0; 15]);
2659 assert_eq!(c.stream_position()?, 0);
2660 assert_eq!(c.stream_position()?, 0);
2662 c.seek(SeekFrom::End(0))?;
2663 assert_eq!(c.stream_position()?, 15);
2664 assert_eq!(c.stream_position()?, 15);
2666 c.seek(SeekFrom::Start(7))?;
2667 c.seek(SeekFrom::Current(2))?;
2668 assert_eq!(c.stream_position()?, 9);
2669 assert_eq!(c.stream_position()?, 9);
2671 c.seek(SeekFrom::End(-3))?;
2672 c.seek(SeekFrom::Current(1))?;
2673 c.seek(SeekFrom::Current(-5))?;
2674 assert_eq!(c.stream_position()?, 8);
2675 assert_eq!(c.stream_position()?, 8);
2680 // A simple example reader which uses the default implementation of
2682 struct ExampleSliceReader<'a> {
2686 impl<'a> Read for ExampleSliceReader<'a> {
2687 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
2688 let len = cmp::min(self.slice.len(), buf.len());
2689 buf[..len].copy_from_slice(&self.slice[..len]);
2690 self.slice = &self.slice[len..];
2696 fn test_read_to_end_capacity() -> io::Result<()> {
2697 let input = &b"foo"[..];
2699 // read_to_end() generally needs to over-allocate, both for efficiency
2700 // and so that it can distinguish EOF. Assert that this is the case
2701 // with this simple ExampleSliceReader struct, which uses the default
2702 // implementation of read_to_end. Even though vec1 is allocated with
2703 // exactly enough capacity for the read, read_to_end will allocate more
2705 let mut vec1 = Vec::with_capacity(input.len());
2706 ExampleSliceReader { slice: input }.read_to_end(&mut vec1)?;
2707 assert_eq!(vec1.len(), input.len());
2708 assert!(vec1.capacity() > input.len(), "allocated more");
2710 // However, std::io::Take includes an implementation of read_to_end
2711 // that will not allocate when the limit has already been reached. In
2712 // this case, vec2 never grows.
2713 let mut vec2 = Vec::with_capacity(input.len());
2714 ExampleSliceReader { slice: input }.take(input.len() as u64).read_to_end(&mut vec2)?;
2715 assert_eq!(vec2.len(), input.len());
2716 assert_eq!(vec2.capacity(), input.len(), "did not allocate more");
2722 fn io_slice_mut_advance() {
2723 let mut buf1 = [1; 8];
2724 let mut buf2 = [2; 16];
2725 let mut buf3 = [3; 8];
2726 let mut bufs = &mut [
2727 IoSliceMut::new(&mut buf1),
2728 IoSliceMut::new(&mut buf2),
2729 IoSliceMut::new(&mut buf3),
2732 // Only in a single buffer..
2733 bufs = IoSliceMut::advance(bufs, 1);
2734 assert_eq!(bufs[0].deref(), [1; 7].as_ref());
2735 assert_eq!(bufs[1].deref(), [2; 16].as_ref());
2736 assert_eq!(bufs[2].deref(), [3; 8].as_ref());
2738 // Removing a buffer, leaving others as is.
2739 bufs = IoSliceMut::advance(bufs, 7);
2740 assert_eq!(bufs[0].deref(), [2; 16].as_ref());
2741 assert_eq!(bufs[1].deref(), [3; 8].as_ref());
2743 // Removing a buffer and removing from the next buffer.
2744 bufs = IoSliceMut::advance(bufs, 18);
2745 assert_eq!(bufs[0].deref(), [3; 6].as_ref());
2749 fn io_slice_mut_advance_empty_slice() {
2750 let empty_bufs = &mut [][..];
2752 IoSliceMut::advance(empty_bufs, 1);
2756 fn io_slice_mut_advance_beyond_total_length() {
2757 let mut buf1 = [1; 8];
2758 let mut bufs = &mut [IoSliceMut::new(&mut buf1)][..];
2760 // Going beyond the total length should be ok.
2761 bufs = IoSliceMut::advance(bufs, 9);
2762 assert!(bufs.is_empty());
2766 fn io_slice_advance() {
2770 let mut bufs = &mut [IoSlice::new(&buf1), IoSlice::new(&buf2), IoSlice::new(&buf3)][..];
2772 // Only in a single buffer..
2773 bufs = IoSlice::advance(bufs, 1);
2774 assert_eq!(bufs[0].deref(), [1; 7].as_ref());
2775 assert_eq!(bufs[1].deref(), [2; 16].as_ref());
2776 assert_eq!(bufs[2].deref(), [3; 8].as_ref());
2778 // Removing a buffer, leaving others as is.
2779 bufs = IoSlice::advance(bufs, 7);
2780 assert_eq!(bufs[0].deref(), [2; 16].as_ref());
2781 assert_eq!(bufs[1].deref(), [3; 8].as_ref());
2783 // Removing a buffer and removing from the next buffer.
2784 bufs = IoSlice::advance(bufs, 18);
2785 assert_eq!(bufs[0].deref(), [3; 6].as_ref());
2789 fn io_slice_advance_empty_slice() {
2790 let empty_bufs = &mut [][..];
2792 IoSlice::advance(empty_bufs, 1);
2796 fn io_slice_advance_beyond_total_length() {
2798 let mut bufs = &mut [IoSlice::new(&buf1)][..];
2800 // Going beyond the total length should be ok.
2801 bufs = IoSlice::advance(bufs, 9);
2802 assert!(bufs.is_empty());