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 foo() -> 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 foo() -> 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 foo() -> 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 foo() -> 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 foo() -> 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>` (e.g. `main`). Instead, you can call `.unwrap()` or `match`
151 //! 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 foo() -> 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 foo() -> io::Result<()> {
189 //! let f = File::open("foo.txt")?;
190 //! let reader = BufReader::new(f);
192 //! for line in reader.lines() {
193 //! println!("{}", line?);
202 //! There are a number of [functions][functions-list] that offer access to various
203 //! features. For example, we can use three of these functions to copy everything
204 //! from standard input to standard output:
209 //! # fn foo() -> io::Result<()> {
210 //! io::copy(&mut io::stdin(), &mut io::stdout())?;
215 //! [functions-list]: #functions-1
219 //! Last, but certainly not least, is [`io::Result`]. This type is used
220 //! as the return type of many `std::io` functions that can cause an error, and
221 //! can be returned from your own functions as well. Many of the examples in this
222 //! module use the [`?` operator]:
227 //! fn read_input() -> io::Result<()> {
228 //! let mut input = String::new();
230 //! io::stdin().read_line(&mut input)?;
232 //! println!("You typed: {}", input.trim());
238 //! The return type of `read_input()`, [`io::Result<()>`][`io::Result`], is a very
239 //! common type for functions which don't have a 'real' return value, but do want to
240 //! return errors if they happen. In this case, the only purpose of this function is
241 //! to read the line and print it, so we use `()`.
243 //! ## Platform-specific behavior
245 //! Many I/O functions throughout the standard library are documented to indicate
246 //! what various library or syscalls they are delegated to. This is done to help
247 //! applications both understand what's happening under the hood as well as investigate
248 //! any possibly unclear semantics. Note, however, that this is informative, not a binding
249 //! contract. The implementation of many of these functions are subject to change over
250 //! time and may call fewer or more syscalls/library functions.
252 //! [`Read`]: trait.Read.html
253 //! [`Write`]: trait.Write.html
254 //! [`Seek`]: trait.Seek.html
255 //! [`BufRead`]: trait.BufRead.html
256 //! [`File`]: ../fs/struct.File.html
257 //! [`TcpStream`]: ../net/struct.TcpStream.html
258 //! [`Vec<T>`]: ../vec/struct.Vec.html
259 //! [`BufReader`]: struct.BufReader.html
260 //! [`BufWriter`]: struct.BufWriter.html
261 //! [`Write::write`]: trait.Write.html#tymethod.write
262 //! [`io::stdout`]: fn.stdout.html
263 //! [`println!`]: ../macro.println.html
264 //! [`Lines`]: struct.Lines.html
265 //! [`io::Result`]: type.Result.html
266 //! [`?` operator]: ../../book/syntax-index.html
267 //! [`Read::read`]: trait.Read.html#tymethod.read
269 #![stable(feature = "rust1", since = "1.0.0")]
272 use core::str as core_str;
273 use error as std_error;
279 #[stable(feature = "rust1", since = "1.0.0")]
280 pub use self::buffered::{BufReader, BufWriter, LineWriter};
281 #[stable(feature = "rust1", since = "1.0.0")]
282 pub use self::buffered::IntoInnerError;
283 #[stable(feature = "rust1", since = "1.0.0")]
284 pub use self::cursor::Cursor;
285 #[stable(feature = "rust1", since = "1.0.0")]
286 pub use self::error::{Result, Error, ErrorKind};
287 #[stable(feature = "rust1", since = "1.0.0")]
288 pub use self::util::{copy, sink, Sink, empty, Empty, repeat, Repeat};
289 #[stable(feature = "rust1", since = "1.0.0")]
290 pub use self::stdio::{stdin, stdout, stderr, _print, Stdin, Stdout, Stderr};
291 #[stable(feature = "rust1", since = "1.0.0")]
292 pub use self::stdio::{StdoutLock, StderrLock, StdinLock};
293 #[unstable(feature = "libstd_io_internals", issue = "0")]
294 #[doc(no_inline, hidden)]
295 pub use self::stdio::{set_panic, set_print};
306 const DEFAULT_BUF_SIZE: usize = ::sys_common::io::DEFAULT_BUF_SIZE;
308 // A few methods below (read_to_string, read_line) will append data into a
309 // `String` buffer, but we need to be pretty careful when doing this. The
310 // implementation will just call `.as_mut_vec()` and then delegate to a
311 // byte-oriented reading method, but we must ensure that when returning we never
312 // leave `buf` in a state such that it contains invalid UTF-8 in its bounds.
314 // To this end, we use an RAII guard (to protect against panics) which updates
315 // the length of the string when it is dropped. This guard initially truncates
316 // the string to the prior length and only after we've validated that the
317 // new contents are valid UTF-8 do we allow it to set a longer length.
319 // The unsafety in this function is twofold:
321 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
323 // 2. We're passing a raw buffer to the function `f`, and it is expected that
324 // the function only *appends* bytes to the buffer. We'll get undefined
325 // behavior if existing bytes are overwritten to have non-UTF-8 data.
326 fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
327 where F: FnOnce(&mut Vec<u8>) -> Result<usize>
329 struct Guard<'a> { s: &'a mut Vec<u8>, len: usize }
330 impl<'a> Drop for Guard<'a> {
332 unsafe { self.s.set_len(self.len); }
337 let mut g = Guard { len: buf.len(), s: buf.as_mut_vec() };
339 if str::from_utf8(&g.s[g.len..]).is_err() {
341 Err(Error::new(ErrorKind::InvalidData,
342 "stream did not contain valid UTF-8"))
351 // This uses an adaptive system to extend the vector when it fills. We want to
352 // avoid paying to allocate and zero a huge chunk of memory if the reader only
353 // has 4 bytes while still making large reads if the reader does have a ton
354 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
355 // time is 4,500 times (!) slower than this if the reader has a very small
356 // amount of data to return.
357 fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
358 let start_len = buf.len();
359 let mut len = start_len;
360 let mut new_write_size = 16;
363 if len == buf.len() {
364 if new_write_size < DEFAULT_BUF_SIZE {
367 buf.resize(len + new_write_size, 0);
370 match r.read(&mut buf[len..]) {
372 ret = Ok(len - start_len);
376 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
388 /// The `Read` trait allows for reading bytes from a source.
390 /// Implementors of the `Read` trait are sometimes called 'readers'.
392 /// Readers are defined by one required method, `read()`. Each call to `read`
393 /// will attempt to pull bytes from this source into a provided buffer. A
394 /// number of other methods are implemented in terms of `read()`, giving
395 /// implementors a number of ways to read bytes while only needing to implement
398 /// Readers are intended to be composable with one another. Many implementors
399 /// throughout `std::io` take and provide types which implement the `Read`
402 /// Please note that each call to `read` may involve a system call, and
403 /// therefore, using something that implements [`BufRead`][bufread], such as
404 /// [`BufReader`][bufreader], will be more efficient.
406 /// [bufread]: trait.BufRead.html
407 /// [bufreader]: struct.BufReader.html
411 /// [`File`][file]s implement `Read`:
413 /// [file]: ../fs/struct.File.html
417 /// use std::io::prelude::*;
418 /// use std::fs::File;
420 /// # fn foo() -> io::Result<()> {
421 /// let mut f = File::open("foo.txt")?;
422 /// let mut buffer = [0; 10];
424 /// // read up to 10 bytes
425 /// f.read(&mut buffer)?;
427 /// let mut buffer = vec![0; 10];
428 /// // read the whole file
429 /// f.read_to_end(&mut buffer)?;
431 /// // read into a String, so that you don't need to do the conversion.
432 /// let mut buffer = String::new();
433 /// f.read_to_string(&mut buffer)?;
435 /// // and more! See the other methods for more details.
439 #[stable(feature = "rust1", since = "1.0.0")]
441 /// Pull some bytes from this source into the specified buffer, returning
442 /// how many bytes were read.
444 /// This function does not provide any guarantees about whether it blocks
445 /// waiting for data, but if an object needs to block for a read but cannot
446 /// it will typically signal this via an `Err` return value.
448 /// If the return value of this method is `Ok(n)`, then it must be
449 /// guaranteed that `0 <= n <= buf.len()`. A nonzero `n` value indicates
450 /// that the buffer `buf` has been filled in with `n` bytes of data from this
451 /// source. If `n` is `0`, then it can indicate one of two scenarios:
453 /// 1. This reader has reached its "end of file" and will likely no longer
454 /// be able to produce bytes. Note that this does not mean that the
455 /// reader will *always* no longer be able to produce bytes.
456 /// 2. The buffer specified was 0 bytes in length.
458 /// No guarantees are provided about the contents of `buf` when this
459 /// function is called, implementations cannot rely on any property of the
460 /// contents of `buf` being true. It is recommended that implementations
461 /// only write data to `buf` instead of reading its contents.
465 /// If this function encounters any form of I/O or other error, an error
466 /// variant will be returned. If an error is returned then it must be
467 /// guaranteed that no bytes were read.
471 /// [`File`][file]s implement `Read`:
473 /// [file]: ../fs/struct.File.html
477 /// use std::io::prelude::*;
478 /// use std::fs::File;
480 /// # fn foo() -> io::Result<()> {
481 /// let mut f = File::open("foo.txt")?;
482 /// let mut buffer = [0; 10];
485 /// f.read(&mut buffer[..])?;
489 #[stable(feature = "rust1", since = "1.0.0")]
490 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
492 /// Read all bytes until EOF in this source, placing them into `buf`.
494 /// All bytes read from this source will be appended to the specified buffer
495 /// `buf`. This function will continuously call `read` to append more data to
496 /// `buf` until `read` returns either `Ok(0)` or an error of
497 /// non-`ErrorKind::Interrupted` kind.
499 /// If successful, this function will return the total number of bytes read.
503 /// If this function encounters an error of the kind
504 /// `ErrorKind::Interrupted` then the error is ignored and the operation
507 /// If any other read error is encountered then this function immediately
508 /// returns. Any bytes which have already been read will be appended to
513 /// [`File`][file]s implement `Read`:
515 /// [file]: ../fs/struct.File.html
519 /// use std::io::prelude::*;
520 /// use std::fs::File;
522 /// # fn foo() -> io::Result<()> {
523 /// let mut f = File::open("foo.txt")?;
524 /// let mut buffer = Vec::new();
526 /// // read the whole file
527 /// f.read_to_end(&mut buffer)?;
531 #[stable(feature = "rust1", since = "1.0.0")]
532 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
533 read_to_end(self, buf)
536 /// Read all bytes until EOF in this source, placing them into `buf`.
538 /// If successful, this function returns the number of bytes which were read
539 /// and appended to `buf`.
543 /// If the data in this stream is *not* valid UTF-8 then an error is
544 /// returned and `buf` is unchanged.
546 /// See [`read_to_end`][readtoend] for other error semantics.
548 /// [readtoend]: #method.read_to_end
552 /// [`File`][file]s implement `Read`:
554 /// [file]: ../fs/struct.File.html
558 /// use std::io::prelude::*;
559 /// use std::fs::File;
561 /// # fn foo() -> io::Result<()> {
562 /// let mut f = File::open("foo.txt")?;
563 /// let mut buffer = String::new();
565 /// f.read_to_string(&mut buffer)?;
569 #[stable(feature = "rust1", since = "1.0.0")]
570 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
571 // Note that we do *not* call `.read_to_end()` here. We are passing
572 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
573 // method to fill it up. An arbitrary implementation could overwrite the
574 // entire contents of the vector, not just append to it (which is what
575 // we are expecting).
577 // To prevent extraneously checking the UTF-8-ness of the entire buffer
578 // we pass it to our hardcoded `read_to_end` implementation which we
579 // know is guaranteed to only read data into the end of the buffer.
580 append_to_string(buf, |b| read_to_end(self, b))
583 /// Read the exact number of bytes required to fill `buf`.
585 /// This function reads as many bytes as necessary to completely fill the
586 /// specified buffer `buf`.
588 /// No guarantees are provided about the contents of `buf` when this
589 /// function is called, implementations cannot rely on any property of the
590 /// contents of `buf` being true. It is recommended that implementations
591 /// only write data to `buf` instead of reading its contents.
595 /// If this function encounters an error of the kind
596 /// `ErrorKind::Interrupted` then the error is ignored and the operation
599 /// If this function encounters an "end of file" before completely filling
600 /// the buffer, it returns an error of the kind `ErrorKind::UnexpectedEof`.
601 /// The contents of `buf` are unspecified in this case.
603 /// If any other read error is encountered then this function immediately
604 /// returns. The contents of `buf` are unspecified in this case.
606 /// If this function returns an error, it is unspecified how many bytes it
607 /// has read, but it will never read more than would be necessary to
608 /// completely fill the buffer.
612 /// [`File`][file]s implement `Read`:
614 /// [file]: ../fs/struct.File.html
618 /// use std::io::prelude::*;
619 /// use std::fs::File;
621 /// # fn foo() -> io::Result<()> {
622 /// let mut f = File::open("foo.txt")?;
623 /// let mut buffer = [0; 10];
625 /// // read exactly 10 bytes
626 /// f.read_exact(&mut buffer)?;
630 #[stable(feature = "read_exact", since = "1.6.0")]
631 fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
632 while !buf.is_empty() {
633 match self.read(buf) {
635 Ok(n) => { let tmp = buf; buf = &mut tmp[n..]; }
636 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
637 Err(e) => return Err(e),
641 Err(Error::new(ErrorKind::UnexpectedEof,
642 "failed to fill whole buffer"))
648 /// Creates a "by reference" adaptor for this instance of `Read`.
650 /// The returned adaptor also implements `Read` and will simply borrow this
655 /// [`File`][file]s implement `Read`:
657 /// [file]: ../fs/struct.File.html
661 /// use std::io::Read;
662 /// use std::fs::File;
664 /// # fn foo() -> io::Result<()> {
665 /// let mut f = File::open("foo.txt")?;
666 /// let mut buffer = Vec::new();
667 /// let mut other_buffer = Vec::new();
670 /// let reference = f.by_ref();
672 /// // read at most 5 bytes
673 /// reference.take(5).read_to_end(&mut buffer)?;
675 /// } // drop our &mut reference so we can use f again
677 /// // original file still usable, read the rest
678 /// f.read_to_end(&mut other_buffer)?;
682 #[stable(feature = "rust1", since = "1.0.0")]
683 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
685 /// Transforms this `Read` instance to an `Iterator` over its bytes.
687 /// The returned type implements `Iterator` where the `Item` is `Result<u8,
688 /// R::Err>`. The yielded item is `Ok` if a byte was successfully read and
689 /// `Err` otherwise for I/O errors. EOF is mapped to returning `None` from
694 /// [`File`][file]s implement `Read`:
696 /// [file]: ../fs/struct.File.html
700 /// use std::io::prelude::*;
701 /// use std::fs::File;
703 /// # fn foo() -> io::Result<()> {
704 /// let mut f = File::open("foo.txt")?;
706 /// for byte in f.bytes() {
707 /// println!("{}", byte.unwrap());
712 #[stable(feature = "rust1", since = "1.0.0")]
713 fn bytes(self) -> Bytes<Self> where Self: Sized {
714 Bytes { inner: self }
717 /// Transforms this `Read` instance to an `Iterator` over `char`s.
719 /// This adaptor will attempt to interpret this reader as a UTF-8 encoded
720 /// sequence of characters. The returned iterator will return `None` once
721 /// EOF is reached for this reader. Otherwise each element yielded will be a
722 /// `Result<char, E>` where `E` may contain information about what I/O error
723 /// occurred or where decoding failed.
725 /// Currently this adaptor will discard intermediate data read, and should
726 /// be avoided if this is not desired.
730 /// [`File`][file]s implement `Read`:
732 /// [file]: ../fs/struct.File.html
737 /// use std::io::prelude::*;
738 /// use std::fs::File;
740 /// # fn foo() -> io::Result<()> {
741 /// let mut f = File::open("foo.txt")?;
743 /// for c in f.chars() {
744 /// println!("{}", c.unwrap());
749 #[unstable(feature = "io", reason = "the semantics of a partial read/write \
750 of where errors happen is currently \
751 unclear and may change",
753 fn chars(self) -> Chars<Self> where Self: Sized {
754 Chars { inner: self }
757 /// Creates an adaptor which will chain this stream with another.
759 /// The returned `Read` instance will first read all bytes from this object
760 /// until EOF is encountered. Afterwards the output is equivalent to the
761 /// output of `next`.
765 /// [`File`][file]s implement `Read`:
767 /// [file]: ../fs/struct.File.html
771 /// use std::io::prelude::*;
772 /// use std::fs::File;
774 /// # fn foo() -> io::Result<()> {
775 /// let mut f1 = File::open("foo.txt")?;
776 /// let mut f2 = File::open("bar.txt")?;
778 /// let mut handle = f1.chain(f2);
779 /// let mut buffer = String::new();
781 /// // read the value into a String. We could use any Read method here,
782 /// // this is just one example.
783 /// handle.read_to_string(&mut buffer)?;
787 #[stable(feature = "rust1", since = "1.0.0")]
788 fn chain<R: Read>(self, next: R) -> Chain<Self, R> where Self: Sized {
789 Chain { first: self, second: next, done_first: false }
792 /// Creates an adaptor which will read at most `limit` bytes from it.
794 /// This function returns a new instance of `Read` which will read at most
795 /// `limit` bytes, after which it will always return EOF (`Ok(0)`). Any
796 /// read errors will not count towards the number of bytes read and future
797 /// calls to `read` may succeed.
801 /// [`File`][file]s implement `Read`:
803 /// [file]: ../fs/struct.File.html
807 /// use std::io::prelude::*;
808 /// use std::fs::File;
810 /// # fn foo() -> io::Result<()> {
811 /// let mut f = File::open("foo.txt")?;
812 /// let mut buffer = [0; 5];
814 /// // read at most five bytes
815 /// let mut handle = f.take(5);
817 /// handle.read(&mut buffer)?;
821 #[stable(feature = "rust1", since = "1.0.0")]
822 fn take(self, limit: u64) -> Take<Self> where Self: Sized {
823 Take { inner: self, limit: limit }
827 /// A trait for objects which are byte-oriented sinks.
829 /// Implementors of the `Write` trait are sometimes called 'writers'.
831 /// Writers are defined by two required methods, [`write`] and [`flush`]:
833 /// * The [`write`] method will attempt to write some data into the object,
834 /// returning how many bytes were successfully written.
836 /// * The [`flush`] method is useful for adaptors and explicit buffers
837 /// themselves for ensuring that all buffered data has been pushed out to the
840 /// Writers are intended to be composable with one another. Many implementors
841 /// throughout [`std::io`] take and provide types which implement the `Write`
844 /// [`write`]: #tymethod.write
845 /// [`flush`]: #tymethod.flush
846 /// [`std::io`]: index.html
851 /// use std::io::prelude::*;
852 /// use std::fs::File;
854 /// # fn foo() -> std::io::Result<()> {
855 /// let mut buffer = File::create("foo.txt")?;
857 /// buffer.write(b"some bytes")?;
861 #[stable(feature = "rust1", since = "1.0.0")]
863 /// Write a buffer into this object, returning how many bytes were written.
865 /// This function will attempt to write the entire contents of `buf`, but
866 /// the entire write may not succeed, or the write may also generate an
867 /// error. A call to `write` represents *at most one* attempt to write to
868 /// any wrapped object.
870 /// Calls to `write` are not guaranteed to block waiting for data to be
871 /// written, and a write which would otherwise block can be indicated through
872 /// an `Err` variant.
874 /// If the return value is `Ok(n)` then it must be guaranteed that
875 /// `0 <= n <= buf.len()`. A return value of `0` typically means that the
876 /// underlying object is no longer able to accept bytes and will likely not
877 /// be able to in the future as well, or that the buffer provided is empty.
881 /// Each call to `write` may generate an I/O error indicating that the
882 /// operation could not be completed. If an error is returned then no bytes
883 /// in the buffer were written to this writer.
885 /// It is **not** considered an error if the entire buffer could not be
886 /// written to this writer.
891 /// use std::io::prelude::*;
892 /// use std::fs::File;
894 /// # fn foo() -> std::io::Result<()> {
895 /// let mut buffer = File::create("foo.txt")?;
897 /// buffer.write(b"some bytes")?;
901 #[stable(feature = "rust1", since = "1.0.0")]
902 fn write(&mut self, buf: &[u8]) -> Result<usize>;
904 /// Flush this output stream, ensuring that all intermediately buffered
905 /// contents reach their destination.
909 /// It is considered an error if not all bytes could be written due to
910 /// I/O errors or EOF being reached.
915 /// use std::io::prelude::*;
916 /// use std::io::BufWriter;
917 /// use std::fs::File;
919 /// # fn foo() -> std::io::Result<()> {
920 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
922 /// buffer.write(b"some bytes")?;
927 #[stable(feature = "rust1", since = "1.0.0")]
928 fn flush(&mut self) -> Result<()>;
930 /// Attempts to write an entire buffer into this write.
932 /// This method will continuously call `write` while there is more data to
933 /// write. This method will not return until the entire buffer has been
934 /// successfully written or an error occurs. The first error generated from
935 /// this method will be returned.
939 /// This function will return the first error that `write` returns.
944 /// use std::io::prelude::*;
945 /// use std::fs::File;
947 /// # fn foo() -> std::io::Result<()> {
948 /// let mut buffer = File::create("foo.txt")?;
950 /// buffer.write_all(b"some bytes")?;
954 #[stable(feature = "rust1", since = "1.0.0")]
955 fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
956 while !buf.is_empty() {
957 match self.write(buf) {
958 Ok(0) => return Err(Error::new(ErrorKind::WriteZero,
959 "failed to write whole buffer")),
960 Ok(n) => buf = &buf[n..],
961 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
962 Err(e) => return Err(e),
968 /// Writes a formatted string into this writer, returning any error
971 /// This method is primarily used to interface with the
972 /// [`format_args!`][formatargs] macro, but it is rare that this should
973 /// explicitly be called. The [`write!`][write] macro should be favored to
974 /// invoke this method instead.
976 /// [formatargs]: ../macro.format_args.html
977 /// [write]: ../macro.write.html
979 /// This function internally uses the [`write_all`][writeall] method on
980 /// this trait and hence will continuously write data so long as no errors
981 /// are received. This also means that partial writes are not indicated in
984 /// [writeall]: #method.write_all
988 /// This function will return any I/O error reported while formatting.
993 /// use std::io::prelude::*;
994 /// use std::fs::File;
996 /// # fn foo() -> std::io::Result<()> {
997 /// let mut buffer = File::create("foo.txt")?;
1000 /// write!(buffer, "{:.*}", 2, 1.234567)?;
1001 /// // turns into this:
1002 /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1006 #[stable(feature = "rust1", since = "1.0.0")]
1007 fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()> {
1008 // Create a shim which translates a Write to a fmt::Write and saves
1009 // off I/O errors. instead of discarding them
1010 struct Adaptor<'a, T: ?Sized + 'a> {
1015 impl<'a, T: Write + ?Sized> fmt::Write for Adaptor<'a, T> {
1016 fn write_str(&mut self, s: &str) -> fmt::Result {
1017 match self.inner.write_all(s.as_bytes()) {
1020 self.error = Err(e);
1027 let mut output = Adaptor { inner: self, error: Ok(()) };
1028 match fmt::write(&mut output, fmt) {
1031 // check if the error came from the underlying `Write` or not
1032 if output.error.is_err() {
1035 Err(Error::new(ErrorKind::Other, "formatter error"))
1041 /// Creates a "by reference" adaptor for this instance of `Write`.
1043 /// The returned adaptor also implements `Write` and will simply borrow this
1049 /// use std::io::Write;
1050 /// use std::fs::File;
1052 /// # fn foo() -> std::io::Result<()> {
1053 /// let mut buffer = File::create("foo.txt")?;
1055 /// let reference = buffer.by_ref();
1057 /// // we can use reference just like our original buffer
1058 /// reference.write_all(b"some bytes")?;
1062 #[stable(feature = "rust1", since = "1.0.0")]
1063 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1066 /// The `Seek` trait provides a cursor which can be moved within a stream of
1069 /// The stream typically has a fixed size, allowing seeking relative to either
1070 /// end or the current offset.
1074 /// [`File`][file]s implement `Seek`:
1076 /// [file]: ../fs/struct.File.html
1080 /// use std::io::prelude::*;
1081 /// use std::fs::File;
1082 /// use std::io::SeekFrom;
1084 /// # fn foo() -> io::Result<()> {
1085 /// let mut f = File::open("foo.txt")?;
1087 /// // move the cursor 42 bytes from the start of the file
1088 /// f.seek(SeekFrom::Start(42))?;
1092 #[stable(feature = "rust1", since = "1.0.0")]
1094 /// Seek to an offset, in bytes, in a stream.
1096 /// A seek beyond the end of a stream is allowed, but implementation
1099 /// If the seek operation completed successfully,
1100 /// this method returns the new position from the start of the stream.
1101 /// That position can be used later with [`SeekFrom::Start`].
1105 /// Seeking to a negative offset is considered an error.
1107 /// [`SeekFrom::Start`]: enum.SeekFrom.html#variant.Start
1108 #[stable(feature = "rust1", since = "1.0.0")]
1109 fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1112 /// Enumeration of possible methods to seek within an I/O object.
1114 /// It is used by the [`Seek`] trait.
1116 /// [`Seek`]: trait.Seek.html
1117 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1118 #[stable(feature = "rust1", since = "1.0.0")]
1120 /// Set the offset to the provided number of bytes.
1121 #[stable(feature = "rust1", since = "1.0.0")]
1122 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1124 /// Set the offset to the size of this object plus the specified number of
1127 /// It is possible to seek beyond the end of an object, but it's an error to
1128 /// seek before byte 0.
1129 #[stable(feature = "rust1", since = "1.0.0")]
1130 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1132 /// Set the offset to the current position plus the specified number of
1135 /// It is possible to seek beyond the end of an object, but it's an error to
1136 /// seek before byte 0.
1137 #[stable(feature = "rust1", since = "1.0.0")]
1138 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1141 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>)
1145 let (done, used) = {
1146 let available = match r.fill_buf() {
1148 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1149 Err(e) => return Err(e)
1151 match memchr::memchr(delim, available) {
1153 buf.extend_from_slice(&available[..i + 1]);
1157 buf.extend_from_slice(available);
1158 (false, available.len())
1164 if done || used == 0 {
1170 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1171 /// to perform extra ways of reading.
1173 /// For example, reading line-by-line is inefficient without using a buffer, so
1174 /// if you want to read by line, you'll need `BufRead`, which includes a
1175 /// [`read_line`] method as well as a [`lines`] iterator.
1179 /// A locked standard input implements `BufRead`:
1183 /// use std::io::prelude::*;
1185 /// let stdin = io::stdin();
1186 /// for line in stdin.lock().lines() {
1187 /// println!("{}", line.unwrap());
1191 /// If you have something that implements [`Read`], you can use the [`BufReader`
1192 /// type][`BufReader`] to turn it into a `BufRead`.
1194 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1195 /// [`BufReader`] to the rescue!
1197 /// [`BufReader`]: struct.BufReader.html
1198 /// [`File`]: ../fs/struct.File.html
1199 /// [`read_line`]: #method.read_line
1200 /// [`lines`]: #method.lines
1201 /// [`Read`]: trait.Read.html
1204 /// use std::io::{self, BufReader};
1205 /// use std::io::prelude::*;
1206 /// use std::fs::File;
1208 /// # fn foo() -> io::Result<()> {
1209 /// let f = File::open("foo.txt")?;
1210 /// let f = BufReader::new(f);
1212 /// for line in f.lines() {
1213 /// println!("{}", line.unwrap());
1220 #[stable(feature = "rust1", since = "1.0.0")]
1221 pub trait BufRead: Read {
1222 /// Fills the internal buffer of this object, returning the buffer contents.
1224 /// This function is a lower-level call. It needs to be paired with the
1225 /// [`consume`] method to function properly. When calling this
1226 /// method, none of the contents will be "read" in the sense that later
1227 /// calling `read` may return the same contents. As such, [`consume`] must
1228 /// be called with the number of bytes that are consumed from this buffer to
1229 /// ensure that the bytes are never returned twice.
1231 /// [`consume`]: #tymethod.consume
1233 /// An empty buffer returned indicates that the stream has reached EOF.
1237 /// This function will return an I/O error if the underlying reader was
1238 /// read, but returned an error.
1242 /// A locked standard input implements `BufRead`:
1246 /// use std::io::prelude::*;
1248 /// let stdin = io::stdin();
1249 /// let mut stdin = stdin.lock();
1251 /// // we can't have two `&mut` references to `stdin`, so use a block
1252 /// // to end the borrow early.
1254 /// let buffer = stdin.fill_buf().unwrap();
1256 /// // work with buffer
1257 /// println!("{:?}", buffer);
1262 /// // ensure the bytes we worked with aren't returned again later
1263 /// stdin.consume(length);
1265 #[stable(feature = "rust1", since = "1.0.0")]
1266 fn fill_buf(&mut self) -> Result<&[u8]>;
1268 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1269 /// so they should no longer be returned in calls to `read`.
1271 /// This function is a lower-level call. It needs to be paired with the
1272 /// [`fill_buf`] method to function properly. This function does
1273 /// not perform any I/O, it simply informs this object that some amount of
1274 /// its buffer, returned from [`fill_buf`], has been consumed and should
1275 /// no longer be returned. As such, this function may do odd things if
1276 /// [`fill_buf`] isn't called before calling it.
1278 /// The `amt` must be `<=` the number of bytes in the buffer returned by
1283 /// Since `consume()` is meant to be used with [`fill_buf`],
1284 /// that method's example includes an example of `consume()`.
1286 /// [`fill_buf`]: #tymethod.fill_buf
1287 #[stable(feature = "rust1", since = "1.0.0")]
1288 fn consume(&mut self, amt: usize);
1290 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
1292 /// This function will read bytes from the underlying stream until the
1293 /// delimiter or EOF is found. Once found, all bytes up to, and including,
1294 /// the delimiter (if found) will be appended to `buf`.
1296 /// If successful, this function will return the total number of bytes read.
1300 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1301 /// will otherwise return any errors returned by [`fill_buf`].
1303 /// If an I/O error is encountered then all bytes read so far will be
1304 /// present in `buf` and its length will have been adjusted appropriately.
1306 /// [`fill_buf`]: #tymethod.fill_buf
1307 /// [`ErrorKind::Interrupted`]: enum.ErrorKind.html#variant.Interrupted
1311 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1312 /// this example, we use [`Cursor`] to read all the bytes in a byte slice
1313 /// in hyphen delimited segments:
1315 /// [`Cursor`]: struct.Cursor.html
1318 /// use std::io::{self, BufRead};
1320 /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
1321 /// let mut buf = vec![];
1323 /// // cursor is at 'l'
1324 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1325 /// .expect("reading from cursor won't fail");
1326 /// assert_eq!(num_bytes, 6);
1327 /// assert_eq!(buf, b"lorem-");
1330 /// // cursor is at 'i'
1331 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1332 /// .expect("reading from cursor won't fail");
1333 /// assert_eq!(num_bytes, 5);
1334 /// assert_eq!(buf, b"ipsum");
1337 /// // cursor is at EOF
1338 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1339 /// .expect("reading from cursor won't fail");
1340 /// assert_eq!(num_bytes, 0);
1341 /// assert_eq!(buf, b"");
1343 #[stable(feature = "rust1", since = "1.0.0")]
1344 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
1345 read_until(self, byte, buf)
1348 /// Read all bytes until a newline (the 0xA byte) is reached, and append
1349 /// them to the provided buffer.
1351 /// This function will read bytes from the underlying stream until the
1352 /// newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes
1353 /// up to, and including, the delimiter (if found) will be appended to
1356 /// If successful, this function will return the total number of bytes read.
1360 /// This function has the same error semantics as [`read_until`] and will
1361 /// also return an error if the read bytes are not valid UTF-8. If an I/O
1362 /// error is encountered then `buf` may contain some bytes already read in
1363 /// the event that all data read so far was valid UTF-8.
1367 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1368 /// this example, we use [`Cursor`] to read all the lines in a byte slice:
1370 /// [`Cursor`]: struct.Cursor.html
1373 /// use std::io::{self, BufRead};
1375 /// let mut cursor = io::Cursor::new(b"foo\nbar");
1376 /// let mut buf = String::new();
1378 /// // cursor is at 'f'
1379 /// let num_bytes = cursor.read_line(&mut buf)
1380 /// .expect("reading from cursor won't fail");
1381 /// assert_eq!(num_bytes, 4);
1382 /// assert_eq!(buf, "foo\n");
1385 /// // cursor is at 'b'
1386 /// let num_bytes = cursor.read_line(&mut buf)
1387 /// .expect("reading from cursor won't fail");
1388 /// assert_eq!(num_bytes, 3);
1389 /// assert_eq!(buf, "bar");
1392 /// // cursor is at EOF
1393 /// let num_bytes = cursor.read_line(&mut buf)
1394 /// .expect("reading from cursor won't fail");
1395 /// assert_eq!(num_bytes, 0);
1396 /// assert_eq!(buf, "");
1398 #[stable(feature = "rust1", since = "1.0.0")]
1399 fn read_line(&mut self, buf: &mut String) -> Result<usize> {
1400 // Note that we are not calling the `.read_until` method here, but
1401 // rather our hardcoded implementation. For more details as to why, see
1402 // the comments in `read_to_end`.
1403 append_to_string(buf, |b| read_until(self, b'\n', b))
1406 /// Returns an iterator over the contents of this reader split on the byte
1409 /// The iterator returned from this function will return instances of
1410 /// [`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
1411 /// the delimiter byte at the end.
1413 /// This function will yield errors whenever [`read_until`] would have
1414 /// also yielded an error.
1416 /// [`io::Result`]: type.Result.html
1417 /// [`Vec<u8>`]: ../vec/struct.Vec.html
1418 /// [`read_until`]: #method.read_until
1422 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1423 /// this example, we use [`Cursor`] to iterate over all hyphen delimited
1424 /// segments in a byte slice
1426 /// [`Cursor`]: struct.Cursor.html
1429 /// use std::io::{self, BufRead};
1431 /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
1433 /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
1434 /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
1435 /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
1436 /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
1437 /// assert_eq!(split_iter.next(), None);
1439 #[stable(feature = "rust1", since = "1.0.0")]
1440 fn split(self, byte: u8) -> Split<Self> where Self: Sized {
1441 Split { buf: self, delim: byte }
1444 /// Returns an iterator over the lines of this reader.
1446 /// The iterator returned from this function will yield instances of
1447 /// [`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline
1448 /// byte (the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.
1450 /// [`io::Result`]: type.Result.html
1451 /// [`String`]: ../string/struct.String.html
1455 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1456 /// this example, we use [`Cursor`] to iterate over all the lines in a byte
1459 /// [`Cursor`]: struct.Cursor.html
1462 /// use std::io::{self, BufRead};
1464 /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
1466 /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
1467 /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
1468 /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
1469 /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
1470 /// assert_eq!(lines_iter.next(), None);
1475 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
1477 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
1478 #[stable(feature = "rust1", since = "1.0.0")]
1479 fn lines(self) -> Lines<Self> where Self: Sized {
1484 /// Adaptor to chain together two readers.
1486 /// This struct is generally created by calling [`chain`] on a reader.
1487 /// Please see the documentation of [`chain`] for more details.
1489 /// [`chain`]: trait.Read.html#method.chain
1490 #[stable(feature = "rust1", since = "1.0.0")]
1491 pub struct Chain<T, U> {
1497 #[stable(feature = "std_debug", since = "1.16.0")]
1498 impl<T: fmt::Debug, U: fmt::Debug> fmt::Debug for Chain<T, U> {
1499 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1500 f.debug_struct("Chain")
1501 .field("t", &self.first)
1502 .field("u", &self.second)
1507 #[stable(feature = "rust1", since = "1.0.0")]
1508 impl<T: Read, U: Read> Read for Chain<T, U> {
1509 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1510 if !self.done_first {
1511 match self.first.read(buf)? {
1512 0 if buf.len() != 0 => { self.done_first = true; }
1516 self.second.read(buf)
1520 #[stable(feature = "chain_bufread", since = "1.9.0")]
1521 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
1522 fn fill_buf(&mut self) -> Result<&[u8]> {
1523 if !self.done_first {
1524 match self.first.fill_buf()? {
1525 buf if buf.len() == 0 => { self.done_first = true; }
1526 buf => return Ok(buf),
1529 self.second.fill_buf()
1532 fn consume(&mut self, amt: usize) {
1533 if !self.done_first {
1534 self.first.consume(amt)
1536 self.second.consume(amt)
1541 /// Reader adaptor which limits the bytes read from an underlying reader.
1543 /// This struct is generally created by calling [`take`] on a reader.
1544 /// Please see the documentation of [`take`] for more details.
1546 /// [`take`]: trait.Read.html#method.take
1547 #[stable(feature = "rust1", since = "1.0.0")]
1549 pub struct Take<T> {
1555 /// Returns the number of bytes that can be read before this instance will
1560 /// This instance may reach `EOF` after reading fewer bytes than indicated by
1561 /// this method if the underlying [`Read`] instance reaches EOF.
1563 /// [`Read`]: ../../std/io/trait.Read.html
1569 /// use std::io::prelude::*;
1570 /// use std::fs::File;
1572 /// # fn foo() -> io::Result<()> {
1573 /// let f = File::open("foo.txt")?;
1575 /// // read at most five bytes
1576 /// let handle = f.take(5);
1578 /// println!("limit: {}", handle.limit());
1582 #[stable(feature = "rust1", since = "1.0.0")]
1583 pub fn limit(&self) -> u64 { self.limit }
1585 /// Consumes the `Take`, returning the wrapped reader.
1591 /// use std::io::prelude::*;
1592 /// use std::fs::File;
1594 /// # fn foo() -> io::Result<()> {
1595 /// let mut file = File::open("foo.txt")?;
1597 /// let mut buffer = [0; 5];
1598 /// let mut handle = file.take(5);
1599 /// handle.read(&mut buffer)?;
1601 /// let file = handle.into_inner();
1605 #[stable(feature = "io_take_into_inner", since = "1.15.0")]
1606 pub fn into_inner(self) -> T {
1611 #[stable(feature = "rust1", since = "1.0.0")]
1612 impl<T: Read> Read for Take<T> {
1613 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1614 // Don't call into inner reader at all at EOF because it may still block
1615 if self.limit == 0 {
1619 let max = cmp::min(buf.len() as u64, self.limit) as usize;
1620 let n = self.inner.read(&mut buf[..max])?;
1621 self.limit -= n as u64;
1626 #[stable(feature = "rust1", since = "1.0.0")]
1627 impl<T: BufRead> BufRead for Take<T> {
1628 fn fill_buf(&mut self) -> Result<&[u8]> {
1629 // Don't call into inner reader at all at EOF because it may still block
1630 if self.limit == 0 {
1634 let buf = self.inner.fill_buf()?;
1635 let cap = cmp::min(buf.len() as u64, self.limit) as usize;
1639 fn consume(&mut self, amt: usize) {
1640 // Don't let callers reset the limit by passing an overlarge value
1641 let amt = cmp::min(amt as u64, self.limit) as usize;
1642 self.limit -= amt as u64;
1643 self.inner.consume(amt);
1647 fn read_one_byte(reader: &mut Read) -> Option<Result<u8>> {
1650 return match reader.read(&mut buf) {
1652 Ok(..) => Some(Ok(buf[0])),
1653 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1654 Err(e) => Some(Err(e)),
1659 /// An iterator over `u8` values of a reader.
1661 /// This struct is generally created by calling [`bytes`] on a reader.
1662 /// Please see the documentation of [`bytes`] for more details.
1664 /// [`bytes`]: trait.Read.html#method.bytes
1665 #[stable(feature = "rust1", since = "1.0.0")]
1667 pub struct Bytes<R> {
1671 #[stable(feature = "rust1", since = "1.0.0")]
1672 impl<R: Read> Iterator for Bytes<R> {
1673 type Item = Result<u8>;
1675 fn next(&mut self) -> Option<Result<u8>> {
1676 read_one_byte(&mut self.inner)
1680 /// An iterator over the `char`s of a reader.
1682 /// This struct is generally created by calling [`chars`][chars] on a reader.
1683 /// Please see the documentation of `chars()` for more details.
1685 /// [chars]: trait.Read.html#method.chars
1686 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1689 pub struct Chars<R> {
1693 /// An enumeration of possible errors that can be generated from the `Chars`
1696 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1698 pub enum CharsError {
1699 /// Variant representing that the underlying stream was read successfully
1700 /// but it did not contain valid utf8 data.
1703 /// Variant representing that an I/O error occurred.
1707 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1709 impl<R: Read> Iterator for Chars<R> {
1710 type Item = result::Result<char, CharsError>;
1712 fn next(&mut self) -> Option<result::Result<char, CharsError>> {
1713 let first_byte = match read_one_byte(&mut self.inner) {
1714 None => return None,
1716 Some(Err(e)) => return Some(Err(CharsError::Other(e))),
1718 let width = core_str::utf8_char_width(first_byte);
1719 if width == 1 { return Some(Ok(first_byte as char)) }
1720 if width == 0 { return Some(Err(CharsError::NotUtf8)) }
1721 let mut buf = [first_byte, 0, 0, 0];
1724 while start < width {
1725 match self.inner.read(&mut buf[start..width]) {
1726 Ok(0) => return Some(Err(CharsError::NotUtf8)),
1727 Ok(n) => start += n,
1728 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1729 Err(e) => return Some(Err(CharsError::Other(e))),
1733 Some(match str::from_utf8(&buf[..width]).ok() {
1734 Some(s) => Ok(s.chars().next().unwrap()),
1735 None => Err(CharsError::NotUtf8),
1740 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1742 impl std_error::Error for CharsError {
1743 fn description(&self) -> &str {
1745 CharsError::NotUtf8 => "invalid utf8 encoding",
1746 CharsError::Other(ref e) => std_error::Error::description(e),
1749 fn cause(&self) -> Option<&std_error::Error> {
1751 CharsError::NotUtf8 => None,
1752 CharsError::Other(ref e) => e.cause(),
1757 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1759 impl fmt::Display for CharsError {
1760 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1762 CharsError::NotUtf8 => {
1763 "byte stream did not contain valid utf8".fmt(f)
1765 CharsError::Other(ref e) => e.fmt(f),
1770 /// An iterator over the contents of an instance of `BufRead` split on a
1771 /// particular byte.
1773 /// This struct is generally created by calling [`split`][split] on a
1774 /// `BufRead`. Please see the documentation of `split()` for more details.
1776 /// [split]: trait.BufRead.html#method.split
1777 #[stable(feature = "rust1", since = "1.0.0")]
1779 pub struct Split<B> {
1784 #[stable(feature = "rust1", since = "1.0.0")]
1785 impl<B: BufRead> Iterator for Split<B> {
1786 type Item = Result<Vec<u8>>;
1788 fn next(&mut self) -> Option<Result<Vec<u8>>> {
1789 let mut buf = Vec::new();
1790 match self.buf.read_until(self.delim, &mut buf) {
1793 if buf[buf.len() - 1] == self.delim {
1798 Err(e) => Some(Err(e))
1803 /// An iterator over the lines of an instance of `BufRead`.
1805 /// This struct is generally created by calling [`lines`][lines] on a
1806 /// `BufRead`. Please see the documentation of `lines()` for more details.
1808 /// [lines]: trait.BufRead.html#method.lines
1809 #[stable(feature = "rust1", since = "1.0.0")]
1811 pub struct Lines<B> {
1815 #[stable(feature = "rust1", since = "1.0.0")]
1816 impl<B: BufRead> Iterator for Lines<B> {
1817 type Item = Result<String>;
1819 fn next(&mut self) -> Option<Result<String>> {
1820 let mut buf = String::new();
1821 match self.buf.read_line(&mut buf) {
1824 if buf.ends_with("\n") {
1826 if buf.ends_with("\r") {
1832 Err(e) => Some(Err(e))
1846 #[cfg_attr(target_os = "emscripten", ignore)]
1848 let mut buf = Cursor::new(&b"12"[..]);
1849 let mut v = Vec::new();
1850 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 2);
1851 assert_eq!(v, b"12");
1853 let mut buf = Cursor::new(&b"1233"[..]);
1854 let mut v = Vec::new();
1855 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 3);
1856 assert_eq!(v, b"123");
1858 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 1);
1859 assert_eq!(v, b"3");
1861 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 0);
1867 let buf = Cursor::new(&b"12"[..]);
1868 let mut s = buf.split(b'3');
1869 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
1870 assert!(s.next().is_none());
1872 let buf = Cursor::new(&b"1233"[..]);
1873 let mut s = buf.split(b'3');
1874 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
1875 assert_eq!(s.next().unwrap().unwrap(), vec![]);
1876 assert!(s.next().is_none());
1881 let mut buf = Cursor::new(&b"12"[..]);
1882 let mut v = String::new();
1883 assert_eq!(buf.read_line(&mut v).unwrap(), 2);
1884 assert_eq!(v, "12");
1886 let mut buf = Cursor::new(&b"12\n\n"[..]);
1887 let mut v = String::new();
1888 assert_eq!(buf.read_line(&mut v).unwrap(), 3);
1889 assert_eq!(v, "12\n");
1891 assert_eq!(buf.read_line(&mut v).unwrap(), 1);
1892 assert_eq!(v, "\n");
1894 assert_eq!(buf.read_line(&mut v).unwrap(), 0);
1900 let buf = Cursor::new(&b"12\r"[..]);
1901 let mut s = buf.lines();
1902 assert_eq!(s.next().unwrap().unwrap(), "12\r".to_string());
1903 assert!(s.next().is_none());
1905 let buf = Cursor::new(&b"12\r\n\n"[..]);
1906 let mut s = buf.lines();
1907 assert_eq!(s.next().unwrap().unwrap(), "12".to_string());
1908 assert_eq!(s.next().unwrap().unwrap(), "".to_string());
1909 assert!(s.next().is_none());
1914 let mut c = Cursor::new(&b""[..]);
1915 let mut v = Vec::new();
1916 assert_eq!(c.read_to_end(&mut v).unwrap(), 0);
1919 let mut c = Cursor::new(&b"1"[..]);
1920 let mut v = Vec::new();
1921 assert_eq!(c.read_to_end(&mut v).unwrap(), 1);
1922 assert_eq!(v, b"1");
1924 let cap = 1024 * 1024;
1925 let data = (0..cap).map(|i| (i / 3) as u8).collect::<Vec<_>>();
1926 let mut v = Vec::new();
1927 let (a, b) = data.split_at(data.len() / 2);
1928 assert_eq!(Cursor::new(a).read_to_end(&mut v).unwrap(), a.len());
1929 assert_eq!(Cursor::new(b).read_to_end(&mut v).unwrap(), b.len());
1930 assert_eq!(v, data);
1934 fn read_to_string() {
1935 let mut c = Cursor::new(&b""[..]);
1936 let mut v = String::new();
1937 assert_eq!(c.read_to_string(&mut v).unwrap(), 0);
1940 let mut c = Cursor::new(&b"1"[..]);
1941 let mut v = String::new();
1942 assert_eq!(c.read_to_string(&mut v).unwrap(), 1);
1945 let mut c = Cursor::new(&b"\xff"[..]);
1946 let mut v = String::new();
1947 assert!(c.read_to_string(&mut v).is_err());
1952 let mut buf = [0; 4];
1954 let mut c = Cursor::new(&b""[..]);
1955 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1956 io::ErrorKind::UnexpectedEof);
1958 let mut c = Cursor::new(&b"123"[..]).chain(Cursor::new(&b"456789"[..]));
1959 c.read_exact(&mut buf).unwrap();
1960 assert_eq!(&buf, b"1234");
1961 c.read_exact(&mut buf).unwrap();
1962 assert_eq!(&buf, b"5678");
1963 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1964 io::ErrorKind::UnexpectedEof);
1968 fn read_exact_slice() {
1969 let mut buf = [0; 4];
1971 let mut c = &b""[..];
1972 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1973 io::ErrorKind::UnexpectedEof);
1975 let mut c = &b"123"[..];
1976 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1977 io::ErrorKind::UnexpectedEof);
1978 // make sure the optimized (early returning) method is being used
1979 assert_eq!(&buf, &[0; 4]);
1981 let mut c = &b"1234"[..];
1982 c.read_exact(&mut buf).unwrap();
1983 assert_eq!(&buf, b"1234");
1985 let mut c = &b"56789"[..];
1986 c.read_exact(&mut buf).unwrap();
1987 assert_eq!(&buf, b"5678");
1988 assert_eq!(c, b"9");
1996 fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
1997 Err(io::Error::new(io::ErrorKind::Other, ""))
2000 impl BufRead for R {
2001 fn fill_buf(&mut self) -> io::Result<&[u8]> {
2002 Err(io::Error::new(io::ErrorKind::Other, ""))
2004 fn consume(&mut self, _amt: usize) { }
2007 let mut buf = [0; 1];
2008 assert_eq!(0, R.take(0).read(&mut buf).unwrap());
2009 assert_eq!(b"", R.take(0).fill_buf().unwrap());
2012 fn cmp_bufread<Br1: BufRead, Br2: BufRead>(mut br1: Br1, mut br2: Br2, exp: &[u8]) {
2013 let mut cat = Vec::new();
2016 let buf1 = br1.fill_buf().unwrap();
2017 let buf2 = br2.fill_buf().unwrap();
2018 let minlen = if buf1.len() < buf2.len() { buf1.len() } else { buf2.len() };
2019 assert_eq!(buf1[..minlen], buf2[..minlen]);
2020 cat.extend_from_slice(&buf1[..minlen]);
2026 br1.consume(consume);
2027 br2.consume(consume);
2029 assert_eq!(br1.fill_buf().unwrap().len(), 0);
2030 assert_eq!(br2.fill_buf().unwrap().len(), 0);
2031 assert_eq!(&cat[..], &exp[..])
2035 fn chain_bufread() {
2036 let testdata = b"ABCDEFGHIJKL";
2037 let chain1 = (&testdata[..3]).chain(&testdata[3..6])
2038 .chain(&testdata[6..9])
2039 .chain(&testdata[9..]);
2040 let chain2 = (&testdata[..4]).chain(&testdata[4..8])
2041 .chain(&testdata[8..]);
2042 cmp_bufread(chain1, chain2, &testdata[..]);
2046 fn chain_zero_length_read_is_not_eof() {
2049 let mut s = String::new();
2050 let mut chain = (&a[..]).chain(&b[..]);
2051 chain.read(&mut []).unwrap();
2052 chain.read_to_string(&mut s).unwrap();
2053 assert_eq!("AB", s);
2057 #[cfg_attr(target_os = "emscripten", ignore)]
2058 fn bench_read_to_end(b: &mut test::Bencher) {
2060 let mut lr = repeat(1).take(10000000);
2061 let mut vec = Vec::with_capacity(1024);
2062 super::read_to_end(&mut lr, &mut vec)