1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Traits, helpers, and type definitions for core I/O functionality.
13 //! The `std::io` module contains a number of common things you'll need
14 //! when doing input and output. The most core part of this module is
15 //! the [`Read`] and [`Write`] traits, which provide the
16 //! most general interface for reading and writing input and output.
20 //! Because they are traits, [`Read`] and [`Write`] are implemented by a number
21 //! of other types, and you can implement them for your types too. As such,
22 //! you'll see a few different types of I/O throughout the documentation in
23 //! this module: [`File`]s, [`TcpStream`]s, and sometimes even [`Vec<T>`]s. For
24 //! example, [`Read`] adds a [`read`][`Read::read`] method, which we can use on
29 //! use std::io::prelude::*;
30 //! use std::fs::File;
32 //! fn main() -> io::Result<()> {
33 //! let mut f = File::open("foo.txt")?;
34 //! let mut buffer = [0; 10];
36 //! // read up to 10 bytes
37 //! f.read(&mut buffer)?;
39 //! println!("The bytes: {:?}", buffer);
44 //! [`Read`] and [`Write`] are so important, implementors of the two traits have a
45 //! nickname: readers and writers. So you'll sometimes see 'a reader' instead
46 //! of 'a type that implements the [`Read`] trait'. Much easier!
48 //! ## Seek and BufRead
50 //! Beyond that, there are two important traits that are provided: [`Seek`]
51 //! and [`BufRead`]. Both of these build on top of a reader to control
52 //! how the reading happens. [`Seek`] lets you control where the next byte is
57 //! use std::io::prelude::*;
58 //! use std::io::SeekFrom;
59 //! use std::fs::File;
61 //! fn main() -> io::Result<()> {
62 //! let mut f = File::open("foo.txt")?;
63 //! let mut buffer = [0; 10];
65 //! // skip to the last 10 bytes of the file
66 //! f.seek(SeekFrom::End(-10))?;
68 //! // read up to 10 bytes
69 //! f.read(&mut buffer)?;
71 //! println!("The bytes: {:?}", buffer);
76 //! [`BufRead`] uses an internal buffer to provide a number of other ways to read, but
77 //! to show it off, we'll need to talk about buffers in general. Keep reading!
79 //! ## BufReader and BufWriter
81 //! Byte-based interfaces are unwieldy and can be inefficient, as we'd need to be
82 //! making near-constant calls to the operating system. To help with this,
83 //! `std::io` comes with two structs, [`BufReader`] and [`BufWriter`], which wrap
84 //! readers and writers. The wrapper uses a buffer, reducing the number of
85 //! calls and providing nicer methods for accessing exactly what you want.
87 //! For example, [`BufReader`] works with the [`BufRead`] trait to add extra
88 //! methods to any reader:
92 //! use std::io::prelude::*;
93 //! use std::io::BufReader;
94 //! use std::fs::File;
96 //! fn main() -> io::Result<()> {
97 //! let f = File::open("foo.txt")?;
98 //! let mut reader = BufReader::new(f);
99 //! let mut buffer = String::new();
101 //! // read a line into buffer
102 //! reader.read_line(&mut buffer)?;
104 //! println!("{}", buffer);
109 //! [`BufWriter`] doesn't add any new ways of writing; it just buffers every call
110 //! to [`write`][`Write::write`]:
114 //! use std::io::prelude::*;
115 //! use std::io::BufWriter;
116 //! use std::fs::File;
118 //! fn main() -> io::Result<()> {
119 //! let f = File::create("foo.txt")?;
121 //! let mut writer = BufWriter::new(f);
123 //! // write a byte to the buffer
124 //! writer.write(&[42])?;
126 //! } // the buffer is flushed once writer goes out of scope
132 //! ## Standard input and output
134 //! A very common source of input is standard input:
139 //! fn main() -> io::Result<()> {
140 //! let mut input = String::new();
142 //! io::stdin().read_line(&mut input)?;
144 //! println!("You typed: {}", input.trim());
149 //! Note that you cannot use the [`?` operator] in functions that do not return
150 //! a [`Result<T, E>`][`Result`]. Instead, you can call [`.unwrap()`]
151 //! or `match` on the return value to catch any possible errors:
156 //! let mut input = String::new();
158 //! io::stdin().read_line(&mut input).unwrap();
161 //! And a very common source of output is standard output:
165 //! use std::io::prelude::*;
167 //! fn main() -> io::Result<()> {
168 //! io::stdout().write(&[42])?;
173 //! Of course, using [`io::stdout`] directly is less common than something like
176 //! ## Iterator types
178 //! A large number of the structures provided by `std::io` are for various
179 //! ways of iterating over I/O. For example, [`Lines`] is used to split over
184 //! use std::io::prelude::*;
185 //! use std::io::BufReader;
186 //! use std::fs::File;
188 //! fn main() -> io::Result<()> {
189 //! let f = File::open("foo.txt")?;
190 //! let reader = BufReader::new(f);
192 //! for line in reader.lines() {
193 //! println!("{}", line?);
201 //! There are a number of [functions][functions-list] that offer access to various
202 //! features. For example, we can use three of these functions to copy everything
203 //! from standard input to standard output:
208 //! fn main() -> io::Result<()> {
209 //! io::copy(&mut io::stdin(), &mut io::stdout())?;
214 //! [functions-list]: #functions-1
218 //! Last, but certainly not least, is [`io::Result`]. This type is used
219 //! as the return type of many `std::io` functions that can cause an error, and
220 //! can be returned from your own functions as well. Many of the examples in this
221 //! module use the [`?` operator]:
226 //! fn read_input() -> io::Result<()> {
227 //! let mut input = String::new();
229 //! io::stdin().read_line(&mut input)?;
231 //! println!("You typed: {}", input.trim());
237 //! The return type of `read_input()`, [`io::Result<()>`][`io::Result`], is a very
238 //! common type for functions which don't have a 'real' return value, but do want to
239 //! return errors if they happen. In this case, the only purpose of this function is
240 //! to read the line and print it, so we use `()`.
242 //! ## Platform-specific behavior
244 //! Many I/O functions throughout the standard library are documented to indicate
245 //! what various library or syscalls they are delegated to. This is done to help
246 //! applications both understand what's happening under the hood as well as investigate
247 //! any possibly unclear semantics. Note, however, that this is informative, not a binding
248 //! contract. The implementation of many of these functions are subject to change over
249 //! time and may call fewer or more syscalls/library functions.
251 //! [`Read`]: trait.Read.html
252 //! [`Write`]: trait.Write.html
253 //! [`Seek`]: trait.Seek.html
254 //! [`BufRead`]: trait.BufRead.html
255 //! [`File`]: ../fs/struct.File.html
256 //! [`TcpStream`]: ../net/struct.TcpStream.html
257 //! [`Vec<T>`]: ../vec/struct.Vec.html
258 //! [`BufReader`]: struct.BufReader.html
259 //! [`BufWriter`]: struct.BufWriter.html
260 //! [`Write::write`]: trait.Write.html#tymethod.write
261 //! [`io::stdout`]: fn.stdout.html
262 //! [`println!`]: ../macro.println.html
263 //! [`Lines`]: struct.Lines.html
264 //! [`io::Result`]: type.Result.html
265 //! [`?` operator]: ../../book/first-edition/syntax-index.html
266 //! [`Read::read`]: trait.Read.html#tymethod.read
267 //! [`Result`]: ../result/enum.Result.html
268 //! [`.unwrap()`]: ../result/enum.Result.html#method.unwrap
270 #![stable(feature = "rust1", since = "1.0.0")]
273 use core::str as core_str;
274 use error as std_error;
281 #[stable(feature = "rust1", since = "1.0.0")]
282 pub use self::buffered::{BufReader, BufWriter, LineWriter};
283 #[stable(feature = "rust1", since = "1.0.0")]
284 pub use self::buffered::IntoInnerError;
285 #[stable(feature = "rust1", since = "1.0.0")]
286 pub use self::cursor::Cursor;
287 #[stable(feature = "rust1", since = "1.0.0")]
288 pub use self::error::{Result, Error, ErrorKind};
289 #[stable(feature = "rust1", since = "1.0.0")]
290 pub use self::util::{copy, sink, Sink, empty, Empty, repeat, Repeat};
291 #[stable(feature = "rust1", since = "1.0.0")]
292 pub use self::stdio::{stdin, stdout, stderr, Stdin, Stdout, Stderr};
293 #[stable(feature = "rust1", since = "1.0.0")]
294 pub use self::stdio::{StdoutLock, StderrLock, StdinLock};
295 #[unstable(feature = "print_internals", issue = "0")]
296 pub use self::stdio::{_print, _eprint};
297 #[unstable(feature = "libstd_io_internals", issue = "42788")]
298 #[doc(no_inline, hidden)]
299 pub use self::stdio::{set_panic, set_print};
310 const DEFAULT_BUF_SIZE: usize = ::sys_common::io::DEFAULT_BUF_SIZE;
312 struct Guard<'a> { buf: &'a mut Vec<u8>, len: usize }
314 impl<'a> Drop for Guard<'a> {
316 unsafe { self.buf.set_len(self.len); }
320 // A few methods below (read_to_string, read_line) will append data into a
321 // `String` buffer, but we need to be pretty careful when doing this. The
322 // implementation will just call `.as_mut_vec()` and then delegate to a
323 // byte-oriented reading method, but we must ensure that when returning we never
324 // leave `buf` in a state such that it contains invalid UTF-8 in its bounds.
326 // To this end, we use an RAII guard (to protect against panics) which updates
327 // the length of the string when it is dropped. This guard initially truncates
328 // the string to the prior length and only after we've validated that the
329 // new contents are valid UTF-8 do we allow it to set a longer length.
331 // The unsafety in this function is twofold:
333 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
335 // 2. We're passing a raw buffer to the function `f`, and it is expected that
336 // the function only *appends* bytes to the buffer. We'll get undefined
337 // behavior if existing bytes are overwritten to have non-UTF-8 data.
338 fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
339 where F: FnOnce(&mut Vec<u8>) -> Result<usize>
342 let mut g = Guard { len: buf.len(), buf: buf.as_mut_vec() };
344 if str::from_utf8(&g.buf[g.len..]).is_err() {
346 Err(Error::new(ErrorKind::InvalidData,
347 "stream did not contain valid UTF-8"))
356 // This uses an adaptive system to extend the vector when it fills. We want to
357 // avoid paying to allocate and zero a huge chunk of memory if the reader only
358 // has 4 bytes while still making large reads if the reader does have a ton
359 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
360 // time is 4,500 times (!) slower than this if the reader has a very small
361 // amount of data to return.
363 // Because we're extending the buffer with uninitialized data for trusted
364 // readers, we need to make sure to truncate that if any of this panics.
365 fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
366 let start_len = buf.len();
367 let mut g = Guard { len: buf.len(), buf: buf };
370 if g.len == g.buf.len() {
373 let capacity = g.buf.capacity();
374 g.buf.set_len(capacity);
375 r.initializer().initialize(&mut g.buf[g.len..]);
379 match r.read(&mut g.buf[g.len..]) {
381 ret = Ok(g.len - start_len);
385 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
396 /// The `Read` trait allows for reading bytes from a source.
398 /// Implementors of the `Read` trait are called 'readers'.
400 /// Readers are defined by one required method, [`read()`]. Each call to [`read()`]
401 /// will attempt to pull bytes from this source into a provided buffer. A
402 /// number of other methods are implemented in terms of [`read()`], giving
403 /// implementors a number of ways to read bytes while only needing to implement
406 /// Readers are intended to be composable with one another. Many implementors
407 /// throughout [`std::io`] take and provide types which implement the `Read`
410 /// Please note that each call to [`read()`] may involve a system call, and
411 /// therefore, using something that implements [`BufRead`], such as
412 /// [`BufReader`], will be more efficient.
416 /// [`File`]s implement `Read`:
420 /// use std::io::prelude::*;
421 /// use std::fs::File;
423 /// fn main() -> io::Result<()> {
424 /// let mut f = File::open("foo.txt")?;
425 /// let mut buffer = [0; 10];
427 /// // read up to 10 bytes
428 /// f.read(&mut buffer)?;
430 /// let mut buffer = vec![0; 10];
431 /// // read the whole file
432 /// f.read_to_end(&mut buffer)?;
434 /// // read into a String, so that you don't need to do the conversion.
435 /// let mut buffer = String::new();
436 /// f.read_to_string(&mut buffer)?;
438 /// // and more! See the other methods for more details.
443 /// Read from [`&str`] because [`&[u8]`][slice] implements `Read`:
447 /// use std::io::prelude::*;
449 /// fn main() -> io::Result<()> {
450 /// let mut b = "This string will be read".as_bytes();
451 /// let mut buffer = [0; 10];
453 /// // read up to 10 bytes
454 /// b.read(&mut buffer)?;
456 /// // etc... it works exactly as a File does!
461 /// [`read()`]: trait.Read.html#tymethod.read
462 /// [`std::io`]: ../../std/io/index.html
463 /// [`File`]: ../fs/struct.File.html
464 /// [`BufRead`]: trait.BufRead.html
465 /// [`BufReader`]: struct.BufReader.html
466 /// [`&str`]: ../../std/primitive.str.html
467 /// [slice]: ../../std/primitive.slice.html
468 #[stable(feature = "rust1", since = "1.0.0")]
471 /// Pull some bytes from this source into the specified buffer, returning
472 /// how many bytes were read.
474 /// This function does not provide any guarantees about whether it blocks
475 /// waiting for data, but if an object needs to block for a read but cannot
476 /// it will typically signal this via an [`Err`] return value.
478 /// If the return value of this method is [`Ok(n)`], then it must be
479 /// guaranteed that `0 <= n <= buf.len()`. A nonzero `n` value indicates
480 /// that the buffer `buf` has been filled in with `n` bytes of data from this
481 /// source. If `n` is `0`, then it can indicate one of two scenarios:
483 /// 1. This reader has reached its "end of file" and will likely no longer
484 /// be able to produce bytes. Note that this does not mean that the
485 /// reader will *always* no longer be able to produce bytes.
486 /// 2. The buffer specified was 0 bytes in length.
488 /// No guarantees are provided about the contents of `buf` when this
489 /// function is called, implementations cannot rely on any property of the
490 /// contents of `buf` being true. It is recommended that implementations
491 /// only write data to `buf` instead of reading its contents.
495 /// If this function encounters any form of I/O or other error, an error
496 /// variant will be returned. If an error is returned then it must be
497 /// guaranteed that no bytes were read.
499 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
500 /// operation should be retried if there is nothing else to do.
504 /// [`File`]s implement `Read`:
506 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
507 /// [`Ok(n)`]: ../../std/result/enum.Result.html#variant.Ok
508 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
509 /// [`File`]: ../fs/struct.File.html
513 /// use std::io::prelude::*;
514 /// use std::fs::File;
516 /// fn main() -> io::Result<()> {
517 /// let mut f = File::open("foo.txt")?;
518 /// let mut buffer = [0; 10];
520 /// // read up to 10 bytes
521 /// f.read(&mut buffer[..])?;
525 #[stable(feature = "rust1", since = "1.0.0")]
526 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
528 /// Determines if this `Read`er can work with buffers of uninitialized
531 /// The default implementation returns an initializer which will zero
534 /// If a `Read`er guarantees that it can work properly with uninitialized
535 /// memory, it should call [`Initializer::nop()`]. See the documentation for
536 /// [`Initializer`] for details.
538 /// The behavior of this method must be independent of the state of the
539 /// `Read`er - the method only takes `&self` so that it can be used through
544 /// This method is unsafe because a `Read`er could otherwise return a
545 /// non-zeroing `Initializer` from another `Read` type without an `unsafe`
548 /// [`Initializer::nop()`]: ../../std/io/struct.Initializer.html#method.nop
549 /// [`Initializer`]: ../../std/io/struct.Initializer.html
550 #[unstable(feature = "read_initializer", issue = "42788")]
552 unsafe fn initializer(&self) -> Initializer {
553 Initializer::zeroing()
556 /// Read all bytes until EOF in this source, placing them into `buf`.
558 /// All bytes read from this source will be appended to the specified buffer
559 /// `buf`. This function will continuously call [`read()`] to append more data to
560 /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of
561 /// non-[`ErrorKind::Interrupted`] kind.
563 /// If successful, this function will return the total number of bytes read.
567 /// If this function encounters an error of the kind
568 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
571 /// If any other read error is encountered then this function immediately
572 /// returns. Any bytes which have already been read will be appended to
577 /// [`File`]s implement `Read`:
579 /// [`read()`]: trait.Read.html#tymethod.read
580 /// [`Ok(0)`]: ../../std/result/enum.Result.html#variant.Ok
581 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
582 /// [`File`]: ../fs/struct.File.html
586 /// use std::io::prelude::*;
587 /// use std::fs::File;
589 /// fn main() -> io::Result<()> {
590 /// let mut f = File::open("foo.txt")?;
591 /// let mut buffer = Vec::new();
593 /// // read the whole file
594 /// f.read_to_end(&mut buffer)?;
599 /// (See also the [`std::fs::read`] convenience function for reading from a
602 /// [`std::fs::read`]: ../fs/fn.read.html
603 #[stable(feature = "rust1", since = "1.0.0")]
604 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
605 read_to_end(self, buf)
608 /// Read all bytes until EOF in this source, appending them to `buf`.
610 /// If successful, this function returns the number of bytes which were read
611 /// and appended to `buf`.
615 /// If the data in this stream is *not* valid UTF-8 then an error is
616 /// returned and `buf` is unchanged.
618 /// See [`read_to_end`][readtoend] for other error semantics.
620 /// [readtoend]: #method.read_to_end
624 /// [`File`][file]s implement `Read`:
626 /// [file]: ../fs/struct.File.html
630 /// use std::io::prelude::*;
631 /// use std::fs::File;
633 /// fn main() -> io::Result<()> {
634 /// let mut f = File::open("foo.txt")?;
635 /// let mut buffer = String::new();
637 /// f.read_to_string(&mut buffer)?;
642 /// (See also the [`std::fs::read_to_string`] convenience function for
643 /// reading from a file.)
645 /// [`std::fs::read_to_string`]: ../fs/fn.read_to_string.html
646 #[stable(feature = "rust1", since = "1.0.0")]
647 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
648 // Note that we do *not* call `.read_to_end()` here. We are passing
649 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
650 // method to fill it up. An arbitrary implementation could overwrite the
651 // entire contents of the vector, not just append to it (which is what
652 // we are expecting).
654 // To prevent extraneously checking the UTF-8-ness of the entire buffer
655 // we pass it to our hardcoded `read_to_end` implementation which we
656 // know is guaranteed to only read data into the end of the buffer.
657 append_to_string(buf, |b| read_to_end(self, b))
660 /// Read the exact number of bytes required to fill `buf`.
662 /// This function reads as many bytes as necessary to completely fill the
663 /// specified buffer `buf`.
665 /// No guarantees are provided about the contents of `buf` when this
666 /// function is called, implementations cannot rely on any property of the
667 /// contents of `buf` being true. It is recommended that implementations
668 /// only write data to `buf` instead of reading its contents.
672 /// If this function encounters an error of the kind
673 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
676 /// If this function encounters an "end of file" before completely filling
677 /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
678 /// The contents of `buf` are unspecified in this case.
680 /// If any other read error is encountered then this function immediately
681 /// returns. The contents of `buf` are unspecified in this case.
683 /// If this function returns an error, it is unspecified how many bytes it
684 /// has read, but it will never read more than would be necessary to
685 /// completely fill the buffer.
689 /// [`File`]s implement `Read`:
691 /// [`File`]: ../fs/struct.File.html
692 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
693 /// [`ErrorKind::UnexpectedEof`]: ../../std/io/enum.ErrorKind.html#variant.UnexpectedEof
697 /// use std::io::prelude::*;
698 /// use std::fs::File;
700 /// fn main() -> io::Result<()> {
701 /// let mut f = File::open("foo.txt")?;
702 /// let mut buffer = [0; 10];
704 /// // read exactly 10 bytes
705 /// f.read_exact(&mut buffer)?;
709 #[stable(feature = "read_exact", since = "1.6.0")]
710 fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
711 while !buf.is_empty() {
712 match self.read(buf) {
714 Ok(n) => { let tmp = buf; buf = &mut tmp[n..]; }
715 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
716 Err(e) => return Err(e),
720 Err(Error::new(ErrorKind::UnexpectedEof,
721 "failed to fill whole buffer"))
727 /// Creates a "by reference" adaptor for this instance of `Read`.
729 /// The returned adaptor also implements `Read` and will simply borrow this
734 /// [`File`][file]s implement `Read`:
736 /// [file]: ../fs/struct.File.html
740 /// use std::io::Read;
741 /// use std::fs::File;
743 /// fn main() -> io::Result<()> {
744 /// let mut f = File::open("foo.txt")?;
745 /// let mut buffer = Vec::new();
746 /// let mut other_buffer = Vec::new();
749 /// let reference = f.by_ref();
751 /// // read at most 5 bytes
752 /// reference.take(5).read_to_end(&mut buffer)?;
754 /// } // drop our &mut reference so we can use f again
756 /// // original file still usable, read the rest
757 /// f.read_to_end(&mut other_buffer)?;
761 #[stable(feature = "rust1", since = "1.0.0")]
762 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
764 /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
766 /// The returned type implements [`Iterator`] where the `Item` is
767 /// [`Result`]`<`[`u8`]`, `[`io::Error`]`>`.
768 /// The yielded item is [`Ok`] if a byte was successfully read and [`Err`]
769 /// otherwise. EOF is mapped to returning [`None`] from this iterator.
773 /// [`File`][file]s implement `Read`:
775 /// [file]: ../fs/struct.File.html
776 /// [`Iterator`]: ../../std/iter/trait.Iterator.html
777 /// [`Result`]: ../../std/result/enum.Result.html
778 /// [`io::Error`]: ../../std/io/struct.Error.html
779 /// [`u8`]: ../../std/primitive.u8.html
780 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
781 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
782 /// [`None`]: ../../std/option/enum.Option.html#variant.None
786 /// use std::io::prelude::*;
787 /// use std::fs::File;
789 /// fn main() -> io::Result<()> {
790 /// let mut f = File::open("foo.txt")?;
792 /// for byte in f.bytes() {
793 /// println!("{}", byte.unwrap());
798 #[stable(feature = "rust1", since = "1.0.0")]
799 fn bytes(self) -> Bytes<Self> where Self: Sized {
800 Bytes { inner: self }
803 /// Transforms this `Read` instance to an [`Iterator`] over [`char`]s.
805 /// This adaptor will attempt to interpret this reader as a UTF-8 encoded
806 /// sequence of characters. The returned iterator will return [`None`] once
807 /// EOF is reached for this reader. Otherwise each element yielded will be a
808 /// [`Result`]`<`[`char`]`, E>` where `E` may contain information about what I/O error
809 /// occurred or where decoding failed.
811 /// Currently this adaptor will discard intermediate data read, and should
812 /// be avoided if this is not desired.
816 /// [`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 /// [`char`]: ../../std/primitive.char.html
822 /// [`None`]: ../../std/option/enum.Option.html#variant.None
827 /// use std::io::prelude::*;
828 /// use std::fs::File;
830 /// fn main() -> io::Result<()> {
831 /// let mut f = File::open("foo.txt")?;
833 /// for c in f.chars() {
834 /// println!("{}", c.unwrap());
839 #[unstable(feature = "io", reason = "the semantics of a partial read/write \
840 of where errors happen is currently \
841 unclear and may change",
843 #[rustc_deprecated(since = "1.27.0", reason = "Use str::from_utf8 instead:
844 https://doc.rust-lang.org/nightly/std/str/struct.Utf8Error.html#examples")]
846 fn chars(self) -> Chars<Self> where Self: Sized {
847 Chars { inner: self }
850 /// Creates an adaptor which will chain this stream with another.
852 /// The returned `Read` instance will first read all bytes from this object
853 /// until EOF is encountered. Afterwards the output is equivalent to the
854 /// output of `next`.
858 /// [`File`][file]s implement `Read`:
860 /// [file]: ../fs/struct.File.html
864 /// use std::io::prelude::*;
865 /// use std::fs::File;
867 /// fn main() -> io::Result<()> {
868 /// let mut f1 = File::open("foo.txt")?;
869 /// let mut f2 = File::open("bar.txt")?;
871 /// let mut handle = f1.chain(f2);
872 /// let mut buffer = String::new();
874 /// // read the value into a String. We could use any Read method here,
875 /// // this is just one example.
876 /// handle.read_to_string(&mut buffer)?;
880 #[stable(feature = "rust1", since = "1.0.0")]
881 fn chain<R: Read>(self, next: R) -> Chain<Self, R> where Self: Sized {
882 Chain { first: self, second: next, done_first: false }
885 /// Creates an adaptor which will read at most `limit` bytes from it.
887 /// This function returns a new instance of `Read` which will read at most
888 /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
889 /// read errors will not count towards the number of bytes read and future
890 /// calls to [`read()`] may succeed.
894 /// [`File`]s implement `Read`:
896 /// [`File`]: ../fs/struct.File.html
897 /// [`Ok(0)`]: ../../std/result/enum.Result.html#variant.Ok
898 /// [`read()`]: trait.Read.html#tymethod.read
902 /// use std::io::prelude::*;
903 /// use std::fs::File;
905 /// fn main() -> io::Result<()> {
906 /// let mut f = File::open("foo.txt")?;
907 /// let mut buffer = [0; 5];
909 /// // read at most five bytes
910 /// let mut handle = f.take(5);
912 /// handle.read(&mut buffer)?;
916 #[stable(feature = "rust1", since = "1.0.0")]
917 fn take(self, limit: u64) -> Take<Self> where Self: Sized {
918 Take { inner: self, limit: limit }
922 /// A type used to conditionally initialize buffers passed to `Read` methods.
923 #[unstable(feature = "read_initializer", issue = "42788")]
925 pub struct Initializer(bool);
928 /// Returns a new `Initializer` which will zero out buffers.
929 #[unstable(feature = "read_initializer", issue = "42788")]
931 pub fn zeroing() -> Initializer {
935 /// Returns a new `Initializer` which will not zero out buffers.
939 /// This may only be called by `Read`ers which guarantee that they will not
940 /// read from buffers passed to `Read` methods, and that the return value of
941 /// the method accurately reflects the number of bytes that have been
942 /// written to the head of the buffer.
943 #[unstable(feature = "read_initializer", issue = "42788")]
945 pub unsafe fn nop() -> Initializer {
949 /// Indicates if a buffer should be initialized.
950 #[unstable(feature = "read_initializer", issue = "42788")]
952 pub fn should_initialize(&self) -> bool {
956 /// Initializes a buffer if necessary.
957 #[unstable(feature = "read_initializer", issue = "42788")]
959 pub fn initialize(&self, buf: &mut [u8]) {
960 if self.should_initialize() {
961 unsafe { ptr::write_bytes(buf.as_mut_ptr(), 0, buf.len()) }
966 /// A trait for objects which are byte-oriented sinks.
968 /// Implementors of the `Write` trait are sometimes called 'writers'.
970 /// Writers are defined by two required methods, [`write`] and [`flush`]:
972 /// * The [`write`] method will attempt to write some data into the object,
973 /// returning how many bytes were successfully written.
975 /// * The [`flush`] method is useful for adaptors and explicit buffers
976 /// themselves for ensuring that all buffered data has been pushed out to the
979 /// Writers are intended to be composable with one another. Many implementors
980 /// throughout [`std::io`] take and provide types which implement the `Write`
983 /// [`write`]: #tymethod.write
984 /// [`flush`]: #tymethod.flush
985 /// [`std::io`]: index.html
990 /// use std::io::prelude::*;
991 /// use std::fs::File;
993 /// fn main() -> std::io::Result<()> {
994 /// let mut buffer = File::create("foo.txt")?;
996 /// buffer.write(b"some bytes")?;
1000 #[stable(feature = "rust1", since = "1.0.0")]
1003 /// Write a buffer into this object, returning how many bytes were written.
1005 /// This function will attempt to write the entire contents of `buf`, but
1006 /// the entire write may not succeed, or the write may also generate an
1007 /// error. A call to `write` represents *at most one* attempt to write to
1008 /// any wrapped object.
1010 /// Calls to `write` are not guaranteed to block waiting for data to be
1011 /// written, and a write which would otherwise block can be indicated through
1012 /// an [`Err`] variant.
1014 /// If the return value is [`Ok(n)`] then it must be guaranteed that
1015 /// `0 <= n <= buf.len()`. A return value of `0` typically means that the
1016 /// underlying object is no longer able to accept bytes and will likely not
1017 /// be able to in the future as well, or that the buffer provided is empty.
1021 /// Each call to `write` may generate an I/O error indicating that the
1022 /// operation could not be completed. If an error is returned then no bytes
1023 /// in the buffer were written to this writer.
1025 /// It is **not** considered an error if the entire buffer could not be
1026 /// written to this writer.
1028 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the
1029 /// write operation should be retried if there is nothing else to do.
1031 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
1032 /// [`Ok(n)`]: ../../std/result/enum.Result.html#variant.Ok
1033 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
1038 /// use std::io::prelude::*;
1039 /// use std::fs::File;
1041 /// fn main() -> std::io::Result<()> {
1042 /// let mut buffer = File::create("foo.txt")?;
1044 /// // Writes some prefix of the byte string, not necessarily all of it.
1045 /// buffer.write(b"some bytes")?;
1049 #[stable(feature = "rust1", since = "1.0.0")]
1050 fn write(&mut self, buf: &[u8]) -> Result<usize>;
1052 /// Flush this output stream, ensuring that all intermediately buffered
1053 /// contents reach their destination.
1057 /// It is considered an error if not all bytes could be written due to
1058 /// I/O errors or EOF being reached.
1063 /// use std::io::prelude::*;
1064 /// use std::io::BufWriter;
1065 /// use std::fs::File;
1067 /// fn main() -> std::io::Result<()> {
1068 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
1070 /// buffer.write(b"some bytes")?;
1071 /// buffer.flush()?;
1075 #[stable(feature = "rust1", since = "1.0.0")]
1076 fn flush(&mut self) -> Result<()>;
1078 /// Attempts to write an entire buffer into this write.
1080 /// This method will continuously call [`write`] until there is no more data
1081 /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is
1082 /// returned. This method will not return until the entire buffer has been
1083 /// successfully written or such an error occurs. The first error that is
1084 /// not of [`ErrorKind::Interrupted`] kind generated from this method will be
1089 /// This function will return the first error of
1090 /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns.
1092 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
1093 /// [`write`]: #tymethod.write
1098 /// use std::io::prelude::*;
1099 /// use std::fs::File;
1101 /// fn main() -> std::io::Result<()> {
1102 /// let mut buffer = File::create("foo.txt")?;
1104 /// buffer.write_all(b"some bytes")?;
1108 #[stable(feature = "rust1", since = "1.0.0")]
1109 fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
1110 while !buf.is_empty() {
1111 match self.write(buf) {
1112 Ok(0) => return Err(Error::new(ErrorKind::WriteZero,
1113 "failed to write whole buffer")),
1114 Ok(n) => buf = &buf[n..],
1115 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1116 Err(e) => return Err(e),
1122 /// Writes a formatted string into this writer, returning any error
1125 /// This method is primarily used to interface with the
1126 /// [`format_args!`][formatargs] macro, but it is rare that this should
1127 /// explicitly be called. The [`write!`][write] macro should be favored to
1128 /// invoke this method instead.
1130 /// [formatargs]: ../macro.format_args.html
1131 /// [write]: ../macro.write.html
1133 /// This function internally uses the [`write_all`][writeall] method on
1134 /// this trait and hence will continuously write data so long as no errors
1135 /// are received. This also means that partial writes are not indicated in
1138 /// [writeall]: #method.write_all
1142 /// This function will return any I/O error reported while formatting.
1147 /// use std::io::prelude::*;
1148 /// use std::fs::File;
1150 /// fn main() -> std::io::Result<()> {
1151 /// let mut buffer = File::create("foo.txt")?;
1154 /// write!(buffer, "{:.*}", 2, 1.234567)?;
1155 /// // turns into this:
1156 /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1160 #[stable(feature = "rust1", since = "1.0.0")]
1161 fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()> {
1162 // Create a shim which translates a Write to a fmt::Write and saves
1163 // off I/O errors. instead of discarding them
1164 struct Adaptor<'a, T: ?Sized + 'a> {
1169 impl<'a, T: Write + ?Sized> fmt::Write for Adaptor<'a, T> {
1170 fn write_str(&mut self, s: &str) -> fmt::Result {
1171 match self.inner.write_all(s.as_bytes()) {
1174 self.error = Err(e);
1181 let mut output = Adaptor { inner: self, error: Ok(()) };
1182 match fmt::write(&mut output, fmt) {
1185 // check if the error came from the underlying `Write` or not
1186 if output.error.is_err() {
1189 Err(Error::new(ErrorKind::Other, "formatter error"))
1195 /// Creates a "by reference" adaptor for this instance of `Write`.
1197 /// The returned adaptor also implements `Write` and will simply borrow this
1203 /// use std::io::Write;
1204 /// use std::fs::File;
1206 /// fn main() -> std::io::Result<()> {
1207 /// let mut buffer = File::create("foo.txt")?;
1209 /// let reference = buffer.by_ref();
1211 /// // we can use reference just like our original buffer
1212 /// reference.write_all(b"some bytes")?;
1216 #[stable(feature = "rust1", since = "1.0.0")]
1217 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1220 /// The `Seek` trait provides a cursor which can be moved within a stream of
1223 /// The stream typically has a fixed size, allowing seeking relative to either
1224 /// end or the current offset.
1228 /// [`File`][file]s implement `Seek`:
1230 /// [file]: ../fs/struct.File.html
1234 /// use std::io::prelude::*;
1235 /// use std::fs::File;
1236 /// use std::io::SeekFrom;
1238 /// fn main() -> io::Result<()> {
1239 /// let mut f = File::open("foo.txt")?;
1241 /// // move the cursor 42 bytes from the start of the file
1242 /// f.seek(SeekFrom::Start(42))?;
1246 #[stable(feature = "rust1", since = "1.0.0")]
1248 /// Seek to an offset, in bytes, in a stream.
1250 /// A seek beyond the end of a stream is allowed, but implementation
1253 /// If the seek operation completed successfully,
1254 /// this method returns the new position from the start of the stream.
1255 /// That position can be used later with [`SeekFrom::Start`].
1259 /// Seeking to a negative offset is considered an error.
1261 /// [`SeekFrom::Start`]: enum.SeekFrom.html#variant.Start
1262 #[stable(feature = "rust1", since = "1.0.0")]
1263 fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1266 /// Enumeration of possible methods to seek within an I/O object.
1268 /// It is used by the [`Seek`] trait.
1270 /// [`Seek`]: trait.Seek.html
1271 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1272 #[stable(feature = "rust1", since = "1.0.0")]
1274 /// Set the offset to the provided number of bytes.
1275 #[stable(feature = "rust1", since = "1.0.0")]
1276 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1278 /// Set the offset to the size of this object plus the specified number of
1281 /// It is possible to seek beyond the end of an object, but it's an error to
1282 /// seek before byte 0.
1283 #[stable(feature = "rust1", since = "1.0.0")]
1284 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1286 /// Set the offset to the current position plus the specified number of
1289 /// It is possible to seek beyond the end of an object, but it's an error to
1290 /// seek before byte 0.
1291 #[stable(feature = "rust1", since = "1.0.0")]
1292 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1295 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>)
1299 let (done, used) = {
1300 let available = match r.fill_buf() {
1302 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1303 Err(e) => return Err(e)
1305 match memchr::memchr(delim, available) {
1307 buf.extend_from_slice(&available[..i + 1]);
1311 buf.extend_from_slice(available);
1312 (false, available.len())
1318 if done || used == 0 {
1324 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1325 /// to perform extra ways of reading.
1327 /// For example, reading line-by-line is inefficient without using a buffer, so
1328 /// if you want to read by line, you'll need `BufRead`, which includes a
1329 /// [`read_line`] method as well as a [`lines`] iterator.
1333 /// A locked standard input implements `BufRead`:
1337 /// use std::io::prelude::*;
1339 /// let stdin = io::stdin();
1340 /// for line in stdin.lock().lines() {
1341 /// println!("{}", line.unwrap());
1345 /// If you have something that implements [`Read`], you can use the [`BufReader`
1346 /// type][`BufReader`] to turn it into a `BufRead`.
1348 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1349 /// [`BufReader`] to the rescue!
1351 /// [`BufReader`]: struct.BufReader.html
1352 /// [`File`]: ../fs/struct.File.html
1353 /// [`read_line`]: #method.read_line
1354 /// [`lines`]: #method.lines
1355 /// [`Read`]: trait.Read.html
1358 /// use std::io::{self, BufReader};
1359 /// use std::io::prelude::*;
1360 /// use std::fs::File;
1362 /// fn main() -> io::Result<()> {
1363 /// let f = File::open("foo.txt")?;
1364 /// let f = BufReader::new(f);
1366 /// for line in f.lines() {
1367 /// println!("{}", line.unwrap());
1374 #[stable(feature = "rust1", since = "1.0.0")]
1375 pub trait BufRead: Read {
1376 /// Fills the internal buffer of this object, returning the buffer contents.
1378 /// This function is a lower-level call. It needs to be paired with the
1379 /// [`consume`] method to function properly. When calling this
1380 /// method, none of the contents will be "read" in the sense that later
1381 /// calling `read` may return the same contents. As such, [`consume`] must
1382 /// be called with the number of bytes that are consumed from this buffer to
1383 /// ensure that the bytes are never returned twice.
1385 /// [`consume`]: #tymethod.consume
1387 /// An empty buffer returned indicates that the stream has reached EOF.
1391 /// This function will return an I/O error if the underlying reader was
1392 /// read, but returned an error.
1396 /// A locked standard input implements `BufRead`:
1400 /// use std::io::prelude::*;
1402 /// let stdin = io::stdin();
1403 /// let mut stdin = stdin.lock();
1405 /// // we can't have two `&mut` references to `stdin`, so use a block
1406 /// // to end the borrow early.
1408 /// let buffer = stdin.fill_buf().unwrap();
1410 /// // work with buffer
1411 /// println!("{:?}", buffer);
1416 /// // ensure the bytes we worked with aren't returned again later
1417 /// stdin.consume(length);
1419 #[stable(feature = "rust1", since = "1.0.0")]
1420 fn fill_buf(&mut self) -> Result<&[u8]>;
1422 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1423 /// so they should no longer be returned in calls to `read`.
1425 /// This function is a lower-level call. It needs to be paired with the
1426 /// [`fill_buf`] method to function properly. This function does
1427 /// not perform any I/O, it simply informs this object that some amount of
1428 /// its buffer, returned from [`fill_buf`], has been consumed and should
1429 /// no longer be returned. As such, this function may do odd things if
1430 /// [`fill_buf`] isn't called before calling it.
1432 /// The `amt` must be `<=` the number of bytes in the buffer returned by
1437 /// Since `consume()` is meant to be used with [`fill_buf`],
1438 /// that method's example includes an example of `consume()`.
1440 /// [`fill_buf`]: #tymethod.fill_buf
1441 #[stable(feature = "rust1", since = "1.0.0")]
1442 fn consume(&mut self, amt: usize);
1444 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
1446 /// This function will read bytes from the underlying stream until the
1447 /// delimiter or EOF is found. Once found, all bytes up to, and including,
1448 /// the delimiter (if found) will be appended to `buf`.
1450 /// If successful, this function will return the total number of bytes read.
1454 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1455 /// will otherwise return any errors returned by [`fill_buf`].
1457 /// If an I/O error is encountered then all bytes read so far will be
1458 /// present in `buf` and its length will have been adjusted appropriately.
1460 /// [`fill_buf`]: #tymethod.fill_buf
1461 /// [`ErrorKind::Interrupted`]: enum.ErrorKind.html#variant.Interrupted
1465 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1466 /// this example, we use [`Cursor`] to read all the bytes in a byte slice
1467 /// in hyphen delimited segments:
1469 /// [`Cursor`]: struct.Cursor.html
1472 /// use std::io::{self, BufRead};
1474 /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
1475 /// let mut buf = vec![];
1477 /// // cursor is at 'l'
1478 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1479 /// .expect("reading from cursor won't fail");
1480 /// assert_eq!(num_bytes, 6);
1481 /// assert_eq!(buf, b"lorem-");
1484 /// // cursor is at 'i'
1485 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1486 /// .expect("reading from cursor won't fail");
1487 /// assert_eq!(num_bytes, 5);
1488 /// assert_eq!(buf, b"ipsum");
1491 /// // cursor is at EOF
1492 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1493 /// .expect("reading from cursor won't fail");
1494 /// assert_eq!(num_bytes, 0);
1495 /// assert_eq!(buf, b"");
1497 #[stable(feature = "rust1", since = "1.0.0")]
1498 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
1499 read_until(self, byte, buf)
1502 /// Read all bytes until a newline (the 0xA byte) is reached, and append
1503 /// them to the provided buffer.
1505 /// This function will read bytes from the underlying stream until the
1506 /// newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes
1507 /// up to, and including, the delimiter (if found) will be appended to
1510 /// If successful, this function will return the total number of bytes read.
1512 /// An empty buffer returned indicates that the stream has reached EOF.
1516 /// This function has the same error semantics as [`read_until`] and will
1517 /// also return an error if the read bytes are not valid UTF-8. If an I/O
1518 /// error is encountered then `buf` may contain some bytes already read in
1519 /// the event that all data read so far was valid UTF-8.
1521 /// [`read_until`]: #method.read_until
1525 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1526 /// this example, we use [`Cursor`] to read all the lines in a byte slice:
1528 /// [`Cursor`]: struct.Cursor.html
1531 /// use std::io::{self, BufRead};
1533 /// let mut cursor = io::Cursor::new(b"foo\nbar");
1534 /// let mut buf = String::new();
1536 /// // cursor is at 'f'
1537 /// let num_bytes = cursor.read_line(&mut buf)
1538 /// .expect("reading from cursor won't fail");
1539 /// assert_eq!(num_bytes, 4);
1540 /// assert_eq!(buf, "foo\n");
1543 /// // cursor is at 'b'
1544 /// let num_bytes = cursor.read_line(&mut buf)
1545 /// .expect("reading from cursor won't fail");
1546 /// assert_eq!(num_bytes, 3);
1547 /// assert_eq!(buf, "bar");
1550 /// // cursor is at EOF
1551 /// let num_bytes = cursor.read_line(&mut buf)
1552 /// .expect("reading from cursor won't fail");
1553 /// assert_eq!(num_bytes, 0);
1554 /// assert_eq!(buf, "");
1556 #[stable(feature = "rust1", since = "1.0.0")]
1557 fn read_line(&mut self, buf: &mut String) -> Result<usize> {
1558 // Note that we are not calling the `.read_until` method here, but
1559 // rather our hardcoded implementation. For more details as to why, see
1560 // the comments in `read_to_end`.
1561 append_to_string(buf, |b| read_until(self, b'\n', b))
1564 /// Returns an iterator over the contents of this reader split on the byte
1567 /// The iterator returned from this function will return instances of
1568 /// [`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
1569 /// the delimiter byte at the end.
1571 /// This function will yield errors whenever [`read_until`] would have
1572 /// also yielded an error.
1574 /// [`io::Result`]: type.Result.html
1575 /// [`Vec<u8>`]: ../vec/struct.Vec.html
1576 /// [`read_until`]: #method.read_until
1580 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1581 /// this example, we use [`Cursor`] to iterate over all hyphen delimited
1582 /// segments in a byte slice
1584 /// [`Cursor`]: struct.Cursor.html
1587 /// use std::io::{self, BufRead};
1589 /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
1591 /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
1592 /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
1593 /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
1594 /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
1595 /// assert_eq!(split_iter.next(), None);
1597 #[stable(feature = "rust1", since = "1.0.0")]
1598 fn split(self, byte: u8) -> Split<Self> where Self: Sized {
1599 Split { buf: self, delim: byte }
1602 /// Returns an iterator over the lines of this reader.
1604 /// The iterator returned from this function will yield instances of
1605 /// [`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline
1606 /// byte (the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.
1608 /// [`io::Result`]: type.Result.html
1609 /// [`String`]: ../string/struct.String.html
1613 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1614 /// this example, we use [`Cursor`] to iterate over all the lines in a byte
1617 /// [`Cursor`]: struct.Cursor.html
1620 /// use std::io::{self, BufRead};
1622 /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
1624 /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
1625 /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
1626 /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
1627 /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
1628 /// assert_eq!(lines_iter.next(), None);
1633 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
1635 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
1636 #[stable(feature = "rust1", since = "1.0.0")]
1637 fn lines(self) -> Lines<Self> where Self: Sized {
1642 /// Adaptor to chain together two readers.
1644 /// This struct is generally created by calling [`chain`] on a reader.
1645 /// Please see the documentation of [`chain`] for more details.
1647 /// [`chain`]: trait.Read.html#method.chain
1648 #[stable(feature = "rust1", since = "1.0.0")]
1649 pub struct Chain<T, U> {
1655 impl<T, U> Chain<T, U> {
1656 /// Consumes the `Chain`, returning the wrapped readers.
1662 /// use std::io::prelude::*;
1663 /// use std::fs::File;
1665 /// fn main() -> io::Result<()> {
1666 /// let mut foo_file = File::open("foo.txt")?;
1667 /// let mut bar_file = File::open("bar.txt")?;
1669 /// let chain = foo_file.chain(bar_file);
1670 /// let (foo_file, bar_file) = chain.into_inner();
1674 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1675 pub fn into_inner(self) -> (T, U) {
1676 (self.first, self.second)
1679 /// Gets references to the underlying readers in this `Chain`.
1685 /// use std::io::prelude::*;
1686 /// use std::fs::File;
1688 /// fn main() -> io::Result<()> {
1689 /// let mut foo_file = File::open("foo.txt")?;
1690 /// let mut bar_file = File::open("bar.txt")?;
1692 /// let chain = foo_file.chain(bar_file);
1693 /// let (foo_file, bar_file) = chain.get_ref();
1697 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1698 pub fn get_ref(&self) -> (&T, &U) {
1699 (&self.first, &self.second)
1702 /// Gets mutable references to the underlying readers in this `Chain`.
1704 /// Care should be taken to avoid modifying the internal I/O state of the
1705 /// underlying readers as doing so may corrupt the internal state of this
1712 /// use std::io::prelude::*;
1713 /// use std::fs::File;
1715 /// fn main() -> io::Result<()> {
1716 /// let mut foo_file = File::open("foo.txt")?;
1717 /// let mut bar_file = File::open("bar.txt")?;
1719 /// let mut chain = foo_file.chain(bar_file);
1720 /// let (foo_file, bar_file) = chain.get_mut();
1724 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1725 pub fn get_mut(&mut self) -> (&mut T, &mut U) {
1726 (&mut self.first, &mut self.second)
1730 #[stable(feature = "std_debug", since = "1.16.0")]
1731 impl<T: fmt::Debug, U: fmt::Debug> fmt::Debug for Chain<T, U> {
1732 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1733 f.debug_struct("Chain")
1734 .field("t", &self.first)
1735 .field("u", &self.second)
1740 #[stable(feature = "rust1", since = "1.0.0")]
1741 impl<T: Read, U: Read> Read for Chain<T, U> {
1742 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1743 if !self.done_first {
1744 match self.first.read(buf)? {
1745 0 if buf.len() != 0 => { self.done_first = true; }
1749 self.second.read(buf)
1752 unsafe fn initializer(&self) -> Initializer {
1753 let initializer = self.first.initializer();
1754 if initializer.should_initialize() {
1757 self.second.initializer()
1762 #[stable(feature = "chain_bufread", since = "1.9.0")]
1763 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
1764 fn fill_buf(&mut self) -> Result<&[u8]> {
1765 if !self.done_first {
1766 match self.first.fill_buf()? {
1767 buf if buf.len() == 0 => { self.done_first = true; }
1768 buf => return Ok(buf),
1771 self.second.fill_buf()
1774 fn consume(&mut self, amt: usize) {
1775 if !self.done_first {
1776 self.first.consume(amt)
1778 self.second.consume(amt)
1783 /// Reader adaptor which limits the bytes read from an underlying reader.
1785 /// This struct is generally created by calling [`take`] on a reader.
1786 /// Please see the documentation of [`take`] for more details.
1788 /// [`take`]: trait.Read.html#method.take
1789 #[stable(feature = "rust1", since = "1.0.0")]
1791 pub struct Take<T> {
1797 /// Returns the number of bytes that can be read before this instance will
1802 /// This instance may reach `EOF` after reading fewer bytes than indicated by
1803 /// this method if the underlying [`Read`] instance reaches EOF.
1805 /// [`Read`]: ../../std/io/trait.Read.html
1811 /// use std::io::prelude::*;
1812 /// use std::fs::File;
1814 /// fn main() -> io::Result<()> {
1815 /// let f = File::open("foo.txt")?;
1817 /// // read at most five bytes
1818 /// let handle = f.take(5);
1820 /// println!("limit: {}", handle.limit());
1824 #[stable(feature = "rust1", since = "1.0.0")]
1825 pub fn limit(&self) -> u64 { self.limit }
1827 /// Sets the number of bytes that can be read before this instance will
1828 /// return EOF. This is the same as constructing a new `Take` instance, so
1829 /// the amount of bytes read and the previous limit value don't matter when
1830 /// calling this method.
1836 /// use std::io::prelude::*;
1837 /// use std::fs::File;
1839 /// fn main() -> io::Result<()> {
1840 /// let f = File::open("foo.txt")?;
1842 /// // read at most five bytes
1843 /// let mut handle = f.take(5);
1844 /// handle.set_limit(10);
1846 /// assert_eq!(handle.limit(), 10);
1850 #[stable(feature = "take_set_limit", since = "1.27.0")]
1851 pub fn set_limit(&mut self, limit: u64) {
1855 /// Consumes the `Take`, returning the wrapped reader.
1861 /// use std::io::prelude::*;
1862 /// use std::fs::File;
1864 /// fn main() -> io::Result<()> {
1865 /// let mut file = File::open("foo.txt")?;
1867 /// let mut buffer = [0; 5];
1868 /// let mut handle = file.take(5);
1869 /// handle.read(&mut buffer)?;
1871 /// let file = handle.into_inner();
1875 #[stable(feature = "io_take_into_inner", since = "1.15.0")]
1876 pub fn into_inner(self) -> T {
1880 /// Gets a reference to the underlying reader.
1886 /// use std::io::prelude::*;
1887 /// use std::fs::File;
1889 /// fn main() -> io::Result<()> {
1890 /// let mut file = File::open("foo.txt")?;
1892 /// let mut buffer = [0; 5];
1893 /// let mut handle = file.take(5);
1894 /// handle.read(&mut buffer)?;
1896 /// let file = handle.get_ref();
1900 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1901 pub fn get_ref(&self) -> &T {
1905 /// Gets a mutable reference to the underlying reader.
1907 /// Care should be taken to avoid modifying the internal I/O state of the
1908 /// underlying reader as doing so may corrupt the internal limit of this
1915 /// use std::io::prelude::*;
1916 /// use std::fs::File;
1918 /// fn main() -> io::Result<()> {
1919 /// let mut file = File::open("foo.txt")?;
1921 /// let mut buffer = [0; 5];
1922 /// let mut handle = file.take(5);
1923 /// handle.read(&mut buffer)?;
1925 /// let file = handle.get_mut();
1929 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
1930 pub fn get_mut(&mut self) -> &mut T {
1935 #[stable(feature = "rust1", since = "1.0.0")]
1936 impl<T: Read> Read for Take<T> {
1937 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1938 // Don't call into inner reader at all at EOF because it may still block
1939 if self.limit == 0 {
1943 let max = cmp::min(buf.len() as u64, self.limit) as usize;
1944 let n = self.inner.read(&mut buf[..max])?;
1945 self.limit -= n as u64;
1949 unsafe fn initializer(&self) -> Initializer {
1950 self.inner.initializer()
1954 #[stable(feature = "rust1", since = "1.0.0")]
1955 impl<T: BufRead> BufRead for Take<T> {
1956 fn fill_buf(&mut self) -> Result<&[u8]> {
1957 // Don't call into inner reader at all at EOF because it may still block
1958 if self.limit == 0 {
1962 let buf = self.inner.fill_buf()?;
1963 let cap = cmp::min(buf.len() as u64, self.limit) as usize;
1967 fn consume(&mut self, amt: usize) {
1968 // Don't let callers reset the limit by passing an overlarge value
1969 let amt = cmp::min(amt as u64, self.limit) as usize;
1970 self.limit -= amt as u64;
1971 self.inner.consume(amt);
1975 fn read_one_byte(reader: &mut Read) -> Option<Result<u8>> {
1978 return match reader.read(&mut buf) {
1980 Ok(..) => Some(Ok(buf[0])),
1981 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1982 Err(e) => Some(Err(e)),
1987 /// An iterator over `u8` values of a reader.
1989 /// This struct is generally created by calling [`bytes`] on a reader.
1990 /// Please see the documentation of [`bytes`] for more details.
1992 /// [`bytes`]: trait.Read.html#method.bytes
1993 #[stable(feature = "rust1", since = "1.0.0")]
1995 pub struct Bytes<R> {
1999 #[stable(feature = "rust1", since = "1.0.0")]
2000 impl<R: Read> Iterator for Bytes<R> {
2001 type Item = Result<u8>;
2003 fn next(&mut self) -> Option<Result<u8>> {
2004 read_one_byte(&mut self.inner)
2008 /// An iterator over the `char`s of a reader.
2010 /// This struct is generally created by calling [`chars`][chars] on a reader.
2011 /// Please see the documentation of `chars()` for more details.
2013 /// [chars]: trait.Read.html#method.chars
2014 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
2016 #[rustc_deprecated(since = "1.27.0", reason = "Use str::from_utf8 instead:
2017 https://doc.rust-lang.org/nightly/std/str/struct.Utf8Error.html#examples")]
2019 #[allow(deprecated)]
2020 pub struct Chars<R> {
2024 /// An enumeration of possible errors that can be generated from the `Chars`
2026 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
2028 #[rustc_deprecated(since = "1.27.0", reason = "Use str::from_utf8 instead:
2029 https://doc.rust-lang.org/nightly/std/str/struct.Utf8Error.html#examples")]
2031 #[allow(deprecated)]
2032 pub enum CharsError {
2033 /// Variant representing that the underlying stream was read successfully
2034 /// but it did not contain valid utf8 data.
2037 /// Variant representing that an I/O error occurred.
2041 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
2043 #[allow(deprecated)]
2044 impl<R: Read> Iterator for Chars<R> {
2045 type Item = result::Result<char, CharsError>;
2047 fn next(&mut self) -> Option<result::Result<char, CharsError>> {
2048 let first_byte = match read_one_byte(&mut self.inner)? {
2050 Err(e) => return Some(Err(CharsError::Other(e))),
2052 let width = core_str::utf8_char_width(first_byte);
2053 if width == 1 { return Some(Ok(first_byte as char)) }
2054 if width == 0 { return Some(Err(CharsError::NotUtf8)) }
2055 let mut buf = [first_byte, 0, 0, 0];
2058 while start < width {
2059 match self.inner.read(&mut buf[start..width]) {
2060 Ok(0) => return Some(Err(CharsError::NotUtf8)),
2061 Ok(n) => start += n,
2062 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
2063 Err(e) => return Some(Err(CharsError::Other(e))),
2067 Some(match str::from_utf8(&buf[..width]).ok() {
2068 Some(s) => Ok(s.chars().next().unwrap()),
2069 None => Err(CharsError::NotUtf8),
2074 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
2076 #[allow(deprecated)]
2077 impl std_error::Error for CharsError {
2078 fn description(&self) -> &str {
2080 CharsError::NotUtf8 => "invalid utf8 encoding",
2081 CharsError::Other(ref e) => std_error::Error::description(e),
2084 fn cause(&self) -> Option<&std_error::Error> {
2086 CharsError::NotUtf8 => None,
2087 CharsError::Other(ref e) => e.cause(),
2092 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
2094 #[allow(deprecated)]
2095 impl fmt::Display for CharsError {
2096 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2098 CharsError::NotUtf8 => {
2099 "byte stream did not contain valid utf8".fmt(f)
2101 CharsError::Other(ref e) => e.fmt(f),
2106 /// An iterator over the contents of an instance of `BufRead` split on a
2107 /// particular byte.
2109 /// This struct is generally created by calling [`split`][split] on a
2110 /// `BufRead`. Please see the documentation of `split()` for more details.
2112 /// [split]: trait.BufRead.html#method.split
2113 #[stable(feature = "rust1", since = "1.0.0")]
2115 pub struct Split<B> {
2120 #[stable(feature = "rust1", since = "1.0.0")]
2121 impl<B: BufRead> Iterator for Split<B> {
2122 type Item = Result<Vec<u8>>;
2124 fn next(&mut self) -> Option<Result<Vec<u8>>> {
2125 let mut buf = Vec::new();
2126 match self.buf.read_until(self.delim, &mut buf) {
2129 if buf[buf.len() - 1] == self.delim {
2134 Err(e) => Some(Err(e))
2139 /// An iterator over the lines of an instance of `BufRead`.
2141 /// This struct is generally created by calling [`lines`][lines] on a
2142 /// `BufRead`. Please see the documentation of `lines()` for more details.
2144 /// [lines]: trait.BufRead.html#method.lines
2145 #[stable(feature = "rust1", since = "1.0.0")]
2147 pub struct Lines<B> {
2151 #[stable(feature = "rust1", since = "1.0.0")]
2152 impl<B: BufRead> Iterator for Lines<B> {
2153 type Item = Result<String>;
2155 fn next(&mut self) -> Option<Result<String>> {
2156 let mut buf = String::new();
2157 match self.buf.read_line(&mut buf) {
2160 if buf.ends_with("\n") {
2162 if buf.ends_with("\r") {
2168 Err(e) => Some(Err(e))
2182 #[cfg_attr(target_os = "emscripten", ignore)]
2184 let mut buf = Cursor::new(&b"12"[..]);
2185 let mut v = Vec::new();
2186 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 2);
2187 assert_eq!(v, b"12");
2189 let mut buf = Cursor::new(&b"1233"[..]);
2190 let mut v = Vec::new();
2191 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 3);
2192 assert_eq!(v, b"123");
2194 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 1);
2195 assert_eq!(v, b"3");
2197 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 0);
2203 let buf = Cursor::new(&b"12"[..]);
2204 let mut s = buf.split(b'3');
2205 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2206 assert!(s.next().is_none());
2208 let buf = Cursor::new(&b"1233"[..]);
2209 let mut s = buf.split(b'3');
2210 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2211 assert_eq!(s.next().unwrap().unwrap(), vec![]);
2212 assert!(s.next().is_none());
2217 let mut buf = Cursor::new(&b"12"[..]);
2218 let mut v = String::new();
2219 assert_eq!(buf.read_line(&mut v).unwrap(), 2);
2220 assert_eq!(v, "12");
2222 let mut buf = Cursor::new(&b"12\n\n"[..]);
2223 let mut v = String::new();
2224 assert_eq!(buf.read_line(&mut v).unwrap(), 3);
2225 assert_eq!(v, "12\n");
2227 assert_eq!(buf.read_line(&mut v).unwrap(), 1);
2228 assert_eq!(v, "\n");
2230 assert_eq!(buf.read_line(&mut v).unwrap(), 0);
2236 let buf = Cursor::new(&b"12\r"[..]);
2237 let mut s = buf.lines();
2238 assert_eq!(s.next().unwrap().unwrap(), "12\r".to_string());
2239 assert!(s.next().is_none());
2241 let buf = Cursor::new(&b"12\r\n\n"[..]);
2242 let mut s = buf.lines();
2243 assert_eq!(s.next().unwrap().unwrap(), "12".to_string());
2244 assert_eq!(s.next().unwrap().unwrap(), "".to_string());
2245 assert!(s.next().is_none());
2250 let mut c = Cursor::new(&b""[..]);
2251 let mut v = Vec::new();
2252 assert_eq!(c.read_to_end(&mut v).unwrap(), 0);
2255 let mut c = Cursor::new(&b"1"[..]);
2256 let mut v = Vec::new();
2257 assert_eq!(c.read_to_end(&mut v).unwrap(), 1);
2258 assert_eq!(v, b"1");
2260 let cap = 1024 * 1024;
2261 let data = (0..cap).map(|i| (i / 3) as u8).collect::<Vec<_>>();
2262 let mut v = Vec::new();
2263 let (a, b) = data.split_at(data.len() / 2);
2264 assert_eq!(Cursor::new(a).read_to_end(&mut v).unwrap(), a.len());
2265 assert_eq!(Cursor::new(b).read_to_end(&mut v).unwrap(), b.len());
2266 assert_eq!(v, data);
2270 fn read_to_string() {
2271 let mut c = Cursor::new(&b""[..]);
2272 let mut v = String::new();
2273 assert_eq!(c.read_to_string(&mut v).unwrap(), 0);
2276 let mut c = Cursor::new(&b"1"[..]);
2277 let mut v = String::new();
2278 assert_eq!(c.read_to_string(&mut v).unwrap(), 1);
2281 let mut c = Cursor::new(&b"\xff"[..]);
2282 let mut v = String::new();
2283 assert!(c.read_to_string(&mut v).is_err());
2288 let mut buf = [0; 4];
2290 let mut c = Cursor::new(&b""[..]);
2291 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2292 io::ErrorKind::UnexpectedEof);
2294 let mut c = Cursor::new(&b"123"[..]).chain(Cursor::new(&b"456789"[..]));
2295 c.read_exact(&mut buf).unwrap();
2296 assert_eq!(&buf, b"1234");
2297 c.read_exact(&mut buf).unwrap();
2298 assert_eq!(&buf, b"5678");
2299 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2300 io::ErrorKind::UnexpectedEof);
2304 fn read_exact_slice() {
2305 let mut buf = [0; 4];
2307 let mut c = &b""[..];
2308 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2309 io::ErrorKind::UnexpectedEof);
2311 let mut c = &b"123"[..];
2312 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2313 io::ErrorKind::UnexpectedEof);
2314 // make sure the optimized (early returning) method is being used
2315 assert_eq!(&buf, &[0; 4]);
2317 let mut c = &b"1234"[..];
2318 c.read_exact(&mut buf).unwrap();
2319 assert_eq!(&buf, b"1234");
2321 let mut c = &b"56789"[..];
2322 c.read_exact(&mut buf).unwrap();
2323 assert_eq!(&buf, b"5678");
2324 assert_eq!(c, b"9");
2332 fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
2333 Err(io::Error::new(io::ErrorKind::Other, ""))
2336 impl BufRead for R {
2337 fn fill_buf(&mut self) -> io::Result<&[u8]> {
2338 Err(io::Error::new(io::ErrorKind::Other, ""))
2340 fn consume(&mut self, _amt: usize) { }
2343 let mut buf = [0; 1];
2344 assert_eq!(0, R.take(0).read(&mut buf).unwrap());
2345 assert_eq!(b"", R.take(0).fill_buf().unwrap());
2348 fn cmp_bufread<Br1: BufRead, Br2: BufRead>(mut br1: Br1, mut br2: Br2, exp: &[u8]) {
2349 let mut cat = Vec::new();
2352 let buf1 = br1.fill_buf().unwrap();
2353 let buf2 = br2.fill_buf().unwrap();
2354 let minlen = if buf1.len() < buf2.len() { buf1.len() } else { buf2.len() };
2355 assert_eq!(buf1[..minlen], buf2[..minlen]);
2356 cat.extend_from_slice(&buf1[..minlen]);
2362 br1.consume(consume);
2363 br2.consume(consume);
2365 assert_eq!(br1.fill_buf().unwrap().len(), 0);
2366 assert_eq!(br2.fill_buf().unwrap().len(), 0);
2367 assert_eq!(&cat[..], &exp[..])
2371 fn chain_bufread() {
2372 let testdata = b"ABCDEFGHIJKL";
2373 let chain1 = (&testdata[..3]).chain(&testdata[3..6])
2374 .chain(&testdata[6..9])
2375 .chain(&testdata[9..]);
2376 let chain2 = (&testdata[..4]).chain(&testdata[4..8])
2377 .chain(&testdata[8..]);
2378 cmp_bufread(chain1, chain2, &testdata[..]);
2382 fn chain_zero_length_read_is_not_eof() {
2385 let mut s = String::new();
2386 let mut chain = (&a[..]).chain(&b[..]);
2387 chain.read(&mut []).unwrap();
2388 chain.read_to_string(&mut s).unwrap();
2389 assert_eq!("AB", s);
2393 #[cfg_attr(target_os = "emscripten", ignore)]
2394 fn bench_read_to_end(b: &mut test::Bencher) {
2396 let mut lr = repeat(1).take(10000000);
2397 let mut vec = Vec::with_capacity(1024);
2398 super::read_to_end(&mut lr, &mut vec)