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