]> git.proxmox.com Git - rustc.git/blame - src/libstd/io/mod.rs
New upstream version 1.12.0+dfsg1
[rustc.git] / src / libstd / io / mod.rs
CommitLineData
85aaf69f 1// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
1a4d82fc
JJ
2// file at the top-level directory of this distribution and at
3// http://rust-lang.org/COPYRIGHT.
4//
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.
1a4d82fc 10
85aaf69f 11//! Traits, helpers, and type definitions for core I/O functionality.
c1a9b12d
SL
12//!
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.
17//!
18//! [read]: trait.Read.html
19//! [write]: trait.Write.html
20//!
21//! # Read and Write
22//!
b039eaaf
SL
23//! Because they are traits, `Read` and `Write` are implemented by a number
24//! of other types, and you can implement them for your types too. As such,
25//! you'll see a few different types of I/O throughout the documentation in
26//! this module: `File`s, `TcpStream`s, and sometimes even `Vec<T>`s. For
27//! example, `Read` adds a `read()` method, which we can use on `File`s:
c1a9b12d
SL
28//!
29//! ```
30//! use std::io;
31//! use std::io::prelude::*;
32//! use std::fs::File;
33//!
34//! # fn foo() -> io::Result<()> {
35//! let mut f = try!(File::open("foo.txt"));
36//! let mut buffer = [0; 10];
37//!
38//! // read up to 10 bytes
39//! try!(f.read(&mut buffer));
40//!
41//! println!("The bytes: {:?}", buffer);
42//! # Ok(())
43//! # }
44//! ```
45//!
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!
49//!
50//! ## Seek and BufRead
51//!
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
55//! coming from:
56//!
57//! ```
58//! use std::io;
59//! use std::io::prelude::*;
60//! use std::io::SeekFrom;
61//! use std::fs::File;
62//!
63//! # fn foo() -> io::Result<()> {
64//! let mut f = try!(File::open("foo.txt"));
65//! let mut buffer = [0; 10];
66//!
67//! // skip to the last 10 bytes of the file
68//! try!(f.seek(SeekFrom::End(-10)));
69//!
70//! // read up to 10 bytes
71//! try!(f.read(&mut buffer));
72//!
73//! println!("The bytes: {:?}", buffer);
74//! # Ok(())
75//! # }
76//! ```
77//!
78//! [seek]: trait.Seek.html
79//! [bufread]: trait.BufRead.html
80//!
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!
83//!
84//! ## BufReader and BufWriter
85//!
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.
91//!
92//! For example, `BufReader` works with the `BufRead` trait to add extra
93//! methods to any reader:
94//!
95//! ```
96//! use std::io;
97//! use std::io::prelude::*;
98//! use std::io::BufReader;
99//! use std::fs::File;
100//!
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();
105//!
106//! // read a line into buffer
107//! try!(reader.read_line(&mut buffer));
108//!
109//! println!("{}", buffer);
110//! # Ok(())
111//! # }
112//! ```
113//!
b039eaaf 114//! `BufWriter` doesn't add any new ways of writing; it just buffers every call
9cc50fc6 115//! to [`write()`][write()]:
c1a9b12d
SL
116//!
117//! ```
118//! use std::io;
119//! use std::io::prelude::*;
120//! use std::io::BufWriter;
121//! use std::fs::File;
122//!
123//! # fn foo() -> io::Result<()> {
124//! let f = try!(File::create("foo.txt"));
125//! {
126//! let mut writer = BufWriter::new(f);
127//!
128//! // write a byte to the buffer
129//! try!(writer.write(&[42]));
130//!
131//! } // the buffer is flushed once writer goes out of scope
132//!
133//! # Ok(())
134//! # }
135//! ```
136//!
9cc50fc6 137//! [write()]: trait.Write.html#tymethod.write
c1a9b12d
SL
138//!
139//! ## Standard input and output
140//!
141//! A very common source of input is standard input:
142//!
143//! ```
144//! use std::io;
145//!
146//! # fn foo() -> io::Result<()> {
147//! let mut input = String::new();
148//!
149//! try!(io::stdin().read_line(&mut input));
150//!
151//! println!("You typed: {}", input.trim());
152//! # Ok(())
153//! # }
154//! ```
155//!
156//! And a very common source of output is standard output:
157//!
158//! ```
159//! use std::io;
160//! use std::io::prelude::*;
161//!
162//! # fn foo() -> io::Result<()> {
163//! try!(io::stdout().write(&[42]));
164//! # Ok(())
165//! # }
166//! ```
167//!
b039eaaf 168//! Of course, using `io::stdout()` directly is less common than something like
c1a9b12d
SL
169//! `println!`.
170//!
171//! ## Iterator types
172//!
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
175//! lines:
176//!
177//! ```
178//! use std::io;
179//! use std::io::prelude::*;
180//! use std::io::BufReader;
181//! use std::fs::File;
182//!
183//! # fn foo() -> io::Result<()> {
184//! let f = try!(File::open("foo.txt"));
a7813a04 185//! let reader = BufReader::new(f);
c1a9b12d
SL
186//!
187//! for line in reader.lines() {
a7813a04 188//! println!("{}", try!(line));
c1a9b12d
SL
189//! }
190//!
191//! # Ok(())
192//! # }
193//! ```
194//!
195//! ## Functions
196//!
a7813a04 197//! There are a number of [functions][functions-list] that offer access to various
c1a9b12d
SL
198//! features. For example, we can use three of these functions to copy everything
199//! from standard input to standard output:
200//!
201//! ```
202//! use std::io;
203//!
204//! # fn foo() -> io::Result<()> {
205//! try!(io::copy(&mut io::stdin(), &mut io::stdout()));
206//! # Ok(())
207//! # }
208//! ```
209//!
a7813a04 210//! [functions-list]: #functions-1
c1a9b12d
SL
211//!
212//! ## io::Result
213//!
214//! Last, but certainly not least, is [`io::Result`][result]. This type is used
215//! as the return type of many `std::io` functions that can cause an error, and
216//! can be returned from your own functions as well. Many of the examples in this
217//! module use the [`try!`][try] macro:
218//!
219//! ```
220//! use std::io;
221//!
222//! fn read_input() -> io::Result<()> {
223//! let mut input = String::new();
224//!
225//! try!(io::stdin().read_line(&mut input));
226//!
227//! println!("You typed: {}", input.trim());
228//!
229//! Ok(())
230//! }
231//! ```
232//!
233//! The return type of `read_input()`, `io::Result<()>`, is a very common type
234//! for functions which don't have a 'real' return value, but do want to return
235//! errors if they happen. In this case, the only purpose of this function is
b039eaaf 236//! to read the line and print it, so we use `()`.
c1a9b12d
SL
237//!
238//! [result]: type.Result.html
9cc50fc6
SL
239//! [try]: ../macro.try!.html
240//!
241//! ## Platform-specific behavior
242//!
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.
1a4d82fc 249
c34b1796 250#![stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 251
85aaf69f 252use cmp;
d9579d0f 253use rustc_unicode::str as core_str;
c34b1796 254use error as std_error;
1a4d82fc 255use fmt;
c1a9b12d 256use iter::{Iterator};
1a4d82fc 257use marker::Sized;
85aaf69f
SL
258use ops::{Drop, FnOnce};
259use option::Option::{self, Some, None};
1a4d82fc 260use result::Result::{Ok, Err};
85aaf69f 261use result;
1a4d82fc 262use string::String;
c34b1796 263use str;
1a4d82fc 264use vec::Vec;
9cc50fc6 265use memchr;
1a4d82fc 266
92a42be0 267#[stable(feature = "rust1", since = "1.0.0")]
e9174d1e 268pub use self::buffered::{BufReader, BufWriter, LineWriter};
92a42be0 269#[stable(feature = "rust1", since = "1.0.0")]
85aaf69f 270pub use self::buffered::IntoInnerError;
92a42be0 271#[stable(feature = "rust1", since = "1.0.0")]
85aaf69f 272pub use self::cursor::Cursor;
92a42be0 273#[stable(feature = "rust1", since = "1.0.0")]
85aaf69f 274pub use self::error::{Result, Error, ErrorKind};
92a42be0 275#[stable(feature = "rust1", since = "1.0.0")]
85aaf69f 276pub use self::util::{copy, sink, Sink, empty, Empty, repeat, Repeat};
92a42be0 277#[stable(feature = "rust1", since = "1.0.0")]
c34b1796 278pub use self::stdio::{stdin, stdout, stderr, _print, Stdin, Stdout, Stderr};
92a42be0 279#[stable(feature = "rust1", since = "1.0.0")]
c34b1796 280pub use self::stdio::{StdoutLock, StderrLock, StdinLock};
92a42be0 281#[unstable(feature = "libstd_io_internals", issue = "0")]
c34b1796
AL
282#[doc(no_inline, hidden)]
283pub use self::stdio::{set_panic, set_print};
284
85aaf69f 285pub mod prelude;
1a4d82fc 286mod buffered;
85aaf69f
SL
287mod cursor;
288mod error;
289mod impls;
62682a34 290mod lazy;
85aaf69f 291mod util;
c34b1796 292mod stdio;
1a4d82fc 293
54a0048b 294const DEFAULT_BUF_SIZE: usize = 8 * 1024;
1a4d82fc 295
85aaf69f
SL
296// A few methods below (read_to_string, read_line) will append data into a
297// `String` buffer, but we need to be pretty careful when doing this. The
298// implementation will just call `.as_mut_vec()` and then delegate to a
299// byte-oriented reading method, but we must ensure that when returning we never
300// leave `buf` in a state such that it contains invalid UTF-8 in its bounds.
301//
302// To this end, we use an RAII guard (to protect against panics) which updates
303// the length of the string when it is dropped. This guard initially truncates
304// the string to the prior length and only after we've validated that the
305// new contents are valid UTF-8 do we allow it to set a longer length.
306//
307// The unsafety in this function is twofold:
308//
309// 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
310// checks.
311// 2. We're passing a raw buffer to the function `f`, and it is expected that
312// the function only *appends* bytes to the buffer. We'll get undefined
313// behavior if existing bytes are overwritten to have non-UTF-8 data.
c34b1796
AL
314fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
315 where F: FnOnce(&mut Vec<u8>) -> Result<usize>
85aaf69f
SL
316{
317 struct Guard<'a> { s: &'a mut Vec<u8>, len: usize }
d9579d0f 318 impl<'a> Drop for Guard<'a> {
85aaf69f
SL
319 fn drop(&mut self) {
320 unsafe { self.s.set_len(self.len); }
1a4d82fc
JJ
321 }
322 }
1a4d82fc 323
85aaf69f
SL
324 unsafe {
325 let mut g = Guard { len: buf.len(), s: buf.as_mut_vec() };
326 let ret = f(g.s);
327 if str::from_utf8(&g.s[g.len..]).is_err() {
c34b1796 328 ret.and_then(|_| {
62682a34 329 Err(Error::new(ErrorKind::InvalidData,
c34b1796 330 "stream did not contain valid UTF-8"))
85aaf69f
SL
331 })
332 } else {
333 g.len = g.s.len();
334 ret
335 }
1a4d82fc
JJ
336 }
337}
338
c34b1796
AL
339// This uses an adaptive system to extend the vector when it fills. We want to
340// avoid paying to allocate and zero a huge chunk of memory if the reader only
341// has 4 bytes while still making large reads if the reader does have a ton
342// of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
343// time is 4,500 times (!) slower than this if the reader has a very small
344// amount of data to return.
345fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
346 let start_len = buf.len();
347 let mut len = start_len;
348 let mut new_write_size = 16;
349 let ret;
85aaf69f 350 loop {
c34b1796
AL
351 if len == buf.len() {
352 if new_write_size < DEFAULT_BUF_SIZE {
353 new_write_size *= 2;
354 }
c1a9b12d 355 buf.resize(len + new_write_size, 0);
85aaf69f 356 }
c34b1796
AL
357
358 match r.read(&mut buf[len..]) {
359 Ok(0) => {
360 ret = Ok(len - start_len);
361 break;
362 }
363 Ok(n) => len += n,
85aaf69f 364 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
c34b1796
AL
365 Err(e) => {
366 ret = Err(e);
367 break;
368 }
85aaf69f 369 }
1a4d82fc 370 }
c34b1796
AL
371
372 buf.truncate(len);
373 ret
1a4d82fc
JJ
374}
375
c1a9b12d 376/// The `Read` trait allows for reading bytes from a source.
85aaf69f 377///
c1a9b12d 378/// Implementors of the `Read` trait are sometimes called 'readers'.
1a4d82fc 379///
c1a9b12d
SL
380/// Readers are defined by one required method, `read()`. Each call to `read`
381/// will attempt to pull bytes from this source into a provided buffer. A
382/// number of other methods are implemented in terms of `read()`, giving
383/// implementors a number of ways to read bytes while only needing to implement
384/// a single method.
385///
386/// Readers are intended to be composable with one another. Many implementors
387/// throughout `std::io` take and provide types which implement the `Read`
388/// trait.
389///
b039eaaf
SL
390/// Please note that each call to `read` may involve a system call, and
391/// therefore, using something that implements [`BufRead`][bufread], such as
392/// [`BufReader`][bufreader], will be more efficient.
393///
394/// [bufread]: trait.BufRead.html
395/// [bufreader]: struct.BufReader.html
396///
c1a9b12d
SL
397/// # Examples
398///
399/// [`File`][file]s implement `Read`:
400///
9cc50fc6 401/// [file]: ../fs/struct.File.html
c1a9b12d
SL
402///
403/// ```
404/// use std::io;
405/// use std::io::prelude::*;
406/// use std::fs::File;
407///
408/// # fn foo() -> io::Result<()> {
409/// let mut f = try!(File::open("foo.txt"));
410/// let mut buffer = [0; 10];
411///
412/// // read up to 10 bytes
413/// try!(f.read(&mut buffer));
414///
415/// let mut buffer = vec![0; 10];
416/// // read the whole file
417/// try!(f.read_to_end(&mut buffer));
418///
419/// // read into a String, so that you don't need to do the conversion.
420/// let mut buffer = String::new();
421/// try!(f.read_to_string(&mut buffer));
422///
423/// // and more! See the other methods for more details.
424/// # Ok(())
425/// # }
426/// ```
c34b1796 427#[stable(feature = "rust1", since = "1.0.0")]
85aaf69f
SL
428pub trait Read {
429 /// Pull some bytes from this source into the specified buffer, returning
430 /// how many bytes were read.
431 ///
432 /// This function does not provide any guarantees about whether it blocks
433 /// waiting for data, but if an object needs to block for a read but cannot
434 /// it will typically signal this via an `Err` return value.
435 ///
436 /// If the return value of this method is `Ok(n)`, then it must be
437 /// guaranteed that `0 <= n <= buf.len()`. A nonzero `n` value indicates
9346a6ac 438 /// that the buffer `buf` has been filled in with `n` bytes of data from this
85aaf69f
SL
439 /// source. If `n` is `0`, then it can indicate one of two scenarios:
440 ///
441 /// 1. This reader has reached its "end of file" and will likely no longer
442 /// be able to produce bytes. Note that this does not mean that the
443 /// reader will *always* no longer be able to produce bytes.
444 /// 2. The buffer specified was 0 bytes in length.
445 ///
446 /// No guarantees are provided about the contents of `buf` when this
447 /// function is called, implementations cannot rely on any property of the
448 /// contents of `buf` being true. It is recommended that implementations
449 /// only write data to `buf` instead of reading its contents.
1a4d82fc 450 ///
85aaf69f 451 /// # Errors
1a4d82fc 452 ///
85aaf69f
SL
453 /// If this function encounters any form of I/O or other error, an error
454 /// variant will be returned. If an error is returned then it must be
455 /// guaranteed that no bytes were read.
c1a9b12d
SL
456 ///
457 /// # Examples
458 ///
459 /// [`File`][file]s implement `Read`:
460 ///
9cc50fc6 461 /// [file]: ../fs/struct.File.html
c1a9b12d
SL
462 ///
463 /// ```
464 /// use std::io;
465 /// use std::io::prelude::*;
466 /// use std::fs::File;
467 ///
468 /// # fn foo() -> io::Result<()> {
469 /// let mut f = try!(File::open("foo.txt"));
470 /// let mut buffer = [0; 10];
471 ///
472 /// // read 10 bytes
473 /// try!(f.read(&mut buffer[..]));
474 /// # Ok(())
475 /// # }
476 /// ```
c34b1796 477 #[stable(feature = "rust1", since = "1.0.0")]
85aaf69f 478 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
1a4d82fc 479
85aaf69f 480 /// Read all bytes until EOF in this source, placing them into `buf`.
1a4d82fc 481 ///
85aaf69f 482 /// All bytes read from this source will be appended to the specified buffer
9346a6ac
AL
483 /// `buf`. This function will continuously call `read` to append more data to
484 /// `buf` until `read` returns either `Ok(0)` or an error of
485 /// non-`ErrorKind::Interrupted` kind.
1a4d82fc 486 ///
9346a6ac 487 /// If successful, this function will return the total number of bytes read.
1a4d82fc 488 ///
85aaf69f 489 /// # Errors
1a4d82fc 490 ///
85aaf69f
SL
491 /// If this function encounters an error of the kind
492 /// `ErrorKind::Interrupted` then the error is ignored and the operation
493 /// will continue.
1a4d82fc 494 ///
85aaf69f
SL
495 /// If any other read error is encountered then this function immediately
496 /// returns. Any bytes which have already been read will be appended to
497 /// `buf`.
c1a9b12d
SL
498 ///
499 /// # Examples
500 ///
501 /// [`File`][file]s implement `Read`:
502 ///
9cc50fc6 503 /// [file]: ../fs/struct.File.html
c1a9b12d
SL
504 ///
505 /// ```
506 /// use std::io;
507 /// use std::io::prelude::*;
508 /// use std::fs::File;
509 ///
510 /// # fn foo() -> io::Result<()> {
511 /// let mut f = try!(File::open("foo.txt"));
512 /// let mut buffer = Vec::new();
513 ///
514 /// // read the whole file
515 /// try!(f.read_to_end(&mut buffer));
516 /// # Ok(())
517 /// # }
518 /// ```
c34b1796
AL
519 #[stable(feature = "rust1", since = "1.0.0")]
520 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
85aaf69f 521 read_to_end(self, buf)
1a4d82fc
JJ
522 }
523
85aaf69f 524 /// Read all bytes until EOF in this source, placing them into `buf`.
1a4d82fc 525 ///
c34b1796
AL
526 /// If successful, this function returns the number of bytes which were read
527 /// and appended to `buf`.
528 ///
85aaf69f 529 /// # Errors
1a4d82fc 530 ///
85aaf69f
SL
531 /// If the data in this stream is *not* valid UTF-8 then an error is
532 /// returned and `buf` is unchanged.
1a4d82fc 533 ///
c1a9b12d
SL
534 /// See [`read_to_end()`][readtoend] for other error semantics.
535 ///
536 /// [readtoend]: #method.read_to_end
537 ///
538 /// # Examples
539 ///
540 /// [`File`][file]s implement `Read`:
541 ///
9cc50fc6 542 /// [file]: ../fs/struct.File.html
c1a9b12d
SL
543 ///
544 /// ```
545 /// use std::io;
546 /// use std::io::prelude::*;
547 /// use std::fs::File;
548 ///
549 /// # fn foo() -> io::Result<()> {
550 /// let mut f = try!(File::open("foo.txt"));
551 /// let mut buffer = String::new();
552 ///
553 /// try!(f.read_to_string(&mut buffer));
554 /// # Ok(())
555 /// # }
556 /// ```
c34b1796
AL
557 #[stable(feature = "rust1", since = "1.0.0")]
558 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
85aaf69f
SL
559 // Note that we do *not* call `.read_to_end()` here. We are passing
560 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
561 // method to fill it up. An arbitrary implementation could overwrite the
562 // entire contents of the vector, not just append to it (which is what
563 // we are expecting).
564 //
565 // To prevent extraneously checking the UTF-8-ness of the entire buffer
566 // we pass it to our hardcoded `read_to_end` implementation which we
567 // know is guaranteed to only read data into the end of the buffer.
568 append_to_string(buf, |b| read_to_end(self, b))
1a4d82fc
JJ
569 }
570
e9174d1e
SL
571 /// Read the exact number of bytes required to fill `buf`.
572 ///
573 /// This function reads as many bytes as necessary to completely fill the
574 /// specified buffer `buf`.
575 ///
576 /// No guarantees are provided about the contents of `buf` when this
577 /// function is called, implementations cannot rely on any property of the
578 /// contents of `buf` being true. It is recommended that implementations
579 /// only write data to `buf` instead of reading its contents.
580 ///
581 /// # Errors
582 ///
583 /// If this function encounters an error of the kind
584 /// `ErrorKind::Interrupted` then the error is ignored and the operation
585 /// will continue.
586 ///
587 /// If this function encounters an "end of file" before completely filling
92a42be0 588 /// the buffer, it returns an error of the kind `ErrorKind::UnexpectedEof`.
e9174d1e
SL
589 /// The contents of `buf` are unspecified in this case.
590 ///
591 /// If any other read error is encountered then this function immediately
592 /// returns. The contents of `buf` are unspecified in this case.
593 ///
594 /// If this function returns an error, it is unspecified how many bytes it
595 /// has read, but it will never read more than would be necessary to
596 /// completely fill the buffer.
597 ///
598 /// # Examples
599 ///
600 /// [`File`][file]s implement `Read`:
601 ///
9cc50fc6 602 /// [file]: ../fs/struct.File.html
e9174d1e
SL
603 ///
604 /// ```
e9174d1e
SL
605 /// use std::io;
606 /// use std::io::prelude::*;
607 /// use std::fs::File;
608 ///
609 /// # fn foo() -> io::Result<()> {
610 /// let mut f = try!(File::open("foo.txt"));
611 /// let mut buffer = [0; 10];
612 ///
613 /// // read exactly 10 bytes
614 /// try!(f.read_exact(&mut buffer));
615 /// # Ok(())
616 /// # }
617 /// ```
92a42be0 618 #[stable(feature = "read_exact", since = "1.6.0")]
e9174d1e
SL
619 fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
620 while !buf.is_empty() {
621 match self.read(buf) {
622 Ok(0) => break,
623 Ok(n) => { let tmp = buf; buf = &mut tmp[n..]; }
624 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
625 Err(e) => return Err(e),
626 }
627 }
628 if !buf.is_empty() {
92a42be0 629 Err(Error::new(ErrorKind::UnexpectedEof,
e9174d1e
SL
630 "failed to fill whole buffer"))
631 } else {
632 Ok(())
633 }
634 }
635
9346a6ac 636 /// Creates a "by reference" adaptor for this instance of `Read`.
1a4d82fc 637 ///
85aaf69f
SL
638 /// The returned adaptor also implements `Read` and will simply borrow this
639 /// current reader.
c1a9b12d
SL
640 ///
641 /// # Examples
642 ///
643 /// [`File`][file]s implement `Read`:
644 ///
9cc50fc6 645 /// [file]: ../fs/struct.File.html
c1a9b12d
SL
646 ///
647 /// ```
648 /// use std::io;
649 /// use std::io::Read;
650 /// use std::fs::File;
651 ///
652 /// # fn foo() -> io::Result<()> {
653 /// let mut f = try!(File::open("foo.txt"));
654 /// let mut buffer = Vec::new();
655 /// let mut other_buffer = Vec::new();
656 ///
657 /// {
658 /// let reference = f.by_ref();
659 ///
660 /// // read at most 5 bytes
661 /// try!(reference.take(5).read_to_end(&mut buffer));
662 ///
663 /// } // drop our &mut reference so we can use f again
664 ///
665 /// // original file still usable, read the rest
666 /// try!(f.read_to_end(&mut other_buffer));
667 /// # Ok(())
668 /// # }
669 /// ```
c34b1796
AL
670 #[stable(feature = "rust1", since = "1.0.0")]
671 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1a4d82fc 672
9346a6ac 673 /// Transforms this `Read` instance to an `Iterator` over its bytes.
1a4d82fc 674 ///
85aaf69f
SL
675 /// The returned type implements `Iterator` where the `Item` is `Result<u8,
676 /// R::Err>`. The yielded item is `Ok` if a byte was successfully read and
677 /// `Err` otherwise for I/O errors. EOF is mapped to returning `None` from
678 /// this iterator.
c1a9b12d
SL
679 ///
680 /// # Examples
681 ///
682 /// [`File`][file]s implement `Read`:
683 ///
9cc50fc6 684 /// [file]: ../fs/struct.File.html
c1a9b12d
SL
685 ///
686 /// ```
687 /// use std::io;
688 /// use std::io::prelude::*;
689 /// use std::fs::File;
690 ///
691 /// # fn foo() -> io::Result<()> {
692 /// let mut f = try!(File::open("foo.txt"));
693 ///
694 /// for byte in f.bytes() {
695 /// println!("{}", byte.unwrap());
696 /// }
697 /// # Ok(())
698 /// # }
699 /// ```
c34b1796
AL
700 #[stable(feature = "rust1", since = "1.0.0")]
701 fn bytes(self) -> Bytes<Self> where Self: Sized {
85aaf69f 702 Bytes { inner: self }
1a4d82fc
JJ
703 }
704
9346a6ac 705 /// Transforms this `Read` instance to an `Iterator` over `char`s.
1a4d82fc 706 ///
d9579d0f 707 /// This adaptor will attempt to interpret this reader as a UTF-8 encoded
85aaf69f
SL
708 /// sequence of characters. The returned iterator will return `None` once
709 /// EOF is reached for this reader. Otherwise each element yielded will be a
710 /// `Result<char, E>` where `E` may contain information about what I/O error
711 /// occurred or where decoding failed.
1a4d82fc 712 ///
85aaf69f
SL
713 /// Currently this adaptor will discard intermediate data read, and should
714 /// be avoided if this is not desired.
c1a9b12d
SL
715 ///
716 /// # Examples
717 ///
718 /// [`File`][file]s implement `Read`:
719 ///
9cc50fc6 720 /// [file]: ../fs/struct.File.html
c1a9b12d
SL
721 ///
722 /// ```
723 /// #![feature(io)]
724 /// use std::io;
725 /// use std::io::prelude::*;
726 /// use std::fs::File;
727 ///
728 /// # fn foo() -> io::Result<()> {
729 /// let mut f = try!(File::open("foo.txt"));
730 ///
731 /// for c in f.chars() {
732 /// println!("{}", c.unwrap());
733 /// }
734 /// # Ok(())
735 /// # }
736 /// ```
c34b1796
AL
737 #[unstable(feature = "io", reason = "the semantics of a partial read/write \
738 of where errors happen is currently \
e9174d1e
SL
739 unclear and may change",
740 issue = "27802")]
c34b1796 741 fn chars(self) -> Chars<Self> where Self: Sized {
85aaf69f 742 Chars { inner: self }
1a4d82fc
JJ
743 }
744
9346a6ac 745 /// Creates an adaptor which will chain this stream with another.
1a4d82fc 746 ///
85aaf69f
SL
747 /// The returned `Read` instance will first read all bytes from this object
748 /// until EOF is encountered. Afterwards the output is equivalent to the
749 /// output of `next`.
c1a9b12d
SL
750 ///
751 /// # Examples
752 ///
753 /// [`File`][file]s implement `Read`:
754 ///
9cc50fc6 755 /// [file]: ../fs/struct.File.html
c1a9b12d
SL
756 ///
757 /// ```
758 /// use std::io;
759 /// use std::io::prelude::*;
760 /// use std::fs::File;
761 ///
762 /// # fn foo() -> io::Result<()> {
763 /// let mut f1 = try!(File::open("foo.txt"));
764 /// let mut f2 = try!(File::open("bar.txt"));
765 ///
766 /// let mut handle = f1.chain(f2);
767 /// let mut buffer = String::new();
768 ///
769 /// // read the value into a String. We could use any Read method here,
770 /// // this is just one example.
771 /// try!(handle.read_to_string(&mut buffer));
772 /// # Ok(())
773 /// # }
774 /// ```
c34b1796
AL
775 #[stable(feature = "rust1", since = "1.0.0")]
776 fn chain<R: Read>(self, next: R) -> Chain<Self, R> where Self: Sized {
85aaf69f 777 Chain { first: self, second: next, done_first: false }
1a4d82fc
JJ
778 }
779
9346a6ac 780 /// Creates an adaptor which will read at most `limit` bytes from it.
1a4d82fc 781 ///
85aaf69f
SL
782 /// This function returns a new instance of `Read` which will read at most
783 /// `limit` bytes, after which it will always return EOF (`Ok(0)`). Any
784 /// read errors will not count towards the number of bytes read and future
785 /// calls to `read` may succeed.
c1a9b12d
SL
786 ///
787 /// # Examples
788 ///
789 /// [`File`][file]s implement `Read`:
790 ///
9cc50fc6 791 /// [file]: ../fs/struct.File.html
c1a9b12d
SL
792 ///
793 /// ```
794 /// use std::io;
795 /// use std::io::prelude::*;
796 /// use std::fs::File;
797 ///
798 /// # fn foo() -> io::Result<()> {
799 /// let mut f = try!(File::open("foo.txt"));
800 /// let mut buffer = [0; 5];
801 ///
802 /// // read at most five bytes
803 /// let mut handle = f.take(5);
804 ///
805 /// try!(handle.read(&mut buffer));
806 /// # Ok(())
807 /// # }
808 /// ```
c34b1796
AL
809 #[stable(feature = "rust1", since = "1.0.0")]
810 fn take(self, limit: u64) -> Take<Self> where Self: Sized {
85aaf69f 811 Take { inner: self, limit: limit }
1a4d82fc 812 }
85aaf69f 813}
1a4d82fc 814
85aaf69f
SL
815/// A trait for objects which are byte-oriented sinks.
816///
c1a9b12d
SL
817/// Implementors of the `Write` trait are sometimes called 'writers'.
818///
819/// Writers are defined by two required methods, `write()` and `flush()`:
820///
821/// * The `write()` method will attempt to write some data into the object,
822/// returning how many bytes were successfully written.
823///
824/// * The `flush()` method is useful for adaptors and explicit buffers
825/// themselves for ensuring that all buffered data has been pushed out to the
826/// 'true sink'.
827///
828/// Writers are intended to be composable with one another. Many implementors
829/// throughout `std::io` take and provide types which implement the `Write`
830/// trait.
831///
832/// # Examples
833///
834/// ```
835/// use std::io::prelude::*;
836/// use std::fs::File;
85aaf69f 837///
c1a9b12d
SL
838/// # fn foo() -> std::io::Result<()> {
839/// let mut buffer = try!(File::create("foo.txt"));
85aaf69f 840///
c1a9b12d
SL
841/// try!(buffer.write(b"some bytes"));
842/// # Ok(())
843/// # }
844/// ```
c34b1796 845#[stable(feature = "rust1", since = "1.0.0")]
85aaf69f
SL
846pub trait Write {
847 /// Write a buffer into this object, returning how many bytes were written.
1a4d82fc 848 ///
85aaf69f
SL
849 /// This function will attempt to write the entire contents of `buf`, but
850 /// the entire write may not succeed, or the write may also generate an
851 /// error. A call to `write` represents *at most one* attempt to write to
852 /// any wrapped object.
1a4d82fc 853 ///
85aaf69f 854 /// Calls to `write` are not guaranteed to block waiting for data to be
62682a34 855 /// written, and a write which would otherwise block can be indicated through
85aaf69f 856 /// an `Err` variant.
1a4d82fc 857 ///
85aaf69f
SL
858 /// If the return value is `Ok(n)` then it must be guaranteed that
859 /// `0 <= n <= buf.len()`. A return value of `0` typically means that the
860 /// underlying object is no longer able to accept bytes and will likely not
861 /// be able to in the future as well, or that the buffer provided is empty.
1a4d82fc 862 ///
85aaf69f 863 /// # Errors
1a4d82fc 864 ///
85aaf69f
SL
865 /// Each call to `write` may generate an I/O error indicating that the
866 /// operation could not be completed. If an error is returned then no bytes
867 /// in the buffer were written to this writer.
1a4d82fc 868 ///
85aaf69f
SL
869 /// It is **not** considered an error if the entire buffer could not be
870 /// written to this writer.
c1a9b12d
SL
871 ///
872 /// # Examples
873 ///
874 /// ```
875 /// use std::io::prelude::*;
876 /// use std::fs::File;
877 ///
878 /// # fn foo() -> std::io::Result<()> {
879 /// let mut buffer = try!(File::create("foo.txt"));
880 ///
881 /// try!(buffer.write(b"some bytes"));
882 /// # Ok(())
883 /// # }
884 /// ```
c34b1796 885 #[stable(feature = "rust1", since = "1.0.0")]
85aaf69f 886 fn write(&mut self, buf: &[u8]) -> Result<usize>;
1a4d82fc 887
85aaf69f
SL
888 /// Flush this output stream, ensuring that all intermediately buffered
889 /// contents reach their destination.
1a4d82fc 890 ///
85aaf69f 891 /// # Errors
1a4d82fc 892 ///
85aaf69f
SL
893 /// It is considered an error if not all bytes could be written due to
894 /// I/O errors or EOF being reached.
c1a9b12d
SL
895 ///
896 /// # Examples
897 ///
898 /// ```
899 /// use std::io::prelude::*;
900 /// use std::io::BufWriter;
901 /// use std::fs::File;
902 ///
903 /// # fn foo() -> std::io::Result<()> {
904 /// let mut buffer = BufWriter::new(try!(File::create("foo.txt")));
905 ///
906 /// try!(buffer.write(b"some bytes"));
907 /// try!(buffer.flush());
908 /// # Ok(())
909 /// # }
910 /// ```
c34b1796 911 #[stable(feature = "rust1", since = "1.0.0")]
85aaf69f 912 fn flush(&mut self) -> Result<()>;
1a4d82fc 913
85aaf69f 914 /// Attempts to write an entire buffer into this write.
1a4d82fc 915 ///
85aaf69f
SL
916 /// This method will continuously call `write` while there is more data to
917 /// write. This method will not return until the entire buffer has been
918 /// successfully written or an error occurs. The first error generated from
919 /// this method will be returned.
1a4d82fc
JJ
920 ///
921 /// # Errors
922 ///
85aaf69f 923 /// This function will return the first error that `write` returns.
c1a9b12d
SL
924 ///
925 /// # Examples
926 ///
927 /// ```
928 /// use std::io::prelude::*;
929 /// use std::fs::File;
930 ///
931 /// # fn foo() -> std::io::Result<()> {
932 /// let mut buffer = try!(File::create("foo.txt"));
933 ///
934 /// try!(buffer.write_all(b"some bytes"));
935 /// # Ok(())
936 /// # }
937 /// ```
c34b1796 938 #[stable(feature = "rust1", since = "1.0.0")]
85aaf69f 939 fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
9346a6ac 940 while !buf.is_empty() {
85aaf69f
SL
941 match self.write(buf) {
942 Ok(0) => return Err(Error::new(ErrorKind::WriteZero,
c34b1796 943 "failed to write whole buffer")),
85aaf69f
SL
944 Ok(n) => buf = &buf[n..],
945 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
946 Err(e) => return Err(e),
947 }
948 }
949 Ok(())
950 }
1a4d82fc
JJ
951
952 /// Writes a formatted string into this writer, returning any error
953 /// encountered.
954 ///
c1a9b12d
SL
955 /// This method is primarily used to interface with the
956 /// [`format_args!`][formatargs] macro, but it is rare that this should
957 /// explicitly be called. The [`write!`][write] macro should be favored to
958 /// invoke this method instead.
959 ///
9cc50fc6
SL
960 /// [formatargs]: ../macro.format_args!.html
961 /// [write]: ../macro.write!.html
1a4d82fc 962 ///
c1a9b12d
SL
963 /// This function internally uses the [`write_all`][writeall] method on
964 /// this trait and hence will continuously write data so long as no errors
965 /// are received. This also means that partial writes are not indicated in
966 /// this signature.
967 ///
968 /// [writeall]: #method.write_all
85aaf69f 969 ///
1a4d82fc
JJ
970 /// # Errors
971 ///
972 /// This function will return any I/O error reported while formatting.
c1a9b12d
SL
973 ///
974 /// # Examples
975 ///
976 /// ```
977 /// use std::io::prelude::*;
978 /// use std::fs::File;
979 ///
980 /// # fn foo() -> std::io::Result<()> {
981 /// let mut buffer = try!(File::create("foo.txt"));
982 ///
983 /// // this call
984 /// try!(write!(buffer, "{:.*}", 2, 1.234567));
985 /// // turns into this:
986 /// try!(buffer.write_fmt(format_args!("{:.*}", 2, 1.234567)));
987 /// # Ok(())
988 /// # }
989 /// ```
c34b1796 990 #[stable(feature = "rust1", since = "1.0.0")]
85aaf69f
SL
991 fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()> {
992 // Create a shim which translates a Write to a fmt::Write and saves
1a4d82fc 993 // off I/O errors. instead of discarding them
85aaf69f 994 struct Adaptor<'a, T: ?Sized + 'a> {
1a4d82fc 995 inner: &'a mut T,
85aaf69f 996 error: Result<()>,
1a4d82fc
JJ
997 }
998
85aaf69f 999 impl<'a, T: Write + ?Sized> fmt::Write for Adaptor<'a, T> {
1a4d82fc 1000 fn write_str(&mut self, s: &str) -> fmt::Result {
85aaf69f 1001 match self.inner.write_all(s.as_bytes()) {
1a4d82fc
JJ
1002 Ok(()) => Ok(()),
1003 Err(e) => {
1004 self.error = Err(e);
1005 Err(fmt::Error)
1006 }
1007 }
1008 }
1009 }
1010
1011 let mut output = Adaptor { inner: self, error: Ok(()) };
1012 match fmt::write(&mut output, fmt) {
1013 Ok(()) => Ok(()),
7453a54e
SL
1014 Err(..) => {
1015 // check if the error came from the underlying `Write` or not
1016 if output.error.is_err() {
1017 output.error
1018 } else {
1019 Err(Error::new(ErrorKind::Other, "formatter error"))
1020 }
1021 }
1a4d82fc
JJ
1022 }
1023 }
1a4d82fc 1024
9346a6ac 1025 /// Creates a "by reference" adaptor for this instance of `Write`.
1a4d82fc 1026 ///
85aaf69f
SL
1027 /// The returned adaptor also implements `Write` and will simply borrow this
1028 /// current writer.
c1a9b12d
SL
1029 ///
1030 /// # Examples
1031 ///
1032 /// ```
1033 /// use std::io::Write;
1034 /// use std::fs::File;
1035 ///
1036 /// # fn foo() -> std::io::Result<()> {
1037 /// let mut buffer = try!(File::create("foo.txt"));
1038 ///
1039 /// let reference = buffer.by_ref();
1040 ///
1041 /// // we can use reference just like our original buffer
1042 /// try!(reference.write_all(b"some bytes"));
1043 /// # Ok(())
1044 /// # }
1045 /// ```
c34b1796
AL
1046 #[stable(feature = "rust1", since = "1.0.0")]
1047 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1a4d82fc
JJ
1048}
1049
c1a9b12d
SL
1050/// The `Seek` trait provides a cursor which can be moved within a stream of
1051/// bytes.
1a4d82fc 1052///
85aaf69f
SL
1053/// The stream typically has a fixed size, allowing seeking relative to either
1054/// end or the current offset.
c1a9b12d
SL
1055///
1056/// # Examples
1057///
1058/// [`File`][file]s implement `Seek`:
1059///
9cc50fc6 1060/// [file]: ../fs/struct.File.html
c1a9b12d
SL
1061///
1062/// ```
1063/// use std::io;
1064/// use std::io::prelude::*;
1065/// use std::fs::File;
1066/// use std::io::SeekFrom;
1067///
1068/// # fn foo() -> io::Result<()> {
1069/// let mut f = try!(File::open("foo.txt"));
1070///
1071/// // move the cursor 42 bytes from the start of the file
1072/// try!(f.seek(SeekFrom::Start(42)));
1073/// # Ok(())
1074/// # }
1075/// ```
c34b1796 1076#[stable(feature = "rust1", since = "1.0.0")]
85aaf69f 1077pub trait Seek {
c1a9b12d 1078 /// Seek to an offset, in bytes, in a stream.
85aaf69f 1079 ///
c1a9b12d
SL
1080 /// A seek beyond the end of a stream is allowed, but implementation
1081 /// defined.
85aaf69f 1082 ///
c1a9b12d
SL
1083 /// If the seek operation completed successfully,
1084 /// this method returns the new position from the start of the stream.
5bcae85e 1085 /// That position can be used later with [`SeekFrom::Start`].
85aaf69f
SL
1086 ///
1087 /// # Errors
1088 ///
c1a9b12d 1089 /// Seeking to a negative offset is considered an error.
5bcae85e
SL
1090 ///
1091 /// [`SeekFrom::Start`]: enum.SeekFrom.html#variant.Start
c34b1796 1092 #[stable(feature = "rust1", since = "1.0.0")]
85aaf69f 1093 fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1a4d82fc
JJ
1094}
1095
85aaf69f 1096/// Enumeration of possible methods to seek within an I/O object.
5bcae85e
SL
1097///
1098/// It is used by the [`Seek`] trait.
1099///
1100/// [`Seek`]: trait.Seek.html
85aaf69f 1101#[derive(Copy, PartialEq, Eq, Clone, Debug)]
c34b1796 1102#[stable(feature = "rust1", since = "1.0.0")]
85aaf69f
SL
1103pub enum SeekFrom {
1104 /// Set the offset to the provided number of bytes.
c34b1796 1105 #[stable(feature = "rust1", since = "1.0.0")]
7453a54e 1106 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1a4d82fc 1107
85aaf69f
SL
1108 /// Set the offset to the size of this object plus the specified number of
1109 /// bytes.
1110 ///
9cc50fc6 1111 /// It is possible to seek beyond the end of an object, but it's an error to
85aaf69f 1112 /// seek before byte 0.
c34b1796 1113 #[stable(feature = "rust1", since = "1.0.0")]
7453a54e 1114 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1a4d82fc 1115
85aaf69f
SL
1116 /// Set the offset to the current position plus the specified number of
1117 /// bytes.
1118 ///
9cc50fc6 1119 /// It is possible to seek beyond the end of an object, but it's an error to
85aaf69f 1120 /// seek before byte 0.
c34b1796 1121 #[stable(feature = "rust1", since = "1.0.0")]
7453a54e 1122 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1a4d82fc
JJ
1123}
1124
85aaf69f 1125fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>)
c34b1796
AL
1126 -> Result<usize> {
1127 let mut read = 0;
85aaf69f
SL
1128 loop {
1129 let (done, used) = {
1130 let available = match r.fill_buf() {
1131 Ok(n) => n,
1132 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1133 Err(e) => return Err(e)
1134 };
9cc50fc6 1135 match memchr::memchr(delim, available) {
85aaf69f 1136 Some(i) => {
92a42be0 1137 buf.extend_from_slice(&available[..i + 1]);
85aaf69f
SL
1138 (true, i + 1)
1139 }
1140 None => {
92a42be0 1141 buf.extend_from_slice(available);
85aaf69f
SL
1142 (false, available.len())
1143 }
1144 }
1145 };
1146 r.consume(used);
c34b1796 1147 read += used;
85aaf69f 1148 if done || used == 0 {
c34b1796 1149 return Ok(read);
1a4d82fc
JJ
1150 }
1151 }
1152}
1153
c1a9b12d
SL
1154/// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1155/// to perform extra ways of reading.
1156///
1157/// For example, reading line-by-line is inefficient without using a buffer, so
1158/// if you want to read by line, you'll need `BufRead`, which includes a
1159/// [`read_line()`][readline] method as well as a [`lines()`][lines] iterator.
1160///
1161/// [readline]: #method.read_line
1162/// [lines]: #method.lines
1163///
1164/// # Examples
1165///
1166/// A locked standard input implements `BufRead`:
1167///
1168/// ```
1169/// use std::io;
1170/// use std::io::prelude::*;
1171///
1172/// let stdin = io::stdin();
1173/// for line in stdin.lock().lines() {
1174/// println!("{}", line.unwrap());
1175/// }
1176/// ```
1177///
1178/// If you have something that implements `Read`, you can use the [`BufReader`
1179/// type][bufreader] to turn it into a `BufRead`.
1180///
1181/// For example, [`File`][file] implements `Read`, but not `BufRead`.
1182/// `BufReader` to the rescue!
85aaf69f 1183///
c1a9b12d
SL
1184/// [bufreader]: struct.BufReader.html
1185/// [file]: ../fs/struct.File.html
1186///
1187/// ```
1188/// use std::io::{self, BufReader};
1189/// use std::io::prelude::*;
1190/// use std::fs::File;
1191///
1192/// # fn foo() -> io::Result<()> {
1193/// let f = try!(File::open("foo.txt"));
1194/// let f = BufReader::new(f);
1195///
1196/// for line in f.lines() {
1197/// println!("{}", line.unwrap());
1198/// }
1199///
1200/// # Ok(())
1201/// # }
1202/// ```
62682a34 1203///
c34b1796 1204#[stable(feature = "rust1", since = "1.0.0")]
85aaf69f 1205pub trait BufRead: Read {
1a4d82fc 1206 /// Fills the internal buffer of this object, returning the buffer contents.
85aaf69f 1207 ///
c1a9b12d
SL
1208 /// This function is a lower-level call. It needs to be paired with the
1209 /// [`consume`][consume] method to function properly. When calling this
1210 /// method, none of the contents will be "read" in the sense that later
1211 /// calling `read` may return the same contents. As such, `consume` must be
1212 /// called with the number of bytes that are consumed from this buffer to
1213 /// ensure that the bytes are never returned twice.
1a4d82fc 1214 ///
c1a9b12d 1215 /// [consume]: #tymethod.consume
1a4d82fc 1216 ///
85aaf69f
SL
1217 /// An empty buffer returned indicates that the stream has reached EOF.
1218 ///
1219 /// # Errors
1a4d82fc
JJ
1220 ///
1221 /// This function will return an I/O error if the underlying reader was
85aaf69f 1222 /// read, but returned an error.
c1a9b12d
SL
1223 ///
1224 /// # Examples
1225 ///
1226 /// A locked standard input implements `BufRead`:
1227 ///
1228 /// ```
1229 /// use std::io;
1230 /// use std::io::prelude::*;
1231 ///
1232 /// let stdin = io::stdin();
1233 /// let mut stdin = stdin.lock();
1234 ///
1235 /// // we can't have two `&mut` references to `stdin`, so use a block
1236 /// // to end the borrow early.
1237 /// let length = {
1238 /// let buffer = stdin.fill_buf().unwrap();
1239 ///
1240 /// // work with buffer
1241 /// println!("{:?}", buffer);
1242 ///
1243 /// buffer.len()
1244 /// };
1245 ///
1246 /// // ensure the bytes we worked with aren't returned again later
1247 /// stdin.consume(length);
1248 /// ```
c34b1796 1249 #[stable(feature = "rust1", since = "1.0.0")]
85aaf69f 1250 fn fill_buf(&mut self) -> Result<&[u8]>;
1a4d82fc
JJ
1251
1252 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1253 /// so they should no longer be returned in calls to `read`.
c34b1796 1254 ///
c1a9b12d
SL
1255 /// This function is a lower-level call. It needs to be paired with the
1256 /// [`fill_buf`][fillbuf] method to function properly. This function does
1257 /// not perform any I/O, it simply informs this object that some amount of
1258 /// its buffer, returned from `fill_buf`, has been consumed and should no
1259 /// longer be returned. As such, this function may do odd things if
1260 /// `fill_buf` isn't called before calling it.
1261 ///
54a0048b 1262 /// [fillbuf]: #tymethod.fill_buf
c1a9b12d
SL
1263 ///
1264 /// The `amt` must be `<=` the number of bytes in the buffer returned by
1265 /// `fill_buf`.
c34b1796 1266 ///
c1a9b12d 1267 /// # Examples
c34b1796 1268 ///
c1a9b12d
SL
1269 /// Since `consume()` is meant to be used with [`fill_buf()`][fillbuf],
1270 /// that method's example includes an example of `consume()`.
c34b1796 1271 #[stable(feature = "rust1", since = "1.0.0")]
85aaf69f 1272 fn consume(&mut self, amt: usize);
1a4d82fc 1273
c1a9b12d 1274 /// Read all bytes into `buf` until the delimiter `byte` is reached.
1a4d82fc 1275 ///
c1a9b12d
SL
1276 /// This function will read bytes from the underlying stream until the
1277 /// delimiter or EOF is found. Once found, all bytes up to, and including,
1278 /// the delimiter (if found) will be appended to `buf`.
1a4d82fc 1279 ///
c1a9b12d
SL
1280 /// If this reader is currently at EOF then this function will not modify
1281 /// `buf` and will return `Ok(n)` where `n` is the number of bytes which
1282 /// were read.
1a4d82fc 1283 ///
85aaf69f 1284 /// # Errors
1a4d82fc 1285 ///
85aaf69f
SL
1286 /// This function will ignore all instances of `ErrorKind::Interrupted` and
1287 /// will otherwise return any errors returned by `fill_buf`.
1a4d82fc 1288 ///
85aaf69f
SL
1289 /// If an I/O error is encountered then all bytes read so far will be
1290 /// present in `buf` and its length will have been adjusted appropriately.
c1a9b12d
SL
1291 ///
1292 /// # Examples
1293 ///
1294 /// A locked standard input implements `BufRead`. In this example, we'll
1295 /// read from standard input until we see an `a` byte.
1296 ///
1297 /// ```
1298 /// use std::io;
1299 /// use std::io::prelude::*;
1300 ///
1301 /// fn foo() -> io::Result<()> {
1302 /// let stdin = io::stdin();
1303 /// let mut stdin = stdin.lock();
1304 /// let mut buffer = Vec::new();
1305 ///
1306 /// try!(stdin.read_until(b'a', &mut buffer));
1307 ///
1308 /// println!("{:?}", buffer);
1309 /// # Ok(())
1310 /// # }
1311 /// ```
c34b1796
AL
1312 #[stable(feature = "rust1", since = "1.0.0")]
1313 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
85aaf69f 1314 read_until(self, byte, buf)
1a4d82fc
JJ
1315 }
1316
c1a9b12d
SL
1317 /// Read all bytes until a newline (the 0xA byte) is reached, and append
1318 /// them to the provided buffer.
1a4d82fc 1319 ///
c1a9b12d
SL
1320 /// This function will read bytes from the underlying stream until the
1321 /// newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes
1322 /// up to, and including, the delimiter (if found) will be appended to
1323 /// `buf`.
1a4d82fc 1324 ///
85aaf69f 1325 /// If this reader is currently at EOF then this function will not modify
c34b1796
AL
1326 /// `buf` and will return `Ok(n)` where `n` is the number of bytes which
1327 /// were read.
85aaf69f
SL
1328 ///
1329 /// # Errors
1330 ///
1331 /// This function has the same error semantics as `read_until` and will also
1332 /// return an error if the read bytes are not valid UTF-8. If an I/O error
1333 /// is encountered then `buf` may contain some bytes already read in the
1334 /// event that all data read so far was valid UTF-8.
c1a9b12d
SL
1335 ///
1336 /// # Examples
1337 ///
1338 /// A locked standard input implements `BufRead`. In this example, we'll
1339 /// read all of the lines from standard input. If we were to do this in
1340 /// an actual project, the [`lines()`][lines] method would be easier, of
1341 /// course.
1342 ///
1343 /// [lines]: #method.lines
1344 ///
1345 /// ```
1346 /// use std::io;
1347 /// use std::io::prelude::*;
1348 ///
1349 /// let stdin = io::stdin();
1350 /// let mut stdin = stdin.lock();
1351 /// let mut buffer = String::new();
1352 ///
1353 /// while stdin.read_line(&mut buffer).unwrap() > 0 {
1354 /// // work with buffer
1355 /// println!("{:?}", buffer);
1356 ///
1357 /// buffer.clear();
1358 /// }
1359 /// ```
c34b1796
AL
1360 #[stable(feature = "rust1", since = "1.0.0")]
1361 fn read_line(&mut self, buf: &mut String) -> Result<usize> {
85aaf69f
SL
1362 // Note that we are not calling the `.read_until` method here, but
1363 // rather our hardcoded implementation. For more details as to why, see
1364 // the comments in `read_to_end`.
1365 append_to_string(buf, |b| read_until(self, b'\n', b))
1a4d82fc 1366 }
1a4d82fc 1367
85aaf69f
SL
1368 /// Returns an iterator over the contents of this reader split on the byte
1369 /// `byte`.
1a4d82fc 1370 ///
85aaf69f
SL
1371 /// The iterator returned from this function will return instances of
1372 /// `io::Result<Vec<u8>>`. Each vector returned will *not* have the
1373 /// delimiter byte at the end.
1a4d82fc 1374 ///
85aaf69f
SL
1375 /// This function will yield errors whenever `read_until` would have also
1376 /// yielded an error.
c1a9b12d
SL
1377 ///
1378 /// # Examples
1379 ///
1380 /// A locked standard input implements `BufRead`. In this example, we'll
1381 /// read some input from standard input, splitting on commas.
1382 ///
1383 /// ```
1384 /// use std::io;
1385 /// use std::io::prelude::*;
1386 ///
1387 /// let stdin = io::stdin();
1388 ///
1389 /// for content in stdin.lock().split(b',') {
1390 /// println!("{:?}", content.unwrap());
1391 /// }
1392 /// ```
c34b1796
AL
1393 #[stable(feature = "rust1", since = "1.0.0")]
1394 fn split(self, byte: u8) -> Split<Self> where Self: Sized {
85aaf69f
SL
1395 Split { buf: self, delim: byte }
1396 }
1a4d82fc 1397
85aaf69f 1398 /// Returns an iterator over the lines of this reader.
1a4d82fc 1399 ///
85aaf69f
SL
1400 /// The iterator returned from this function will yield instances of
1401 /// `io::Result<String>`. Each string returned will *not* have a newline
e9174d1e 1402 /// byte (the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.
c1a9b12d
SL
1403 ///
1404 /// # Examples
1405 ///
1406 /// A locked standard input implements `BufRead`:
1407 ///
1408 /// ```
1409 /// use std::io;
1410 /// use std::io::prelude::*;
1411 ///
1412 /// let stdin = io::stdin();
1413 ///
1414 /// for line in stdin.lock().lines() {
1415 /// println!("{}", line.unwrap());
1416 /// }
1417 /// ```
c34b1796
AL
1418 #[stable(feature = "rust1", since = "1.0.0")]
1419 fn lines(self) -> Lines<Self> where Self: Sized {
85aaf69f
SL
1420 Lines { buf: self }
1421 }
1422}
1423
c1a9b12d
SL
1424/// Adaptor to chain together two readers.
1425///
1426/// This struct is generally created by calling [`chain()`][chain] on a reader.
1427/// Please see the documentation of `chain()` for more details.
85aaf69f 1428///
c1a9b12d 1429/// [chain]: trait.Read.html#method.chain
c34b1796 1430#[stable(feature = "rust1", since = "1.0.0")]
85aaf69f
SL
1431pub struct Chain<T, U> {
1432 first: T,
1433 second: U,
1434 done_first: bool,
1a4d82fc
JJ
1435}
1436
c34b1796 1437#[stable(feature = "rust1", since = "1.0.0")]
85aaf69f
SL
1438impl<T: Read, U: Read> Read for Chain<T, U> {
1439 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1440 if !self.done_first {
54a0048b 1441 match self.first.read(buf)? {
85aaf69f
SL
1442 0 => { self.done_first = true; }
1443 n => return Ok(n),
1444 }
1445 }
1446 self.second.read(buf)
1447 }
1a4d82fc
JJ
1448}
1449
54a0048b
SL
1450#[stable(feature = "chain_bufread", since = "1.9.0")]
1451impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
1452 fn fill_buf(&mut self) -> Result<&[u8]> {
1453 if !self.done_first {
1454 match self.first.fill_buf()? {
1455 buf if buf.len() == 0 => { self.done_first = true; }
1456 buf => return Ok(buf),
1457 }
1458 }
1459 self.second.fill_buf()
1460 }
1461
1462 fn consume(&mut self, amt: usize) {
1463 if !self.done_first {
1464 self.first.consume(amt)
1465 } else {
1466 self.second.consume(amt)
1467 }
1468 }
1469}
1470
85aaf69f 1471/// Reader adaptor which limits the bytes read from an underlying reader.
1a4d82fc 1472///
c1a9b12d
SL
1473/// This struct is generally created by calling [`take()`][take] on a reader.
1474/// Please see the documentation of `take()` for more details.
1475///
1476/// [take]: trait.Read.html#method.take
c34b1796 1477#[stable(feature = "rust1", since = "1.0.0")]
85aaf69f
SL
1478pub struct Take<T> {
1479 inner: T,
1480 limit: u64,
1a4d82fc
JJ
1481}
1482
85aaf69f
SL
1483impl<T> Take<T> {
1484 /// Returns the number of bytes that can be read before this instance will
1485 /// return EOF.
1a4d82fc 1486 ///
85aaf69f 1487 /// # Note
1a4d82fc 1488 ///
85aaf69f
SL
1489 /// This instance may reach EOF after reading fewer bytes than indicated by
1490 /// this method if the underlying `Read` instance reaches EOF.
5bcae85e
SL
1491 ///
1492 /// # Examples
1493 ///
1494 /// ```
1495 /// use std::io;
1496 /// use std::io::prelude::*;
1497 /// use std::fs::File;
1498 ///
1499 /// # fn foo() -> io::Result<()> {
1500 /// let f = try!(File::open("foo.txt"));
1501 ///
1502 /// // read at most five bytes
1503 /// let handle = f.take(5);
1504 ///
1505 /// println!("limit: {}", handle.limit());
1506 /// # Ok(())
1507 /// # }
1508 /// ```
c34b1796 1509 #[stable(feature = "rust1", since = "1.0.0")]
85aaf69f
SL
1510 pub fn limit(&self) -> u64 { self.limit }
1511}
1a4d82fc 1512
c34b1796 1513#[stable(feature = "rust1", since = "1.0.0")]
85aaf69f
SL
1514impl<T: Read> Read for Take<T> {
1515 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
c34b1796
AL
1516 // Don't call into inner reader at all at EOF because it may still block
1517 if self.limit == 0 {
1518 return Ok(0);
1519 }
1520
85aaf69f 1521 let max = cmp::min(buf.len() as u64, self.limit) as usize;
54a0048b 1522 let n = self.inner.read(&mut buf[..max])?;
85aaf69f
SL
1523 self.limit -= n as u64;
1524 Ok(n)
1a4d82fc
JJ
1525 }
1526}
1527
c34b1796
AL
1528#[stable(feature = "rust1", since = "1.0.0")]
1529impl<T: BufRead> BufRead for Take<T> {
1530 fn fill_buf(&mut self) -> Result<&[u8]> {
a7813a04
XL
1531 // Don't call into inner reader at all at EOF because it may still block
1532 if self.limit == 0 {
1533 return Ok(&[]);
1534 }
1535
54a0048b 1536 let buf = self.inner.fill_buf()?;
c34b1796
AL
1537 let cap = cmp::min(buf.len() as u64, self.limit) as usize;
1538 Ok(&buf[..cap])
1539 }
1540
1541 fn consume(&mut self, amt: usize) {
1542 // Don't let callers reset the limit by passing an overlarge value
1543 let amt = cmp::min(amt as u64, self.limit) as usize;
1544 self.limit -= amt as u64;
1545 self.inner.consume(amt);
1546 }
1547}
1548
5bcae85e
SL
1549fn read_one_byte(reader: &mut Read) -> Option<Result<u8>> {
1550 let mut buf = [0];
1551 loop {
1552 return match reader.read(&mut buf) {
1553 Ok(0) => None,
1554 Ok(..) => Some(Ok(buf[0])),
1555 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1556 Err(e) => Some(Err(e)),
1557 };
1558 }
1559}
1560
c1a9b12d
SL
1561/// An iterator over `u8` values of a reader.
1562///
1563/// This struct is generally created by calling [`bytes()`][bytes] on a reader.
1564/// Please see the documentation of `bytes()` for more details.
1a4d82fc 1565///
c1a9b12d 1566/// [bytes]: trait.Read.html#method.bytes
c34b1796 1567#[stable(feature = "rust1", since = "1.0.0")]
85aaf69f
SL
1568pub struct Bytes<R> {
1569 inner: R,
1a4d82fc
JJ
1570}
1571
c34b1796 1572#[stable(feature = "rust1", since = "1.0.0")]
85aaf69f
SL
1573impl<R: Read> Iterator for Bytes<R> {
1574 type Item = Result<u8>;
1a4d82fc 1575
85aaf69f 1576 fn next(&mut self) -> Option<Result<u8>> {
5bcae85e 1577 read_one_byte(&mut self.inner)
85aaf69f 1578 }
1a4d82fc
JJ
1579}
1580
c1a9b12d 1581/// An iterator over the `char`s of a reader.
1a4d82fc 1582///
c1a9b12d
SL
1583/// This struct is generally created by calling [`chars()`][chars] on a reader.
1584/// Please see the documentation of `chars()` for more details.
1585///
1586/// [chars]: trait.Read.html#method.chars
e9174d1e
SL
1587#[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1588 issue = "27802")]
85aaf69f
SL
1589pub struct Chars<R> {
1590 inner: R,
1a4d82fc
JJ
1591}
1592
85aaf69f
SL
1593/// An enumeration of possible errors that can be generated from the `Chars`
1594/// adapter.
c34b1796 1595#[derive(Debug)]
e9174d1e
SL
1596#[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1597 issue = "27802")]
85aaf69f
SL
1598pub enum CharsError {
1599 /// Variant representing that the underlying stream was read successfully
1600 /// but it did not contain valid utf8 data.
1601 NotUtf8,
1a4d82fc 1602
85aaf69f
SL
1603 /// Variant representing that an I/O error occurred.
1604 Other(Error),
1a4d82fc
JJ
1605}
1606
e9174d1e
SL
1607#[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1608 issue = "27802")]
85aaf69f
SL
1609impl<R: Read> Iterator for Chars<R> {
1610 type Item = result::Result<char, CharsError>;
1a4d82fc 1611
85aaf69f 1612 fn next(&mut self) -> Option<result::Result<char, CharsError>> {
5bcae85e
SL
1613 let first_byte = match read_one_byte(&mut self.inner) {
1614 None => return None,
1615 Some(Ok(b)) => b,
1616 Some(Err(e)) => return Some(Err(CharsError::Other(e))),
85aaf69f
SL
1617 };
1618 let width = core_str::utf8_char_width(first_byte);
1619 if width == 1 { return Some(Ok(first_byte as char)) }
1620 if width == 0 { return Some(Err(CharsError::NotUtf8)) }
1621 let mut buf = [first_byte, 0, 0, 0];
1622 {
1623 let mut start = 1;
1624 while start < width {
1625 match self.inner.read(&mut buf[start..width]) {
1626 Ok(0) => return Some(Err(CharsError::NotUtf8)),
1627 Ok(n) => start += n,
5bcae85e 1628 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
85aaf69f
SL
1629 Err(e) => return Some(Err(CharsError::Other(e))),
1630 }
1631 }
1632 }
1633 Some(match str::from_utf8(&buf[..width]).ok() {
54a0048b 1634 Some(s) => Ok(s.chars().next().unwrap()),
85aaf69f
SL
1635 None => Err(CharsError::NotUtf8),
1636 })
1637 }
1a4d82fc
JJ
1638}
1639
e9174d1e
SL
1640#[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1641 issue = "27802")]
c34b1796 1642impl std_error::Error for CharsError {
85aaf69f
SL
1643 fn description(&self) -> &str {
1644 match *self {
1645 CharsError::NotUtf8 => "invalid utf8 encoding",
c34b1796 1646 CharsError::Other(ref e) => std_error::Error::description(e),
85aaf69f
SL
1647 }
1648 }
c34b1796 1649 fn cause(&self) -> Option<&std_error::Error> {
85aaf69f
SL
1650 match *self {
1651 CharsError::NotUtf8 => None,
1652 CharsError::Other(ref e) => e.cause(),
1653 }
1a4d82fc
JJ
1654 }
1655}
1656
e9174d1e
SL
1657#[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1658 issue = "27802")]
85aaf69f 1659impl fmt::Display for CharsError {
1a4d82fc 1660 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
85aaf69f
SL
1661 match *self {
1662 CharsError::NotUtf8 => {
1663 "byte stream did not contain valid utf8".fmt(f)
1664 }
1665 CharsError::Other(ref e) => e.fmt(f),
1666 }
1a4d82fc
JJ
1667 }
1668}
1669
85aaf69f
SL
1670/// An iterator over the contents of an instance of `BufRead` split on a
1671/// particular byte.
1672///
c1a9b12d
SL
1673/// This struct is generally created by calling [`split()`][split] on a
1674/// `BufRead`. Please see the documentation of `split()` for more details.
1675///
1676/// [split]: trait.BufRead.html#method.split
c34b1796 1677#[stable(feature = "rust1", since = "1.0.0")]
85aaf69f
SL
1678pub struct Split<B> {
1679 buf: B,
1680 delim: u8,
1681}
1a4d82fc 1682
c34b1796 1683#[stable(feature = "rust1", since = "1.0.0")]
85aaf69f
SL
1684impl<B: BufRead> Iterator for Split<B> {
1685 type Item = Result<Vec<u8>>;
1a4d82fc 1686
85aaf69f
SL
1687 fn next(&mut self) -> Option<Result<Vec<u8>>> {
1688 let mut buf = Vec::new();
1689 match self.buf.read_until(self.delim, &mut buf) {
c34b1796
AL
1690 Ok(0) => None,
1691 Ok(_n) => {
85aaf69f
SL
1692 if buf[buf.len() - 1] == self.delim {
1693 buf.pop();
1694 }
1695 Some(Ok(buf))
1696 }
1697 Err(e) => Some(Err(e))
1a4d82fc
JJ
1698 }
1699 }
85aaf69f
SL
1700}
1701
c1a9b12d 1702/// An iterator over the lines of an instance of `BufRead`.
85aaf69f 1703///
c1a9b12d
SL
1704/// This struct is generally created by calling [`lines()`][lines] on a
1705/// `BufRead`. Please see the documentation of `lines()` for more details.
1706///
1707/// [lines]: trait.BufRead.html#method.lines
c34b1796 1708#[stable(feature = "rust1", since = "1.0.0")]
85aaf69f
SL
1709pub struct Lines<B> {
1710 buf: B,
1711}
1712
c34b1796 1713#[stable(feature = "rust1", since = "1.0.0")]
85aaf69f
SL
1714impl<B: BufRead> Iterator for Lines<B> {
1715 type Item = Result<String>;
1a4d82fc 1716
85aaf69f
SL
1717 fn next(&mut self) -> Option<Result<String>> {
1718 let mut buf = String::new();
1719 match self.buf.read_line(&mut buf) {
c34b1796
AL
1720 Ok(0) => None,
1721 Ok(_n) => {
85aaf69f
SL
1722 if buf.ends_with("\n") {
1723 buf.pop();
e9174d1e
SL
1724 if buf.ends_with("\r") {
1725 buf.pop();
1726 }
1a4d82fc 1727 }
85aaf69f 1728 Some(Ok(buf))
1a4d82fc 1729 }
85aaf69f 1730 Err(e) => Some(Err(e))
1a4d82fc
JJ
1731 }
1732 }
85aaf69f
SL
1733}
1734
1735#[cfg(test)]
1736mod tests {
1737 use prelude::v1::*;
1738 use io::prelude::*;
c34b1796 1739 use io;
85aaf69f 1740 use super::Cursor;
c1a9b12d
SL
1741 use test;
1742 use super::repeat;
1a4d82fc
JJ
1743
1744 #[test]
85aaf69f 1745 fn read_until() {
c34b1796 1746 let mut buf = Cursor::new(&b"12"[..]);
85aaf69f 1747 let mut v = Vec::new();
c34b1796 1748 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 2);
85aaf69f
SL
1749 assert_eq!(v, b"12");
1750
c34b1796 1751 let mut buf = Cursor::new(&b"1233"[..]);
85aaf69f 1752 let mut v = Vec::new();
c34b1796 1753 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 3);
85aaf69f
SL
1754 assert_eq!(v, b"123");
1755 v.truncate(0);
c34b1796 1756 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 1);
85aaf69f
SL
1757 assert_eq!(v, b"3");
1758 v.truncate(0);
c34b1796 1759 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 0);
85aaf69f 1760 assert_eq!(v, []);
1a4d82fc
JJ
1761 }
1762
1763 #[test]
85aaf69f 1764 fn split() {
c34b1796 1765 let buf = Cursor::new(&b"12"[..]);
85aaf69f 1766 let mut s = buf.split(b'3');
c34b1796
AL
1767 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
1768 assert!(s.next().is_none());
1a4d82fc 1769
c34b1796 1770 let buf = Cursor::new(&b"1233"[..]);
85aaf69f 1771 let mut s = buf.split(b'3');
c34b1796
AL
1772 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
1773 assert_eq!(s.next().unwrap().unwrap(), vec![]);
1774 assert!(s.next().is_none());
85aaf69f 1775 }
1a4d82fc 1776
85aaf69f
SL
1777 #[test]
1778 fn read_line() {
c34b1796 1779 let mut buf = Cursor::new(&b"12"[..]);
85aaf69f 1780 let mut v = String::new();
c34b1796 1781 assert_eq!(buf.read_line(&mut v).unwrap(), 2);
85aaf69f
SL
1782 assert_eq!(v, "12");
1783
c34b1796 1784 let mut buf = Cursor::new(&b"12\n\n"[..]);
85aaf69f 1785 let mut v = String::new();
c34b1796 1786 assert_eq!(buf.read_line(&mut v).unwrap(), 3);
85aaf69f
SL
1787 assert_eq!(v, "12\n");
1788 v.truncate(0);
c34b1796 1789 assert_eq!(buf.read_line(&mut v).unwrap(), 1);
85aaf69f
SL
1790 assert_eq!(v, "\n");
1791 v.truncate(0);
c34b1796 1792 assert_eq!(buf.read_line(&mut v).unwrap(), 0);
85aaf69f
SL
1793 assert_eq!(v, "");
1794 }
1a4d82fc 1795
85aaf69f
SL
1796 #[test]
1797 fn lines() {
e9174d1e 1798 let buf = Cursor::new(&b"12\r"[..]);
85aaf69f 1799 let mut s = buf.lines();
e9174d1e 1800 assert_eq!(s.next().unwrap().unwrap(), "12\r".to_string());
c34b1796 1801 assert!(s.next().is_none());
1a4d82fc 1802
e9174d1e 1803 let buf = Cursor::new(&b"12\r\n\n"[..]);
85aaf69f 1804 let mut s = buf.lines();
c34b1796
AL
1805 assert_eq!(s.next().unwrap().unwrap(), "12".to_string());
1806 assert_eq!(s.next().unwrap().unwrap(), "".to_string());
1807 assert!(s.next().is_none());
1a4d82fc
JJ
1808 }
1809
1810 #[test]
85aaf69f 1811 fn read_to_end() {
c34b1796 1812 let mut c = Cursor::new(&b""[..]);
85aaf69f 1813 let mut v = Vec::new();
c34b1796 1814 assert_eq!(c.read_to_end(&mut v).unwrap(), 0);
85aaf69f
SL
1815 assert_eq!(v, []);
1816
c34b1796 1817 let mut c = Cursor::new(&b"1"[..]);
85aaf69f 1818 let mut v = Vec::new();
c34b1796 1819 assert_eq!(c.read_to_end(&mut v).unwrap(), 1);
85aaf69f 1820 assert_eq!(v, b"1");
c1a9b12d
SL
1821
1822 let cap = 1024 * 1024;
1823 let data = (0..cap).map(|i| (i / 3) as u8).collect::<Vec<_>>();
1824 let mut v = Vec::new();
1825 let (a, b) = data.split_at(data.len() / 2);
1826 assert_eq!(Cursor::new(a).read_to_end(&mut v).unwrap(), a.len());
1827 assert_eq!(Cursor::new(b).read_to_end(&mut v).unwrap(), b.len());
1828 assert_eq!(v, data);
1a4d82fc
JJ
1829 }
1830
85aaf69f
SL
1831 #[test]
1832 fn read_to_string() {
c34b1796 1833 let mut c = Cursor::new(&b""[..]);
85aaf69f 1834 let mut v = String::new();
c34b1796 1835 assert_eq!(c.read_to_string(&mut v).unwrap(), 0);
85aaf69f
SL
1836 assert_eq!(v, "");
1837
c34b1796 1838 let mut c = Cursor::new(&b"1"[..]);
85aaf69f 1839 let mut v = String::new();
c34b1796 1840 assert_eq!(c.read_to_string(&mut v).unwrap(), 1);
85aaf69f
SL
1841 assert_eq!(v, "1");
1842
c34b1796 1843 let mut c = Cursor::new(&b"\xff"[..]);
85aaf69f
SL
1844 let mut v = String::new();
1845 assert!(c.read_to_string(&mut v).is_err());
1a4d82fc 1846 }
c34b1796 1847
e9174d1e
SL
1848 #[test]
1849 fn read_exact() {
1850 let mut buf = [0; 4];
1851
1852 let mut c = Cursor::new(&b""[..]);
1853 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
92a42be0 1854 io::ErrorKind::UnexpectedEof);
e9174d1e
SL
1855
1856 let mut c = Cursor::new(&b"123"[..]).chain(Cursor::new(&b"456789"[..]));
1857 c.read_exact(&mut buf).unwrap();
1858 assert_eq!(&buf, b"1234");
1859 c.read_exact(&mut buf).unwrap();
1860 assert_eq!(&buf, b"5678");
1861 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
92a42be0 1862 io::ErrorKind::UnexpectedEof);
e9174d1e
SL
1863 }
1864
1865 #[test]
1866 fn read_exact_slice() {
1867 let mut buf = [0; 4];
1868
1869 let mut c = &b""[..];
1870 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
92a42be0 1871 io::ErrorKind::UnexpectedEof);
e9174d1e
SL
1872
1873 let mut c = &b"123"[..];
1874 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
92a42be0 1875 io::ErrorKind::UnexpectedEof);
e9174d1e
SL
1876 // make sure the optimized (early returning) method is being used
1877 assert_eq!(&buf, &[0; 4]);
1878
1879 let mut c = &b"1234"[..];
1880 c.read_exact(&mut buf).unwrap();
1881 assert_eq!(&buf, b"1234");
1882
1883 let mut c = &b"56789"[..];
1884 c.read_exact(&mut buf).unwrap();
1885 assert_eq!(&buf, b"5678");
1886 assert_eq!(c, b"9");
1887 }
1888
c34b1796
AL
1889 #[test]
1890 fn take_eof() {
1891 struct R;
1892
1893 impl Read for R {
1894 fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
1895 Err(io::Error::new(io::ErrorKind::Other, ""))
1896 }
1897 }
a7813a04
XL
1898 impl BufRead for R {
1899 fn fill_buf(&mut self) -> io::Result<&[u8]> {
1900 Err(io::Error::new(io::ErrorKind::Other, ""))
1901 }
1902 fn consume(&mut self, _amt: usize) { }
1903 }
c34b1796
AL
1904
1905 let mut buf = [0; 1];
1906 assert_eq!(0, R.take(0).read(&mut buf).unwrap());
a7813a04 1907 assert_eq!(b"", R.take(0).fill_buf().unwrap());
c34b1796 1908 }
c1a9b12d 1909
54a0048b
SL
1910 fn cmp_bufread<Br1: BufRead, Br2: BufRead>(mut br1: Br1, mut br2: Br2, exp: &[u8]) {
1911 let mut cat = Vec::new();
1912 loop {
1913 let consume = {
1914 let buf1 = br1.fill_buf().unwrap();
1915 let buf2 = br2.fill_buf().unwrap();
1916 let minlen = if buf1.len() < buf2.len() { buf1.len() } else { buf2.len() };
1917 assert_eq!(buf1[..minlen], buf2[..minlen]);
1918 cat.extend_from_slice(&buf1[..minlen]);
1919 minlen
1920 };
1921 if consume == 0 {
1922 break;
1923 }
1924 br1.consume(consume);
1925 br2.consume(consume);
1926 }
1927 assert_eq!(br1.fill_buf().unwrap().len(), 0);
1928 assert_eq!(br2.fill_buf().unwrap().len(), 0);
1929 assert_eq!(&cat[..], &exp[..])
1930 }
1931
1932 #[test]
1933 fn chain_bufread() {
1934 let testdata = b"ABCDEFGHIJKL";
1935 let chain1 = (&testdata[..3]).chain(&testdata[3..6])
1936 .chain(&testdata[6..9])
1937 .chain(&testdata[9..]);
1938 let chain2 = (&testdata[..4]).chain(&testdata[4..8])
1939 .chain(&testdata[8..]);
1940 cmp_bufread(chain1, chain2, &testdata[..]);
1941 }
1942
c1a9b12d
SL
1943 #[bench]
1944 fn bench_read_to_end(b: &mut test::Bencher) {
1945 b.iter(|| {
1946 let mut lr = repeat(1).take(10000000);
1947 let mut vec = Vec::with_capacity(1024);
9cc50fc6 1948 super::read_to_end(&mut lr, &mut vec)
c1a9b12d
SL
1949 });
1950 }
1a4d82fc 1951}