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 = File::open("foo.txt")?;
33 //! let mut buffer = [0; 10];
35 //! // read up to 10 bytes
36 //! 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 = File::open("foo.txt")?;
62 //! let mut buffer = [0; 10];
64 //! // skip to the last 10 bytes of the file
65 //! f.seek(SeekFrom::End(-10))?;
67 //! // read up to 10 bytes
68 //! 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 = File::open("foo.txt")?;
97 //! let mut reader = BufReader::new(f);
98 //! let mut buffer = String::new();
100 //! // read a line into buffer
101 //! 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 = File::create("foo.txt")?;
120 //! let mut writer = BufWriter::new(f);
122 //! // write a byte to the buffer
123 //! 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 //! io::stdin().read_line(&mut input)?;
143 //! println!("You typed: {}", input.trim());
148 //! Note that you cannot use the `?` operator in functions that do not return a `Result<T, E>` (e.g. `main`).
149 //! Instead, you can `match` on the return value to catch any possible errors:
152 //! let mut input = String::new();
153 //! match io::stdin().read_line(&mut input) {
154 //! Err(why) => panic!("Failed to read input: {}", why.description()),
155 //! Ok(_) => println!("You typed: {}", input.trim()),
159 //! And a very common source of output is standard output:
163 //! use std::io::prelude::*;
165 //! # fn foo() -> io::Result<()> {
166 //! io::stdout().write(&[42])?;
171 //! Of course, using [`io::stdout`] directly is less common than something like
174 //! ## Iterator types
176 //! A large number of the structures provided by `std::io` are for various
177 //! ways of iterating over I/O. For example, [`Lines`] is used to split over
182 //! use std::io::prelude::*;
183 //! use std::io::BufReader;
184 //! use std::fs::File;
186 //! # fn foo() -> io::Result<()> {
187 //! let f = File::open("foo.txt")?;
188 //! let reader = BufReader::new(f);
190 //! for line in reader.lines() {
191 //! println!("{}", line?);
200 //! There are a number of [functions][functions-list] that offer access to various
201 //! features. For example, we can use three of these functions to copy everything
202 //! from standard input to standard output:
207 //! # fn foo() -> io::Result<()> {
208 //! io::copy(&mut io::stdin(), &mut io::stdout())?;
213 //! [functions-list]: #functions-1
217 //! Last, but certainly not least, is [`io::Result`]. This type is used
218 //! as the return type of many `std::io` functions that can cause an error, and
219 //! can be returned from your own functions as well. Many of the examples in this
220 //! module use the [`?` operator]:
225 //! fn read_input() -> io::Result<()> {
226 //! let mut input = String::new();
228 //! io::stdin().read_line(&mut input)?;
230 //! println!("You typed: {}", input.trim());
236 //! The return type of `read_input()`, [`io::Result<()>`][`io::Result`], is a very
237 //! common type for functions which don't have a 'real' return value, but do want to
238 //! return errors if they happen. In this case, the only purpose of this function is
239 //! to read the line and print it, so we use `()`.
241 //! ## Platform-specific behavior
243 //! Many I/O functions throughout the standard library are documented to indicate
244 //! what various library or syscalls they are delegated to. This is done to help
245 //! applications both understand what's happening under the hood as well as investigate
246 //! any possibly unclear semantics. Note, however, that this is informative, not a binding
247 //! contract. The implementation of many of these functions are subject to change over
248 //! time and may call fewer or more syscalls/library functions.
250 //! [`Read`]: trait.Read.html
251 //! [`Write`]: trait.Write.html
252 //! [`Seek`]: trait.Seek.html
253 //! [`BufRead`]: trait.BufRead.html
254 //! [`File`]: ../fs/struct.File.html
255 //! [`TcpStream`]: ../net/struct.TcpStream.html
256 //! [`Vec<T>`]: ../vec/struct.Vec.html
257 //! [`BufReader`]: struct.BufReader.html
258 //! [`BufWriter`]: struct.BufWriter.html
259 //! [`write`]: trait.Write.html#tymethod.write
260 //! [`io::stdout`]: fn.stdout.html
261 //! [`println!`]: ../macro.println.html
262 //! [`Lines`]: struct.Lines.html
263 //! [`io::Result`]: type.Result.html
264 //! [`?` operator]: ../../book/syntax-index.html
265 //! [`read`]: trait.Read.html#tymethod.read
267 #![stable(feature = "rust1", since = "1.0.0")]
270 use core::str as core_str;
271 use error as std_error;
277 #[stable(feature = "rust1", since = "1.0.0")]
278 pub use self::buffered::{BufReader, BufWriter, LineWriter};
279 #[stable(feature = "rust1", since = "1.0.0")]
280 pub use self::buffered::IntoInnerError;
281 #[stable(feature = "rust1", since = "1.0.0")]
282 pub use self::cursor::Cursor;
283 #[stable(feature = "rust1", since = "1.0.0")]
284 pub use self::error::{Result, Error, ErrorKind};
285 #[stable(feature = "rust1", since = "1.0.0")]
286 pub use self::util::{copy, sink, Sink, empty, Empty, repeat, Repeat};
287 #[stable(feature = "rust1", since = "1.0.0")]
288 pub use self::stdio::{stdin, stdout, stderr, _print, Stdin, Stdout, Stderr};
289 #[stable(feature = "rust1", since = "1.0.0")]
290 pub use self::stdio::{StdoutLock, StderrLock, StdinLock};
291 #[unstable(feature = "libstd_io_internals", issue = "0")]
292 #[doc(no_inline, hidden)]
293 pub use self::stdio::{set_panic, set_print};
304 const DEFAULT_BUF_SIZE: usize = ::sys_common::io::DEFAULT_BUF_SIZE;
306 // A few methods below (read_to_string, read_line) will append data into a
307 // `String` buffer, but we need to be pretty careful when doing this. The
308 // implementation will just call `.as_mut_vec()` and then delegate to a
309 // byte-oriented reading method, but we must ensure that when returning we never
310 // leave `buf` in a state such that it contains invalid UTF-8 in its bounds.
312 // To this end, we use an RAII guard (to protect against panics) which updates
313 // the length of the string when it is dropped. This guard initially truncates
314 // the string to the prior length and only after we've validated that the
315 // new contents are valid UTF-8 do we allow it to set a longer length.
317 // The unsafety in this function is twofold:
319 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
321 // 2. We're passing a raw buffer to the function `f`, and it is expected that
322 // the function only *appends* bytes to the buffer. We'll get undefined
323 // behavior if existing bytes are overwritten to have non-UTF-8 data.
324 fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
325 where F: FnOnce(&mut Vec<u8>) -> Result<usize>
327 struct Guard<'a> { s: &'a mut Vec<u8>, len: usize }
328 impl<'a> Drop for Guard<'a> {
330 unsafe { self.s.set_len(self.len); }
335 let mut g = Guard { len: buf.len(), s: buf.as_mut_vec() };
337 if str::from_utf8(&g.s[g.len..]).is_err() {
339 Err(Error::new(ErrorKind::InvalidData,
340 "stream did not contain valid UTF-8"))
349 // This uses an adaptive system to extend the vector when it fills. We want to
350 // avoid paying to allocate and zero a huge chunk of memory if the reader only
351 // has 4 bytes while still making large reads if the reader does have a ton
352 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
353 // time is 4,500 times (!) slower than this if the reader has a very small
354 // amount of data to return.
355 fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
356 let start_len = buf.len();
357 let mut len = start_len;
358 let mut new_write_size = 16;
361 if len == buf.len() {
362 if new_write_size < DEFAULT_BUF_SIZE {
365 buf.resize(len + new_write_size, 0);
368 match r.read(&mut buf[len..]) {
370 ret = Ok(len - start_len);
374 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
386 /// The `Read` trait allows for reading bytes from a source.
388 /// Implementors of the `Read` trait are sometimes called 'readers'.
390 /// Readers are defined by one required method, `read()`. Each call to `read`
391 /// will attempt to pull bytes from this source into a provided buffer. A
392 /// number of other methods are implemented in terms of `read()`, giving
393 /// implementors a number of ways to read bytes while only needing to implement
396 /// Readers are intended to be composable with one another. Many implementors
397 /// throughout `std::io` take and provide types which implement the `Read`
400 /// Please note that each call to `read` may involve a system call, and
401 /// therefore, using something that implements [`BufRead`][bufread], such as
402 /// [`BufReader`][bufreader], will be more efficient.
404 /// [bufread]: trait.BufRead.html
405 /// [bufreader]: struct.BufReader.html
409 /// [`File`][file]s implement `Read`:
411 /// [file]: ../fs/struct.File.html
415 /// use std::io::prelude::*;
416 /// use std::fs::File;
418 /// # fn foo() -> io::Result<()> {
419 /// let mut f = File::open("foo.txt")?;
420 /// let mut buffer = [0; 10];
422 /// // read up to 10 bytes
423 /// f.read(&mut buffer)?;
425 /// let mut buffer = vec![0; 10];
426 /// // read the whole file
427 /// f.read_to_end(&mut buffer)?;
429 /// // read into a String, so that you don't need to do the conversion.
430 /// let mut buffer = String::new();
431 /// f.read_to_string(&mut buffer)?;
433 /// // and more! See the other methods for more details.
437 #[stable(feature = "rust1", since = "1.0.0")]
439 /// Pull some bytes from this source into the specified buffer, returning
440 /// how many bytes were read.
442 /// This function does not provide any guarantees about whether it blocks
443 /// waiting for data, but if an object needs to block for a read but cannot
444 /// it will typically signal this via an `Err` return value.
446 /// If the return value of this method is `Ok(n)`, then it must be
447 /// guaranteed that `0 <= n <= buf.len()`. A nonzero `n` value indicates
448 /// that the buffer `buf` has been filled in with `n` bytes of data from this
449 /// source. If `n` is `0`, then it can indicate one of two scenarios:
451 /// 1. This reader has reached its "end of file" and will likely no longer
452 /// be able to produce bytes. Note that this does not mean that the
453 /// reader will *always* no longer be able to produce bytes.
454 /// 2. The buffer specified was 0 bytes in length.
456 /// No guarantees are provided about the contents of `buf` when this
457 /// function is called, implementations cannot rely on any property of the
458 /// contents of `buf` being true. It is recommended that implementations
459 /// only write data to `buf` instead of reading its contents.
463 /// If this function encounters any form of I/O or other error, an error
464 /// variant will be returned. If an error is returned then it must be
465 /// guaranteed that no bytes were read.
469 /// [`File`][file]s implement `Read`:
471 /// [file]: ../fs/struct.File.html
475 /// use std::io::prelude::*;
476 /// use std::fs::File;
478 /// # fn foo() -> io::Result<()> {
479 /// let mut f = File::open("foo.txt")?;
480 /// let mut buffer = [0; 10];
483 /// f.read(&mut buffer[..])?;
487 #[stable(feature = "rust1", since = "1.0.0")]
488 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
490 /// Read all bytes until EOF in this source, placing them into `buf`.
492 /// All bytes read from this source will be appended to the specified buffer
493 /// `buf`. This function will continuously call `read` to append more data to
494 /// `buf` until `read` returns either `Ok(0)` or an error of
495 /// non-`ErrorKind::Interrupted` kind.
497 /// If successful, this function will return the total number of bytes read.
501 /// If this function encounters an error of the kind
502 /// `ErrorKind::Interrupted` then the error is ignored and the operation
505 /// If any other read error is encountered then this function immediately
506 /// returns. Any bytes which have already been read will be appended to
511 /// [`File`][file]s implement `Read`:
513 /// [file]: ../fs/struct.File.html
517 /// use std::io::prelude::*;
518 /// use std::fs::File;
520 /// # fn foo() -> io::Result<()> {
521 /// let mut f = File::open("foo.txt")?;
522 /// let mut buffer = Vec::new();
524 /// // read the whole file
525 /// f.read_to_end(&mut buffer)?;
529 #[stable(feature = "rust1", since = "1.0.0")]
530 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
531 read_to_end(self, buf)
534 /// Read all bytes until EOF in this source, placing them into `buf`.
536 /// If successful, this function returns the number of bytes which were read
537 /// and appended to `buf`.
541 /// If the data in this stream is *not* valid UTF-8 then an error is
542 /// returned and `buf` is unchanged.
544 /// See [`read_to_end`][readtoend] for other error semantics.
546 /// [readtoend]: #method.read_to_end
550 /// [`File`][file]s implement `Read`:
552 /// [file]: ../fs/struct.File.html
556 /// use std::io::prelude::*;
557 /// use std::fs::File;
559 /// # fn foo() -> io::Result<()> {
560 /// let mut f = File::open("foo.txt")?;
561 /// let mut buffer = String::new();
563 /// f.read_to_string(&mut buffer)?;
567 #[stable(feature = "rust1", since = "1.0.0")]
568 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
569 // Note that we do *not* call `.read_to_end()` here. We are passing
570 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
571 // method to fill it up. An arbitrary implementation could overwrite the
572 // entire contents of the vector, not just append to it (which is what
573 // we are expecting).
575 // To prevent extraneously checking the UTF-8-ness of the entire buffer
576 // we pass it to our hardcoded `read_to_end` implementation which we
577 // know is guaranteed to only read data into the end of the buffer.
578 append_to_string(buf, |b| read_to_end(self, b))
581 /// Read the exact number of bytes required to fill `buf`.
583 /// This function reads as many bytes as necessary to completely fill the
584 /// specified buffer `buf`.
586 /// No guarantees are provided about the contents of `buf` when this
587 /// function is called, implementations cannot rely on any property of the
588 /// contents of `buf` being true. It is recommended that implementations
589 /// only write data to `buf` instead of reading its contents.
593 /// If this function encounters an error of the kind
594 /// `ErrorKind::Interrupted` then the error is ignored and the operation
597 /// If this function encounters an "end of file" before completely filling
598 /// the buffer, it returns an error of the kind `ErrorKind::UnexpectedEof`.
599 /// The contents of `buf` are unspecified in this case.
601 /// If any other read error is encountered then this function immediately
602 /// returns. The contents of `buf` are unspecified in this case.
604 /// If this function returns an error, it is unspecified how many bytes it
605 /// has read, but it will never read more than would be necessary to
606 /// completely fill the buffer.
610 /// [`File`][file]s implement `Read`:
612 /// [file]: ../fs/struct.File.html
616 /// use std::io::prelude::*;
617 /// use std::fs::File;
619 /// # fn foo() -> io::Result<()> {
620 /// let mut f = File::open("foo.txt")?;
621 /// let mut buffer = [0; 10];
623 /// // read exactly 10 bytes
624 /// f.read_exact(&mut buffer)?;
628 #[stable(feature = "read_exact", since = "1.6.0")]
629 fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
630 while !buf.is_empty() {
631 match self.read(buf) {
633 Ok(n) => { let tmp = buf; buf = &mut tmp[n..]; }
634 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
635 Err(e) => return Err(e),
639 Err(Error::new(ErrorKind::UnexpectedEof,
640 "failed to fill whole buffer"))
646 /// Creates a "by reference" adaptor for this instance of `Read`.
648 /// The returned adaptor also implements `Read` and will simply borrow this
653 /// [`File`][file]s implement `Read`:
655 /// [file]: ../fs/struct.File.html
659 /// use std::io::Read;
660 /// use std::fs::File;
662 /// # fn foo() -> io::Result<()> {
663 /// let mut f = File::open("foo.txt")?;
664 /// let mut buffer = Vec::new();
665 /// let mut other_buffer = Vec::new();
668 /// let reference = f.by_ref();
670 /// // read at most 5 bytes
671 /// reference.take(5).read_to_end(&mut buffer)?;
673 /// } // drop our &mut reference so we can use f again
675 /// // original file still usable, read the rest
676 /// f.read_to_end(&mut other_buffer)?;
680 #[stable(feature = "rust1", since = "1.0.0")]
681 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
683 /// Transforms this `Read` instance to an `Iterator` over its bytes.
685 /// The returned type implements `Iterator` where the `Item` is `Result<u8,
686 /// R::Err>`. The yielded item is `Ok` if a byte was successfully read and
687 /// `Err` otherwise for I/O errors. EOF is mapped to returning `None` from
692 /// [`File`][file]s implement `Read`:
694 /// [file]: ../fs/struct.File.html
698 /// use std::io::prelude::*;
699 /// use std::fs::File;
701 /// # fn foo() -> io::Result<()> {
702 /// let mut f = File::open("foo.txt")?;
704 /// for byte in f.bytes() {
705 /// println!("{}", byte.unwrap());
710 #[stable(feature = "rust1", since = "1.0.0")]
711 fn bytes(self) -> Bytes<Self> where Self: Sized {
712 Bytes { inner: self }
715 /// Transforms this `Read` instance to an `Iterator` over `char`s.
717 /// This adaptor will attempt to interpret this reader as a UTF-8 encoded
718 /// sequence of characters. The returned iterator will return `None` once
719 /// EOF is reached for this reader. Otherwise each element yielded will be a
720 /// `Result<char, E>` where `E` may contain information about what I/O error
721 /// occurred or where decoding failed.
723 /// Currently this adaptor will discard intermediate data read, and should
724 /// be avoided if this is not desired.
728 /// [`File`][file]s implement `Read`:
730 /// [file]: ../fs/struct.File.html
735 /// use std::io::prelude::*;
736 /// use std::fs::File;
738 /// # fn foo() -> io::Result<()> {
739 /// let mut f = File::open("foo.txt")?;
741 /// for c in f.chars() {
742 /// println!("{}", c.unwrap());
747 #[unstable(feature = "io", reason = "the semantics of a partial read/write \
748 of where errors happen is currently \
749 unclear and may change",
751 fn chars(self) -> Chars<Self> where Self: Sized {
752 Chars { inner: self }
755 /// Creates an adaptor which will chain this stream with another.
757 /// The returned `Read` instance will first read all bytes from this object
758 /// until EOF is encountered. Afterwards the output is equivalent to the
759 /// output of `next`.
763 /// [`File`][file]s implement `Read`:
765 /// [file]: ../fs/struct.File.html
769 /// use std::io::prelude::*;
770 /// use std::fs::File;
772 /// # fn foo() -> io::Result<()> {
773 /// let mut f1 = File::open("foo.txt")?;
774 /// let mut f2 = File::open("bar.txt")?;
776 /// let mut handle = f1.chain(f2);
777 /// let mut buffer = String::new();
779 /// // read the value into a String. We could use any Read method here,
780 /// // this is just one example.
781 /// handle.read_to_string(&mut buffer)?;
785 #[stable(feature = "rust1", since = "1.0.0")]
786 fn chain<R: Read>(self, next: R) -> Chain<Self, R> where Self: Sized {
787 Chain { first: self, second: next, done_first: false }
790 /// Creates an adaptor which will read at most `limit` bytes from it.
792 /// This function returns a new instance of `Read` which will read at most
793 /// `limit` bytes, after which it will always return EOF (`Ok(0)`). Any
794 /// read errors will not count towards the number of bytes read and future
795 /// calls to `read` may succeed.
799 /// [`File`][file]s implement `Read`:
801 /// [file]: ../fs/struct.File.html
805 /// use std::io::prelude::*;
806 /// use std::fs::File;
808 /// # fn foo() -> io::Result<()> {
809 /// let mut f = File::open("foo.txt")?;
810 /// let mut buffer = [0; 5];
812 /// // read at most five bytes
813 /// let mut handle = f.take(5);
815 /// handle.read(&mut buffer)?;
819 #[stable(feature = "rust1", since = "1.0.0")]
820 fn take(self, limit: u64) -> Take<Self> where Self: Sized {
821 Take { inner: self, limit: limit }
825 /// A trait for objects which are byte-oriented sinks.
827 /// Implementors of the `Write` trait are sometimes called 'writers'.
829 /// Writers are defined by two required methods, [`write`] and [`flush`]:
831 /// * The [`write`] method will attempt to write some data into the object,
832 /// returning how many bytes were successfully written.
834 /// * The [`flush`] method is useful for adaptors and explicit buffers
835 /// themselves for ensuring that all buffered data has been pushed out to the
838 /// Writers are intended to be composable with one another. Many implementors
839 /// throughout [`std::io`] take and provide types which implement the `Write`
842 /// [`write`]: #tymethod.write
843 /// [`flush`]: #tymethod.flush
844 /// [`std::io`]: index.html
849 /// use std::io::prelude::*;
850 /// use std::fs::File;
852 /// # fn foo() -> std::io::Result<()> {
853 /// let mut buffer = File::create("foo.txt")?;
855 /// buffer.write(b"some bytes")?;
859 #[stable(feature = "rust1", since = "1.0.0")]
861 /// Write a buffer into this object, returning how many bytes were written.
863 /// This function will attempt to write the entire contents of `buf`, but
864 /// the entire write may not succeed, or the write may also generate an
865 /// error. A call to `write` represents *at most one* attempt to write to
866 /// any wrapped object.
868 /// Calls to `write` are not guaranteed to block waiting for data to be
869 /// written, and a write which would otherwise block can be indicated through
870 /// an `Err` variant.
872 /// If the return value is `Ok(n)` then it must be guaranteed that
873 /// `0 <= n <= buf.len()`. A return value of `0` typically means that the
874 /// underlying object is no longer able to accept bytes and will likely not
875 /// be able to in the future as well, or that the buffer provided is empty.
879 /// Each call to `write` may generate an I/O error indicating that the
880 /// operation could not be completed. If an error is returned then no bytes
881 /// in the buffer were written to this writer.
883 /// It is **not** considered an error if the entire buffer could not be
884 /// written to this writer.
889 /// use std::io::prelude::*;
890 /// use std::fs::File;
892 /// # fn foo() -> std::io::Result<()> {
893 /// let mut buffer = File::create("foo.txt")?;
895 /// buffer.write(b"some bytes")?;
899 #[stable(feature = "rust1", since = "1.0.0")]
900 fn write(&mut self, buf: &[u8]) -> Result<usize>;
902 /// Flush this output stream, ensuring that all intermediately buffered
903 /// contents reach their destination.
907 /// It is considered an error if not all bytes could be written due to
908 /// I/O errors or EOF being reached.
913 /// use std::io::prelude::*;
914 /// use std::io::BufWriter;
915 /// use std::fs::File;
917 /// # fn foo() -> std::io::Result<()> {
918 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
920 /// buffer.write(b"some bytes")?;
925 #[stable(feature = "rust1", since = "1.0.0")]
926 fn flush(&mut self) -> Result<()>;
928 /// Attempts to write an entire buffer into this write.
930 /// This method will continuously call `write` while there is more data to
931 /// write. This method will not return until the entire buffer has been
932 /// successfully written or an error occurs. The first error generated from
933 /// this method will be returned.
937 /// This function will return the first error that `write` returns.
942 /// use std::io::prelude::*;
943 /// use std::fs::File;
945 /// # fn foo() -> std::io::Result<()> {
946 /// let mut buffer = File::create("foo.txt")?;
948 /// buffer.write_all(b"some bytes")?;
952 #[stable(feature = "rust1", since = "1.0.0")]
953 fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
954 while !buf.is_empty() {
955 match self.write(buf) {
956 Ok(0) => return Err(Error::new(ErrorKind::WriteZero,
957 "failed to write whole buffer")),
958 Ok(n) => buf = &buf[n..],
959 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
960 Err(e) => return Err(e),
966 /// Writes a formatted string into this writer, returning any error
969 /// This method is primarily used to interface with the
970 /// [`format_args!`][formatargs] macro, but it is rare that this should
971 /// explicitly be called. The [`write!`][write] macro should be favored to
972 /// invoke this method instead.
974 /// [formatargs]: ../macro.format_args.html
975 /// [write]: ../macro.write.html
977 /// This function internally uses the [`write_all`][writeall] method on
978 /// this trait and hence will continuously write data so long as no errors
979 /// are received. This also means that partial writes are not indicated in
982 /// [writeall]: #method.write_all
986 /// This function will return any I/O error reported while formatting.
991 /// use std::io::prelude::*;
992 /// use std::fs::File;
994 /// # fn foo() -> std::io::Result<()> {
995 /// let mut buffer = File::create("foo.txt")?;
998 /// write!(buffer, "{:.*}", 2, 1.234567)?;
999 /// // turns into this:
1000 /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1004 #[stable(feature = "rust1", since = "1.0.0")]
1005 fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()> {
1006 // Create a shim which translates a Write to a fmt::Write and saves
1007 // off I/O errors. instead of discarding them
1008 struct Adaptor<'a, T: ?Sized + 'a> {
1013 impl<'a, T: Write + ?Sized> fmt::Write for Adaptor<'a, T> {
1014 fn write_str(&mut self, s: &str) -> fmt::Result {
1015 match self.inner.write_all(s.as_bytes()) {
1018 self.error = Err(e);
1025 let mut output = Adaptor { inner: self, error: Ok(()) };
1026 match fmt::write(&mut output, fmt) {
1029 // check if the error came from the underlying `Write` or not
1030 if output.error.is_err() {
1033 Err(Error::new(ErrorKind::Other, "formatter error"))
1039 /// Creates a "by reference" adaptor for this instance of `Write`.
1041 /// The returned adaptor also implements `Write` and will simply borrow this
1047 /// use std::io::Write;
1048 /// use std::fs::File;
1050 /// # fn foo() -> std::io::Result<()> {
1051 /// let mut buffer = File::create("foo.txt")?;
1053 /// let reference = buffer.by_ref();
1055 /// // we can use reference just like our original buffer
1056 /// reference.write_all(b"some bytes")?;
1060 #[stable(feature = "rust1", since = "1.0.0")]
1061 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1064 /// The `Seek` trait provides a cursor which can be moved within a stream of
1067 /// The stream typically has a fixed size, allowing seeking relative to either
1068 /// end or the current offset.
1072 /// [`File`][file]s implement `Seek`:
1074 /// [file]: ../fs/struct.File.html
1078 /// use std::io::prelude::*;
1079 /// use std::fs::File;
1080 /// use std::io::SeekFrom;
1082 /// # fn foo() -> io::Result<()> {
1083 /// let mut f = File::open("foo.txt")?;
1085 /// // move the cursor 42 bytes from the start of the file
1086 /// f.seek(SeekFrom::Start(42))?;
1090 #[stable(feature = "rust1", since = "1.0.0")]
1092 /// Seek to an offset, in bytes, in a stream.
1094 /// A seek beyond the end of a stream is allowed, but implementation
1097 /// If the seek operation completed successfully,
1098 /// this method returns the new position from the start of the stream.
1099 /// That position can be used later with [`SeekFrom::Start`].
1103 /// Seeking to a negative offset is considered an error.
1105 /// [`SeekFrom::Start`]: enum.SeekFrom.html#variant.Start
1106 #[stable(feature = "rust1", since = "1.0.0")]
1107 fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1110 /// Enumeration of possible methods to seek within an I/O object.
1112 /// It is used by the [`Seek`] trait.
1114 /// [`Seek`]: trait.Seek.html
1115 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1116 #[stable(feature = "rust1", since = "1.0.0")]
1118 /// Set the offset to the provided number of bytes.
1119 #[stable(feature = "rust1", since = "1.0.0")]
1120 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1122 /// Set the offset to the size of this object plus the specified number of
1125 /// It is possible to seek beyond the end of an object, but it's an error to
1126 /// seek before byte 0.
1127 #[stable(feature = "rust1", since = "1.0.0")]
1128 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1130 /// Set the offset to the current position plus the specified number of
1133 /// It is possible to seek beyond the end of an object, but it's an error to
1134 /// seek before byte 0.
1135 #[stable(feature = "rust1", since = "1.0.0")]
1136 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1139 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>)
1143 let (done, used) = {
1144 let available = match r.fill_buf() {
1146 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1147 Err(e) => return Err(e)
1149 match memchr::memchr(delim, available) {
1151 buf.extend_from_slice(&available[..i + 1]);
1155 buf.extend_from_slice(available);
1156 (false, available.len())
1162 if done || used == 0 {
1168 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1169 /// to perform extra ways of reading.
1171 /// For example, reading line-by-line is inefficient without using a buffer, so
1172 /// if you want to read by line, you'll need `BufRead`, which includes a
1173 /// [`read_line`] method as well as a [`lines`] iterator.
1177 /// A locked standard input implements `BufRead`:
1181 /// use std::io::prelude::*;
1183 /// let stdin = io::stdin();
1184 /// for line in stdin.lock().lines() {
1185 /// println!("{}", line.unwrap());
1189 /// If you have something that implements [`Read`], you can use the [`BufReader`
1190 /// type][`BufReader`] to turn it into a `BufRead`.
1192 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1193 /// [`BufReader`] to the rescue!
1195 /// [`BufReader`]: struct.BufReader.html
1196 /// [`File`]: ../fs/struct.File.html
1197 /// [`read_line`]: #method.read_line
1198 /// [`lines`]: #method.lines
1199 /// [`Read`]: trait.Read.html
1202 /// use std::io::{self, BufReader};
1203 /// use std::io::prelude::*;
1204 /// use std::fs::File;
1206 /// # fn foo() -> io::Result<()> {
1207 /// let f = File::open("foo.txt")?;
1208 /// let f = BufReader::new(f);
1210 /// for line in f.lines() {
1211 /// println!("{}", line.unwrap());
1218 #[stable(feature = "rust1", since = "1.0.0")]
1219 pub trait BufRead: Read {
1220 /// Fills the internal buffer of this object, returning the buffer contents.
1222 /// This function is a lower-level call. It needs to be paired with the
1223 /// [`consume`] method to function properly. When calling this
1224 /// method, none of the contents will be "read" in the sense that later
1225 /// calling `read` may return the same contents. As such, [`consume`] must
1226 /// be called with the number of bytes that are consumed from this buffer to
1227 /// ensure that the bytes are never returned twice.
1229 /// [`consume`]: #tymethod.consume
1231 /// An empty buffer returned indicates that the stream has reached EOF.
1235 /// This function will return an I/O error if the underlying reader was
1236 /// read, but returned an error.
1240 /// A locked standard input implements `BufRead`:
1244 /// use std::io::prelude::*;
1246 /// let stdin = io::stdin();
1247 /// let mut stdin = stdin.lock();
1249 /// // we can't have two `&mut` references to `stdin`, so use a block
1250 /// // to end the borrow early.
1252 /// let buffer = stdin.fill_buf().unwrap();
1254 /// // work with buffer
1255 /// println!("{:?}", buffer);
1260 /// // ensure the bytes we worked with aren't returned again later
1261 /// stdin.consume(length);
1263 #[stable(feature = "rust1", since = "1.0.0")]
1264 fn fill_buf(&mut self) -> Result<&[u8]>;
1266 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1267 /// so they should no longer be returned in calls to `read`.
1269 /// This function is a lower-level call. It needs to be paired with the
1270 /// [`fill_buf`] method to function properly. This function does
1271 /// not perform any I/O, it simply informs this object that some amount of
1272 /// its buffer, returned from [`fill_buf`], has been consumed and should
1273 /// no longer be returned. As such, this function may do odd things if
1274 /// [`fill_buf`] isn't called before calling it.
1276 /// The `amt` must be `<=` the number of bytes in the buffer returned by
1281 /// Since `consume()` is meant to be used with [`fill_buf`],
1282 /// that method's example includes an example of `consume()`.
1284 /// [`fill_buf`]: #tymethod.fill_buf
1285 #[stable(feature = "rust1", since = "1.0.0")]
1286 fn consume(&mut self, amt: usize);
1288 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
1290 /// This function will read bytes from the underlying stream until the
1291 /// delimiter or EOF is found. Once found, all bytes up to, and including,
1292 /// the delimiter (if found) will be appended to `buf`.
1294 /// If successful, this function will return the total number of bytes read.
1298 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1299 /// will otherwise return any errors returned by [`fill_buf`].
1301 /// If an I/O error is encountered then all bytes read so far will be
1302 /// present in `buf` and its length will have been adjusted appropriately.
1306 /// A locked standard input implements `BufRead`. In this example, we'll
1307 /// read from standard input until we see an `a` byte.
1309 /// [`fill_buf`]: #tymethod.fill_buf
1310 /// [`ErrorKind::Interrupted`]: enum.ErrorKind.html#variant.Interrupted
1314 /// use std::io::prelude::*;
1316 /// fn foo() -> io::Result<()> {
1317 /// let stdin = io::stdin();
1318 /// let mut stdin = stdin.lock();
1319 /// let mut buffer = Vec::new();
1321 /// stdin.read_until(b'a', &mut buffer)?;
1323 /// println!("{:?}", buffer);
1327 #[stable(feature = "rust1", since = "1.0.0")]
1328 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
1329 read_until(self, byte, buf)
1332 /// Read all bytes until a newline (the 0xA byte) is reached, and append
1333 /// them to the provided buffer.
1335 /// This function will read bytes from the underlying stream until the
1336 /// newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes
1337 /// up to, and including, the delimiter (if found) will be appended to
1340 /// If successful, this function will return the total number of bytes read.
1344 /// This function has the same error semantics as [`read_until`] and will
1345 /// also return an error if the read bytes are not valid UTF-8. If an I/O
1346 /// error is encountered then `buf` may contain some bytes already read in
1347 /// the event that all data read so far was valid UTF-8.
1351 /// A locked standard input implements `BufRead`. In this example, we'll
1352 /// read all of the lines from standard input. If we were to do this in
1353 /// an actual project, the [`lines`] method would be easier, of
1356 /// [`lines`]: #method.lines
1357 /// [`read_until`]: #method.read_until
1361 /// use std::io::prelude::*;
1363 /// let stdin = io::stdin();
1364 /// let mut stdin = stdin.lock();
1365 /// let mut buffer = String::new();
1367 /// while stdin.read_line(&mut buffer).unwrap() > 0 {
1368 /// // work with buffer
1369 /// println!("{:?}", buffer);
1374 #[stable(feature = "rust1", since = "1.0.0")]
1375 fn read_line(&mut self, buf: &mut String) -> Result<usize> {
1376 // Note that we are not calling the `.read_until` method here, but
1377 // rather our hardcoded implementation. For more details as to why, see
1378 // the comments in `read_to_end`.
1379 append_to_string(buf, |b| read_until(self, b'\n', b))
1382 /// Returns an iterator over the contents of this reader split on the byte
1385 /// The iterator returned from this function will return instances of
1386 /// [`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
1387 /// the delimiter byte at the end.
1389 /// This function will yield errors whenever [`read_until`] would have
1390 /// also yielded an error.
1394 /// A locked standard input implements `BufRead`. In this example, we'll
1395 /// read some input from standard input, splitting on commas.
1397 /// [`io::Result`]: type.Result.html
1398 /// [`Vec<u8>`]: ../vec/struct.Vec.html
1399 /// [`read_until`]: #method.read_until
1403 /// use std::io::prelude::*;
1405 /// let stdin = io::stdin();
1407 /// for content in stdin.lock().split(b',') {
1408 /// println!("{:?}", content.unwrap());
1411 #[stable(feature = "rust1", since = "1.0.0")]
1412 fn split(self, byte: u8) -> Split<Self> where Self: Sized {
1413 Split { buf: self, delim: byte }
1416 /// Returns an iterator over the lines of this reader.
1418 /// The iterator returned from this function will yield instances of
1419 /// [`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline
1420 /// byte (the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.
1422 /// [`io::Result`]: type.Result.html
1423 /// [`String`]: ../string/struct.String.html
1427 /// A locked standard input implements `BufRead`:
1431 /// use std::io::prelude::*;
1433 /// let stdin = io::stdin();
1435 /// for line in stdin.lock().lines() {
1436 /// println!("{}", line.unwrap());
1442 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
1444 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
1445 #[stable(feature = "rust1", since = "1.0.0")]
1446 fn lines(self) -> Lines<Self> where Self: Sized {
1451 /// Adaptor to chain together two readers.
1453 /// This struct is generally created by calling [`chain`] on a reader.
1454 /// Please see the documentation of [`chain`] for more details.
1456 /// [`chain`]: trait.Read.html#method.chain
1457 #[stable(feature = "rust1", since = "1.0.0")]
1458 pub struct Chain<T, U> {
1464 #[stable(feature = "std_debug", since = "1.16.0")]
1465 impl<T: fmt::Debug, U: fmt::Debug> fmt::Debug for Chain<T, U> {
1466 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1467 f.debug_struct("Chain")
1468 .field("t", &self.first)
1469 .field("u", &self.second)
1474 #[stable(feature = "rust1", since = "1.0.0")]
1475 impl<T: Read, U: Read> Read for Chain<T, U> {
1476 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1477 if !self.done_first {
1478 match self.first.read(buf)? {
1479 0 if buf.len() != 0 => { self.done_first = true; }
1483 self.second.read(buf)
1487 #[stable(feature = "chain_bufread", since = "1.9.0")]
1488 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
1489 fn fill_buf(&mut self) -> Result<&[u8]> {
1490 if !self.done_first {
1491 match self.first.fill_buf()? {
1492 buf if buf.len() == 0 => { self.done_first = true; }
1493 buf => return Ok(buf),
1496 self.second.fill_buf()
1499 fn consume(&mut self, amt: usize) {
1500 if !self.done_first {
1501 self.first.consume(amt)
1503 self.second.consume(amt)
1508 /// Reader adaptor which limits the bytes read from an underlying reader.
1510 /// This struct is generally created by calling [`take`] on a reader.
1511 /// Please see the documentation of [`take`] for more details.
1513 /// [`take`]: trait.Read.html#method.take
1514 #[stable(feature = "rust1", since = "1.0.0")]
1516 pub struct Take<T> {
1522 /// Returns the number of bytes that can be read before this instance will
1527 /// This instance may reach `EOF` after reading fewer bytes than indicated by
1528 /// this method if the underlying [`Read`] instance reaches EOF.
1530 /// [`Read`]: ../../std/io/trait.Read.html
1536 /// use std::io::prelude::*;
1537 /// use std::fs::File;
1539 /// # fn foo() -> io::Result<()> {
1540 /// let f = File::open("foo.txt")?;
1542 /// // read at most five bytes
1543 /// let handle = f.take(5);
1545 /// println!("limit: {}", handle.limit());
1549 #[stable(feature = "rust1", since = "1.0.0")]
1550 pub fn limit(&self) -> u64 { self.limit }
1552 /// Consumes the `Take`, returning the wrapped reader.
1558 /// use std::io::prelude::*;
1559 /// use std::fs::File;
1561 /// # fn foo() -> io::Result<()> {
1562 /// let mut file = File::open("foo.txt")?;
1564 /// let mut buffer = [0; 5];
1565 /// let mut handle = file.take(5);
1566 /// handle.read(&mut buffer)?;
1568 /// let file = handle.into_inner();
1572 #[stable(feature = "io_take_into_inner", since = "1.15.0")]
1573 pub fn into_inner(self) -> T {
1578 #[stable(feature = "rust1", since = "1.0.0")]
1579 impl<T: Read> Read for Take<T> {
1580 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1581 // Don't call into inner reader at all at EOF because it may still block
1582 if self.limit == 0 {
1586 let max = cmp::min(buf.len() as u64, self.limit) as usize;
1587 let n = self.inner.read(&mut buf[..max])?;
1588 self.limit -= n as u64;
1593 #[stable(feature = "rust1", since = "1.0.0")]
1594 impl<T: BufRead> BufRead for Take<T> {
1595 fn fill_buf(&mut self) -> Result<&[u8]> {
1596 // Don't call into inner reader at all at EOF because it may still block
1597 if self.limit == 0 {
1601 let buf = self.inner.fill_buf()?;
1602 let cap = cmp::min(buf.len() as u64, self.limit) as usize;
1606 fn consume(&mut self, amt: usize) {
1607 // Don't let callers reset the limit by passing an overlarge value
1608 let amt = cmp::min(amt as u64, self.limit) as usize;
1609 self.limit -= amt as u64;
1610 self.inner.consume(amt);
1614 fn read_one_byte(reader: &mut Read) -> Option<Result<u8>> {
1617 return match reader.read(&mut buf) {
1619 Ok(..) => Some(Ok(buf[0])),
1620 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1621 Err(e) => Some(Err(e)),
1626 /// An iterator over `u8` values of a reader.
1628 /// This struct is generally created by calling [`bytes`] on a reader.
1629 /// Please see the documentation of [`bytes`] for more details.
1631 /// [`bytes`]: trait.Read.html#method.bytes
1632 #[stable(feature = "rust1", since = "1.0.0")]
1634 pub struct Bytes<R> {
1638 #[stable(feature = "rust1", since = "1.0.0")]
1639 impl<R: Read> Iterator for Bytes<R> {
1640 type Item = Result<u8>;
1642 fn next(&mut self) -> Option<Result<u8>> {
1643 read_one_byte(&mut self.inner)
1647 /// An iterator over the `char`s of a reader.
1649 /// This struct is generally created by calling [`chars`][chars] on a reader.
1650 /// Please see the documentation of `chars()` for more details.
1652 /// [chars]: trait.Read.html#method.chars
1653 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1656 pub struct Chars<R> {
1660 /// An enumeration of possible errors that can be generated from the `Chars`
1663 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1665 pub enum CharsError {
1666 /// Variant representing that the underlying stream was read successfully
1667 /// but it did not contain valid utf8 data.
1670 /// Variant representing that an I/O error occurred.
1674 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1676 impl<R: Read> Iterator for Chars<R> {
1677 type Item = result::Result<char, CharsError>;
1679 fn next(&mut self) -> Option<result::Result<char, CharsError>> {
1680 let first_byte = match read_one_byte(&mut self.inner) {
1681 None => return None,
1683 Some(Err(e)) => return Some(Err(CharsError::Other(e))),
1685 let width = core_str::utf8_char_width(first_byte);
1686 if width == 1 { return Some(Ok(first_byte as char)) }
1687 if width == 0 { return Some(Err(CharsError::NotUtf8)) }
1688 let mut buf = [first_byte, 0, 0, 0];
1691 while start < width {
1692 match self.inner.read(&mut buf[start..width]) {
1693 Ok(0) => return Some(Err(CharsError::NotUtf8)),
1694 Ok(n) => start += n,
1695 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1696 Err(e) => return Some(Err(CharsError::Other(e))),
1700 Some(match str::from_utf8(&buf[..width]).ok() {
1701 Some(s) => Ok(s.chars().next().unwrap()),
1702 None => Err(CharsError::NotUtf8),
1707 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1709 impl std_error::Error for CharsError {
1710 fn description(&self) -> &str {
1712 CharsError::NotUtf8 => "invalid utf8 encoding",
1713 CharsError::Other(ref e) => std_error::Error::description(e),
1716 fn cause(&self) -> Option<&std_error::Error> {
1718 CharsError::NotUtf8 => None,
1719 CharsError::Other(ref e) => e.cause(),
1724 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1726 impl fmt::Display for CharsError {
1727 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1729 CharsError::NotUtf8 => {
1730 "byte stream did not contain valid utf8".fmt(f)
1732 CharsError::Other(ref e) => e.fmt(f),
1737 /// An iterator over the contents of an instance of `BufRead` split on a
1738 /// particular byte.
1740 /// This struct is generally created by calling [`split`][split] on a
1741 /// `BufRead`. Please see the documentation of `split()` for more details.
1743 /// [split]: trait.BufRead.html#method.split
1744 #[stable(feature = "rust1", since = "1.0.0")]
1746 pub struct Split<B> {
1751 #[stable(feature = "rust1", since = "1.0.0")]
1752 impl<B: BufRead> Iterator for Split<B> {
1753 type Item = Result<Vec<u8>>;
1755 fn next(&mut self) -> Option<Result<Vec<u8>>> {
1756 let mut buf = Vec::new();
1757 match self.buf.read_until(self.delim, &mut buf) {
1760 if buf[buf.len() - 1] == self.delim {
1765 Err(e) => Some(Err(e))
1770 /// An iterator over the lines of an instance of `BufRead`.
1772 /// This struct is generally created by calling [`lines`][lines] on a
1773 /// `BufRead`. Please see the documentation of `lines()` for more details.
1775 /// [lines]: trait.BufRead.html#method.lines
1776 #[stable(feature = "rust1", since = "1.0.0")]
1778 pub struct Lines<B> {
1782 #[stable(feature = "rust1", since = "1.0.0")]
1783 impl<B: BufRead> Iterator for Lines<B> {
1784 type Item = Result<String>;
1786 fn next(&mut self) -> Option<Result<String>> {
1787 let mut buf = String::new();
1788 match self.buf.read_line(&mut buf) {
1791 if buf.ends_with("\n") {
1793 if buf.ends_with("\r") {
1799 Err(e) => Some(Err(e))
1813 #[cfg_attr(target_os = "emscripten", ignore)]
1815 let mut buf = Cursor::new(&b"12"[..]);
1816 let mut v = Vec::new();
1817 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 2);
1818 assert_eq!(v, b"12");
1820 let mut buf = Cursor::new(&b"1233"[..]);
1821 let mut v = Vec::new();
1822 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 3);
1823 assert_eq!(v, b"123");
1825 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 1);
1826 assert_eq!(v, b"3");
1828 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 0);
1834 let buf = Cursor::new(&b"12"[..]);
1835 let mut s = buf.split(b'3');
1836 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
1837 assert!(s.next().is_none());
1839 let buf = Cursor::new(&b"1233"[..]);
1840 let mut s = buf.split(b'3');
1841 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
1842 assert_eq!(s.next().unwrap().unwrap(), vec![]);
1843 assert!(s.next().is_none());
1848 let mut buf = Cursor::new(&b"12"[..]);
1849 let mut v = String::new();
1850 assert_eq!(buf.read_line(&mut v).unwrap(), 2);
1851 assert_eq!(v, "12");
1853 let mut buf = Cursor::new(&b"12\n\n"[..]);
1854 let mut v = String::new();
1855 assert_eq!(buf.read_line(&mut v).unwrap(), 3);
1856 assert_eq!(v, "12\n");
1858 assert_eq!(buf.read_line(&mut v).unwrap(), 1);
1859 assert_eq!(v, "\n");
1861 assert_eq!(buf.read_line(&mut v).unwrap(), 0);
1867 let buf = Cursor::new(&b"12\r"[..]);
1868 let mut s = buf.lines();
1869 assert_eq!(s.next().unwrap().unwrap(), "12\r".to_string());
1870 assert!(s.next().is_none());
1872 let buf = Cursor::new(&b"12\r\n\n"[..]);
1873 let mut s = buf.lines();
1874 assert_eq!(s.next().unwrap().unwrap(), "12".to_string());
1875 assert_eq!(s.next().unwrap().unwrap(), "".to_string());
1876 assert!(s.next().is_none());
1881 let mut c = Cursor::new(&b""[..]);
1882 let mut v = Vec::new();
1883 assert_eq!(c.read_to_end(&mut v).unwrap(), 0);
1886 let mut c = Cursor::new(&b"1"[..]);
1887 let mut v = Vec::new();
1888 assert_eq!(c.read_to_end(&mut v).unwrap(), 1);
1889 assert_eq!(v, b"1");
1891 let cap = 1024 * 1024;
1892 let data = (0..cap).map(|i| (i / 3) as u8).collect::<Vec<_>>();
1893 let mut v = Vec::new();
1894 let (a, b) = data.split_at(data.len() / 2);
1895 assert_eq!(Cursor::new(a).read_to_end(&mut v).unwrap(), a.len());
1896 assert_eq!(Cursor::new(b).read_to_end(&mut v).unwrap(), b.len());
1897 assert_eq!(v, data);
1901 fn read_to_string() {
1902 let mut c = Cursor::new(&b""[..]);
1903 let mut v = String::new();
1904 assert_eq!(c.read_to_string(&mut v).unwrap(), 0);
1907 let mut c = Cursor::new(&b"1"[..]);
1908 let mut v = String::new();
1909 assert_eq!(c.read_to_string(&mut v).unwrap(), 1);
1912 let mut c = Cursor::new(&b"\xff"[..]);
1913 let mut v = String::new();
1914 assert!(c.read_to_string(&mut v).is_err());
1919 let mut buf = [0; 4];
1921 let mut c = Cursor::new(&b""[..]);
1922 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1923 io::ErrorKind::UnexpectedEof);
1925 let mut c = Cursor::new(&b"123"[..]).chain(Cursor::new(&b"456789"[..]));
1926 c.read_exact(&mut buf).unwrap();
1927 assert_eq!(&buf, b"1234");
1928 c.read_exact(&mut buf).unwrap();
1929 assert_eq!(&buf, b"5678");
1930 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1931 io::ErrorKind::UnexpectedEof);
1935 fn read_exact_slice() {
1936 let mut buf = [0; 4];
1938 let mut c = &b""[..];
1939 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1940 io::ErrorKind::UnexpectedEof);
1942 let mut c = &b"123"[..];
1943 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1944 io::ErrorKind::UnexpectedEof);
1945 // make sure the optimized (early returning) method is being used
1946 assert_eq!(&buf, &[0; 4]);
1948 let mut c = &b"1234"[..];
1949 c.read_exact(&mut buf).unwrap();
1950 assert_eq!(&buf, b"1234");
1952 let mut c = &b"56789"[..];
1953 c.read_exact(&mut buf).unwrap();
1954 assert_eq!(&buf, b"5678");
1955 assert_eq!(c, b"9");
1963 fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
1964 Err(io::Error::new(io::ErrorKind::Other, ""))
1967 impl BufRead for R {
1968 fn fill_buf(&mut self) -> io::Result<&[u8]> {
1969 Err(io::Error::new(io::ErrorKind::Other, ""))
1971 fn consume(&mut self, _amt: usize) { }
1974 let mut buf = [0; 1];
1975 assert_eq!(0, R.take(0).read(&mut buf).unwrap());
1976 assert_eq!(b"", R.take(0).fill_buf().unwrap());
1979 fn cmp_bufread<Br1: BufRead, Br2: BufRead>(mut br1: Br1, mut br2: Br2, exp: &[u8]) {
1980 let mut cat = Vec::new();
1983 let buf1 = br1.fill_buf().unwrap();
1984 let buf2 = br2.fill_buf().unwrap();
1985 let minlen = if buf1.len() < buf2.len() { buf1.len() } else { buf2.len() };
1986 assert_eq!(buf1[..minlen], buf2[..minlen]);
1987 cat.extend_from_slice(&buf1[..minlen]);
1993 br1.consume(consume);
1994 br2.consume(consume);
1996 assert_eq!(br1.fill_buf().unwrap().len(), 0);
1997 assert_eq!(br2.fill_buf().unwrap().len(), 0);
1998 assert_eq!(&cat[..], &exp[..])
2002 fn chain_bufread() {
2003 let testdata = b"ABCDEFGHIJKL";
2004 let chain1 = (&testdata[..3]).chain(&testdata[3..6])
2005 .chain(&testdata[6..9])
2006 .chain(&testdata[9..]);
2007 let chain2 = (&testdata[..4]).chain(&testdata[4..8])
2008 .chain(&testdata[8..]);
2009 cmp_bufread(chain1, chain2, &testdata[..]);
2013 fn chain_zero_length_read_is_not_eof() {
2016 let mut s = String::new();
2017 let mut chain = (&a[..]).chain(&b[..]);
2018 chain.read(&mut []).unwrap();
2019 chain.read_to_string(&mut s).unwrap();
2020 assert_eq!("AB", s);
2024 #[cfg_attr(target_os = "emscripten", ignore)]
2025 fn bench_read_to_end(b: &mut test::Bencher) {
2027 let mut lr = repeat(1).take(10000000);
2028 let mut vec = Vec::with_capacity(1024);
2029 super::read_to_end(&mut lr, &mut vec)