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()` method, which we can use on `File`s:
28 //! use std::io::prelude::*;
29 //! use std::fs::File;
31 //! # fn foo() -> io::Result<()> {
32 //! let mut f = try!(File::open("foo.txt"));
33 //! let mut buffer = [0; 10];
35 //! // read up to 10 bytes
36 //! try!(f.read(&mut buffer));
38 //! println!("The bytes: {:?}", buffer);
43 //! [`Read`] and [`Write`] are so important, implementors of the two traits have a
44 //! nickname: readers and writers. So you'll sometimes see 'a reader' instead
45 //! of 'a type that implements the [`Read`] trait'. Much easier!
47 //! ## Seek and BufRead
49 //! Beyond that, there are two important traits that are provided: [`Seek`]
50 //! and [`BufRead`]. Both of these build on top of a reader to control
51 //! how the reading happens. [`Seek`] lets you control where the next byte is
56 //! use std::io::prelude::*;
57 //! use std::io::SeekFrom;
58 //! use std::fs::File;
60 //! # fn foo() -> io::Result<()> {
61 //! let mut f = try!(File::open("foo.txt"));
62 //! let mut buffer = [0; 10];
64 //! // skip to the last 10 bytes of the file
65 //! try!(f.seek(SeekFrom::End(-10)));
67 //! // read up to 10 bytes
68 //! try!(f.read(&mut buffer));
70 //! println!("The bytes: {:?}", buffer);
75 //! [`BufRead`] uses an internal buffer to provide a number of other ways to read, but
76 //! to show it off, we'll need to talk about buffers in general. Keep reading!
78 //! ## BufReader and BufWriter
80 //! Byte-based interfaces are unwieldy and can be inefficient, as we'd need to be
81 //! making near-constant calls to the operating system. To help with this,
82 //! `std::io` comes with two structs, [`BufReader`] and [`BufWriter`], which wrap
83 //! readers and writers. The wrapper uses a buffer, reducing the number of
84 //! calls and providing nicer methods for accessing exactly what you want.
86 //! For example, [`BufReader`] works with the [`BufRead`] trait to add extra
87 //! methods to any reader:
91 //! use std::io::prelude::*;
92 //! use std::io::BufReader;
93 //! use std::fs::File;
95 //! # fn foo() -> io::Result<()> {
96 //! let f = try!(File::open("foo.txt"));
97 //! let mut reader = BufReader::new(f);
98 //! let mut buffer = String::new();
100 //! // read a line into buffer
101 //! try!(reader.read_line(&mut buffer));
103 //! println!("{}", buffer);
108 //! [`BufWriter`] doesn't add any new ways of writing; it just buffers every call
113 //! use std::io::prelude::*;
114 //! use std::io::BufWriter;
115 //! use std::fs::File;
117 //! # fn foo() -> io::Result<()> {
118 //! let f = try!(File::create("foo.txt"));
120 //! let mut writer = BufWriter::new(f);
122 //! // write a byte to the buffer
123 //! try!(writer.write(&[42]));
125 //! } // the buffer is flushed once writer goes out of scope
131 //! ## Standard input and output
133 //! A very common source of input is standard input:
138 //! # fn foo() -> io::Result<()> {
139 //! let mut input = String::new();
141 //! try!(io::stdin().read_line(&mut input));
143 //! println!("You typed: {}", input.trim());
148 //! And a very common source of output is standard output:
152 //! use std::io::prelude::*;
154 //! # fn foo() -> io::Result<()> {
155 //! try!(io::stdout().write(&[42]));
160 //! Of course, using [`io::stdout()`] directly is less common than something like
163 //! ## Iterator types
165 //! A large number of the structures provided by `std::io` are for various
166 //! ways of iterating over I/O. For example, [`Lines`] is used to split over
171 //! use std::io::prelude::*;
172 //! use std::io::BufReader;
173 //! use std::fs::File;
175 //! # fn foo() -> io::Result<()> {
176 //! let f = try!(File::open("foo.txt"));
177 //! let reader = BufReader::new(f);
179 //! for line in reader.lines() {
180 //! println!("{}", try!(line));
189 //! There are a number of [functions][functions-list] that offer access to various
190 //! features. For example, we can use three of these functions to copy everything
191 //! from standard input to standard output:
196 //! # fn foo() -> io::Result<()> {
197 //! try!(io::copy(&mut io::stdin(), &mut io::stdout()));
202 //! [functions-list]: #functions-1
206 //! Last, but certainly not least, is [`io::Result`]. This type is used
207 //! as the return type of many `std::io` functions that can cause an error, and
208 //! can be returned from your own functions as well. Many of the examples in this
209 //! module use the [`try!`] macro:
214 //! fn read_input() -> io::Result<()> {
215 //! let mut input = String::new();
217 //! try!(io::stdin().read_line(&mut input));
219 //! println!("You typed: {}", input.trim());
225 //! The return type of `read_input()`, [`io::Result<()>`][`io::Result`], is a very
226 //! common type for functions which don't have a 'real' return value, but do want to
227 //! return errors if they happen. In this case, the only purpose of this function is
228 //! to read the line and print it, so we use `()`.
230 //! ## Platform-specific behavior
232 //! Many I/O functions throughout the standard library are documented to indicate
233 //! what various library or syscalls they are delegated to. This is done to help
234 //! applications both understand what's happening under the hood as well as investigate
235 //! any possibly unclear semantics. Note, however, that this is informative, not a binding
236 //! contract. The implementation of many of these functions are subject to change over
237 //! time and may call fewer or more syscalls/library functions.
239 //! [`Read`]: trait.Read.html
240 //! [`Write`]: trait.Write.html
241 //! [`Seek`]: trait.Seek.html
242 //! [`BufRead`]: trait.BufRead.html
243 //! [`File`]: ../fs/struct.File.html
244 //! [`TcpStream`]: ../net/struct.TcpStream.html
245 //! [`Vec<T>`]: ../vec/struct.Vec.html
246 //! [`BufReader`]: struct.BufReader.html
247 //! [`BufWriter`]: struct.BufWriter.html
248 //! [`write()`]: trait.Write.html#tymethod.write
249 //! [`io::stdout()`]: fn.stdout.html
250 //! [`println!`]: ../macro.println.html
251 //! [`Lines`]: struct.Lines.html
252 //! [`io::Result`]: type.Result.html
253 //! [`try!`]: ../macro.try.html
255 #![stable(feature = "rust1", since = "1.0.0")]
258 use rustc_unicode
::str as core_str
;
259 use error
as std_error
;
265 #[stable(feature = "rust1", since = "1.0.0")]
266 pub use self::buffered
::{BufReader, BufWriter, LineWriter}
;
267 #[stable(feature = "rust1", since = "1.0.0")]
268 pub use self::buffered
::IntoInnerError
;
269 #[stable(feature = "rust1", since = "1.0.0")]
270 pub use self::cursor
::Cursor
;
271 #[stable(feature = "rust1", since = "1.0.0")]
272 pub use self::error
::{Result, Error, ErrorKind}
;
273 #[stable(feature = "rust1", since = "1.0.0")]
274 pub use self::util
::{copy, sink, Sink, empty, Empty, repeat, Repeat}
;
275 #[stable(feature = "rust1", since = "1.0.0")]
276 pub use self::stdio
::{stdin, stdout, stderr, _print, Stdin, Stdout, Stderr}
;
277 #[stable(feature = "rust1", since = "1.0.0")]
278 pub use self::stdio
::{StdoutLock, StderrLock, StdinLock}
;
279 #[unstable(feature = "libstd_io_internals", issue = "0")]
280 #[doc(no_inline, hidden)]
281 pub use self::stdio
::{set_panic, set_print}
;
292 const DEFAULT_BUF_SIZE
: usize = ::sys_common
::io
::DEFAULT_BUF_SIZE
;
294 // A few methods below (read_to_string, read_line) will append data into a
295 // `String` buffer, but we need to be pretty careful when doing this. The
296 // implementation will just call `.as_mut_vec()` and then delegate to a
297 // byte-oriented reading method, but we must ensure that when returning we never
298 // leave `buf` in a state such that it contains invalid UTF-8 in its bounds.
300 // To this end, we use an RAII guard (to protect against panics) which updates
301 // the length of the string when it is dropped. This guard initially truncates
302 // the string to the prior length and only after we've validated that the
303 // new contents are valid UTF-8 do we allow it to set a longer length.
305 // The unsafety in this function is twofold:
307 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
309 // 2. We're passing a raw buffer to the function `f`, and it is expected that
310 // the function only *appends* bytes to the buffer. We'll get undefined
311 // behavior if existing bytes are overwritten to have non-UTF-8 data.
312 fn append_to_string
<F
>(buf
: &mut String
, f
: F
) -> Result
<usize>
313 where F
: FnOnce(&mut Vec
<u8>) -> Result
<usize>
315 struct Guard
<'a
> { s: &'a mut Vec<u8>, len: usize }
316 impl<'a
> Drop
for Guard
<'a
> {
318 unsafe { self.s.set_len(self.len); }
323 let mut g
= Guard { len: buf.len(), s: buf.as_mut_vec() }
;
325 if str::from_utf8(&g
.s
[g
.len
..]).is_err() {
327 Err(Error
::new(ErrorKind
::InvalidData
,
328 "stream did not contain valid UTF-8"))
337 // This uses an adaptive system to extend the vector when it fills. We want to
338 // avoid paying to allocate and zero a huge chunk of memory if the reader only
339 // has 4 bytes while still making large reads if the reader does have a ton
340 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
341 // time is 4,500 times (!) slower than this if the reader has a very small
342 // amount of data to return.
343 fn read_to_end
<R
: Read
+ ?Sized
>(r
: &mut R
, buf
: &mut Vec
<u8>) -> Result
<usize> {
344 let start_len
= buf
.len();
345 let mut len
= start_len
;
346 let mut new_write_size
= 16;
349 if len
== buf
.len() {
350 if new_write_size
< DEFAULT_BUF_SIZE
{
353 buf
.resize(len
+ new_write_size
, 0);
356 match r
.read(&mut buf
[len
..]) {
358 ret
= Ok(len
- start_len
);
362 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> {}
374 /// The `Read` trait allows for reading bytes from a source.
376 /// Implementors of the `Read` trait are sometimes called 'readers'.
378 /// Readers are defined by one required method, `read()`. Each call to `read`
379 /// will attempt to pull bytes from this source into a provided buffer. A
380 /// number of other methods are implemented in terms of `read()`, giving
381 /// implementors a number of ways to read bytes while only needing to implement
384 /// Readers are intended to be composable with one another. Many implementors
385 /// throughout `std::io` take and provide types which implement the `Read`
388 /// Please note that each call to `read` may involve a system call, and
389 /// therefore, using something that implements [`BufRead`][bufread], such as
390 /// [`BufReader`][bufreader], will be more efficient.
392 /// [bufread]: trait.BufRead.html
393 /// [bufreader]: struct.BufReader.html
397 /// [`File`][file]s implement `Read`:
399 /// [file]: ../fs/struct.File.html
403 /// use std::io::prelude::*;
404 /// use std::fs::File;
406 /// # fn foo() -> io::Result<()> {
407 /// let mut f = try!(File::open("foo.txt"));
408 /// let mut buffer = [0; 10];
410 /// // read up to 10 bytes
411 /// try!(f.read(&mut buffer));
413 /// let mut buffer = vec![0; 10];
414 /// // read the whole file
415 /// try!(f.read_to_end(&mut buffer));
417 /// // read into a String, so that you don't need to do the conversion.
418 /// let mut buffer = String::new();
419 /// try!(f.read_to_string(&mut buffer));
421 /// // and more! See the other methods for more details.
425 #[stable(feature = "rust1", since = "1.0.0")]
427 /// Pull some bytes from this source into the specified buffer, returning
428 /// how many bytes were read.
430 /// This function does not provide any guarantees about whether it blocks
431 /// waiting for data, but if an object needs to block for a read but cannot
432 /// it will typically signal this via an `Err` return value.
434 /// If the return value of this method is `Ok(n)`, then it must be
435 /// guaranteed that `0 <= n <= buf.len()`. A nonzero `n` value indicates
436 /// that the buffer `buf` has been filled in with `n` bytes of data from this
437 /// source. If `n` is `0`, then it can indicate one of two scenarios:
439 /// 1. This reader has reached its "end of file" and will likely no longer
440 /// be able to produce bytes. Note that this does not mean that the
441 /// reader will *always* no longer be able to produce bytes.
442 /// 2. The buffer specified was 0 bytes in length.
444 /// No guarantees are provided about the contents of `buf` when this
445 /// function is called, implementations cannot rely on any property of the
446 /// contents of `buf` being true. It is recommended that implementations
447 /// only write data to `buf` instead of reading its contents.
451 /// If this function encounters any form of I/O or other error, an error
452 /// variant will be returned. If an error is returned then it must be
453 /// guaranteed that no bytes were read.
457 /// [`File`][file]s implement `Read`:
459 /// [file]: ../fs/struct.File.html
463 /// use std::io::prelude::*;
464 /// use std::fs::File;
466 /// # fn foo() -> io::Result<()> {
467 /// let mut f = try!(File::open("foo.txt"));
468 /// let mut buffer = [0; 10];
471 /// try!(f.read(&mut buffer[..]));
475 #[stable(feature = "rust1", since = "1.0.0")]
476 fn read(&mut self, buf
: &mut [u8]) -> Result
<usize>;
478 /// Read all bytes until EOF in this source, placing them into `buf`.
480 /// All bytes read from this source will be appended to the specified buffer
481 /// `buf`. This function will continuously call `read` to append more data to
482 /// `buf` until `read` returns either `Ok(0)` or an error of
483 /// non-`ErrorKind::Interrupted` kind.
485 /// If successful, this function will return the total number of bytes read.
489 /// If this function encounters an error of the kind
490 /// `ErrorKind::Interrupted` then the error is ignored and the operation
493 /// If any other read error is encountered then this function immediately
494 /// returns. Any bytes which have already been read will be appended to
499 /// [`File`][file]s implement `Read`:
501 /// [file]: ../fs/struct.File.html
505 /// use std::io::prelude::*;
506 /// use std::fs::File;
508 /// # fn foo() -> io::Result<()> {
509 /// let mut f = try!(File::open("foo.txt"));
510 /// let mut buffer = Vec::new();
512 /// // read the whole file
513 /// try!(f.read_to_end(&mut buffer));
517 #[stable(feature = "rust1", since = "1.0.0")]
518 fn read_to_end(&mut self, buf
: &mut Vec
<u8>) -> Result
<usize> {
519 read_to_end(self, buf
)
522 /// Read all bytes until EOF in this source, placing them into `buf`.
524 /// If successful, this function returns the number of bytes which were read
525 /// and appended to `buf`.
529 /// If the data in this stream is *not* valid UTF-8 then an error is
530 /// returned and `buf` is unchanged.
532 /// See [`read_to_end()`][readtoend] for other error semantics.
534 /// [readtoend]: #method.read_to_end
538 /// [`File`][file]s implement `Read`:
540 /// [file]: ../fs/struct.File.html
544 /// use std::io::prelude::*;
545 /// use std::fs::File;
547 /// # fn foo() -> io::Result<()> {
548 /// let mut f = try!(File::open("foo.txt"));
549 /// let mut buffer = String::new();
551 /// try!(f.read_to_string(&mut buffer));
555 #[stable(feature = "rust1", since = "1.0.0")]
556 fn read_to_string(&mut self, buf
: &mut String
) -> Result
<usize> {
557 // Note that we do *not* call `.read_to_end()` here. We are passing
558 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
559 // method to fill it up. An arbitrary implementation could overwrite the
560 // entire contents of the vector, not just append to it (which is what
561 // we are expecting).
563 // To prevent extraneously checking the UTF-8-ness of the entire buffer
564 // we pass it to our hardcoded `read_to_end` implementation which we
565 // know is guaranteed to only read data into the end of the buffer.
566 append_to_string(buf
, |b
| read_to_end(self, b
))
569 /// Read the exact number of bytes required to fill `buf`.
571 /// This function reads as many bytes as necessary to completely fill the
572 /// specified buffer `buf`.
574 /// No guarantees are provided about the contents of `buf` when this
575 /// function is called, implementations cannot rely on any property of the
576 /// contents of `buf` being true. It is recommended that implementations
577 /// only write data to `buf` instead of reading its contents.
581 /// If this function encounters an error of the kind
582 /// `ErrorKind::Interrupted` then the error is ignored and the operation
585 /// If this function encounters an "end of file" before completely filling
586 /// the buffer, it returns an error of the kind `ErrorKind::UnexpectedEof`.
587 /// The contents of `buf` are unspecified in this case.
589 /// If any other read error is encountered then this function immediately
590 /// returns. The contents of `buf` are unspecified in this case.
592 /// If this function returns an error, it is unspecified how many bytes it
593 /// has read, but it will never read more than would be necessary to
594 /// completely fill the buffer.
598 /// [`File`][file]s implement `Read`:
600 /// [file]: ../fs/struct.File.html
604 /// use std::io::prelude::*;
605 /// use std::fs::File;
607 /// # fn foo() -> io::Result<()> {
608 /// let mut f = try!(File::open("foo.txt"));
609 /// let mut buffer = [0; 10];
611 /// // read exactly 10 bytes
612 /// try!(f.read_exact(&mut buffer));
616 #[stable(feature = "read_exact", since = "1.6.0")]
617 fn read_exact(&mut self, mut buf
: &mut [u8]) -> Result
<()> {
618 while !buf
.is_empty() {
619 match self.read(buf
) {
621 Ok(n
) => { let tmp = buf; buf = &mut tmp[n..]; }
622 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> {}
623 Err(e
) => return Err(e
),
627 Err(Error
::new(ErrorKind
::UnexpectedEof
,
628 "failed to fill whole buffer"))
634 /// Creates a "by reference" adaptor for this instance of `Read`.
636 /// The returned adaptor also implements `Read` and will simply borrow this
641 /// [`File`][file]s implement `Read`:
643 /// [file]: ../fs/struct.File.html
647 /// use std::io::Read;
648 /// use std::fs::File;
650 /// # fn foo() -> io::Result<()> {
651 /// let mut f = try!(File::open("foo.txt"));
652 /// let mut buffer = Vec::new();
653 /// let mut other_buffer = Vec::new();
656 /// let reference = f.by_ref();
658 /// // read at most 5 bytes
659 /// try!(reference.take(5).read_to_end(&mut buffer));
661 /// } // drop our &mut reference so we can use f again
663 /// // original file still usable, read the rest
664 /// try!(f.read_to_end(&mut other_buffer));
668 #[stable(feature = "rust1", since = "1.0.0")]
669 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
671 /// Transforms this `Read` instance to an `Iterator` over its bytes.
673 /// The returned type implements `Iterator` where the `Item` is `Result<u8,
674 /// R::Err>`. The yielded item is `Ok` if a byte was successfully read and
675 /// `Err` otherwise for I/O errors. EOF is mapped to returning `None` from
680 /// [`File`][file]s implement `Read`:
682 /// [file]: ../fs/struct.File.html
686 /// use std::io::prelude::*;
687 /// use std::fs::File;
689 /// # fn foo() -> io::Result<()> {
690 /// let mut f = try!(File::open("foo.txt"));
692 /// for byte in f.bytes() {
693 /// println!("{}", byte.unwrap());
698 #[stable(feature = "rust1", since = "1.0.0")]
699 fn bytes(self) -> Bytes
<Self> where Self: Sized
{
700 Bytes { inner: self }
703 /// Transforms this `Read` instance to an `Iterator` over `char`s.
705 /// This adaptor will attempt to interpret this reader as a UTF-8 encoded
706 /// sequence of characters. The returned iterator will return `None` once
707 /// EOF is reached for this reader. Otherwise each element yielded will be a
708 /// `Result<char, E>` where `E` may contain information about what I/O error
709 /// occurred or where decoding failed.
711 /// Currently this adaptor will discard intermediate data read, and should
712 /// be avoided if this is not desired.
716 /// [`File`][file]s implement `Read`:
718 /// [file]: ../fs/struct.File.html
723 /// use std::io::prelude::*;
724 /// use std::fs::File;
726 /// # fn foo() -> io::Result<()> {
727 /// let mut f = try!(File::open("foo.txt"));
729 /// for c in f.chars() {
730 /// println!("{}", c.unwrap());
735 #[unstable(feature = "io", reason = "the semantics of a partial read/write \
736 of where errors happen is currently \
737 unclear and may change",
739 fn chars(self) -> Chars
<Self> where Self: Sized
{
740 Chars { inner: self }
743 /// Creates an adaptor which will chain this stream with another.
745 /// The returned `Read` instance will first read all bytes from this object
746 /// until EOF is encountered. Afterwards the output is equivalent to the
747 /// output of `next`.
751 /// [`File`][file]s implement `Read`:
753 /// [file]: ../fs/struct.File.html
757 /// use std::io::prelude::*;
758 /// use std::fs::File;
760 /// # fn foo() -> io::Result<()> {
761 /// let mut f1 = try!(File::open("foo.txt"));
762 /// let mut f2 = try!(File::open("bar.txt"));
764 /// let mut handle = f1.chain(f2);
765 /// let mut buffer = String::new();
767 /// // read the value into a String. We could use any Read method here,
768 /// // this is just one example.
769 /// try!(handle.read_to_string(&mut buffer));
773 #[stable(feature = "rust1", since = "1.0.0")]
774 fn chain
<R
: Read
>(self, next
: R
) -> Chain
<Self, R
> where Self: Sized
{
775 Chain { first: self, second: next, done_first: false }
778 /// Creates an adaptor which will read at most `limit` bytes from it.
780 /// This function returns a new instance of `Read` which will read at most
781 /// `limit` bytes, after which it will always return EOF (`Ok(0)`). Any
782 /// read errors will not count towards the number of bytes read and future
783 /// calls to `read` may succeed.
787 /// [`File`][file]s implement `Read`:
789 /// [file]: ../fs/struct.File.html
793 /// use std::io::prelude::*;
794 /// use std::fs::File;
796 /// # fn foo() -> io::Result<()> {
797 /// let mut f = try!(File::open("foo.txt"));
798 /// let mut buffer = [0; 5];
800 /// // read at most five bytes
801 /// let mut handle = f.take(5);
803 /// try!(handle.read(&mut buffer));
807 #[stable(feature = "rust1", since = "1.0.0")]
808 fn take(self, limit
: u64) -> Take
<Self> where Self: Sized
{
809 Take { inner: self, limit: limit }
813 /// A trait for objects which are byte-oriented sinks.
815 /// Implementors of the `Write` trait are sometimes called 'writers'.
817 /// Writers are defined by two required methods, `write()` and `flush()`:
819 /// * The `write()` method will attempt to write some data into the object,
820 /// returning how many bytes were successfully written.
822 /// * The `flush()` method is useful for adaptors and explicit buffers
823 /// themselves for ensuring that all buffered data has been pushed out to the
826 /// Writers are intended to be composable with one another. Many implementors
827 /// throughout `std::io` take and provide types which implement the `Write`
833 /// use std::io::prelude::*;
834 /// use std::fs::File;
836 /// # fn foo() -> std::io::Result<()> {
837 /// let mut buffer = try!(File::create("foo.txt"));
839 /// try!(buffer.write(b"some bytes"));
843 #[stable(feature = "rust1", since = "1.0.0")]
845 /// Write a buffer into this object, returning how many bytes were written.
847 /// This function will attempt to write the entire contents of `buf`, but
848 /// the entire write may not succeed, or the write may also generate an
849 /// error. A call to `write` represents *at most one* attempt to write to
850 /// any wrapped object.
852 /// Calls to `write` are not guaranteed to block waiting for data to be
853 /// written, and a write which would otherwise block can be indicated through
854 /// an `Err` variant.
856 /// If the return value is `Ok(n)` then it must be guaranteed that
857 /// `0 <= n <= buf.len()`. A return value of `0` typically means that the
858 /// underlying object is no longer able to accept bytes and will likely not
859 /// be able to in the future as well, or that the buffer provided is empty.
863 /// Each call to `write` may generate an I/O error indicating that the
864 /// operation could not be completed. If an error is returned then no bytes
865 /// in the buffer were written to this writer.
867 /// It is **not** considered an error if the entire buffer could not be
868 /// written to this writer.
873 /// use std::io::prelude::*;
874 /// use std::fs::File;
876 /// # fn foo() -> std::io::Result<()> {
877 /// let mut buffer = try!(File::create("foo.txt"));
879 /// try!(buffer.write(b"some bytes"));
883 #[stable(feature = "rust1", since = "1.0.0")]
884 fn write(&mut self, buf
: &[u8]) -> Result
<usize>;
886 /// Flush this output stream, ensuring that all intermediately buffered
887 /// contents reach their destination.
891 /// It is considered an error if not all bytes could be written due to
892 /// I/O errors or EOF being reached.
897 /// use std::io::prelude::*;
898 /// use std::io::BufWriter;
899 /// use std::fs::File;
901 /// # fn foo() -> std::io::Result<()> {
902 /// let mut buffer = BufWriter::new(try!(File::create("foo.txt")));
904 /// try!(buffer.write(b"some bytes"));
905 /// try!(buffer.flush());
909 #[stable(feature = "rust1", since = "1.0.0")]
910 fn flush(&mut self) -> Result
<()>;
912 /// Attempts to write an entire buffer into this write.
914 /// This method will continuously call `write` while there is more data to
915 /// write. This method will not return until the entire buffer has been
916 /// successfully written or an error occurs. The first error generated from
917 /// this method will be returned.
921 /// This function will return the first error that `write` returns.
926 /// use std::io::prelude::*;
927 /// use std::fs::File;
929 /// # fn foo() -> std::io::Result<()> {
930 /// let mut buffer = try!(File::create("foo.txt"));
932 /// try!(buffer.write_all(b"some bytes"));
936 #[stable(feature = "rust1", since = "1.0.0")]
937 fn write_all(&mut self, mut buf
: &[u8]) -> Result
<()> {
938 while !buf
.is_empty() {
939 match self.write(buf
) {
940 Ok(0) => return Err(Error
::new(ErrorKind
::WriteZero
,
941 "failed to write whole buffer")),
942 Ok(n
) => buf
= &buf
[n
..],
943 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> {}
944 Err(e
) => return Err(e
),
950 /// Writes a formatted string into this writer, returning any error
953 /// This method is primarily used to interface with the
954 /// [`format_args!`][formatargs] macro, but it is rare that this should
955 /// explicitly be called. The [`write!`][write] macro should be favored to
956 /// invoke this method instead.
958 /// [formatargs]: ../macro.format_args.html
959 /// [write]: ../macro.write.html
961 /// This function internally uses the [`write_all`][writeall] method on
962 /// this trait and hence will continuously write data so long as no errors
963 /// are received. This also means that partial writes are not indicated in
966 /// [writeall]: #method.write_all
970 /// This function will return any I/O error reported while formatting.
975 /// use std::io::prelude::*;
976 /// use std::fs::File;
978 /// # fn foo() -> std::io::Result<()> {
979 /// let mut buffer = try!(File::create("foo.txt"));
982 /// try!(write!(buffer, "{:.*}", 2, 1.234567));
983 /// // turns into this:
984 /// try!(buffer.write_fmt(format_args!("{:.*}", 2, 1.234567)));
988 #[stable(feature = "rust1", since = "1.0.0")]
989 fn write_fmt(&mut self, fmt
: fmt
::Arguments
) -> Result
<()> {
990 // Create a shim which translates a Write to a fmt::Write and saves
991 // off I/O errors. instead of discarding them
992 struct Adaptor
<'a
, T
: ?Sized
+ 'a
> {
997 impl<'a
, T
: Write
+ ?Sized
> fmt
::Write
for Adaptor
<'a
, T
> {
998 fn write_str(&mut self, s
: &str) -> fmt
::Result
{
999 match self.inner
.write_all(s
.as_bytes()) {
1002 self.error
= Err(e
);
1009 let mut output
= Adaptor { inner: self, error: Ok(()) }
;
1010 match fmt
::write(&mut output
, fmt
) {
1013 // check if the error came from the underlying `Write` or not
1014 if output
.error
.is_err() {
1017 Err(Error
::new(ErrorKind
::Other
, "formatter error"))
1023 /// Creates a "by reference" adaptor for this instance of `Write`.
1025 /// The returned adaptor also implements `Write` and will simply borrow this
1031 /// use std::io::Write;
1032 /// use std::fs::File;
1034 /// # fn foo() -> std::io::Result<()> {
1035 /// let mut buffer = try!(File::create("foo.txt"));
1037 /// let reference = buffer.by_ref();
1039 /// // we can use reference just like our original buffer
1040 /// try!(reference.write_all(b"some bytes"));
1044 #[stable(feature = "rust1", since = "1.0.0")]
1045 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1048 /// The `Seek` trait provides a cursor which can be moved within a stream of
1051 /// The stream typically has a fixed size, allowing seeking relative to either
1052 /// end or the current offset.
1056 /// [`File`][file]s implement `Seek`:
1058 /// [file]: ../fs/struct.File.html
1062 /// use std::io::prelude::*;
1063 /// use std::fs::File;
1064 /// use std::io::SeekFrom;
1066 /// # fn foo() -> io::Result<()> {
1067 /// let mut f = try!(File::open("foo.txt"));
1069 /// // move the cursor 42 bytes from the start of the file
1070 /// try!(f.seek(SeekFrom::Start(42)));
1074 #[stable(feature = "rust1", since = "1.0.0")]
1076 /// Seek to an offset, in bytes, in a stream.
1078 /// A seek beyond the end of a stream is allowed, but implementation
1081 /// If the seek operation completed successfully,
1082 /// this method returns the new position from the start of the stream.
1083 /// That position can be used later with [`SeekFrom::Start`].
1087 /// Seeking to a negative offset is considered an error.
1089 /// [`SeekFrom::Start`]: enum.SeekFrom.html#variant.Start
1090 #[stable(feature = "rust1", since = "1.0.0")]
1091 fn seek(&mut self, pos
: SeekFrom
) -> Result
<u64>;
1094 /// Enumeration of possible methods to seek within an I/O object.
1096 /// It is used by the [`Seek`] trait.
1098 /// [`Seek`]: trait.Seek.html
1099 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1100 #[stable(feature = "rust1", since = "1.0.0")]
1102 /// Set the offset to the provided number of bytes.
1103 #[stable(feature = "rust1", since = "1.0.0")]
1104 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1106 /// Set the offset to the size of this object plus the specified number of
1109 /// It is possible to seek beyond the end of an object, but it's an error to
1110 /// seek before byte 0.
1111 #[stable(feature = "rust1", since = "1.0.0")]
1112 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1114 /// Set the offset to the current position plus the specified number of
1117 /// It is possible to seek beyond the end of an object, but it's an error to
1118 /// seek before byte 0.
1119 #[stable(feature = "rust1", since = "1.0.0")]
1120 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1123 fn read_until
<R
: BufRead
+ ?Sized
>(r
: &mut R
, delim
: u8, buf
: &mut Vec
<u8>)
1127 let (done
, used
) = {
1128 let available
= match r
.fill_buf() {
1130 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> continue,
1131 Err(e
) => return Err(e
)
1133 match memchr
::memchr(delim
, available
) {
1135 buf
.extend_from_slice(&available
[..i
+ 1]);
1139 buf
.extend_from_slice(available
);
1140 (false, available
.len())
1146 if done
|| used
== 0 {
1152 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1153 /// to perform extra ways of reading.
1155 /// For example, reading line-by-line is inefficient without using a buffer, so
1156 /// if you want to read by line, you'll need `BufRead`, which includes a
1157 /// [`read_line()`] method as well as a [`lines()`] iterator.
1161 /// A locked standard input implements `BufRead`:
1165 /// use std::io::prelude::*;
1167 /// let stdin = io::stdin();
1168 /// for line in stdin.lock().lines() {
1169 /// println!("{}", line.unwrap());
1173 /// If you have something that implements [`Read`], you can use the [`BufReader`
1174 /// type][`BufReader`] to turn it into a `BufRead`.
1176 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1177 /// [`BufReader`] to the rescue!
1179 /// [`BufReader`]: struct.BufReader.html
1180 /// [`File`]: ../fs/struct.File.html
1181 /// [`read_line()`]: #method.read_line
1182 /// [`lines()`]: #method.lines
1183 /// [`Read`]: trait.Read.html
1186 /// use std::io::{self, BufReader};
1187 /// use std::io::prelude::*;
1188 /// use std::fs::File;
1190 /// # fn foo() -> io::Result<()> {
1191 /// let f = try!(File::open("foo.txt"));
1192 /// let f = BufReader::new(f);
1194 /// for line in f.lines() {
1195 /// println!("{}", line.unwrap());
1202 #[stable(feature = "rust1", since = "1.0.0")]
1203 pub trait BufRead
: Read
{
1204 /// Fills the internal buffer of this object, returning the buffer contents.
1206 /// This function is a lower-level call. It needs to be paired with the
1207 /// [`consume()`] method to function properly. When calling this
1208 /// method, none of the contents will be "read" in the sense that later
1209 /// calling `read` may return the same contents. As such, [`consume()`] must
1210 /// be called with the number of bytes that are consumed from this buffer to
1211 /// ensure that the bytes are never returned twice.
1213 /// [`consume()`]: #tymethod.consume
1215 /// An empty buffer returned indicates that the stream has reached EOF.
1219 /// This function will return an I/O error if the underlying reader was
1220 /// read, but returned an error.
1224 /// A locked standard input implements `BufRead`:
1228 /// use std::io::prelude::*;
1230 /// let stdin = io::stdin();
1231 /// let mut stdin = stdin.lock();
1233 /// // we can't have two `&mut` references to `stdin`, so use a block
1234 /// // to end the borrow early.
1236 /// let buffer = stdin.fill_buf().unwrap();
1238 /// // work with buffer
1239 /// println!("{:?}", buffer);
1244 /// // ensure the bytes we worked with aren't returned again later
1245 /// stdin.consume(length);
1247 #[stable(feature = "rust1", since = "1.0.0")]
1248 fn fill_buf(&mut self) -> Result
<&[u8]>;
1250 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1251 /// so they should no longer be returned in calls to `read`.
1253 /// This function is a lower-level call. It needs to be paired with the
1254 /// [`fill_buf()`] method to function properly. This function does
1255 /// not perform any I/O, it simply informs this object that some amount of
1256 /// its buffer, returned from [`fill_buf()`], has been consumed and should
1257 /// no longer be returned. As such, this function may do odd things if
1258 /// [`fill_buf()`] isn't called before calling it.
1260 /// The `amt` must be `<=` the number of bytes in the buffer returned by
1265 /// Since `consume()` is meant to be used with [`fill_buf()`],
1266 /// that method's example includes an example of `consume()`.
1268 /// [`fill_buf()`]: #tymethod.fill_buf
1269 #[stable(feature = "rust1", since = "1.0.0")]
1270 fn consume(&mut self, amt
: usize);
1272 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
1274 /// This function will read bytes from the underlying stream until the
1275 /// delimiter or EOF is found. Once found, all bytes up to, and including,
1276 /// the delimiter (if found) will be appended to `buf`.
1278 /// If successful, this function will return the total number of bytes read.
1282 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1283 /// will otherwise return any errors returned by [`fill_buf()`].
1285 /// If an I/O error is encountered then all bytes read so far will be
1286 /// present in `buf` and its length will have been adjusted appropriately.
1290 /// A locked standard input implements `BufRead`. In this example, we'll
1291 /// read from standard input until we see an `a` byte.
1293 /// [`fill_buf()`]: #tymethod.fill_buf
1294 /// [`ErrorKind::Interrupted`]: enum.ErrorKind.html#variant.Interrupted
1298 /// use std::io::prelude::*;
1300 /// fn foo() -> io::Result<()> {
1301 /// let stdin = io::stdin();
1302 /// let mut stdin = stdin.lock();
1303 /// let mut buffer = Vec::new();
1305 /// try!(stdin.read_until(b'a', &mut buffer));
1307 /// println!("{:?}", buffer);
1311 #[stable(feature = "rust1", since = "1.0.0")]
1312 fn read_until(&mut self, byte
: u8, buf
: &mut Vec
<u8>) -> Result
<usize> {
1313 read_until(self, byte
, buf
)
1316 /// Read all bytes until a newline (the 0xA byte) is reached, and append
1317 /// them to the provided buffer.
1319 /// This function will read bytes from the underlying stream until the
1320 /// newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes
1321 /// up to, and including, the delimiter (if found) will be appended to
1324 /// If successful, this function will return the total number of bytes read.
1328 /// This function has the same error semantics as [`read_until()`] and will
1329 /// also return an error if the read bytes are not valid UTF-8. If an I/O
1330 /// error is encountered then `buf` may contain some bytes already read in
1331 /// the event that all data read so far was valid UTF-8.
1335 /// A locked standard input implements `BufRead`. In this example, we'll
1336 /// read all of the lines from standard input. If we were to do this in
1337 /// an actual project, the [`lines()`] method would be easier, of
1340 /// [`lines()`]: #method.lines
1341 /// [`read_until()`]: #method.read_until
1345 /// use std::io::prelude::*;
1347 /// let stdin = io::stdin();
1348 /// let mut stdin = stdin.lock();
1349 /// let mut buffer = String::new();
1351 /// while stdin.read_line(&mut buffer).unwrap() > 0 {
1352 /// // work with buffer
1353 /// println!("{:?}", buffer);
1358 #[stable(feature = "rust1", since = "1.0.0")]
1359 fn read_line(&mut self, buf
: &mut String
) -> Result
<usize> {
1360 // Note that we are not calling the `.read_until` method here, but
1361 // rather our hardcoded implementation. For more details as to why, see
1362 // the comments in `read_to_end`.
1363 append_to_string(buf
, |b
| read_until(self, b'
\n'
, b
))
1366 /// Returns an iterator over the contents of this reader split on the byte
1369 /// The iterator returned from this function will return instances of
1370 /// [`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
1371 /// the delimiter byte at the end.
1373 /// This function will yield errors whenever [`read_until()`] would have
1374 /// also yielded an error.
1378 /// A locked standard input implements `BufRead`. In this example, we'll
1379 /// read some input from standard input, splitting on commas.
1381 /// [`io::Result`]: type.Result.html
1382 /// [`Vec<u8>`]: ../vec/struct.Vec.html
1383 /// [`read_until()`]: #method.read_until
1387 /// use std::io::prelude::*;
1389 /// let stdin = io::stdin();
1391 /// for content in stdin.lock().split(b',') {
1392 /// println!("{:?}", content.unwrap());
1395 #[stable(feature = "rust1", since = "1.0.0")]
1396 fn split(self, byte
: u8) -> Split
<Self> where Self: Sized
{
1397 Split { buf: self, delim: byte }
1400 /// Returns an iterator over the lines of this reader.
1402 /// The iterator returned from this function will yield instances of
1403 /// [`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline
1404 /// byte (the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.
1406 /// [`io::Result`]: type.Result.html
1407 /// [`String`]: ../string/struct.String.html
1411 /// A locked standard input implements `BufRead`:
1415 /// use std::io::prelude::*;
1417 /// let stdin = io::stdin();
1419 /// for line in stdin.lock().lines() {
1420 /// println!("{}", line.unwrap());
1423 #[stable(feature = "rust1", since = "1.0.0")]
1424 fn lines(self) -> Lines
<Self> where Self: Sized
{
1429 /// Adaptor to chain together two readers.
1431 /// This struct is generally created by calling [`chain()`] on a reader.
1432 /// Please see the documentation of [`chain()`] for more details.
1434 /// [`chain()`]: trait.Read.html#method.chain
1435 #[stable(feature = "rust1", since = "1.0.0")]
1436 pub struct Chain
<T
, U
> {
1442 #[stable(feature = "rust1", since = "1.0.0")]
1443 impl<T
: Read
, U
: Read
> Read
for Chain
<T
, U
> {
1444 fn read(&mut self, buf
: &mut [u8]) -> Result
<usize> {
1445 if !self.done_first
{
1446 match self.first
.read(buf
)?
{
1447 0 if buf
.len() != 0 => { self.done_first = true; }
1451 self.second
.read(buf
)
1455 #[stable(feature = "chain_bufread", since = "1.9.0")]
1456 impl<T
: BufRead
, U
: BufRead
> BufRead
for Chain
<T
, U
> {
1457 fn fill_buf(&mut self) -> Result
<&[u8]> {
1458 if !self.done_first
{
1459 match self.first
.fill_buf()?
{
1460 buf
if buf
.len() == 0 => { self.done_first = true; }
1461 buf
=> return Ok(buf
),
1464 self.second
.fill_buf()
1467 fn consume(&mut self, amt
: usize) {
1468 if !self.done_first
{
1469 self.first
.consume(amt
)
1471 self.second
.consume(amt
)
1476 /// Reader adaptor which limits the bytes read from an underlying reader.
1478 /// This struct is generally created by calling [`take()`][take] on a reader.
1479 /// Please see the documentation of `take()` for more details.
1481 /// [take]: trait.Read.html#method.take
1482 #[stable(feature = "rust1", since = "1.0.0")]
1483 pub struct Take
<T
> {
1489 /// Returns the number of bytes that can be read before this instance will
1494 /// This instance may reach EOF after reading fewer bytes than indicated by
1495 /// this method if the underlying `Read` instance reaches EOF.
1501 /// use std::io::prelude::*;
1502 /// use std::fs::File;
1504 /// # fn foo() -> io::Result<()> {
1505 /// let f = try!(File::open("foo.txt"));
1507 /// // read at most five bytes
1508 /// let handle = f.take(5);
1510 /// println!("limit: {}", handle.limit());
1514 #[stable(feature = "rust1", since = "1.0.0")]
1515 pub fn limit(&self) -> u64 { self.limit }
1517 /// Consumes the `Take`, returning the wrapped reader.
1522 /// #![feature(io_take_into_inner)]
1525 /// use std::io::prelude::*;
1526 /// use std::fs::File;
1528 /// # fn foo() -> io::Result<()> {
1529 /// let mut file = try!(File::open("foo.txt"));
1531 /// let mut buffer = [0; 5];
1532 /// let mut handle = file.take(5);
1533 /// try!(handle.read(&mut buffer));
1535 /// let file = handle.into_inner();
1539 #[unstable(feature = "io_take_into_inner", issue = "23755")]
1540 pub fn into_inner(self) -> T
{
1545 #[stable(feature = "rust1", since = "1.0.0")]
1546 impl<T
: Read
> Read
for Take
<T
> {
1547 fn read(&mut self, buf
: &mut [u8]) -> Result
<usize> {
1548 // Don't call into inner reader at all at EOF because it may still block
1549 if self.limit
== 0 {
1553 let max
= cmp
::min(buf
.len() as u64, self.limit
) as usize;
1554 let n
= self.inner
.read(&mut buf
[..max
])?
;
1555 self.limit
-= n
as u64;
1560 #[stable(feature = "rust1", since = "1.0.0")]
1561 impl<T
: BufRead
> BufRead
for Take
<T
> {
1562 fn fill_buf(&mut self) -> Result
<&[u8]> {
1563 // Don't call into inner reader at all at EOF because it may still block
1564 if self.limit
== 0 {
1568 let buf
= self.inner
.fill_buf()?
;
1569 let cap
= cmp
::min(buf
.len() as u64, self.limit
) as usize;
1573 fn consume(&mut self, amt
: usize) {
1574 // Don't let callers reset the limit by passing an overlarge value
1575 let amt
= cmp
::min(amt
as u64, self.limit
) as usize;
1576 self.limit
-= amt
as u64;
1577 self.inner
.consume(amt
);
1581 fn read_one_byte(reader
: &mut Read
) -> Option
<Result
<u8>> {
1584 return match reader
.read(&mut buf
) {
1586 Ok(..) => Some(Ok(buf
[0])),
1587 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> continue,
1588 Err(e
) => Some(Err(e
)),
1593 /// An iterator over `u8` values of a reader.
1595 /// This struct is generally created by calling [`bytes()`] on a reader.
1596 /// Please see the documentation of [`bytes()`] for more details.
1598 /// [`bytes()`]: trait.Read.html#method.bytes
1599 #[stable(feature = "rust1", since = "1.0.0")]
1600 pub struct Bytes
<R
> {
1604 #[stable(feature = "rust1", since = "1.0.0")]
1605 impl<R
: Read
> Iterator
for Bytes
<R
> {
1606 type Item
= Result
<u8>;
1608 fn next(&mut self) -> Option
<Result
<u8>> {
1609 read_one_byte(&mut self.inner
)
1613 /// An iterator over the `char`s of a reader.
1615 /// This struct is generally created by calling [`chars()`][chars] on a reader.
1616 /// Please see the documentation of `chars()` for more details.
1618 /// [chars]: trait.Read.html#method.chars
1619 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1621 pub struct Chars
<R
> {
1625 /// An enumeration of possible errors that can be generated from the `Chars`
1628 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1630 pub enum CharsError
{
1631 /// Variant representing that the underlying stream was read successfully
1632 /// but it did not contain valid utf8 data.
1635 /// Variant representing that an I/O error occurred.
1639 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1641 impl<R
: Read
> Iterator
for Chars
<R
> {
1642 type Item
= result
::Result
<char, CharsError
>;
1644 fn next(&mut self) -> Option
<result
::Result
<char, CharsError
>> {
1645 let first_byte
= match read_one_byte(&mut self.inner
) {
1646 None
=> return None
,
1648 Some(Err(e
)) => return Some(Err(CharsError
::Other(e
))),
1650 let width
= core_str
::utf8_char_width(first_byte
);
1651 if width
== 1 { return Some(Ok(first_byte as char)) }
1652 if width
== 0 { return Some(Err(CharsError::NotUtf8)) }
1653 let mut buf
= [first_byte
, 0, 0, 0];
1656 while start
< width
{
1657 match self.inner
.read(&mut buf
[start
..width
]) {
1658 Ok(0) => return Some(Err(CharsError
::NotUtf8
)),
1659 Ok(n
) => start
+= n
,
1660 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> continue,
1661 Err(e
) => return Some(Err(CharsError
::Other(e
))),
1665 Some(match str::from_utf8(&buf
[..width
]).ok() {
1666 Some(s
) => Ok(s
.chars().next().unwrap()),
1667 None
=> Err(CharsError
::NotUtf8
),
1672 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1674 impl std_error
::Error
for CharsError
{
1675 fn description(&self) -> &str {
1677 CharsError
::NotUtf8
=> "invalid utf8 encoding",
1678 CharsError
::Other(ref e
) => std_error
::Error
::description(e
),
1681 fn cause(&self) -> Option
<&std_error
::Error
> {
1683 CharsError
::NotUtf8
=> None
,
1684 CharsError
::Other(ref e
) => e
.cause(),
1689 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1691 impl fmt
::Display
for CharsError
{
1692 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1694 CharsError
::NotUtf8
=> {
1695 "byte stream did not contain valid utf8".fmt(f
)
1697 CharsError
::Other(ref e
) => e
.fmt(f
),
1702 /// An iterator over the contents of an instance of `BufRead` split on a
1703 /// particular byte.
1705 /// This struct is generally created by calling [`split()`][split] on a
1706 /// `BufRead`. Please see the documentation of `split()` for more details.
1708 /// [split]: trait.BufRead.html#method.split
1709 #[stable(feature = "rust1", since = "1.0.0")]
1710 pub struct Split
<B
> {
1715 #[stable(feature = "rust1", since = "1.0.0")]
1716 impl<B
: BufRead
> Iterator
for Split
<B
> {
1717 type Item
= Result
<Vec
<u8>>;
1719 fn next(&mut self) -> Option
<Result
<Vec
<u8>>> {
1720 let mut buf
= Vec
::new();
1721 match self.buf
.read_until(self.delim
, &mut buf
) {
1724 if buf
[buf
.len() - 1] == self.delim
{
1729 Err(e
) => Some(Err(e
))
1734 /// An iterator over the lines of an instance of `BufRead`.
1736 /// This struct is generally created by calling [`lines()`][lines] on a
1737 /// `BufRead`. Please see the documentation of `lines()` for more details.
1739 /// [lines]: trait.BufRead.html#method.lines
1740 #[stable(feature = "rust1", since = "1.0.0")]
1741 pub struct Lines
<B
> {
1745 #[stable(feature = "rust1", since = "1.0.0")]
1746 impl<B
: BufRead
> Iterator
for Lines
<B
> {
1747 type Item
= Result
<String
>;
1749 fn next(&mut self) -> Option
<Result
<String
>> {
1750 let mut buf
= String
::new();
1751 match self.buf
.read_line(&mut buf
) {
1754 if buf
.ends_with("\n") {
1756 if buf
.ends_with("\r") {
1762 Err(e
) => Some(Err(e
))
1776 #[cfg_attr(target_os = "emscripten", ignore)]
1778 let mut buf
= Cursor
::new(&b
"12"[..]);
1779 let mut v
= Vec
::new();
1780 assert_eq
!(buf
.read_until(b'
3'
, &mut v
).unwrap(), 2);
1781 assert_eq
!(v
, b
"12");
1783 let mut buf
= Cursor
::new(&b
"1233"[..]);
1784 let mut v
= Vec
::new();
1785 assert_eq
!(buf
.read_until(b'
3'
, &mut v
).unwrap(), 3);
1786 assert_eq
!(v
, b
"123");
1788 assert_eq
!(buf
.read_until(b'
3'
, &mut v
).unwrap(), 1);
1789 assert_eq
!(v
, b
"3");
1791 assert_eq
!(buf
.read_until(b'
3'
, &mut v
).unwrap(), 0);
1797 let buf
= Cursor
::new(&b
"12"[..]);
1798 let mut s
= buf
.split(b'
3'
);
1799 assert_eq
!(s
.next().unwrap().unwrap(), vec
![b'
1'
, b'
2'
]);
1800 assert
!(s
.next().is_none());
1802 let buf
= Cursor
::new(&b
"1233"[..]);
1803 let mut s
= buf
.split(b'
3'
);
1804 assert_eq
!(s
.next().unwrap().unwrap(), vec
![b'
1'
, b'
2'
]);
1805 assert_eq
!(s
.next().unwrap().unwrap(), vec
![]);
1806 assert
!(s
.next().is_none());
1811 let mut buf
= Cursor
::new(&b
"12"[..]);
1812 let mut v
= String
::new();
1813 assert_eq
!(buf
.read_line(&mut v
).unwrap(), 2);
1814 assert_eq
!(v
, "12");
1816 let mut buf
= Cursor
::new(&b
"12\n\n"[..]);
1817 let mut v
= String
::new();
1818 assert_eq
!(buf
.read_line(&mut v
).unwrap(), 3);
1819 assert_eq
!(v
, "12\n");
1821 assert_eq
!(buf
.read_line(&mut v
).unwrap(), 1);
1822 assert_eq
!(v
, "\n");
1824 assert_eq
!(buf
.read_line(&mut v
).unwrap(), 0);
1830 let buf
= Cursor
::new(&b
"12\r"[..]);
1831 let mut s
= buf
.lines();
1832 assert_eq
!(s
.next().unwrap().unwrap(), "12\r".to_string());
1833 assert
!(s
.next().is_none());
1835 let buf
= Cursor
::new(&b
"12\r\n\n"[..]);
1836 let mut s
= buf
.lines();
1837 assert_eq
!(s
.next().unwrap().unwrap(), "12".to_string());
1838 assert_eq
!(s
.next().unwrap().unwrap(), "".to_string());
1839 assert
!(s
.next().is_none());
1844 let mut c
= Cursor
::new(&b
""[..]);
1845 let mut v
= Vec
::new();
1846 assert_eq
!(c
.read_to_end(&mut v
).unwrap(), 0);
1849 let mut c
= Cursor
::new(&b
"1"[..]);
1850 let mut v
= Vec
::new();
1851 assert_eq
!(c
.read_to_end(&mut v
).unwrap(), 1);
1852 assert_eq
!(v
, b
"1");
1854 let cap
= 1024 * 1024;
1855 let data
= (0..cap
).map(|i
| (i
/ 3) as u8).collect
::<Vec
<_
>>();
1856 let mut v
= Vec
::new();
1857 let (a
, b
) = data
.split_at(data
.len() / 2);
1858 assert_eq
!(Cursor
::new(a
).read_to_end(&mut v
).unwrap(), a
.len());
1859 assert_eq
!(Cursor
::new(b
).read_to_end(&mut v
).unwrap(), b
.len());
1860 assert_eq
!(v
, data
);
1864 fn read_to_string() {
1865 let mut c
= Cursor
::new(&b
""[..]);
1866 let mut v
= String
::new();
1867 assert_eq
!(c
.read_to_string(&mut v
).unwrap(), 0);
1870 let mut c
= Cursor
::new(&b
"1"[..]);
1871 let mut v
= String
::new();
1872 assert_eq
!(c
.read_to_string(&mut v
).unwrap(), 1);
1875 let mut c
= Cursor
::new(&b
"\xff"[..]);
1876 let mut v
= String
::new();
1877 assert
!(c
.read_to_string(&mut v
).is_err());
1882 let mut buf
= [0; 4];
1884 let mut c
= Cursor
::new(&b
""[..]);
1885 assert_eq
!(c
.read_exact(&mut buf
).unwrap_err().kind(),
1886 io
::ErrorKind
::UnexpectedEof
);
1888 let mut c
= Cursor
::new(&b
"123"[..]).chain(Cursor
::new(&b
"456789"[..]));
1889 c
.read_exact(&mut buf
).unwrap();
1890 assert_eq
!(&buf
, b
"1234");
1891 c
.read_exact(&mut buf
).unwrap();
1892 assert_eq
!(&buf
, b
"5678");
1893 assert_eq
!(c
.read_exact(&mut buf
).unwrap_err().kind(),
1894 io
::ErrorKind
::UnexpectedEof
);
1898 fn read_exact_slice() {
1899 let mut buf
= [0; 4];
1901 let mut c
= &b
""[..];
1902 assert_eq
!(c
.read_exact(&mut buf
).unwrap_err().kind(),
1903 io
::ErrorKind
::UnexpectedEof
);
1905 let mut c
= &b
"123"[..];
1906 assert_eq
!(c
.read_exact(&mut buf
).unwrap_err().kind(),
1907 io
::ErrorKind
::UnexpectedEof
);
1908 // make sure the optimized (early returning) method is being used
1909 assert_eq
!(&buf
, &[0; 4]);
1911 let mut c
= &b
"1234"[..];
1912 c
.read_exact(&mut buf
).unwrap();
1913 assert_eq
!(&buf
, b
"1234");
1915 let mut c
= &b
"56789"[..];
1916 c
.read_exact(&mut buf
).unwrap();
1917 assert_eq
!(&buf
, b
"5678");
1918 assert_eq
!(c
, b
"9");
1926 fn read(&mut self, _
: &mut [u8]) -> io
::Result
<usize> {
1927 Err(io
::Error
::new(io
::ErrorKind
::Other
, ""))
1930 impl BufRead
for R
{
1931 fn fill_buf(&mut self) -> io
::Result
<&[u8]> {
1932 Err(io
::Error
::new(io
::ErrorKind
::Other
, ""))
1934 fn consume(&mut self, _amt
: usize) { }
1937 let mut buf
= [0; 1];
1938 assert_eq
!(0, R
.take(0).read(&mut buf
).unwrap());
1939 assert_eq
!(b
"", R
.take(0).fill_buf().unwrap());
1942 fn cmp_bufread
<Br1
: BufRead
, Br2
: BufRead
>(mut br1
: Br1
, mut br2
: Br2
, exp
: &[u8]) {
1943 let mut cat
= Vec
::new();
1946 let buf1
= br1
.fill_buf().unwrap();
1947 let buf2
= br2
.fill_buf().unwrap();
1948 let minlen
= if buf1
.len() < buf2
.len() { buf1.len() }
else { buf2.len() }
;
1949 assert_eq
!(buf1
[..minlen
], buf2
[..minlen
]);
1950 cat
.extend_from_slice(&buf1
[..minlen
]);
1956 br1
.consume(consume
);
1957 br2
.consume(consume
);
1959 assert_eq
!(br1
.fill_buf().unwrap().len(), 0);
1960 assert_eq
!(br2
.fill_buf().unwrap().len(), 0);
1961 assert_eq
!(&cat
[..], &exp
[..])
1965 fn chain_bufread() {
1966 let testdata
= b
"ABCDEFGHIJKL";
1967 let chain1
= (&testdata
[..3]).chain(&testdata
[3..6])
1968 .chain(&testdata
[6..9])
1969 .chain(&testdata
[9..]);
1970 let chain2
= (&testdata
[..4]).chain(&testdata
[4..8])
1971 .chain(&testdata
[8..]);
1972 cmp_bufread(chain1
, chain2
, &testdata
[..]);
1976 fn chain_zero_length_read_is_not_eof() {
1979 let mut s
= String
::new();
1980 let mut chain
= (&a
[..]).chain(&b
[..]);
1981 chain
.read(&mut []).unwrap();
1982 chain
.read_to_string(&mut s
).unwrap();
1983 assert_eq
!("AB", s
);
1987 #[cfg_attr(target_os = "emscripten", ignore)]
1988 fn bench_read_to_end(b
: &mut test
::Bencher
) {
1990 let mut lr
= repeat(1).take(10000000);
1991 let mut vec
= Vec
::with_capacity(1024);
1992 super::read_to_end(&mut lr
, &mut vec
)