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")]
267 use crate::ops::{Deref, DerefMut};
271 #[stable(feature = "rust1", since = "1.0.0")]
272 pub use self::buffered::{BufReader, BufWriter, LineWriter};
273 #[stable(feature = "rust1", since = "1.0.0")]
274 pub use self::buffered::IntoInnerError;
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::{Result, Error, ErrorKind};
279 #[stable(feature = "rust1", since = "1.0.0")]
280 pub use self::util::{copy, sink, Sink, empty, Empty, repeat, Repeat};
281 #[stable(feature = "rust1", since = "1.0.0")]
282 pub use self::stdio::{stdin, stdout, stderr, Stdin, Stdout, Stderr};
283 #[stable(feature = "rust1", since = "1.0.0")]
284 pub use self::stdio::{StdoutLock, StderrLock, StdinLock};
285 #[unstable(feature = "print_internals", issue = "0")]
286 pub use self::stdio::{_print, _eprint};
287 #[unstable(feature = "libstd_io_internals", issue = "42788")]
288 #[doc(no_inline, hidden)]
289 pub use self::stdio::{set_panic, set_print};
300 const DEFAULT_BUF_SIZE: usize = crate::sys_common::io::DEFAULT_BUF_SIZE;
302 struct Guard<'a> { buf: &'a mut Vec<u8>, len: usize }
304 impl Drop for Guard<'_> {
306 unsafe { self.buf.set_len(self.len); }
310 // A few methods below (read_to_string, read_line) will append data into a
311 // `String` buffer, but we need to be pretty careful when doing this. The
312 // implementation will just call `.as_mut_vec()` and then delegate to a
313 // byte-oriented reading method, but we must ensure that when returning we never
314 // leave `buf` in a state such that it contains invalid UTF-8 in its bounds.
316 // To this end, we use an RAII guard (to protect against panics) which updates
317 // the length of the string when it is dropped. This guard initially truncates
318 // the string to the prior length and only after we've validated that the
319 // new contents are valid UTF-8 do we allow it to set a longer length.
321 // The unsafety in this function is twofold:
323 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
325 // 2. We're passing a raw buffer to the function `f`, and it is expected that
326 // the function only *appends* bytes to the buffer. We'll get undefined
327 // behavior if existing bytes are overwritten to have non-UTF-8 data.
328 fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
329 where F: FnOnce(&mut Vec<u8>) -> Result<usize>
332 let mut g = Guard { len: buf.len(), buf: buf.as_mut_vec() };
334 if str::from_utf8(&g.buf[g.len..]).is_err() {
336 Err(Error::new(ErrorKind::InvalidData,
337 "stream did not contain valid UTF-8"))
346 // This uses an adaptive system to extend the vector when it fills. We want to
347 // avoid paying to allocate and zero a huge chunk of memory if the reader only
348 // has 4 bytes while still making large reads if the reader does have a ton
349 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
350 // time is 4,500 times (!) slower than a default reservation size of 32 if the
351 // reader has a very small amount of data to return.
353 // Because we're extending the buffer with uninitialized data for trusted
354 // readers, we need to make sure to truncate that if any of this panics.
355 fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
356 read_to_end_with_reservation(r, buf, 32)
359 fn read_to_end_with_reservation<R: Read + ?Sized>(r: &mut R,
361 reservation_size: usize) -> Result<usize>
363 let start_len = buf.len();
364 let mut g = Guard { len: buf.len(), buf: buf };
367 if g.len == g.buf.len() {
369 g.buf.reserve(reservation_size);
370 let capacity = g.buf.capacity();
371 g.buf.set_len(capacity);
372 r.initializer().initialize(&mut g.buf[g.len..]);
376 match r.read(&mut g.buf[g.len..]) {
378 ret = Ok(g.len - start_len);
382 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
393 pub(crate) fn default_read_vectored<F>(read: F, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
395 F: FnOnce(&mut [u8]) -> Result<usize>
399 .find(|b| !b.is_empty())
400 .map_or(&mut [][..], |b| &mut **b);
404 pub(crate) fn default_write_vectored<F>(write: F, bufs: &[IoSlice<'_>]) -> Result<usize>
406 F: FnOnce(&[u8]) -> Result<usize>
410 .find(|b| !b.is_empty())
411 .map_or(&[][..], |b| &**b);
415 /// The `Read` trait allows for reading bytes from a source.
417 /// Implementors of the `Read` trait are called 'readers'.
419 /// Readers are defined by one required method, [`read()`]. Each call to [`read()`]
420 /// will attempt to pull bytes from this source into a provided buffer. A
421 /// number of other methods are implemented in terms of [`read()`], giving
422 /// implementors a number of ways to read bytes while only needing to implement
425 /// Readers are intended to be composable with one another. Many implementors
426 /// throughout [`std::io`] take and provide types which implement the `Read`
429 /// Please note that each call to [`read()`] may involve a system call, and
430 /// therefore, using something that implements [`BufRead`], such as
431 /// [`BufReader`], will be more efficient.
435 /// [`File`]s implement `Read`:
439 /// use std::io::prelude::*;
440 /// use std::fs::File;
442 /// fn main() -> io::Result<()> {
443 /// let mut f = File::open("foo.txt")?;
444 /// let mut buffer = [0; 10];
446 /// // read up to 10 bytes
447 /// f.read(&mut buffer)?;
449 /// let mut buffer = Vec::new();
450 /// // read the whole file
451 /// f.read_to_end(&mut buffer)?;
453 /// // read into a String, so that you don't need to do the conversion.
454 /// let mut buffer = String::new();
455 /// f.read_to_string(&mut buffer)?;
457 /// // and more! See the other methods for more details.
462 /// Read from [`&str`] because [`&[u8]`][slice] implements `Read`:
466 /// use std::io::prelude::*;
468 /// fn main() -> io::Result<()> {
469 /// let mut b = "This string will be read".as_bytes();
470 /// let mut buffer = [0; 10];
472 /// // read up to 10 bytes
473 /// b.read(&mut buffer)?;
475 /// // etc... it works exactly as a File does!
480 /// [`read()`]: trait.Read.html#tymethod.read
481 /// [`std::io`]: ../../std/io/index.html
482 /// [`File`]: ../fs/struct.File.html
483 /// [`BufRead`]: trait.BufRead.html
484 /// [`BufReader`]: struct.BufReader.html
485 /// [`&str`]: ../../std/primitive.str.html
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 but 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 /// No guarantees are provided about the contents of `buf` when this
508 /// function is called, implementations cannot rely on any property of the
509 /// contents of `buf` being true. It is recommended that *implementations*
510 /// only write data to `buf` instead of reading its contents.
512 /// Correspondingly, however, *callers* of this method may not assume any guarantees
513 /// about how the implementation uses `buf`. The trait is safe to implement,
514 /// so it is possible that the code that's supposed to write to the buffer might also read
515 /// from it. It is your responsibility to make sure that `buf` is initialized
516 /// before calling `read`. Calling `read` with an uninitialized `buf` (of the kind one
517 /// obtains via [`MaybeUninit<T>`]) is not safe, and can lead to undefined behavior.
519 /// [`MaybeUninit<T>`]: ../mem/union.MaybeUninit.html
523 /// If this function encounters any form of I/O or other error, an error
524 /// variant will be returned. If an error is returned then it must be
525 /// guaranteed that no bytes were read.
527 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
528 /// operation should be retried if there is nothing else to do.
532 /// [`File`]s implement `Read`:
534 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
535 /// [`Ok(n)`]: ../../std/result/enum.Result.html#variant.Ok
536 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
537 /// [`File`]: ../fs/struct.File.html
541 /// use std::io::prelude::*;
542 /// use std::fs::File;
544 /// fn main() -> io::Result<()> {
545 /// let mut f = File::open("foo.txt")?;
546 /// let mut buffer = [0; 10];
548 /// // read up to 10 bytes
549 /// let n = f.read(&mut buffer[..])?;
551 /// println!("The bytes: {:?}", &buffer[..n]);
555 #[stable(feature = "rust1", since = "1.0.0")]
556 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
558 /// Like `read`, except that it reads into a slice of buffers.
560 /// Data is copied to fill each buffer in order, with the final buffer
561 /// written to possibly being only partially filled. This method must behave
562 /// as a single call to `read` with the buffers concatenated would.
564 /// The default implementation calls `read` with either the first nonempty
565 /// buffer provided, or an empty one if none exists.
566 #[stable(feature = "iovec", since = "1.36.0")]
567 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
568 default_read_vectored(|b| self.read(b), bufs)
571 /// Determines if this `Read`er can work with buffers of uninitialized
574 /// The default implementation returns an initializer which will zero
577 /// If a `Read`er guarantees that it can work properly with uninitialized
578 /// memory, it should call [`Initializer::nop()`]. See the documentation for
579 /// [`Initializer`] for details.
581 /// The behavior of this method must be independent of the state of the
582 /// `Read`er - the method only takes `&self` so that it can be used through
587 /// This method is unsafe because a `Read`er could otherwise return a
588 /// non-zeroing `Initializer` from another `Read` type without an `unsafe`
591 /// [`Initializer::nop()`]: ../../std/io/struct.Initializer.html#method.nop
592 /// [`Initializer`]: ../../std/io/struct.Initializer.html
593 #[unstable(feature = "read_initializer", issue = "42788")]
595 unsafe fn initializer(&self) -> Initializer {
596 Initializer::zeroing()
599 /// Read all bytes until EOF in this source, placing them into `buf`.
601 /// All bytes read from this source will be appended to the specified buffer
602 /// `buf`. This function will continuously call [`read()`] to append more data to
603 /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of
604 /// non-[`ErrorKind::Interrupted`] kind.
606 /// If successful, this function will return the total number of bytes read.
610 /// If this function encounters an error of the kind
611 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
614 /// If any other read error is encountered then this function immediately
615 /// returns. Any bytes which have already been read will be appended to
620 /// [`File`]s implement `Read`:
622 /// [`read()`]: trait.Read.html#tymethod.read
623 /// [`Ok(0)`]: ../../std/result/enum.Result.html#variant.Ok
624 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
625 /// [`File`]: ../fs/struct.File.html
629 /// use std::io::prelude::*;
630 /// use std::fs::File;
632 /// fn main() -> io::Result<()> {
633 /// let mut f = File::open("foo.txt")?;
634 /// let mut buffer = Vec::new();
636 /// // read the whole file
637 /// f.read_to_end(&mut buffer)?;
642 /// (See also the [`std::fs::read`] convenience function for reading from a
645 /// [`std::fs::read`]: ../fs/fn.read.html
646 #[stable(feature = "rust1", since = "1.0.0")]
647 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
648 read_to_end(self, buf)
651 /// Read all bytes until EOF in this source, appending them to `buf`.
653 /// If successful, this function returns the number of bytes which were read
654 /// and appended to `buf`.
658 /// If the data in this stream is *not* valid UTF-8 then an error is
659 /// returned and `buf` is unchanged.
661 /// See [`read_to_end`][readtoend] for other error semantics.
663 /// [readtoend]: #method.read_to_end
667 /// [`File`][file]s implement `Read`:
669 /// [file]: ../fs/struct.File.html
673 /// use std::io::prelude::*;
674 /// use std::fs::File;
676 /// fn main() -> io::Result<()> {
677 /// let mut f = File::open("foo.txt")?;
678 /// let mut buffer = String::new();
680 /// f.read_to_string(&mut buffer)?;
685 /// (See also the [`std::fs::read_to_string`] convenience function for
686 /// reading from a file.)
688 /// [`std::fs::read_to_string`]: ../fs/fn.read_to_string.html
689 #[stable(feature = "rust1", since = "1.0.0")]
690 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
691 // Note that we do *not* call `.read_to_end()` here. We are passing
692 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
693 // method to fill it up. An arbitrary implementation could overwrite the
694 // entire contents of the vector, not just append to it (which is what
695 // we are expecting).
697 // To prevent extraneously checking the UTF-8-ness of the entire buffer
698 // we pass it to our hardcoded `read_to_end` implementation which we
699 // know is guaranteed to only read data into the end of the buffer.
700 append_to_string(buf, |b| read_to_end(self, b))
703 /// Read the exact number of bytes required to fill `buf`.
705 /// This function reads as many bytes as necessary to completely fill the
706 /// specified buffer `buf`.
708 /// No guarantees are provided about the contents of `buf` when this
709 /// function is called, implementations cannot rely on any property of the
710 /// contents of `buf` being true. It is recommended that implementations
711 /// only write data to `buf` instead of reading its contents.
715 /// If this function encounters an error of the kind
716 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
719 /// If this function encounters an "end of file" before completely filling
720 /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
721 /// The contents of `buf` are unspecified in this case.
723 /// If any other read error is encountered then this function immediately
724 /// returns. The contents of `buf` are unspecified in this case.
726 /// If this function returns an error, it is unspecified how many bytes it
727 /// has read, but it will never read more than would be necessary to
728 /// completely fill the buffer.
732 /// [`File`]s implement `Read`:
734 /// [`File`]: ../fs/struct.File.html
735 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
736 /// [`ErrorKind::UnexpectedEof`]: ../../std/io/enum.ErrorKind.html#variant.UnexpectedEof
740 /// use std::io::prelude::*;
741 /// use std::fs::File;
743 /// fn main() -> io::Result<()> {
744 /// let mut f = File::open("foo.txt")?;
745 /// let mut buffer = [0; 10];
747 /// // read exactly 10 bytes
748 /// f.read_exact(&mut buffer)?;
752 #[stable(feature = "read_exact", since = "1.6.0")]
753 fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
754 while !buf.is_empty() {
755 match self.read(buf) {
757 Ok(n) => { let tmp = buf; buf = &mut tmp[n..]; }
758 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
759 Err(e) => return Err(e),
763 Err(Error::new(ErrorKind::UnexpectedEof,
764 "failed to fill whole buffer"))
770 /// Creates a "by reference" adaptor for this instance of `Read`.
772 /// The returned adaptor also implements `Read` and will simply borrow this
777 /// [`File`][file]s implement `Read`:
779 /// [file]: ../fs/struct.File.html
783 /// use std::io::Read;
784 /// use std::fs::File;
786 /// fn main() -> io::Result<()> {
787 /// let mut f = File::open("foo.txt")?;
788 /// let mut buffer = Vec::new();
789 /// let mut other_buffer = Vec::new();
792 /// let reference = f.by_ref();
794 /// // read at most 5 bytes
795 /// reference.take(5).read_to_end(&mut buffer)?;
797 /// } // drop our &mut reference so we can use f again
799 /// // original file still usable, read the rest
800 /// f.read_to_end(&mut other_buffer)?;
804 #[stable(feature = "rust1", since = "1.0.0")]
805 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
807 /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
809 /// The returned type implements [`Iterator`] where the `Item` is
810 /// [`Result`]`<`[`u8`]`, `[`io::Error`]`>`.
811 /// The yielded item is [`Ok`] if a byte was successfully read and [`Err`]
812 /// otherwise. EOF is mapped to returning [`None`] from this iterator.
816 /// [`File`][file]s implement `Read`:
818 /// [file]: ../fs/struct.File.html
819 /// [`Iterator`]: ../../std/iter/trait.Iterator.html
820 /// [`Result`]: ../../std/result/enum.Result.html
821 /// [`io::Error`]: ../../std/io/struct.Error.html
822 /// [`u8`]: ../../std/primitive.u8.html
823 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
824 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
825 /// [`None`]: ../../std/option/enum.Option.html#variant.None
829 /// use std::io::prelude::*;
830 /// use std::fs::File;
832 /// fn main() -> io::Result<()> {
833 /// let mut f = File::open("foo.txt")?;
835 /// for byte in f.bytes() {
836 /// println!("{}", byte.unwrap());
841 #[stable(feature = "rust1", since = "1.0.0")]
842 fn bytes(self) -> Bytes<Self> where Self: Sized {
843 Bytes { inner: self }
846 /// Creates an adaptor which will chain this stream with another.
848 /// The returned `Read` instance will first read all bytes from this object
849 /// until EOF is encountered. Afterwards the output is equivalent to the
850 /// output of `next`.
854 /// [`File`][file]s implement `Read`:
856 /// [file]: ../fs/struct.File.html
860 /// use std::io::prelude::*;
861 /// use std::fs::File;
863 /// fn main() -> io::Result<()> {
864 /// let mut f1 = File::open("foo.txt")?;
865 /// let mut f2 = File::open("bar.txt")?;
867 /// let mut handle = f1.chain(f2);
868 /// let mut buffer = String::new();
870 /// // read the value into a String. We could use any Read method here,
871 /// // this is just one example.
872 /// handle.read_to_string(&mut buffer)?;
876 #[stable(feature = "rust1", since = "1.0.0")]
877 fn chain<R: Read>(self, next: R) -> Chain<Self, R> where Self: Sized {
878 Chain { first: self, second: next, done_first: false }
881 /// Creates an adaptor which will read at most `limit` bytes from it.
883 /// This function returns a new instance of `Read` which will read at most
884 /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
885 /// read errors will not count towards the number of bytes read and future
886 /// calls to [`read()`] may succeed.
890 /// [`File`]s implement `Read`:
892 /// [`File`]: ../fs/struct.File.html
893 /// [`Ok(0)`]: ../../std/result/enum.Result.html#variant.Ok
894 /// [`read()`]: trait.Read.html#tymethod.read
898 /// use std::io::prelude::*;
899 /// use std::fs::File;
901 /// fn main() -> io::Result<()> {
902 /// let mut f = File::open("foo.txt")?;
903 /// let mut buffer = [0; 5];
905 /// // read at most five bytes
906 /// let mut handle = f.take(5);
908 /// handle.read(&mut buffer)?;
912 #[stable(feature = "rust1", since = "1.0.0")]
913 fn take(self, limit: u64) -> Take<Self> where Self: Sized {
914 Take { inner: self, limit: limit }
918 /// A buffer type used with `Read::read_vectored`.
920 /// It is semantically a wrapper around an `&mut [u8]`, but is guaranteed to be
921 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
923 #[stable(feature = "iovec", since = "1.36.0")]
925 pub struct IoSliceMut<'a>(sys::io::IoSliceMut<'a>);
927 #[stable(feature = "iovec", since = "1.36.0")]
928 impl<'a> fmt::Debug for IoSliceMut<'a> {
929 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
930 fmt::Debug::fmt(self.0.as_slice(), fmt)
934 impl<'a> IoSliceMut<'a> {
935 /// Creates a new `IoSliceMut` wrapping a byte slice.
939 /// Panics on Windows if the slice is larger than 4GB.
940 #[stable(feature = "iovec", since = "1.36.0")]
942 pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> {
943 IoSliceMut(sys::io::IoSliceMut::new(buf))
947 #[stable(feature = "iovec", since = "1.36.0")]
948 impl<'a> Deref for IoSliceMut<'a> {
952 fn deref(&self) -> &[u8] {
957 #[stable(feature = "iovec", since = "1.36.0")]
958 impl<'a> DerefMut for IoSliceMut<'a> {
960 fn deref_mut(&mut self) -> &mut [u8] {
961 self.0.as_mut_slice()
965 /// A buffer type used with `Write::write_vectored`.
967 /// It is semantically a wrapper around an `&[u8]`, but is guaranteed to be
968 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
970 #[stable(feature = "iovec", since = "1.36.0")]
972 pub struct IoSlice<'a>(sys::io::IoSlice<'a>);
974 #[stable(feature = "iovec", since = "1.36.0")]
975 impl<'a> fmt::Debug for IoSlice<'a> {
976 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
977 fmt::Debug::fmt(self.0.as_slice(), fmt)
981 impl<'a> IoSlice<'a> {
982 /// Creates a new `IoSlice` wrapping a byte slice.
986 /// Panics on Windows if the slice is larger than 4GB.
987 #[stable(feature = "iovec", since = "1.36.0")]
989 pub fn new(buf: &'a [u8]) -> IoSlice<'a> {
990 IoSlice(sys::io::IoSlice::new(buf))
994 #[stable(feature = "iovec", since = "1.36.0")]
995 impl<'a> Deref for IoSlice<'a> {
999 fn deref(&self) -> &[u8] {
1004 /// A type used to conditionally initialize buffers passed to `Read` methods.
1005 #[unstable(feature = "read_initializer", issue = "42788")]
1007 pub struct Initializer(bool);
1010 /// Returns a new `Initializer` which will zero out buffers.
1011 #[unstable(feature = "read_initializer", issue = "42788")]
1013 pub fn zeroing() -> Initializer {
1017 /// Returns a new `Initializer` which will not zero out buffers.
1021 /// This may only be called by `Read`ers which guarantee that they will not
1022 /// read from buffers passed to `Read` methods, and that the return value of
1023 /// the method accurately reflects the number of bytes that have been
1024 /// written to the head of the buffer.
1025 #[unstable(feature = "read_initializer", issue = "42788")]
1027 pub unsafe fn nop() -> Initializer {
1031 /// Indicates if a buffer should be initialized.
1032 #[unstable(feature = "read_initializer", issue = "42788")]
1034 pub fn should_initialize(&self) -> bool {
1038 /// Initializes a buffer if necessary.
1039 #[unstable(feature = "read_initializer", issue = "42788")]
1041 pub fn initialize(&self, buf: &mut [u8]) {
1042 if self.should_initialize() {
1043 unsafe { ptr::write_bytes(buf.as_mut_ptr(), 0, buf.len()) }
1048 /// A trait for objects which are byte-oriented sinks.
1050 /// Implementors of the `Write` trait are sometimes called 'writers'.
1052 /// Writers are defined by two required methods, [`write`] and [`flush`]:
1054 /// * The [`write`] method will attempt to write some data into the object,
1055 /// returning how many bytes were successfully written.
1057 /// * The [`flush`] method is useful for adaptors and explicit buffers
1058 /// themselves for ensuring that all buffered data has been pushed out to the
1061 /// Writers are intended to be composable with one another. Many implementors
1062 /// throughout [`std::io`] take and provide types which implement the `Write`
1065 /// [`write`]: #tymethod.write
1066 /// [`flush`]: #tymethod.flush
1067 /// [`std::io`]: index.html
1072 /// use std::io::prelude::*;
1073 /// use std::fs::File;
1075 /// fn main() -> std::io::Result<()> {
1076 /// let data = b"some bytes";
1078 /// let mut pos = 0;
1079 /// let mut buffer = File::create("foo.txt")?;
1081 /// while pos < data.len() {
1082 /// let bytes_written = buffer.write(&data[pos..])?;
1083 /// pos += bytes_written;
1089 /// The trait also provides convenience methods like [`write_all`], which calls
1090 /// `write` in a loop until its entire input has been written.
1092 /// [`write_all`]: #method.write_all
1093 #[stable(feature = "rust1", since = "1.0.0")]
1096 /// Write a buffer into this writer, returning how many bytes were written.
1098 /// This function will attempt to write the entire contents of `buf`, but
1099 /// the entire write may not succeed, or the write may also generate an
1100 /// error. A call to `write` represents *at most one* attempt to write to
1101 /// any wrapped object.
1103 /// Calls to `write` are not guaranteed to block waiting for data to be
1104 /// written, and a write which would otherwise block can be indicated through
1105 /// an [`Err`] variant.
1107 /// If the return value is [`Ok(n)`] then it must be guaranteed that
1108 /// `0 <= n <= buf.len()`. A return value of `0` typically means that the
1109 /// underlying object is no longer able to accept bytes and will likely not
1110 /// be able to in the future as well, or that the buffer provided is empty.
1114 /// Each call to `write` may generate an I/O error indicating that the
1115 /// operation could not be completed. If an error is returned then no bytes
1116 /// in the buffer were written to this writer.
1118 /// It is **not** considered an error if the entire buffer could not be
1119 /// written to this writer.
1121 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the
1122 /// write operation should be retried if there is nothing else to do.
1124 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
1125 /// [`Ok(n)`]: ../../std/result/enum.Result.html#variant.Ok
1126 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
1131 /// use std::io::prelude::*;
1132 /// use std::fs::File;
1134 /// fn main() -> std::io::Result<()> {
1135 /// let mut buffer = File::create("foo.txt")?;
1137 /// // Writes some prefix of the byte string, not necessarily all of it.
1138 /// buffer.write(b"some bytes")?;
1142 #[stable(feature = "rust1", since = "1.0.0")]
1143 fn write(&mut self, buf: &[u8]) -> Result<usize>;
1145 /// Like `write`, except that it writes from a slice of buffers.
1147 /// Data is copied from each buffer in order, with the final buffer
1148 /// read from possibly being only partially consumed. This method must
1149 /// behave as a call to `write` with the buffers concatenated would.
1151 /// The default implementation calls `write` with either the first nonempty
1152 /// buffer provided, or an empty one if none exists.
1153 #[stable(feature = "iovec", since = "1.36.0")]
1154 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize> {
1155 default_write_vectored(|b| self.write(b), bufs)
1158 /// Flush this output stream, ensuring that all intermediately buffered
1159 /// contents reach their destination.
1163 /// It is considered an error if not all bytes could be written due to
1164 /// I/O errors or EOF being reached.
1169 /// use std::io::prelude::*;
1170 /// use std::io::BufWriter;
1171 /// use std::fs::File;
1173 /// fn main() -> std::io::Result<()> {
1174 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
1176 /// buffer.write_all(b"some bytes")?;
1177 /// buffer.flush()?;
1181 #[stable(feature = "rust1", since = "1.0.0")]
1182 fn flush(&mut self) -> Result<()>;
1184 /// Attempts to write an entire buffer into this writer.
1186 /// This method will continuously call [`write`] until there is no more data
1187 /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is
1188 /// returned. This method will not return until the entire buffer has been
1189 /// successfully written or such an error occurs. The first error that is
1190 /// not of [`ErrorKind::Interrupted`] kind generated from this method will be
1195 /// This function will return the first error of
1196 /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns.
1198 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
1199 /// [`write`]: #tymethod.write
1204 /// use std::io::prelude::*;
1205 /// use std::fs::File;
1207 /// fn main() -> std::io::Result<()> {
1208 /// let mut buffer = File::create("foo.txt")?;
1210 /// buffer.write_all(b"some bytes")?;
1214 #[stable(feature = "rust1", since = "1.0.0")]
1215 fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
1216 while !buf.is_empty() {
1217 match self.write(buf) {
1218 Ok(0) => return Err(Error::new(ErrorKind::WriteZero,
1219 "failed to write whole buffer")),
1220 Ok(n) => buf = &buf[n..],
1221 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1222 Err(e) => return Err(e),
1228 /// Writes a formatted string into this writer, returning any error
1231 /// This method is primarily used to interface with the
1232 /// [`format_args!`][formatargs] macro, but it is rare that this should
1233 /// explicitly be called. The [`write!`][write] macro should be favored to
1234 /// invoke this method instead.
1236 /// [formatargs]: ../macro.format_args.html
1237 /// [write]: ../macro.write.html
1239 /// This function internally uses the [`write_all`][writeall] method on
1240 /// this trait and hence will continuously write data so long as no errors
1241 /// are received. This also means that partial writes are not indicated in
1244 /// [writeall]: #method.write_all
1248 /// This function will return any I/O error reported while formatting.
1253 /// use std::io::prelude::*;
1254 /// use std::fs::File;
1256 /// fn main() -> std::io::Result<()> {
1257 /// let mut buffer = File::create("foo.txt")?;
1260 /// write!(buffer, "{:.*}", 2, 1.234567)?;
1261 /// // turns into this:
1262 /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1266 #[stable(feature = "rust1", since = "1.0.0")]
1267 fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> Result<()> {
1268 // Create a shim which translates a Write to a fmt::Write and saves
1269 // off I/O errors. instead of discarding them
1270 struct Adaptor<'a, T: ?Sized + 'a> {
1275 impl<T: Write + ?Sized> fmt::Write for Adaptor<'_, T> {
1276 fn write_str(&mut self, s: &str) -> fmt::Result {
1277 match self.inner.write_all(s.as_bytes()) {
1280 self.error = Err(e);
1287 let mut output = Adaptor { inner: self, error: Ok(()) };
1288 match fmt::write(&mut output, fmt) {
1291 // check if the error came from the underlying `Write` or not
1292 if output.error.is_err() {
1295 Err(Error::new(ErrorKind::Other, "formatter error"))
1301 /// Creates a "by reference" adaptor for this instance of `Write`.
1303 /// The returned adaptor also implements `Write` and will simply borrow this
1309 /// use std::io::Write;
1310 /// use std::fs::File;
1312 /// fn main() -> std::io::Result<()> {
1313 /// let mut buffer = File::create("foo.txt")?;
1315 /// let reference = buffer.by_ref();
1317 /// // we can use reference just like our original buffer
1318 /// reference.write_all(b"some bytes")?;
1322 #[stable(feature = "rust1", since = "1.0.0")]
1323 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1326 /// The `Seek` trait provides a cursor which can be moved within a stream of
1329 /// The stream typically has a fixed size, allowing seeking relative to either
1330 /// end or the current offset.
1334 /// [`File`][file]s implement `Seek`:
1336 /// [file]: ../fs/struct.File.html
1340 /// use std::io::prelude::*;
1341 /// use std::fs::File;
1342 /// use std::io::SeekFrom;
1344 /// fn main() -> io::Result<()> {
1345 /// let mut f = File::open("foo.txt")?;
1347 /// // move the cursor 42 bytes from the start of the file
1348 /// f.seek(SeekFrom::Start(42))?;
1352 #[stable(feature = "rust1", since = "1.0.0")]
1354 /// Seek to an offset, in bytes, in a stream.
1356 /// A seek beyond the end of a stream is allowed, but behavior is defined
1357 /// by the implementation.
1359 /// If the seek operation completed successfully,
1360 /// this method returns the new position from the start of the stream.
1361 /// That position can be used later with [`SeekFrom::Start`].
1365 /// Seeking to a negative offset is considered an error.
1367 /// [`SeekFrom::Start`]: enum.SeekFrom.html#variant.Start
1368 #[stable(feature = "rust1", since = "1.0.0")]
1369 fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1371 /// Returns the length of this stream (in bytes).
1373 /// This method is implemented using up to three seek operations. If this
1374 /// method returns successfully, the seek position is unchanged (i.e. the
1375 /// position before calling this method is the same as afterwards).
1376 /// However, if this method returns an error, the seek position is
1379 /// If you need to obtain the length of *many* streams and you don't care
1380 /// about the seek position afterwards, you can reduce the number of seek
1381 /// operations by simply calling `seek(SeekFrom::End(0))` and using its
1382 /// return value (it is also the stream length).
1384 /// Note that length of a stream can change over time (for example, when
1385 /// data is appended to a file). So calling this method multiple times does
1386 /// not necessarily return the same length each time.
1392 /// #![feature(seek_convenience)]
1394 /// io::{self, Seek},
1398 /// fn main() -> io::Result<()> {
1399 /// let mut f = File::open("foo.txt")?;
1401 /// let len = f.stream_len()?;
1402 /// println!("The file is currently {} bytes long", len);
1406 #[unstable(feature = "seek_convenience", issue = "59359")]
1407 fn stream_len(&mut self) -> Result<u64> {
1408 let old_pos = self.stream_position()?;
1409 let len = self.seek(SeekFrom::End(0))?;
1411 // Avoid seeking a third time when we were already at the end of the
1412 // stream. The branch is usually way cheaper than a seek operation.
1414 self.seek(SeekFrom::Start(old_pos))?;
1420 /// Returns the current seek position from the start of the stream.
1422 /// This is equivalent to `self.seek(SeekFrom::Current(0))`.
1428 /// #![feature(seek_convenience)]
1430 /// io::{self, BufRead, BufReader, Seek},
1434 /// fn main() -> io::Result<()> {
1435 /// let mut f = BufReader::new(File::open("foo.txt")?);
1437 /// let before = f.stream_position()?;
1438 /// f.read_line(&mut String::new())?;
1439 /// let after = f.stream_position()?;
1441 /// println!("The first line was {} bytes long", after - before);
1445 #[unstable(feature = "seek_convenience", issue = "59359")]
1446 fn stream_position(&mut self) -> Result<u64> {
1447 self.seek(SeekFrom::Current(0))
1451 /// Enumeration of possible methods to seek within an I/O object.
1453 /// It is used by the [`Seek`] trait.
1455 /// [`Seek`]: trait.Seek.html
1456 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1457 #[stable(feature = "rust1", since = "1.0.0")]
1459 /// Sets the offset to the provided number of bytes.
1460 #[stable(feature = "rust1", since = "1.0.0")]
1461 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1463 /// Sets the offset to the size of this object plus the specified number of
1466 /// It is possible to seek beyond the end of an object, but it's an error to
1467 /// seek before byte 0.
1468 #[stable(feature = "rust1", since = "1.0.0")]
1469 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1471 /// Sets the offset to the current position plus the specified number of
1474 /// It is possible to seek beyond the end of an object, but it's an error to
1475 /// seek before byte 0.
1476 #[stable(feature = "rust1", since = "1.0.0")]
1477 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1480 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>)
1484 let (done, used) = {
1485 let available = match r.fill_buf() {
1487 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1488 Err(e) => return Err(e)
1490 match memchr::memchr(delim, available) {
1492 buf.extend_from_slice(&available[..=i]);
1496 buf.extend_from_slice(available);
1497 (false, available.len())
1503 if done || used == 0 {
1509 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1510 /// to perform extra ways of reading.
1512 /// For example, reading line-by-line is inefficient without using a buffer, so
1513 /// if you want to read by line, you'll need `BufRead`, which includes a
1514 /// [`read_line`] method as well as a [`lines`] iterator.
1518 /// A locked standard input implements `BufRead`:
1522 /// use std::io::prelude::*;
1524 /// let stdin = io::stdin();
1525 /// for line in stdin.lock().lines() {
1526 /// println!("{}", line.unwrap());
1530 /// If you have something that implements [`Read`], you can use the [`BufReader`
1531 /// type][`BufReader`] to turn it into a `BufRead`.
1533 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1534 /// [`BufReader`] to the rescue!
1536 /// [`BufReader`]: struct.BufReader.html
1537 /// [`File`]: ../fs/struct.File.html
1538 /// [`read_line`]: #method.read_line
1539 /// [`lines`]: #method.lines
1540 /// [`Read`]: trait.Read.html
1543 /// use std::io::{self, BufReader};
1544 /// use std::io::prelude::*;
1545 /// use std::fs::File;
1547 /// fn main() -> io::Result<()> {
1548 /// let f = File::open("foo.txt")?;
1549 /// let f = BufReader::new(f);
1551 /// for line in f.lines() {
1552 /// println!("{}", line.unwrap());
1559 #[stable(feature = "rust1", since = "1.0.0")]
1560 pub trait BufRead: Read {
1561 /// Returns the contents of the internal buffer, filling it with more data
1562 /// from the inner reader if it is empty.
1564 /// This function is a lower-level call. It needs to be paired with the
1565 /// [`consume`] method to function properly. When calling this
1566 /// method, none of the contents will be "read" in the sense that later
1567 /// calling `read` may return the same contents. As such, [`consume`] must
1568 /// be called with the number of bytes that are consumed from this buffer to
1569 /// ensure that the bytes are never returned twice.
1571 /// [`consume`]: #tymethod.consume
1573 /// An empty buffer returned indicates that the stream has reached EOF.
1577 /// This function will return an I/O error if the underlying reader was
1578 /// read, but returned an error.
1582 /// A locked standard input implements `BufRead`:
1586 /// use std::io::prelude::*;
1588 /// let stdin = io::stdin();
1589 /// let mut stdin = stdin.lock();
1591 /// let buffer = stdin.fill_buf().unwrap();
1593 /// // work with buffer
1594 /// println!("{:?}", buffer);
1596 /// // ensure the bytes we worked with aren't returned again later
1597 /// let length = buffer.len();
1598 /// stdin.consume(length);
1600 #[stable(feature = "rust1", since = "1.0.0")]
1601 fn fill_buf(&mut self) -> Result<&[u8]>;
1603 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1604 /// so they should no longer be returned in calls to `read`.
1606 /// This function is a lower-level call. It needs to be paired with the
1607 /// [`fill_buf`] method to function properly. This function does
1608 /// not perform any I/O, it simply informs this object that some amount of
1609 /// its buffer, returned from [`fill_buf`], has been consumed and should
1610 /// no longer be returned. As such, this function may do odd things if
1611 /// [`fill_buf`] isn't called before calling it.
1613 /// The `amt` must be `<=` the number of bytes in the buffer returned by
1618 /// Since `consume()` is meant to be used with [`fill_buf`],
1619 /// that method's example includes an example of `consume()`.
1621 /// [`fill_buf`]: #tymethod.fill_buf
1622 #[stable(feature = "rust1", since = "1.0.0")]
1623 fn consume(&mut self, amt: usize);
1625 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
1627 /// This function will read bytes from the underlying stream until the
1628 /// delimiter or EOF is found. Once found, all bytes up to, and including,
1629 /// the delimiter (if found) will be appended to `buf`.
1631 /// If successful, this function will return the total number of bytes read.
1635 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1636 /// will otherwise return any errors returned by [`fill_buf`].
1638 /// If an I/O error is encountered then all bytes read so far will be
1639 /// present in `buf` and its length will have been adjusted appropriately.
1641 /// [`fill_buf`]: #tymethod.fill_buf
1642 /// [`ErrorKind::Interrupted`]: enum.ErrorKind.html#variant.Interrupted
1646 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1647 /// this example, we use [`Cursor`] to read all the bytes in a byte slice
1648 /// in hyphen delimited segments:
1650 /// [`Cursor`]: struct.Cursor.html
1653 /// use std::io::{self, BufRead};
1655 /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
1656 /// let mut buf = vec![];
1658 /// // cursor is at 'l'
1659 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1660 /// .expect("reading from cursor won't fail");
1661 /// assert_eq!(num_bytes, 6);
1662 /// assert_eq!(buf, b"lorem-");
1665 /// // cursor is at 'i'
1666 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1667 /// .expect("reading from cursor won't fail");
1668 /// assert_eq!(num_bytes, 5);
1669 /// assert_eq!(buf, b"ipsum");
1672 /// // cursor is at EOF
1673 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1674 /// .expect("reading from cursor won't fail");
1675 /// assert_eq!(num_bytes, 0);
1676 /// assert_eq!(buf, b"");
1678 #[stable(feature = "rust1", since = "1.0.0")]
1679 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
1680 read_until(self, byte, buf)
1683 /// Read all bytes until a newline (the 0xA byte) is reached, and append
1684 /// them to the provided buffer.
1686 /// This function will read bytes from the underlying stream until the
1687 /// newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes
1688 /// up to, and including, the delimiter (if found) will be appended to
1691 /// If successful, this function will return the total number of bytes read.
1693 /// If this function returns `Ok(0)`, the stream has reached EOF.
1697 /// This function has the same error semantics as [`read_until`] and will
1698 /// also return an error if the read bytes are not valid UTF-8. If an I/O
1699 /// error is encountered then `buf` may contain some bytes already read in
1700 /// the event that all data read so far was valid UTF-8.
1702 /// [`read_until`]: #method.read_until
1706 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1707 /// this example, we use [`Cursor`] to read all the lines in a byte slice:
1709 /// [`Cursor`]: struct.Cursor.html
1712 /// use std::io::{self, BufRead};
1714 /// let mut cursor = io::Cursor::new(b"foo\nbar");
1715 /// let mut buf = String::new();
1717 /// // cursor is at 'f'
1718 /// let num_bytes = cursor.read_line(&mut buf)
1719 /// .expect("reading from cursor won't fail");
1720 /// assert_eq!(num_bytes, 4);
1721 /// assert_eq!(buf, "foo\n");
1724 /// // cursor is at 'b'
1725 /// let num_bytes = cursor.read_line(&mut buf)
1726 /// .expect("reading from cursor won't fail");
1727 /// assert_eq!(num_bytes, 3);
1728 /// assert_eq!(buf, "bar");
1731 /// // cursor is at EOF
1732 /// let num_bytes = cursor.read_line(&mut buf)
1733 /// .expect("reading from cursor won't fail");
1734 /// assert_eq!(num_bytes, 0);
1735 /// assert_eq!(buf, "");
1737 #[stable(feature = "rust1", since = "1.0.0")]
1738 fn read_line(&mut self, buf: &mut String) -> Result<usize> {
1739 // Note that we are not calling the `.read_until` method here, but
1740 // rather our hardcoded implementation. For more details as to why, see
1741 // the comments in `read_to_end`.
1742 append_to_string(buf, |b| read_until(self, b'\n', b))
1745 /// Returns an iterator over the contents of this reader split on the byte
1748 /// The iterator returned from this function will return instances of
1749 /// [`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
1750 /// the delimiter byte at the end.
1752 /// This function will yield errors whenever [`read_until`] would have
1753 /// also yielded an error.
1755 /// [`io::Result`]: type.Result.html
1756 /// [`Vec<u8>`]: ../vec/struct.Vec.html
1757 /// [`read_until`]: #method.read_until
1761 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1762 /// this example, we use [`Cursor`] to iterate over all hyphen delimited
1763 /// segments in a byte slice
1765 /// [`Cursor`]: struct.Cursor.html
1768 /// use std::io::{self, BufRead};
1770 /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
1772 /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
1773 /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
1774 /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
1775 /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
1776 /// assert_eq!(split_iter.next(), None);
1778 #[stable(feature = "rust1", since = "1.0.0")]
1779 fn split(self, byte: u8) -> Split<Self> where Self: Sized {
1780 Split { buf: self, delim: byte }
1783 /// Returns an iterator over the lines of this reader.
1785 /// The iterator returned from this function will yield instances of
1786 /// [`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline
1787 /// byte (the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.
1789 /// [`io::Result`]: type.Result.html
1790 /// [`String`]: ../string/struct.String.html
1794 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1795 /// this example, we use [`Cursor`] to iterate over all the lines in a byte
1798 /// [`Cursor`]: struct.Cursor.html
1801 /// use std::io::{self, BufRead};
1803 /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
1805 /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
1806 /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
1807 /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
1808 /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
1809 /// assert_eq!(lines_iter.next(), None);
1814 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
1816 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
1817 #[stable(feature = "rust1", since = "1.0.0")]
1818 fn lines(self) -> Lines<Self> where Self: Sized {
1823 /// Adaptor to chain together two readers.
1825 /// This struct is generally created by calling [`chain`] on a reader.
1826 /// Please see the documentation of [`chain`] for more details.
1828 /// [`chain`]: trait.Read.html#method.chain
1829 #[stable(feature = "rust1", since = "1.0.0")]
1830 pub struct Chain<T, U> {
1836 impl<T, U> Chain<T, U> {
1837 /// Consumes the `Chain`, returning the wrapped readers.
1843 /// use std::io::prelude::*;
1844 /// use std::fs::File;
1846 /// fn main() -> io::Result<()> {
1847 /// let mut foo_file = File::open("foo.txt")?;
1848 /// let mut bar_file = File::open("bar.txt")?;
1850 /// let chain = foo_file.chain(bar_file);
1851 /// let (foo_file, bar_file) = chain.into_inner();
1855 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1856 pub fn into_inner(self) -> (T, U) {
1857 (self.first, self.second)
1860 /// Gets references to the underlying readers in this `Chain`.
1866 /// use std::io::prelude::*;
1867 /// use std::fs::File;
1869 /// fn main() -> io::Result<()> {
1870 /// let mut foo_file = File::open("foo.txt")?;
1871 /// let mut bar_file = File::open("bar.txt")?;
1873 /// let chain = foo_file.chain(bar_file);
1874 /// let (foo_file, bar_file) = chain.get_ref();
1878 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1879 pub fn get_ref(&self) -> (&T, &U) {
1880 (&self.first, &self.second)
1883 /// Gets mutable references to the underlying readers in this `Chain`.
1885 /// Care should be taken to avoid modifying the internal I/O state of the
1886 /// underlying readers as doing so may corrupt the internal state of this
1893 /// use std::io::prelude::*;
1894 /// use std::fs::File;
1896 /// fn main() -> io::Result<()> {
1897 /// let mut foo_file = File::open("foo.txt")?;
1898 /// let mut bar_file = File::open("bar.txt")?;
1900 /// let mut chain = foo_file.chain(bar_file);
1901 /// let (foo_file, bar_file) = chain.get_mut();
1905 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1906 pub fn get_mut(&mut self) -> (&mut T, &mut U) {
1907 (&mut self.first, &mut self.second)
1911 #[stable(feature = "std_debug", since = "1.16.0")]
1912 impl<T: fmt::Debug, U: fmt::Debug> fmt::Debug for Chain<T, U> {
1913 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1914 f.debug_struct("Chain")
1915 .field("t", &self.first)
1916 .field("u", &self.second)
1921 #[stable(feature = "rust1", since = "1.0.0")]
1922 impl<T: Read, U: Read> Read for Chain<T, U> {
1923 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1924 if !self.done_first {
1925 match self.first.read(buf)? {
1926 0 if buf.len() != 0 => self.done_first = true,
1930 self.second.read(buf)
1933 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
1934 if !self.done_first {
1935 match self.first.read_vectored(bufs)? {
1936 0 if bufs.iter().any(|b| !b.is_empty()) => self.done_first = true,
1940 self.second.read_vectored(bufs)
1943 unsafe fn initializer(&self) -> Initializer {
1944 let initializer = self.first.initializer();
1945 if initializer.should_initialize() {
1948 self.second.initializer()
1953 #[stable(feature = "chain_bufread", since = "1.9.0")]
1954 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
1955 fn fill_buf(&mut self) -> Result<&[u8]> {
1956 if !self.done_first {
1957 match self.first.fill_buf()? {
1958 buf if buf.len() == 0 => { self.done_first = true; }
1959 buf => return Ok(buf),
1962 self.second.fill_buf()
1965 fn consume(&mut self, amt: usize) {
1966 if !self.done_first {
1967 self.first.consume(amt)
1969 self.second.consume(amt)
1974 /// Reader adaptor which limits the bytes read from an underlying reader.
1976 /// This struct is generally created by calling [`take`] on a reader.
1977 /// Please see the documentation of [`take`] for more details.
1979 /// [`take`]: trait.Read.html#method.take
1980 #[stable(feature = "rust1", since = "1.0.0")]
1982 pub struct Take<T> {
1988 /// Returns the number of bytes that can be read before this instance will
1993 /// This instance may reach `EOF` after reading fewer bytes than indicated by
1994 /// this method if the underlying [`Read`] instance reaches EOF.
1996 /// [`Read`]: ../../std/io/trait.Read.html
2002 /// use std::io::prelude::*;
2003 /// use std::fs::File;
2005 /// fn main() -> io::Result<()> {
2006 /// let f = File::open("foo.txt")?;
2008 /// // read at most five bytes
2009 /// let handle = f.take(5);
2011 /// println!("limit: {}", handle.limit());
2015 #[stable(feature = "rust1", since = "1.0.0")]
2016 pub fn limit(&self) -> u64 { self.limit }
2018 /// Sets the number of bytes that can be read before this instance will
2019 /// return EOF. This is the same as constructing a new `Take` instance, so
2020 /// the amount of bytes read and the previous limit value don't matter when
2021 /// calling this method.
2027 /// use std::io::prelude::*;
2028 /// use std::fs::File;
2030 /// fn main() -> io::Result<()> {
2031 /// let f = File::open("foo.txt")?;
2033 /// // read at most five bytes
2034 /// let mut handle = f.take(5);
2035 /// handle.set_limit(10);
2037 /// assert_eq!(handle.limit(), 10);
2041 #[stable(feature = "take_set_limit", since = "1.27.0")]
2042 pub fn set_limit(&mut self, limit: u64) {
2046 /// Consumes the `Take`, returning the wrapped reader.
2052 /// use std::io::prelude::*;
2053 /// use std::fs::File;
2055 /// fn main() -> io::Result<()> {
2056 /// let mut file = File::open("foo.txt")?;
2058 /// let mut buffer = [0; 5];
2059 /// let mut handle = file.take(5);
2060 /// handle.read(&mut buffer)?;
2062 /// let file = handle.into_inner();
2066 #[stable(feature = "io_take_into_inner", since = "1.15.0")]
2067 pub fn into_inner(self) -> T {
2071 /// Gets a reference to the underlying reader.
2077 /// use std::io::prelude::*;
2078 /// use std::fs::File;
2080 /// fn main() -> io::Result<()> {
2081 /// let mut file = File::open("foo.txt")?;
2083 /// let mut buffer = [0; 5];
2084 /// let mut handle = file.take(5);
2085 /// handle.read(&mut buffer)?;
2087 /// let file = handle.get_ref();
2091 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2092 pub fn get_ref(&self) -> &T {
2096 /// Gets a mutable reference to the underlying reader.
2098 /// Care should be taken to avoid modifying the internal I/O state of the
2099 /// underlying reader as doing so may corrupt the internal limit of this
2106 /// use std::io::prelude::*;
2107 /// use std::fs::File;
2109 /// fn main() -> io::Result<()> {
2110 /// let mut file = File::open("foo.txt")?;
2112 /// let mut buffer = [0; 5];
2113 /// let mut handle = file.take(5);
2114 /// handle.read(&mut buffer)?;
2116 /// let file = handle.get_mut();
2120 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2121 pub fn get_mut(&mut self) -> &mut T {
2126 #[stable(feature = "rust1", since = "1.0.0")]
2127 impl<T: Read> Read for Take<T> {
2128 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2129 // Don't call into inner reader at all at EOF because it may still block
2130 if self.limit == 0 {
2134 let max = cmp::min(buf.len() as u64, self.limit) as usize;
2135 let n = self.inner.read(&mut buf[..max])?;
2136 self.limit -= n as u64;
2140 unsafe fn initializer(&self) -> Initializer {
2141 self.inner.initializer()
2144 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
2145 let reservation_size = cmp::min(self.limit, 32) as usize;
2147 read_to_end_with_reservation(self, buf, reservation_size)
2151 #[stable(feature = "rust1", since = "1.0.0")]
2152 impl<T: BufRead> BufRead for Take<T> {
2153 fn fill_buf(&mut self) -> Result<&[u8]> {
2154 // Don't call into inner reader at all at EOF because it may still block
2155 if self.limit == 0 {
2159 let buf = self.inner.fill_buf()?;
2160 let cap = cmp::min(buf.len() as u64, self.limit) as usize;
2164 fn consume(&mut self, amt: usize) {
2165 // Don't let callers reset the limit by passing an overlarge value
2166 let amt = cmp::min(amt as u64, self.limit) as usize;
2167 self.limit -= amt as u64;
2168 self.inner.consume(amt);
2172 /// An iterator over `u8` values of a reader.
2174 /// This struct is generally created by calling [`bytes`] on a reader.
2175 /// Please see the documentation of [`bytes`] for more details.
2177 /// [`bytes`]: trait.Read.html#method.bytes
2178 #[stable(feature = "rust1", since = "1.0.0")]
2180 pub struct Bytes<R> {
2184 #[stable(feature = "rust1", since = "1.0.0")]
2185 impl<R: Read> Iterator for Bytes<R> {
2186 type Item = Result<u8>;
2188 fn next(&mut self) -> Option<Result<u8>> {
2191 return match self.inner.read(slice::from_mut(&mut byte)) {
2193 Ok(..) => Some(Ok(byte)),
2194 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
2195 Err(e) => Some(Err(e)),
2201 /// An iterator over the contents of an instance of `BufRead` split on a
2202 /// particular byte.
2204 /// This struct is generally created by calling [`split`][split] on a
2205 /// `BufRead`. Please see the documentation of `split()` for more details.
2207 /// [split]: trait.BufRead.html#method.split
2208 #[stable(feature = "rust1", since = "1.0.0")]
2210 pub struct Split<B> {
2215 #[stable(feature = "rust1", since = "1.0.0")]
2216 impl<B: BufRead> Iterator for Split<B> {
2217 type Item = Result<Vec<u8>>;
2219 fn next(&mut self) -> Option<Result<Vec<u8>>> {
2220 let mut buf = Vec::new();
2221 match self.buf.read_until(self.delim, &mut buf) {
2224 if buf[buf.len() - 1] == self.delim {
2229 Err(e) => Some(Err(e))
2234 /// An iterator over the lines of an instance of `BufRead`.
2236 /// This struct is generally created by calling [`lines`][lines] on a
2237 /// `BufRead`. Please see the documentation of `lines()` for more details.
2239 /// [lines]: trait.BufRead.html#method.lines
2240 #[stable(feature = "rust1", since = "1.0.0")]
2242 pub struct Lines<B> {
2246 #[stable(feature = "rust1", since = "1.0.0")]
2247 impl<B: BufRead> Iterator for Lines<B> {
2248 type Item = Result<String>;
2250 fn next(&mut self) -> Option<Result<String>> {
2251 let mut buf = String::new();
2252 match self.buf.read_line(&mut buf) {
2255 if buf.ends_with("\n") {
2257 if buf.ends_with("\r") {
2263 Err(e) => Some(Err(e))
2270 use crate::io::prelude::*;
2272 use super::{Cursor, SeekFrom, repeat};
2275 #[cfg_attr(target_os = "emscripten", ignore)]
2277 let mut buf = Cursor::new(&b"12"[..]);
2278 let mut v = Vec::new();
2279 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 2);
2280 assert_eq!(v, b"12");
2282 let mut buf = Cursor::new(&b"1233"[..]);
2283 let mut v = Vec::new();
2284 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 3);
2285 assert_eq!(v, b"123");
2287 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 1);
2288 assert_eq!(v, b"3");
2290 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 0);
2296 let buf = Cursor::new(&b"12"[..]);
2297 let mut s = buf.split(b'3');
2298 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2299 assert!(s.next().is_none());
2301 let buf = Cursor::new(&b"1233"[..]);
2302 let mut s = buf.split(b'3');
2303 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2304 assert_eq!(s.next().unwrap().unwrap(), vec![]);
2305 assert!(s.next().is_none());
2310 let mut buf = Cursor::new(&b"12"[..]);
2311 let mut v = String::new();
2312 assert_eq!(buf.read_line(&mut v).unwrap(), 2);
2313 assert_eq!(v, "12");
2315 let mut buf = Cursor::new(&b"12\n\n"[..]);
2316 let mut v = String::new();
2317 assert_eq!(buf.read_line(&mut v).unwrap(), 3);
2318 assert_eq!(v, "12\n");
2320 assert_eq!(buf.read_line(&mut v).unwrap(), 1);
2321 assert_eq!(v, "\n");
2323 assert_eq!(buf.read_line(&mut v).unwrap(), 0);
2329 let buf = Cursor::new(&b"12\r"[..]);
2330 let mut s = buf.lines();
2331 assert_eq!(s.next().unwrap().unwrap(), "12\r".to_string());
2332 assert!(s.next().is_none());
2334 let buf = Cursor::new(&b"12\r\n\n"[..]);
2335 let mut s = buf.lines();
2336 assert_eq!(s.next().unwrap().unwrap(), "12".to_string());
2337 assert_eq!(s.next().unwrap().unwrap(), "".to_string());
2338 assert!(s.next().is_none());
2343 let mut c = Cursor::new(&b""[..]);
2344 let mut v = Vec::new();
2345 assert_eq!(c.read_to_end(&mut v).unwrap(), 0);
2348 let mut c = Cursor::new(&b"1"[..]);
2349 let mut v = Vec::new();
2350 assert_eq!(c.read_to_end(&mut v).unwrap(), 1);
2351 assert_eq!(v, b"1");
2353 let cap = 1024 * 1024;
2354 let data = (0..cap).map(|i| (i / 3) as u8).collect::<Vec<_>>();
2355 let mut v = Vec::new();
2356 let (a, b) = data.split_at(data.len() / 2);
2357 assert_eq!(Cursor::new(a).read_to_end(&mut v).unwrap(), a.len());
2358 assert_eq!(Cursor::new(b).read_to_end(&mut v).unwrap(), b.len());
2359 assert_eq!(v, data);
2363 fn read_to_string() {
2364 let mut c = Cursor::new(&b""[..]);
2365 let mut v = String::new();
2366 assert_eq!(c.read_to_string(&mut v).unwrap(), 0);
2369 let mut c = Cursor::new(&b"1"[..]);
2370 let mut v = String::new();
2371 assert_eq!(c.read_to_string(&mut v).unwrap(), 1);
2374 let mut c = Cursor::new(&b"\xff"[..]);
2375 let mut v = String::new();
2376 assert!(c.read_to_string(&mut v).is_err());
2381 let mut buf = [0; 4];
2383 let mut c = Cursor::new(&b""[..]);
2384 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2385 io::ErrorKind::UnexpectedEof);
2387 let mut c = Cursor::new(&b"123"[..]).chain(Cursor::new(&b"456789"[..]));
2388 c.read_exact(&mut buf).unwrap();
2389 assert_eq!(&buf, b"1234");
2390 c.read_exact(&mut buf).unwrap();
2391 assert_eq!(&buf, b"5678");
2392 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2393 io::ErrorKind::UnexpectedEof);
2397 fn read_exact_slice() {
2398 let mut buf = [0; 4];
2400 let mut c = &b""[..];
2401 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2402 io::ErrorKind::UnexpectedEof);
2404 let mut c = &b"123"[..];
2405 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2406 io::ErrorKind::UnexpectedEof);
2407 // make sure the optimized (early returning) method is being used
2408 assert_eq!(&buf, &[0; 4]);
2410 let mut c = &b"1234"[..];
2411 c.read_exact(&mut buf).unwrap();
2412 assert_eq!(&buf, b"1234");
2414 let mut c = &b"56789"[..];
2415 c.read_exact(&mut buf).unwrap();
2416 assert_eq!(&buf, b"5678");
2417 assert_eq!(c, b"9");
2425 fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
2426 Err(io::Error::new(io::ErrorKind::Other, ""))
2429 impl BufRead for R {
2430 fn fill_buf(&mut self) -> io::Result<&[u8]> {
2431 Err(io::Error::new(io::ErrorKind::Other, ""))
2433 fn consume(&mut self, _amt: usize) { }
2436 let mut buf = [0; 1];
2437 assert_eq!(0, R.take(0).read(&mut buf).unwrap());
2438 assert_eq!(b"", R.take(0).fill_buf().unwrap());
2441 fn cmp_bufread<Br1: BufRead, Br2: BufRead>(mut br1: Br1, mut br2: Br2, exp: &[u8]) {
2442 let mut cat = Vec::new();
2445 let buf1 = br1.fill_buf().unwrap();
2446 let buf2 = br2.fill_buf().unwrap();
2447 let minlen = if buf1.len() < buf2.len() { buf1.len() } else { buf2.len() };
2448 assert_eq!(buf1[..minlen], buf2[..minlen]);
2449 cat.extend_from_slice(&buf1[..minlen]);
2455 br1.consume(consume);
2456 br2.consume(consume);
2458 assert_eq!(br1.fill_buf().unwrap().len(), 0);
2459 assert_eq!(br2.fill_buf().unwrap().len(), 0);
2460 assert_eq!(&cat[..], &exp[..])
2464 fn chain_bufread() {
2465 let testdata = b"ABCDEFGHIJKL";
2466 let chain1 = (&testdata[..3]).chain(&testdata[3..6])
2467 .chain(&testdata[6..9])
2468 .chain(&testdata[9..]);
2469 let chain2 = (&testdata[..4]).chain(&testdata[4..8])
2470 .chain(&testdata[8..]);
2471 cmp_bufread(chain1, chain2, &testdata[..]);
2475 fn chain_zero_length_read_is_not_eof() {
2478 let mut s = String::new();
2479 let mut chain = (&a[..]).chain(&b[..]);
2480 chain.read(&mut []).unwrap();
2481 chain.read_to_string(&mut s).unwrap();
2482 assert_eq!("AB", s);
2486 #[cfg_attr(target_os = "emscripten", ignore)]
2487 fn bench_read_to_end(b: &mut test::Bencher) {
2489 let mut lr = repeat(1).take(10000000);
2490 let mut vec = Vec::with_capacity(1024);
2491 super::read_to_end(&mut lr, &mut vec)
2496 fn seek_len() -> io::Result<()> {
2497 let mut c = Cursor::new(vec![0; 15]);
2498 assert_eq!(c.stream_len()?, 15);
2500 c.seek(SeekFrom::End(0))?;
2501 let old_pos = c.stream_position()?;
2502 assert_eq!(c.stream_len()?, 15);
2503 assert_eq!(c.stream_position()?, old_pos);
2505 c.seek(SeekFrom::Start(7))?;
2506 c.seek(SeekFrom::Current(2))?;
2507 let old_pos = c.stream_position()?;
2508 assert_eq!(c.stream_len()?, 15);
2509 assert_eq!(c.stream_position()?, old_pos);
2515 fn seek_position() -> io::Result<()> {
2516 // All `asserts` are duplicated here to make sure the method does not
2517 // change anything about the seek state.
2518 let mut c = Cursor::new(vec![0; 15]);
2519 assert_eq!(c.stream_position()?, 0);
2520 assert_eq!(c.stream_position()?, 0);
2522 c.seek(SeekFrom::End(0))?;
2523 assert_eq!(c.stream_position()?, 15);
2524 assert_eq!(c.stream_position()?, 15);
2527 c.seek(SeekFrom::Start(7))?;
2528 c.seek(SeekFrom::Current(2))?;
2529 assert_eq!(c.stream_position()?, 9);
2530 assert_eq!(c.stream_position()?, 9);
2532 c.seek(SeekFrom::End(-3))?;
2533 c.seek(SeekFrom::Current(1))?;
2534 c.seek(SeekFrom::Current(-5))?;
2535 assert_eq!(c.stream_position()?, 8);
2536 assert_eq!(c.stream_position()?, 8);