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`][read] and [`Write`][write] traits, which provide the
16 //! most general interface for reading and writing input and output.
18 //! [read]: trait.Read.html
19 //! [write]: trait.Write.html
23 //! Because they are traits, they're implemented by a number of other types,
24 //! and you can implement them for your types too. As such, you'll see a
25 //! few different types of I/O throughout the documentation in this module:
26 //! `File`s, `TcpStream`s, and somtimes even `Vec<T>`s. For example, `Read`
27 //! adds a `read()` method, which we can use on `File`s:
31 //! use std::io::prelude::*;
32 //! use std::fs::File;
34 //! # fn foo() -> io::Result<()> {
35 //! let mut f = try!(File::open("foo.txt"));
36 //! let mut buffer = [0; 10];
38 //! // read up to 10 bytes
39 //! try!(f.read(&mut buffer));
41 //! println!("The bytes: {:?}", buffer);
46 //! `Read` and `Write` are so important, implementors of the two traits have a
47 //! nickname: readers and writers. So you'll sometimes see 'a reader' instead
48 //! of 'a type that implements the `Read` trait'. Much easier!
50 //! ## Seek and BufRead
52 //! Beyond that, there are two important traits that are provided: [`Seek`][seek]
53 //! and [`BufRead`][bufread]. Both of these build on top of a reader to control
54 //! how the reading happens. `Seek` lets you control where the next byte is
59 //! use std::io::prelude::*;
60 //! use std::io::SeekFrom;
61 //! use std::fs::File;
63 //! # fn foo() -> io::Result<()> {
64 //! let mut f = try!(File::open("foo.txt"));
65 //! let mut buffer = [0; 10];
67 //! // skip to the last 10 bytes of the file
68 //! try!(f.seek(SeekFrom::End(-10)));
70 //! // read up to 10 bytes
71 //! try!(f.read(&mut buffer));
73 //! println!("The bytes: {:?}", buffer);
78 //! [seek]: trait.Seek.html
79 //! [bufread]: trait.BufRead.html
81 //! `BufRead` uses an internal buffer to provide a number of other ways to read, but
82 //! to show it off, we'll need to talk about buffers in general. Keep reading!
84 //! ## BufReader and BufWriter
86 //! Byte-based interfaces are unwieldy and can be inefficient, as we'd need to be
87 //! making near-constant calls to the operating system. To help with this,
88 //! `std::io` comes with two structs, `BufReader` and `BufWriter`, which wrap
89 //! readers and writers. The wrapper uses a buffer, reducing the number of
90 //! calls and providing nicer methods for accessing exactly what you want.
92 //! For example, `BufReader` works with the `BufRead` trait to add extra
93 //! methods to any reader:
97 //! use std::io::prelude::*;
98 //! use std::io::BufReader;
99 //! use std::fs::File;
101 //! # fn foo() -> io::Result<()> {
102 //! let f = try!(File::open("foo.txt"));
103 //! let mut reader = BufReader::new(f);
104 //! let mut buffer = String::new();
106 //! // read a line into buffer
107 //! try!(reader.read_line(&mut buffer));
109 //! println!("{}", buffer);
114 //! `BufWriter` doesn't add any new ways of writing, it just buffers every call
115 //! to [`write()`][write]:
119 //! use std::io::prelude::*;
120 //! use std::io::BufWriter;
121 //! use std::fs::File;
123 //! # fn foo() -> io::Result<()> {
124 //! let f = try!(File::create("foo.txt"));
126 //! let mut writer = BufWriter::new(f);
128 //! // write a byte to the buffer
129 //! try!(writer.write(&[42]));
131 //! } // the buffer is flushed once writer goes out of scope
137 //! [write]: trait.Write.html#tymethod.write
139 //! ## Standard input and output
141 //! A very common source of input is standard input:
146 //! # fn foo() -> io::Result<()> {
147 //! let mut input = String::new();
149 //! try!(io::stdin().read_line(&mut input));
151 //! println!("You typed: {}", input.trim());
156 //! And a very common source of output is standard output:
160 //! use std::io::prelude::*;
162 //! # fn foo() -> io::Result<()> {
163 //! try!(io::stdout().write(&[42]));
168 //! Of course, using `io::stdout()` directly is less comon than something like
171 //! ## Iterator types
173 //! A large number of the structures provided by `std::io` are for various
174 //! ways of iterating over I/O. For example, `Lines` is used to split over
179 //! use std::io::prelude::*;
180 //! use std::io::BufReader;
181 //! use std::fs::File;
183 //! # fn foo() -> io::Result<()> {
184 //! let f = try!(File::open("foo.txt"));
185 //! let mut reader = BufReader::new(f);
187 //! for line in reader.lines() {
188 //! let line = try!(line);
189 //! println!("{}", line);
198 //! There are a number of [functions][functions] that offer access to various
199 //! features. For example, we can use three of these functions to copy everything
200 //! from standard input to standard output:
205 //! # fn foo() -> io::Result<()> {
206 //! try!(io::copy(&mut io::stdin(), &mut io::stdout()));
211 //! [functions]: #functions
215 //! Last, but certainly not least, is [`io::Result`][result]. This type is used
216 //! as the return type of many `std::io` functions that can cause an error, and
217 //! can be returned from your own functions as well. Many of the examples in this
218 //! module use the [`try!`][try] macro:
223 //! fn read_input() -> io::Result<()> {
224 //! let mut input = String::new();
226 //! try!(io::stdin().read_line(&mut input));
228 //! println!("You typed: {}", input.trim());
234 //! The return type of `read_input()`, `io::Result<()>`, is a very common type
235 //! for functions which don't have a 'real' return value, but do want to return
236 //! errors if they happen. In this case, the only purpose of this function is
237 //! to read the line and print it, so we use use `()`.
239 //! [result]: type.Result.html
240 //! [try]: macro.try!.html
242 #![stable(feature = "rust1", since = "1.0.0")]
245 use rustc_unicode
::str as core_str
;
246 use error
as std_error
;
248 use iter
::{Iterator}
;
250 use ops
::{Drop, FnOnce}
;
251 use option
::Option
::{self, Some, None}
;
252 use result
::Result
::{Ok, Err}
;
258 pub use self::buffered
::{BufReader, BufWriter, BufStream, LineWriter}
;
259 pub use self::buffered
::IntoInnerError
;
260 pub use self::cursor
::Cursor
;
261 pub use self::error
::{Result, Error, ErrorKind}
;
262 pub use self::util
::{copy, sink, Sink, empty, Empty, repeat, Repeat}
;
263 pub use self::stdio
::{stdin, stdout, stderr, _print, Stdin, Stdout, Stderr}
;
264 pub use self::stdio
::{StdoutLock, StderrLock, StdinLock}
;
265 #[doc(no_inline, hidden)]
266 pub use self::stdio
::{set_panic, set_print}
;
277 const DEFAULT_BUF_SIZE
: usize = 64 * 1024;
279 // A few methods below (read_to_string, read_line) will append data into a
280 // `String` buffer, but we need to be pretty careful when doing this. The
281 // implementation will just call `.as_mut_vec()` and then delegate to a
282 // byte-oriented reading method, but we must ensure that when returning we never
283 // leave `buf` in a state such that it contains invalid UTF-8 in its bounds.
285 // To this end, we use an RAII guard (to protect against panics) which updates
286 // the length of the string when it is dropped. This guard initially truncates
287 // the string to the prior length and only after we've validated that the
288 // new contents are valid UTF-8 do we allow it to set a longer length.
290 // The unsafety in this function is twofold:
292 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
294 // 2. We're passing a raw buffer to the function `f`, and it is expected that
295 // the function only *appends* bytes to the buffer. We'll get undefined
296 // behavior if existing bytes are overwritten to have non-UTF-8 data.
297 fn append_to_string
<F
>(buf
: &mut String
, f
: F
) -> Result
<usize>
298 where F
: FnOnce(&mut Vec
<u8>) -> Result
<usize>
300 struct Guard
<'a
> { s: &'a mut Vec<u8>, len: usize }
301 impl<'a
> Drop
for Guard
<'a
> {
303 unsafe { self.s.set_len(self.len); }
308 let mut g
= Guard { len: buf.len(), s: buf.as_mut_vec() }
;
310 if str::from_utf8(&g
.s
[g
.len
..]).is_err() {
312 Err(Error
::new(ErrorKind
::InvalidData
,
313 "stream did not contain valid UTF-8"))
322 // This uses an adaptive system to extend the vector when it fills. We want to
323 // avoid paying to allocate and zero a huge chunk of memory if the reader only
324 // has 4 bytes while still making large reads if the reader does have a ton
325 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
326 // time is 4,500 times (!) slower than this if the reader has a very small
327 // amount of data to return.
328 fn read_to_end
<R
: Read
+ ?Sized
>(r
: &mut R
, buf
: &mut Vec
<u8>) -> Result
<usize> {
329 let start_len
= buf
.len();
330 let mut len
= start_len
;
331 let mut new_write_size
= 16;
334 if len
== buf
.len() {
335 if new_write_size
< DEFAULT_BUF_SIZE
{
338 buf
.resize(len
+ new_write_size
, 0);
341 match r
.read(&mut buf
[len
..]) {
343 ret
= Ok(len
- start_len
);
347 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> {}
359 /// The `Read` trait allows for reading bytes from a source.
361 /// Implementors of the `Read` trait are sometimes called 'readers'.
363 /// Readers are defined by one required method, `read()`. Each call to `read`
364 /// will attempt to pull bytes from this source into a provided buffer. A
365 /// number of other methods are implemented in terms of `read()`, giving
366 /// implementors a number of ways to read bytes while only needing to implement
369 /// Readers are intended to be composable with one another. Many implementors
370 /// throughout `std::io` take and provide types which implement the `Read`
375 /// [`File`][file]s implement `Read`:
377 /// [file]: ../std/fs/struct.File.html
381 /// use std::io::prelude::*;
382 /// use std::fs::File;
384 /// # fn foo() -> io::Result<()> {
385 /// let mut f = try!(File::open("foo.txt"));
386 /// let mut buffer = [0; 10];
388 /// // read up to 10 bytes
389 /// try!(f.read(&mut buffer));
391 /// let mut buffer = vec![0; 10];
392 /// // read the whole file
393 /// try!(f.read_to_end(&mut buffer));
395 /// // read into a String, so that you don't need to do the conversion.
396 /// let mut buffer = String::new();
397 /// try!(f.read_to_string(&mut buffer));
399 /// // and more! See the other methods for more details.
403 #[stable(feature = "rust1", since = "1.0.0")]
405 /// Pull some bytes from this source into the specified buffer, returning
406 /// how many bytes were read.
408 /// This function does not provide any guarantees about whether it blocks
409 /// waiting for data, but if an object needs to block for a read but cannot
410 /// it will typically signal this via an `Err` return value.
412 /// If the return value of this method is `Ok(n)`, then it must be
413 /// guaranteed that `0 <= n <= buf.len()`. A nonzero `n` value indicates
414 /// that the buffer `buf` has been filled in with `n` bytes of data from this
415 /// source. If `n` is `0`, then it can indicate one of two scenarios:
417 /// 1. This reader has reached its "end of file" and will likely no longer
418 /// be able to produce bytes. Note that this does not mean that the
419 /// reader will *always* no longer be able to produce bytes.
420 /// 2. The buffer specified was 0 bytes in length.
422 /// No guarantees are provided about the contents of `buf` when this
423 /// function is called, implementations cannot rely on any property of the
424 /// contents of `buf` being true. It is recommended that implementations
425 /// only write data to `buf` instead of reading its contents.
429 /// If this function encounters any form of I/O or other error, an error
430 /// variant will be returned. If an error is returned then it must be
431 /// guaranteed that no bytes were read.
435 /// [`File`][file]s implement `Read`:
437 /// [file]: ../std/fs/struct.File.html
441 /// use std::io::prelude::*;
442 /// use std::fs::File;
444 /// # fn foo() -> io::Result<()> {
445 /// let mut f = try!(File::open("foo.txt"));
446 /// let mut buffer = [0; 10];
449 /// try!(f.read(&mut buffer[..]));
453 #[stable(feature = "rust1", since = "1.0.0")]
454 fn read(&mut self, buf
: &mut [u8]) -> Result
<usize>;
456 /// Read all bytes until EOF in this source, placing them into `buf`.
458 /// All bytes read from this source will be appended to the specified buffer
459 /// `buf`. This function will continuously call `read` to append more data to
460 /// `buf` until `read` returns either `Ok(0)` or an error of
461 /// non-`ErrorKind::Interrupted` kind.
463 /// If successful, this function will return the total number of bytes read.
467 /// If this function encounters an error of the kind
468 /// `ErrorKind::Interrupted` then the error is ignored and the operation
471 /// If any other read error is encountered then this function immediately
472 /// returns. Any bytes which have already been read will be appended to
477 /// [`File`][file]s implement `Read`:
479 /// [file]: ../std/fs/struct.File.html
483 /// use std::io::prelude::*;
484 /// use std::fs::File;
486 /// # fn foo() -> io::Result<()> {
487 /// let mut f = try!(File::open("foo.txt"));
488 /// let mut buffer = Vec::new();
490 /// // read the whole file
491 /// try!(f.read_to_end(&mut buffer));
495 #[stable(feature = "rust1", since = "1.0.0")]
496 fn read_to_end(&mut self, buf
: &mut Vec
<u8>) -> Result
<usize> {
497 read_to_end(self, buf
)
500 /// Read all bytes until EOF in this source, placing them into `buf`.
502 /// If successful, this function returns the number of bytes which were read
503 /// and appended to `buf`.
507 /// If the data in this stream is *not* valid UTF-8 then an error is
508 /// returned and `buf` is unchanged.
510 /// See [`read_to_end()`][readtoend] for other error semantics.
512 /// [readtoend]: #method.read_to_end
516 /// [`File`][file]s implement `Read`:
518 /// [file]: ../std/fs/struct.File.html
522 /// use std::io::prelude::*;
523 /// use std::fs::File;
525 /// # fn foo() -> io::Result<()> {
526 /// let mut f = try!(File::open("foo.txt"));
527 /// let mut buffer = String::new();
529 /// try!(f.read_to_string(&mut buffer));
533 #[stable(feature = "rust1", since = "1.0.0")]
534 fn read_to_string(&mut self, buf
: &mut String
) -> Result
<usize> {
535 // Note that we do *not* call `.read_to_end()` here. We are passing
536 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
537 // method to fill it up. An arbitrary implementation could overwrite the
538 // entire contents of the vector, not just append to it (which is what
539 // we are expecting).
541 // To prevent extraneously checking the UTF-8-ness of the entire buffer
542 // we pass it to our hardcoded `read_to_end` implementation which we
543 // know is guaranteed to only read data into the end of the buffer.
544 append_to_string(buf
, |b
| read_to_end(self, b
))
547 /// Creates a "by reference" adaptor for this instance of `Read`.
549 /// The returned adaptor also implements `Read` and will simply borrow this
554 /// [`File`][file]s implement `Read`:
556 /// [file]: ../std/fs/struct.File.html
560 /// use std::io::Read;
561 /// use std::fs::File;
563 /// # fn foo() -> io::Result<()> {
564 /// let mut f = try!(File::open("foo.txt"));
565 /// let mut buffer = Vec::new();
566 /// let mut other_buffer = Vec::new();
569 /// let reference = f.by_ref();
571 /// // read at most 5 bytes
572 /// try!(reference.take(5).read_to_end(&mut buffer));
574 /// } // drop our &mut reference so we can use f again
576 /// // original file still usable, read the rest
577 /// try!(f.read_to_end(&mut other_buffer));
581 #[stable(feature = "rust1", since = "1.0.0")]
582 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
584 /// Transforms this `Read` instance to an `Iterator` over its bytes.
586 /// The returned type implements `Iterator` where the `Item` is `Result<u8,
587 /// R::Err>`. The yielded item is `Ok` if a byte was successfully read and
588 /// `Err` otherwise for I/O errors. EOF is mapped to returning `None` from
593 /// [`File`][file]s implement `Read`:
595 /// [file]: ../std/fs/struct.File.html
599 /// use std::io::prelude::*;
600 /// use std::fs::File;
602 /// # fn foo() -> io::Result<()> {
603 /// let mut f = try!(File::open("foo.txt"));
605 /// for byte in f.bytes() {
606 /// println!("{}", byte.unwrap());
611 #[stable(feature = "rust1", since = "1.0.0")]
612 fn bytes(self) -> Bytes
<Self> where Self: Sized
{
613 Bytes { inner: self }
616 /// Transforms this `Read` instance to an `Iterator` over `char`s.
618 /// This adaptor will attempt to interpret this reader as a UTF-8 encoded
619 /// sequence of characters. The returned iterator will return `None` once
620 /// EOF is reached for this reader. Otherwise each element yielded will be a
621 /// `Result<char, E>` where `E` may contain information about what I/O error
622 /// occurred or where decoding failed.
624 /// Currently this adaptor will discard intermediate data read, and should
625 /// be avoided if this is not desired.
629 /// [`File`][file]s implement `Read`:
631 /// [file]: ../std/fs/struct.File.html
636 /// use std::io::prelude::*;
637 /// use std::fs::File;
639 /// # fn foo() -> io::Result<()> {
640 /// let mut f = try!(File::open("foo.txt"));
642 /// for c in f.chars() {
643 /// println!("{}", c.unwrap());
648 #[unstable(feature = "io", reason = "the semantics of a partial read/write \
649 of where errors happen is currently \
650 unclear and may change")]
651 fn chars(self) -> Chars
<Self> where Self: Sized
{
652 Chars { inner: self }
655 /// Creates an adaptor which will chain this stream with another.
657 /// The returned `Read` instance will first read all bytes from this object
658 /// until EOF is encountered. Afterwards the output is equivalent to the
659 /// output of `next`.
663 /// [`File`][file]s implement `Read`:
665 /// [file]: ../std/fs/struct.File.html
669 /// use std::io::prelude::*;
670 /// use std::fs::File;
672 /// # fn foo() -> io::Result<()> {
673 /// let mut f1 = try!(File::open("foo.txt"));
674 /// let mut f2 = try!(File::open("bar.txt"));
676 /// let mut handle = f1.chain(f2);
677 /// let mut buffer = String::new();
679 /// // read the value into a String. We could use any Read method here,
680 /// // this is just one example.
681 /// try!(handle.read_to_string(&mut buffer));
685 #[stable(feature = "rust1", since = "1.0.0")]
686 fn chain
<R
: Read
>(self, next
: R
) -> Chain
<Self, R
> where Self: Sized
{
687 Chain { first: self, second: next, done_first: false }
690 /// Creates an adaptor which will read at most `limit` bytes from it.
692 /// This function returns a new instance of `Read` which will read at most
693 /// `limit` bytes, after which it will always return EOF (`Ok(0)`). Any
694 /// read errors will not count towards the number of bytes read and future
695 /// calls to `read` may succeed.
699 /// [`File`][file]s implement `Read`:
701 /// [file]: ../std/fs/struct.File.html
705 /// use std::io::prelude::*;
706 /// use std::fs::File;
708 /// # fn foo() -> io::Result<()> {
709 /// let mut f = try!(File::open("foo.txt"));
710 /// let mut buffer = [0; 5];
712 /// // read at most five bytes
713 /// let mut handle = f.take(5);
715 /// try!(handle.read(&mut buffer));
719 #[stable(feature = "rust1", since = "1.0.0")]
720 fn take(self, limit
: u64) -> Take
<Self> where Self: Sized
{
721 Take { inner: self, limit: limit }
724 /// Creates a reader adaptor which will write all read data into the given
727 /// Whenever the returned `Read` instance is read it will write the read
728 /// data to `out`. The current semantics of this implementation imply that
729 /// a `write` error will not report how much data was initially read.
733 /// [`File`][file]s implement `Read`:
735 /// [file]: ../std/fs/struct.File.html
740 /// use std::io::prelude::*;
741 /// use std::fs::File;
743 /// # fn foo() -> io::Result<()> {
744 /// let mut f = try!(File::open("foo.txt"));
745 /// let mut buffer1 = Vec::with_capacity(10);
746 /// let mut buffer2 = Vec::with_capacity(10);
748 /// // write the output to buffer1 as we read
749 /// let mut handle = f.tee(&mut buffer1);
751 /// try!(handle.read(&mut buffer2));
755 #[unstable(feature = "io", reason = "the semantics of a partial read/write \
756 of where errors happen is currently \
757 unclear and may change")]
758 fn tee
<W
: Write
>(self, out
: W
) -> Tee
<Self, W
> where Self: Sized
{
759 Tee { reader: self, writer: out }
763 /// A trait for objects which are byte-oriented sinks.
765 /// Implementors of the `Write` trait are sometimes called 'writers'.
767 /// Writers are defined by two required methods, `write()` and `flush()`:
769 /// * The `write()` method will attempt to write some data into the object,
770 /// returning how many bytes were successfully written.
772 /// * The `flush()` method is useful for adaptors and explicit buffers
773 /// themselves for ensuring that all buffered data has been pushed out to the
776 /// Writers are intended to be composable with one another. Many implementors
777 /// throughout `std::io` take and provide types which implement the `Write`
783 /// use std::io::prelude::*;
784 /// use std::fs::File;
786 /// # fn foo() -> std::io::Result<()> {
787 /// let mut buffer = try!(File::create("foo.txt"));
789 /// try!(buffer.write(b"some bytes"));
793 #[stable(feature = "rust1", since = "1.0.0")]
795 /// Write a buffer into this object, returning how many bytes were written.
797 /// This function will attempt to write the entire contents of `buf`, but
798 /// the entire write may not succeed, or the write may also generate an
799 /// error. A call to `write` represents *at most one* attempt to write to
800 /// any wrapped object.
802 /// Calls to `write` are not guaranteed to block waiting for data to be
803 /// written, and a write which would otherwise block can be indicated through
804 /// an `Err` variant.
806 /// If the return value is `Ok(n)` then it must be guaranteed that
807 /// `0 <= n <= buf.len()`. A return value of `0` typically means that the
808 /// underlying object is no longer able to accept bytes and will likely not
809 /// be able to in the future as well, or that the buffer provided is empty.
813 /// Each call to `write` may generate an I/O error indicating that the
814 /// operation could not be completed. If an error is returned then no bytes
815 /// in the buffer were written to this writer.
817 /// It is **not** considered an error if the entire buffer could not be
818 /// written to this writer.
823 /// use std::io::prelude::*;
824 /// use std::fs::File;
826 /// # fn foo() -> std::io::Result<()> {
827 /// let mut buffer = try!(File::create("foo.txt"));
829 /// try!(buffer.write(b"some bytes"));
833 #[stable(feature = "rust1", since = "1.0.0")]
834 fn write(&mut self, buf
: &[u8]) -> Result
<usize>;
836 /// Flush this output stream, ensuring that all intermediately buffered
837 /// contents reach their destination.
841 /// It is considered an error if not all bytes could be written due to
842 /// I/O errors or EOF being reached.
847 /// use std::io::prelude::*;
848 /// use std::io::BufWriter;
849 /// use std::fs::File;
851 /// # fn foo() -> std::io::Result<()> {
852 /// let mut buffer = BufWriter::new(try!(File::create("foo.txt")));
854 /// try!(buffer.write(b"some bytes"));
855 /// try!(buffer.flush());
859 #[stable(feature = "rust1", since = "1.0.0")]
860 fn flush(&mut self) -> Result
<()>;
862 /// Attempts to write an entire buffer into this write.
864 /// This method will continuously call `write` while there is more data to
865 /// write. This method will not return until the entire buffer has been
866 /// successfully written or an error occurs. The first error generated from
867 /// this method will be returned.
871 /// This function will return the first error that `write` returns.
876 /// use std::io::prelude::*;
877 /// use std::fs::File;
879 /// # fn foo() -> std::io::Result<()> {
880 /// let mut buffer = try!(File::create("foo.txt"));
882 /// try!(buffer.write_all(b"some bytes"));
886 #[stable(feature = "rust1", since = "1.0.0")]
887 fn write_all(&mut self, mut buf
: &[u8]) -> Result
<()> {
888 while !buf
.is_empty() {
889 match self.write(buf
) {
890 Ok(0) => return Err(Error
::new(ErrorKind
::WriteZero
,
891 "failed to write whole buffer")),
892 Ok(n
) => buf
= &buf
[n
..],
893 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> {}
894 Err(e
) => return Err(e
),
900 /// Writes a formatted string into this writer, returning any error
903 /// This method is primarily used to interface with the
904 /// [`format_args!`][formatargs] macro, but it is rare that this should
905 /// explicitly be called. The [`write!`][write] macro should be favored to
906 /// invoke this method instead.
908 /// [formatargs]: ../std/macro.format_args!.html
909 /// [write]: ../std/macro.write!.html
911 /// This function internally uses the [`write_all`][writeall] method on
912 /// this trait and hence will continuously write data so long as no errors
913 /// are received. This also means that partial writes are not indicated in
916 /// [writeall]: #method.write_all
920 /// This function will return any I/O error reported while formatting.
925 /// use std::io::prelude::*;
926 /// use std::fs::File;
928 /// # fn foo() -> std::io::Result<()> {
929 /// let mut buffer = try!(File::create("foo.txt"));
932 /// try!(write!(buffer, "{:.*}", 2, 1.234567));
933 /// // turns into this:
934 /// try!(buffer.write_fmt(format_args!("{:.*}", 2, 1.234567)));
938 #[stable(feature = "rust1", since = "1.0.0")]
939 fn write_fmt(&mut self, fmt
: fmt
::Arguments
) -> Result
<()> {
940 // Create a shim which translates a Write to a fmt::Write and saves
941 // off I/O errors. instead of discarding them
942 struct Adaptor
<'a
, T
: ?Sized
+ 'a
> {
947 impl<'a
, T
: Write
+ ?Sized
> fmt
::Write
for Adaptor
<'a
, T
> {
948 fn write_str(&mut self, s
: &str) -> fmt
::Result
{
949 match self.inner
.write_all(s
.as_bytes()) {
959 let mut output
= Adaptor { inner: self, error: Ok(()) }
;
960 match fmt
::write(&mut output
, fmt
) {
962 Err(..) => output
.error
966 /// Creates a "by reference" adaptor for this instance of `Write`.
968 /// The returned adaptor also implements `Write` and will simply borrow this
974 /// use std::io::Write;
975 /// use std::fs::File;
977 /// # fn foo() -> std::io::Result<()> {
978 /// let mut buffer = try!(File::create("foo.txt"));
980 /// let reference = buffer.by_ref();
982 /// // we can use reference just like our original buffer
983 /// try!(reference.write_all(b"some bytes"));
987 #[stable(feature = "rust1", since = "1.0.0")]
988 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
990 /// Creates a new writer which will write all data to both this writer and
993 /// All data written to the returned writer will both be written to `self`
994 /// as well as `other`. Note that the error semantics of the current
995 /// implementation do not precisely track where errors happen. For example
996 /// an error on the second call to `write` will not report that the first
997 /// call to `write` succeeded.
1003 /// use std::io::prelude::*;
1004 /// use std::fs::File;
1006 /// # fn foo() -> std::io::Result<()> {
1007 /// let mut buffer1 = try!(File::create("foo.txt"));
1008 /// let mut buffer2 = Vec::new();
1010 /// // write the output to buffer1 as we read
1011 /// let mut handle = buffer1.broadcast(&mut buffer2);
1013 /// try!(handle.write(b"some bytes"));
1017 #[unstable(feature = "io", reason = "the semantics of a partial read/write \
1018 of where errors happen is currently \
1019 unclear and may change")]
1020 fn broadcast
<W
: Write
>(self, other
: W
) -> Broadcast
<Self, W
>
1023 Broadcast { first: self, second: other }
1027 /// The `Seek` trait provides a cursor which can be moved within a stream of
1030 /// The stream typically has a fixed size, allowing seeking relative to either
1031 /// end or the current offset.
1035 /// [`File`][file]s implement `Seek`:
1037 /// [file]: ../std/fs/struct.File.html
1041 /// use std::io::prelude::*;
1042 /// use std::fs::File;
1043 /// use std::io::SeekFrom;
1045 /// # fn foo() -> io::Result<()> {
1046 /// let mut f = try!(File::open("foo.txt"));
1048 /// // move the cursor 42 bytes from the start of the file
1049 /// try!(f.seek(SeekFrom::Start(42)));
1053 #[stable(feature = "rust1", since = "1.0.0")]
1055 /// Seek to an offset, in bytes, in a stream.
1057 /// A seek beyond the end of a stream is allowed, but implementation
1060 /// The behavior when seeking past the end of the stream is implementation
1063 /// If the seek operation completed successfully,
1064 /// this method returns the new position from the start of the stream.
1065 /// That position can be used later with `SeekFrom::Start`.
1069 /// Seeking to a negative offset is considered an error.
1070 #[stable(feature = "rust1", since = "1.0.0")]
1071 fn seek(&mut self, pos
: SeekFrom
) -> Result
<u64>;
1074 /// Enumeration of possible methods to seek within an I/O object.
1075 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1076 #[stable(feature = "rust1", since = "1.0.0")]
1078 /// Set the offset to the provided number of bytes.
1079 #[stable(feature = "rust1", since = "1.0.0")]
1082 /// Set the offset to the size of this object plus the specified number of
1085 /// It is possible to seek beyond the end of an object, but is an error to
1086 /// seek before byte 0.
1087 #[stable(feature = "rust1", since = "1.0.0")]
1090 /// Set the offset to the current position plus the specified number of
1093 /// It is possible to seek beyond the end of an object, but is an error to
1094 /// seek before byte 0.
1095 #[stable(feature = "rust1", since = "1.0.0")]
1099 fn read_until
<R
: BufRead
+ ?Sized
>(r
: &mut R
, delim
: u8, buf
: &mut Vec
<u8>)
1103 let (done
, used
) = {
1104 let available
= match r
.fill_buf() {
1106 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> continue,
1107 Err(e
) => return Err(e
)
1109 match available
.iter().position(|x
| *x
== delim
) {
1111 buf
.push_all(&available
[..i
+ 1]);
1115 buf
.push_all(available
);
1116 (false, available
.len())
1122 if done
|| used
== 0 {
1128 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1129 /// to perform extra ways of reading.
1131 /// For example, reading line-by-line is inefficient without using a buffer, so
1132 /// if you want to read by line, you'll need `BufRead`, which includes a
1133 /// [`read_line()`][readline] method as well as a [`lines()`][lines] iterator.
1135 /// [readline]: #method.read_line
1136 /// [lines]: #method.lines
1140 /// A locked standard input implements `BufRead`:
1144 /// use std::io::prelude::*;
1146 /// let stdin = io::stdin();
1147 /// for line in stdin.lock().lines() {
1148 /// println!("{}", line.unwrap());
1152 /// If you have something that implements `Read`, you can use the [`BufReader`
1153 /// type][bufreader] to turn it into a `BufRead`.
1155 /// For example, [`File`][file] implements `Read`, but not `BufRead`.
1156 /// `BufReader` to the rescue!
1158 /// [bufreader]: struct.BufReader.html
1159 /// [file]: ../fs/struct.File.html
1162 /// use std::io::{self, BufReader};
1163 /// use std::io::prelude::*;
1164 /// use std::fs::File;
1166 /// # fn foo() -> io::Result<()> {
1167 /// let f = try!(File::open("foo.txt"));
1168 /// let f = BufReader::new(f);
1170 /// for line in f.lines() {
1171 /// println!("{}", line.unwrap());
1178 #[stable(feature = "rust1", since = "1.0.0")]
1179 pub trait BufRead
: Read
{
1180 /// Fills the internal buffer of this object, returning the buffer contents.
1182 /// This function is a lower-level call. It needs to be paired with the
1183 /// [`consume`][consume] method to function properly. When calling this
1184 /// method, none of the contents will be "read" in the sense that later
1185 /// calling `read` may return the same contents. As such, `consume` must be
1186 /// called with the number of bytes that are consumed from this buffer to
1187 /// ensure that the bytes are never returned twice.
1189 /// [consume]: #tymethod.consume
1191 /// An empty buffer returned indicates that the stream has reached EOF.
1195 /// This function will return an I/O error if the underlying reader was
1196 /// read, but returned an error.
1200 /// A locked standard input implements `BufRead`:
1204 /// use std::io::prelude::*;
1206 /// let stdin = io::stdin();
1207 /// let mut stdin = stdin.lock();
1209 /// // we can't have two `&mut` references to `stdin`, so use a block
1210 /// // to end the borrow early.
1212 /// let buffer = stdin.fill_buf().unwrap();
1214 /// // work with buffer
1215 /// println!("{:?}", buffer);
1220 /// // ensure the bytes we worked with aren't returned again later
1221 /// stdin.consume(length);
1223 #[stable(feature = "rust1", since = "1.0.0")]
1224 fn fill_buf(&mut self) -> Result
<&[u8]>;
1226 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1227 /// so they should no longer be returned in calls to `read`.
1229 /// This function is a lower-level call. It needs to be paired with the
1230 /// [`fill_buf`][fillbuf] method to function properly. This function does
1231 /// not perform any I/O, it simply informs this object that some amount of
1232 /// its buffer, returned from `fill_buf`, has been consumed and should no
1233 /// longer be returned. As such, this function may do odd things if
1234 /// `fill_buf` isn't called before calling it.
1236 /// [fillbuf]: #tymethod.fill_buff
1238 /// The `amt` must be `<=` the number of bytes in the buffer returned by
1243 /// Since `consume()` is meant to be used with [`fill_buf()`][fillbuf],
1244 /// that method's example includes an example of `consume()`.
1245 #[stable(feature = "rust1", since = "1.0.0")]
1246 fn consume(&mut self, amt
: usize);
1248 /// Read all bytes into `buf` until the delimiter `byte` is reached.
1250 /// This function will read bytes from the underlying stream until the
1251 /// delimiter or EOF is found. Once found, all bytes up to, and including,
1252 /// the delimiter (if found) will be appended to `buf`.
1254 /// If this reader is currently at EOF then this function will not modify
1255 /// `buf` and will return `Ok(n)` where `n` is the number of bytes which
1260 /// This function will ignore all instances of `ErrorKind::Interrupted` and
1261 /// will otherwise return any errors returned by `fill_buf`.
1263 /// If an I/O error is encountered then all bytes read so far will be
1264 /// present in `buf` and its length will have been adjusted appropriately.
1268 /// A locked standard input implements `BufRead`. In this example, we'll
1269 /// read from standard input until we see an `a` byte.
1273 /// use std::io::prelude::*;
1275 /// fn foo() -> io::Result<()> {
1276 /// let stdin = io::stdin();
1277 /// let mut stdin = stdin.lock();
1278 /// let mut buffer = Vec::new();
1280 /// try!(stdin.read_until(b'a', &mut buffer));
1282 /// println!("{:?}", buffer);
1286 #[stable(feature = "rust1", since = "1.0.0")]
1287 fn read_until(&mut self, byte
: u8, buf
: &mut Vec
<u8>) -> Result
<usize> {
1288 read_until(self, byte
, buf
)
1291 /// Read all bytes until a newline (the 0xA byte) is reached, and append
1292 /// them to the provided buffer.
1294 /// This function will read bytes from the underlying stream until the
1295 /// newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes
1296 /// up to, and including, the delimiter (if found) will be appended to
1299 /// If this reader is currently at EOF then this function will not modify
1300 /// `buf` and will return `Ok(n)` where `n` is the number of bytes which
1305 /// This function has the same error semantics as `read_until` and will also
1306 /// return an error if the read bytes are not valid UTF-8. If an I/O error
1307 /// is encountered then `buf` may contain some bytes already read in the
1308 /// event that all data read so far was valid UTF-8.
1312 /// A locked standard input implements `BufRead`. In this example, we'll
1313 /// read all of the lines from standard input. If we were to do this in
1314 /// an actual project, the [`lines()`][lines] method would be easier, of
1317 /// [lines]: #method.lines
1321 /// use std::io::prelude::*;
1323 /// let stdin = io::stdin();
1324 /// let mut stdin = stdin.lock();
1325 /// let mut buffer = String::new();
1327 /// while stdin.read_line(&mut buffer).unwrap() > 0 {
1328 /// // work with buffer
1329 /// println!("{:?}", buffer);
1334 #[stable(feature = "rust1", since = "1.0.0")]
1335 fn read_line(&mut self, buf
: &mut String
) -> Result
<usize> {
1336 // Note that we are not calling the `.read_until` method here, but
1337 // rather our hardcoded implementation. For more details as to why, see
1338 // the comments in `read_to_end`.
1339 append_to_string(buf
, |b
| read_until(self, b'
\n'
, b
))
1342 /// Returns an iterator over the contents of this reader split on the byte
1345 /// The iterator returned from this function will return instances of
1346 /// `io::Result<Vec<u8>>`. Each vector returned will *not* have the
1347 /// delimiter byte at the end.
1349 /// This function will yield errors whenever `read_until` would have also
1350 /// yielded an error.
1354 /// A locked standard input implements `BufRead`. In this example, we'll
1355 /// read some input from standard input, splitting on commas.
1359 /// use std::io::prelude::*;
1361 /// let stdin = io::stdin();
1363 /// for content in stdin.lock().split(b',') {
1364 /// println!("{:?}", content.unwrap());
1367 #[stable(feature = "rust1", since = "1.0.0")]
1368 fn split(self, byte
: u8) -> Split
<Self> where Self: Sized
{
1369 Split { buf: self, delim: byte }
1372 /// Returns an iterator over the lines of this reader.
1374 /// The iterator returned from this function will yield instances of
1375 /// `io::Result<String>`. Each string returned will *not* have a newline
1376 /// byte (the 0xA byte) at the end.
1380 /// A locked standard input implements `BufRead`:
1384 /// use std::io::prelude::*;
1386 /// let stdin = io::stdin();
1388 /// for line in stdin.lock().lines() {
1389 /// println!("{}", line.unwrap());
1392 #[stable(feature = "rust1", since = "1.0.0")]
1393 fn lines(self) -> Lines
<Self> where Self: Sized
{
1398 /// A `Write` adaptor which will write data to multiple locations.
1400 /// This struct is generally created by calling [`broadcast()`][broadcast] on a
1401 /// writer. Please see the documentation of `broadcast()` for more details.
1403 /// [broadcast]: trait.Write.html#method.broadcast
1404 #[unstable(feature = "io", reason = "awaiting stability of Write::broadcast")]
1405 pub struct Broadcast
<T
, U
> {
1410 #[unstable(feature = "io", reason = "awaiting stability of Write::broadcast")]
1411 impl<T
: Write
, U
: Write
> Write
for Broadcast
<T
, U
> {
1412 fn write(&mut self, data
: &[u8]) -> Result
<usize> {
1413 let n
= try
!(self.first
.write(data
));
1414 // FIXME: what if the write fails? (we wrote something)
1415 try
!(self.second
.write_all(&data
[..n
]));
1419 fn flush(&mut self) -> Result
<()> {
1420 self.first
.flush().and(self.second
.flush())
1424 /// Adaptor to chain together two readers.
1426 /// This struct is generally created by calling [`chain()`][chain] on a reader.
1427 /// Please see the documentation of `chain()` for more details.
1429 /// [chain]: trait.Read.html#method.chain
1430 #[stable(feature = "rust1", since = "1.0.0")]
1431 pub struct Chain
<T
, U
> {
1437 #[stable(feature = "rust1", since = "1.0.0")]
1438 impl<T
: Read
, U
: Read
> Read
for Chain
<T
, U
> {
1439 fn read(&mut self, buf
: &mut [u8]) -> Result
<usize> {
1440 if !self.done_first
{
1441 match try
!(self.first
.read(buf
)) {
1442 0 => { self.done_first = true; }
1446 self.second
.read(buf
)
1450 /// Reader adaptor which limits the bytes read from an underlying reader.
1452 /// This struct is generally created by calling [`take()`][take] on a reader.
1453 /// Please see the documentation of `take()` for more details.
1455 /// [take]: trait.Read.html#method.take
1456 #[stable(feature = "rust1", since = "1.0.0")]
1457 pub struct Take
<T
> {
1462 #[stable(feature = "rust1", since = "1.0.0")]
1464 /// Returns the number of bytes that can be read before this instance will
1469 /// This instance may reach EOF after reading fewer bytes than indicated by
1470 /// this method if the underlying `Read` instance reaches EOF.
1471 #[stable(feature = "rust1", since = "1.0.0")]
1472 pub fn limit(&self) -> u64 { self.limit }
1475 #[stable(feature = "rust1", since = "1.0.0")]
1476 impl<T
: Read
> Read
for Take
<T
> {
1477 fn read(&mut self, buf
: &mut [u8]) -> Result
<usize> {
1478 // Don't call into inner reader at all at EOF because it may still block
1479 if self.limit
== 0 {
1483 let max
= cmp
::min(buf
.len() as u64, self.limit
) as usize;
1484 let n
= try
!(self.inner
.read(&mut buf
[..max
]));
1485 self.limit
-= n
as u64;
1490 #[stable(feature = "rust1", since = "1.0.0")]
1491 impl<T
: BufRead
> BufRead
for Take
<T
> {
1492 fn fill_buf(&mut self) -> Result
<&[u8]> {
1493 let buf
= try
!(self.inner
.fill_buf());
1494 let cap
= cmp
::min(buf
.len() as u64, self.limit
) as usize;
1498 fn consume(&mut self, amt
: usize) {
1499 // Don't let callers reset the limit by passing an overlarge value
1500 let amt
= cmp
::min(amt
as u64, self.limit
) as usize;
1501 self.limit
-= amt
as u64;
1502 self.inner
.consume(amt
);
1506 /// An adaptor which will emit all read data to a specified writer as well.
1508 /// This struct is generally created by calling [`tee()`][tee] on a reader.
1509 /// Please see the documentation of `tee()` for more details.
1511 /// [tee]: trait.Read.html#method.tee
1512 #[unstable(feature = "io", reason = "awaiting stability of Read::tee")]
1513 pub struct Tee
<R
, W
> {
1518 #[unstable(feature = "io", reason = "awaiting stability of Read::tee")]
1519 impl<R
: Read
, W
: Write
> Read
for Tee
<R
, W
> {
1520 fn read(&mut self, buf
: &mut [u8]) -> Result
<usize> {
1521 let n
= try
!(self.reader
.read(buf
));
1522 // FIXME: what if the write fails? (we read something)
1523 try
!(self.writer
.write_all(&buf
[..n
]));
1528 /// An iterator over `u8` values of a reader.
1530 /// This struct is generally created by calling [`bytes()`][bytes] on a reader.
1531 /// Please see the documentation of `bytes()` for more details.
1533 /// [bytes]: trait.Read.html#method.bytes
1534 #[stable(feature = "rust1", since = "1.0.0")]
1535 pub struct Bytes
<R
> {
1539 #[stable(feature = "rust1", since = "1.0.0")]
1540 impl<R
: Read
> Iterator
for Bytes
<R
> {
1541 type Item
= Result
<u8>;
1543 fn next(&mut self) -> Option
<Result
<u8>> {
1545 match self.inner
.read(&mut buf
) {
1547 Ok(..) => Some(Ok(buf
[0])),
1548 Err(e
) => Some(Err(e
)),
1553 /// An iterator over the `char`s of a reader.
1555 /// This struct is generally created by calling [`chars()`][chars] on a reader.
1556 /// Please see the documentation of `chars()` for more details.
1558 /// [chars]: trait.Read.html#method.chars
1559 #[unstable(feature = "io", reason = "awaiting stability of Read::chars")]
1560 pub struct Chars
<R
> {
1564 /// An enumeration of possible errors that can be generated from the `Chars`
1567 #[unstable(feature = "io", reason = "awaiting stability of Read::chars")]
1568 pub enum CharsError
{
1569 /// Variant representing that the underlying stream was read successfully
1570 /// but it did not contain valid utf8 data.
1573 /// Variant representing that an I/O error occurred.
1577 #[unstable(feature = "io", reason = "awaiting stability of Read::chars")]
1578 impl<R
: Read
> Iterator
for Chars
<R
> {
1579 type Item
= result
::Result
<char, CharsError
>;
1581 fn next(&mut self) -> Option
<result
::Result
<char, CharsError
>> {
1583 let first_byte
= match self.inner
.read(&mut buf
) {
1584 Ok(0) => return None
,
1586 Err(e
) => return Some(Err(CharsError
::Other(e
))),
1588 let width
= core_str
::utf8_char_width(first_byte
);
1589 if width
== 1 { return Some(Ok(first_byte as char)) }
1590 if width
== 0 { return Some(Err(CharsError::NotUtf8)) }
1591 let mut buf
= [first_byte
, 0, 0, 0];
1594 while start
< width
{
1595 match self.inner
.read(&mut buf
[start
..width
]) {
1596 Ok(0) => return Some(Err(CharsError
::NotUtf8
)),
1597 Ok(n
) => start
+= n
,
1598 Err(e
) => return Some(Err(CharsError
::Other(e
))),
1602 Some(match str::from_utf8(&buf
[..width
]).ok() {
1603 Some(s
) => Ok(s
.char_at(0)),
1604 None
=> Err(CharsError
::NotUtf8
),
1609 #[unstable(feature = "io", reason = "awaiting stability of Read::chars")]
1610 impl std_error
::Error
for CharsError
{
1611 fn description(&self) -> &str {
1613 CharsError
::NotUtf8
=> "invalid utf8 encoding",
1614 CharsError
::Other(ref e
) => std_error
::Error
::description(e
),
1617 fn cause(&self) -> Option
<&std_error
::Error
> {
1619 CharsError
::NotUtf8
=> None
,
1620 CharsError
::Other(ref e
) => e
.cause(),
1625 #[unstable(feature = "io", reason = "awaiting stability of Read::chars")]
1626 impl fmt
::Display
for CharsError
{
1627 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1629 CharsError
::NotUtf8
=> {
1630 "byte stream did not contain valid utf8".fmt(f
)
1632 CharsError
::Other(ref e
) => e
.fmt(f
),
1637 /// An iterator over the contents of an instance of `BufRead` split on a
1638 /// particular byte.
1640 /// This struct is generally created by calling [`split()`][split] on a
1641 /// `BufRead`. Please see the documentation of `split()` for more details.
1643 /// [split]: trait.BufRead.html#method.split
1644 #[stable(feature = "rust1", since = "1.0.0")]
1645 pub struct Split
<B
> {
1650 #[stable(feature = "rust1", since = "1.0.0")]
1651 impl<B
: BufRead
> Iterator
for Split
<B
> {
1652 type Item
= Result
<Vec
<u8>>;
1654 fn next(&mut self) -> Option
<Result
<Vec
<u8>>> {
1655 let mut buf
= Vec
::new();
1656 match self.buf
.read_until(self.delim
, &mut buf
) {
1659 if buf
[buf
.len() - 1] == self.delim
{
1664 Err(e
) => Some(Err(e
))
1669 /// An iterator over the lines of an instance of `BufRead`.
1671 /// This struct is generally created by calling [`lines()`][lines] on a
1672 /// `BufRead`. Please see the documentation of `lines()` for more details.
1674 /// [lines]: trait.BufRead.html#method.lines
1675 #[stable(feature = "rust1", since = "1.0.0")]
1676 pub struct Lines
<B
> {
1680 #[stable(feature = "rust1", since = "1.0.0")]
1681 impl<B
: BufRead
> Iterator
for Lines
<B
> {
1682 type Item
= Result
<String
>;
1684 fn next(&mut self) -> Option
<Result
<String
>> {
1685 let mut buf
= String
::new();
1686 match self.buf
.read_line(&mut buf
) {
1689 if buf
.ends_with("\n") {
1694 Err(e
) => Some(Err(e
))
1710 let mut buf
= Cursor
::new(&b
"12"[..]);
1711 let mut v
= Vec
::new();
1712 assert_eq
!(buf
.read_until(b'
3'
, &mut v
).unwrap(), 2);
1713 assert_eq
!(v
, b
"12");
1715 let mut buf
= Cursor
::new(&b
"1233"[..]);
1716 let mut v
= Vec
::new();
1717 assert_eq
!(buf
.read_until(b'
3'
, &mut v
).unwrap(), 3);
1718 assert_eq
!(v
, b
"123");
1720 assert_eq
!(buf
.read_until(b'
3'
, &mut v
).unwrap(), 1);
1721 assert_eq
!(v
, b
"3");
1723 assert_eq
!(buf
.read_until(b'
3'
, &mut v
).unwrap(), 0);
1729 let buf
= Cursor
::new(&b
"12"[..]);
1730 let mut s
= buf
.split(b'
3'
);
1731 assert_eq
!(s
.next().unwrap().unwrap(), vec
![b'
1'
, b'
2'
]);
1732 assert
!(s
.next().is_none());
1734 let buf
= Cursor
::new(&b
"1233"[..]);
1735 let mut s
= buf
.split(b'
3'
);
1736 assert_eq
!(s
.next().unwrap().unwrap(), vec
![b'
1'
, b'
2'
]);
1737 assert_eq
!(s
.next().unwrap().unwrap(), vec
![]);
1738 assert
!(s
.next().is_none());
1743 let mut buf
= Cursor
::new(&b
"12"[..]);
1744 let mut v
= String
::new();
1745 assert_eq
!(buf
.read_line(&mut v
).unwrap(), 2);
1746 assert_eq
!(v
, "12");
1748 let mut buf
= Cursor
::new(&b
"12\n\n"[..]);
1749 let mut v
= String
::new();
1750 assert_eq
!(buf
.read_line(&mut v
).unwrap(), 3);
1751 assert_eq
!(v
, "12\n");
1753 assert_eq
!(buf
.read_line(&mut v
).unwrap(), 1);
1754 assert_eq
!(v
, "\n");
1756 assert_eq
!(buf
.read_line(&mut v
).unwrap(), 0);
1762 let buf
= Cursor
::new(&b
"12"[..]);
1763 let mut s
= buf
.lines();
1764 assert_eq
!(s
.next().unwrap().unwrap(), "12".to_string());
1765 assert
!(s
.next().is_none());
1767 let buf
= Cursor
::new(&b
"12\n\n"[..]);
1768 let mut s
= buf
.lines();
1769 assert_eq
!(s
.next().unwrap().unwrap(), "12".to_string());
1770 assert_eq
!(s
.next().unwrap().unwrap(), "".to_string());
1771 assert
!(s
.next().is_none());
1776 let mut c
= Cursor
::new(&b
""[..]);
1777 let mut v
= Vec
::new();
1778 assert_eq
!(c
.read_to_end(&mut v
).unwrap(), 0);
1781 let mut c
= Cursor
::new(&b
"1"[..]);
1782 let mut v
= Vec
::new();
1783 assert_eq
!(c
.read_to_end(&mut v
).unwrap(), 1);
1784 assert_eq
!(v
, b
"1");
1786 let cap
= 1024 * 1024;
1787 let data
= (0..cap
).map(|i
| (i
/ 3) as u8).collect
::<Vec
<_
>>();
1788 let mut v
= Vec
::new();
1789 let (a
, b
) = data
.split_at(data
.len() / 2);
1790 assert_eq
!(Cursor
::new(a
).read_to_end(&mut v
).unwrap(), a
.len());
1791 assert_eq
!(Cursor
::new(b
).read_to_end(&mut v
).unwrap(), b
.len());
1792 assert_eq
!(v
, data
);
1796 fn read_to_string() {
1797 let mut c
= Cursor
::new(&b
""[..]);
1798 let mut v
= String
::new();
1799 assert_eq
!(c
.read_to_string(&mut v
).unwrap(), 0);
1802 let mut c
= Cursor
::new(&b
"1"[..]);
1803 let mut v
= String
::new();
1804 assert_eq
!(c
.read_to_string(&mut v
).unwrap(), 1);
1807 let mut c
= Cursor
::new(&b
"\xff"[..]);
1808 let mut v
= String
::new();
1809 assert
!(c
.read_to_string(&mut v
).is_err());
1817 fn read(&mut self, _
: &mut [u8]) -> io
::Result
<usize> {
1818 Err(io
::Error
::new(io
::ErrorKind
::Other
, ""))
1822 let mut buf
= [0; 1];
1823 assert_eq
!(0, R
.take(0).read(&mut buf
).unwrap());
1827 fn bench_read_to_end(b
: &mut test
::Bencher
) {
1829 let mut lr
= repeat(1).take(10000000);
1830 let mut vec
= Vec
::with_capacity(1024);
1831 super::read_to_end(&mut lr
, &mut vec
);