1 //! Traits, helpers, and type definitions for core I/O functionality.
3 //! The `std::io` module contains a number of common things you'll need
4 //! when doing input and output. The most core part of this module is
5 //! the [`Read`] and [`Write`] traits, which provide the
6 //! most general interface for reading and writing input and output.
10 //! Because they are traits, [`Read`] and [`Write`] are implemented by a number
11 //! of other types, and you can implement them for your types too. As such,
12 //! you'll see a few different types of I/O throughout the documentation in
13 //! this module: [`File`]s, [`TcpStream`]s, and sometimes even [`Vec<T>`]s. For
14 //! example, [`Read`] adds a [`read`][`Read::read`] method, which we can use on
19 //! use std::io::prelude::*;
20 //! use std::fs::File;
22 //! fn main() -> io::Result<()> {
23 //! let mut f = File::open("foo.txt")?;
24 //! let mut buffer = [0; 10];
26 //! // read up to 10 bytes
27 //! let n = f.read(&mut buffer)?;
29 //! println!("The bytes: {:?}", &buffer[..n]);
34 //! [`Read`] and [`Write`] are so important, implementors of the two traits have a
35 //! nickname: readers and writers. So you'll sometimes see 'a reader' instead
36 //! of 'a type that implements the [`Read`] trait'. Much easier!
38 //! ## Seek and BufRead
40 //! Beyond that, there are two important traits that are provided: [`Seek`]
41 //! and [`BufRead`]. Both of these build on top of a reader to control
42 //! how the reading happens. [`Seek`] lets you control where the next byte is
47 //! use std::io::prelude::*;
48 //! use std::io::SeekFrom;
49 //! use std::fs::File;
51 //! fn main() -> io::Result<()> {
52 //! let mut f = File::open("foo.txt")?;
53 //! let mut buffer = [0; 10];
55 //! // skip to the last 10 bytes of the file
56 //! f.seek(SeekFrom::End(-10))?;
58 //! // read up to 10 bytes
59 //! let n = f.read(&mut buffer)?;
61 //! println!("The bytes: {:?}", &buffer[..n]);
66 //! [`BufRead`] uses an internal buffer to provide a number of other ways to read, but
67 //! to show it off, we'll need to talk about buffers in general. Keep reading!
69 //! ## BufReader and BufWriter
71 //! Byte-based interfaces are unwieldy and can be inefficient, as we'd need to be
72 //! making near-constant calls to the operating system. To help with this,
73 //! `std::io` comes with two structs, [`BufReader`] and [`BufWriter`], which wrap
74 //! readers and writers. The wrapper uses a buffer, reducing the number of
75 //! calls and providing nicer methods for accessing exactly what you want.
77 //! For example, [`BufReader`] works with the [`BufRead`] trait to add extra
78 //! methods to any reader:
82 //! use std::io::prelude::*;
83 //! use std::io::BufReader;
84 //! use std::fs::File;
86 //! fn main() -> io::Result<()> {
87 //! let f = File::open("foo.txt")?;
88 //! let mut reader = BufReader::new(f);
89 //! let mut buffer = String::new();
91 //! // read a line into buffer
92 //! reader.read_line(&mut buffer)?;
94 //! println!("{}", buffer);
99 //! [`BufWriter`] doesn't add any new ways of writing; it just buffers every call
100 //! to [`write`][`Write::write`]:
104 //! use std::io::prelude::*;
105 //! use std::io::BufWriter;
106 //! use std::fs::File;
108 //! fn main() -> io::Result<()> {
109 //! let f = File::create("foo.txt")?;
111 //! let mut writer = BufWriter::new(f);
113 //! // write a byte to the buffer
114 //! writer.write(&[42])?;
116 //! } // the buffer is flushed once writer goes out of scope
122 //! ## Standard input and output
124 //! A very common source of input is standard input:
129 //! fn main() -> io::Result<()> {
130 //! let mut input = String::new();
132 //! io::stdin().read_line(&mut input)?;
134 //! println!("You typed: {}", input.trim());
139 //! Note that you cannot use the [`?` operator] in functions that do not return
140 //! a [`Result<T, E>`][`Result`]. Instead, you can call [`.unwrap()`]
141 //! or `match` on the return value to catch any possible errors:
146 //! let mut input = String::new();
148 //! io::stdin().read_line(&mut input).unwrap();
151 //! And a very common source of output is standard output:
155 //! use std::io::prelude::*;
157 //! fn main() -> io::Result<()> {
158 //! io::stdout().write(&[42])?;
163 //! Of course, using [`io::stdout`] directly is less common than something like
166 //! ## Iterator types
168 //! A large number of the structures provided by `std::io` are for various
169 //! ways of iterating over I/O. For example, [`Lines`] is used to split over
174 //! use std::io::prelude::*;
175 //! use std::io::BufReader;
176 //! use std::fs::File;
178 //! fn main() -> io::Result<()> {
179 //! let f = File::open("foo.txt")?;
180 //! let reader = BufReader::new(f);
182 //! for line in reader.lines() {
183 //! println!("{}", line?);
191 //! There are a number of [functions][functions-list] that offer access to various
192 //! features. For example, we can use three of these functions to copy everything
193 //! from standard input to standard output:
198 //! fn main() -> io::Result<()> {
199 //! io::copy(&mut io::stdin(), &mut io::stdout())?;
204 //! [functions-list]: #functions-1
208 //! Last, but certainly not least, is [`io::Result`]. This type is used
209 //! as the return type of many `std::io` functions that can cause an error, and
210 //! can be returned from your own functions as well. Many of the examples in this
211 //! module use the [`?` operator]:
216 //! fn read_input() -> io::Result<()> {
217 //! let mut input = String::new();
219 //! io::stdin().read_line(&mut input)?;
221 //! println!("You typed: {}", input.trim());
227 //! The return type of `read_input()`, [`io::Result<()>`][`io::Result`], is a very
228 //! common type for functions which don't have a 'real' return value, but do want to
229 //! return errors if they happen. In this case, the only purpose of this function is
230 //! to read the line and print it, so we use `()`.
232 //! ## Platform-specific behavior
234 //! Many I/O functions throughout the standard library are documented to indicate
235 //! what various library or syscalls they are delegated to. This is done to help
236 //! applications both understand what's happening under the hood as well as investigate
237 //! any possibly unclear semantics. Note, however, that this is informative, not a binding
238 //! contract. The implementation of many of these functions are subject to change over
239 //! time and may call fewer or more syscalls/library functions.
241 //! [`File`]: crate::fs::File
242 //! [`TcpStream`]: crate::net::TcpStream
243 //! [`io::stdout`]: stdout
244 //! [`io::Result`]: self::Result
245 //! [`?` operator]: ../../book/appendix-02-operators.html
246 //! [`Result`]: crate::result::Result
247 //! [`.unwrap()`]: crate::result::Result::unwrap
249 #![stable(feature = "rust1", since = "1.0.0")]
257 use crate::ops
::{Deref, DerefMut}
;
263 #[stable(feature = "rust1", since = "1.0.0")]
264 pub use self::buffered
::IntoInnerError
;
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::copy
::copy
;
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
::{Error, ErrorKind, Result}
;
273 #[unstable(feature = "internal_output_capture", issue = "none")]
274 #[doc(no_inline, hidden)]
275 pub use self::stdio
::set_output_capture
;
276 #[stable(feature = "rust1", since = "1.0.0")]
277 pub use self::stdio
::{stderr, stdin, stdout, Stderr, Stdin, Stdout}
;
278 #[stable(feature = "rust1", since = "1.0.0")]
279 pub use self::stdio
::{StderrLock, StdinLock, StdoutLock}
;
280 #[unstable(feature = "print_internals", issue = "none")]
281 pub use self::stdio
::{_eprint, _print}
;
282 #[stable(feature = "rust1", since = "1.0.0")]
283 pub use self::util
::{empty, repeat, sink, Empty, Repeat, Sink}
;
294 const DEFAULT_BUF_SIZE
: usize = crate::sys_common
::io
::DEFAULT_BUF_SIZE
;
297 buf
: &'a
mut Vec
<u8>,
301 impl Drop
for Guard
<'_
> {
304 self.buf
.set_len(self.len
);
309 // A few methods below (read_to_string, read_line) will append data into a
310 // `String` buffer, but we need to be pretty careful when doing this. The
311 // implementation will just call `.as_mut_vec()` and then delegate to a
312 // byte-oriented reading method, but we must ensure that when returning we never
313 // leave `buf` in a state such that it contains invalid UTF-8 in its bounds.
315 // To this end, we use an RAII guard (to protect against panics) which updates
316 // the length of the string when it is dropped. This guard initially truncates
317 // the string to the prior length and only after we've validated that the
318 // new contents are valid UTF-8 do we allow it to set a longer length.
320 // The unsafety in this function is twofold:
322 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
324 // 2. We're passing a raw buffer to the function `f`, and it is expected that
325 // the function only *appends* bytes to the buffer. We'll get undefined
326 // behavior if existing bytes are overwritten to have non-UTF-8 data.
327 fn append_to_string
<F
>(buf
: &mut String
, f
: F
) -> Result
<usize>
329 F
: FnOnce(&mut Vec
<u8>) -> Result
<usize>,
332 let mut g
= Guard { len: buf.len(), buf: buf.as_mut_vec() }
;
334 if str::from_utf8(&g
.buf
[g
.len
..]).is_err() {
336 Err(Error
::new(ErrorKind
::InvalidData
, "stream did not contain valid UTF-8"))
345 // This uses an adaptive system to extend the vector when it fills. We want to
346 // avoid paying to allocate and zero a huge chunk of memory if the reader only
347 // has 4 bytes while still making large reads if the reader does have a ton
348 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
349 // time is 4,500 times (!) slower than a default reservation size of 32 if the
350 // reader has a very small amount of data to return.
352 // Because we're extending the buffer with uninitialized data for trusted
353 // readers, we need to make sure to truncate that if any of this panics.
354 fn read_to_end
<R
: Read
+ ?Sized
>(r
: &mut R
, buf
: &mut Vec
<u8>) -> Result
<usize> {
355 read_to_end_with_reservation(r
, buf
, |_
| 32)
358 fn read_to_end_with_reservation
<R
, F
>(
361 mut reservation_size
: F
,
365 F
: FnMut(&R
) -> usize,
367 let start_len
= buf
.len();
368 let mut g
= Guard { len: buf.len(), buf }
;
370 if g
.len
== g
.buf
.len() {
372 // FIXME(danielhenrymantilla): #42788
374 // - This creates a (mut) reference to a slice of
375 // _uninitialized_ integers, which is **undefined behavior**
377 // - Only the standard library gets to soundly "ignore" this,
378 // based on its privileged knowledge of unstable rustc
380 g
.buf
.reserve(reservation_size(r
));
381 let capacity
= g
.buf
.capacity();
382 g
.buf
.set_len(capacity
);
383 r
.initializer().initialize(&mut g
.buf
[g
.len
..]);
387 let buf
= &mut g
.buf
[g
.len
..];
389 Ok(0) => return Ok(g
.len
- start_len
),
391 // We can't allow bogus values from read. If it is too large, the returned vec could have its length
392 // set past its capacity, or if it overflows the vec could be shortened which could create an invalid
393 // string if this is called via read_to_string.
394 assert
!(n
<= buf
.len());
397 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> {}
398 Err(e
) => return Err(e
),
403 pub(crate) fn default_read_vectored
<F
>(read
: F
, bufs
: &mut [IoSliceMut
<'_
>]) -> Result
<usize>
405 F
: FnOnce(&mut [u8]) -> Result
<usize>,
407 let buf
= bufs
.iter_mut().find(|b
| !b
.is_empty()).map_or(&mut [][..], |b
| &mut **b
);
411 pub(crate) fn default_write_vectored
<F
>(write
: F
, bufs
: &[IoSlice
<'_
>]) -> Result
<usize>
413 F
: FnOnce(&[u8]) -> Result
<usize>,
415 let buf
= bufs
.iter().find(|b
| !b
.is_empty()).map_or(&[][..], |b
| &**b
);
419 pub(crate) fn default_read_exact
<R
: Read
+ ?Sized
>(this
: &mut R
, mut buf
: &mut [u8]) -> Result
<()> {
420 while !buf
.is_empty() {
421 match this
.read(buf
) {
427 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> {}
428 Err(e
) => return Err(e
),
432 Err(Error
::new(ErrorKind
::UnexpectedEof
, "failed to fill whole buffer"))
438 /// The `Read` trait allows for reading bytes from a source.
440 /// Implementors of the `Read` trait are called 'readers'.
442 /// Readers are defined by one required method, [`read()`]. Each call to [`read()`]
443 /// will attempt to pull bytes from this source into a provided buffer. A
444 /// number of other methods are implemented in terms of [`read()`], giving
445 /// implementors a number of ways to read bytes while only needing to implement
448 /// Readers are intended to be composable with one another. Many implementors
449 /// throughout [`std::io`] take and provide types which implement the `Read`
452 /// Please note that each call to [`read()`] may involve a system call, and
453 /// therefore, using something that implements [`BufRead`], such as
454 /// [`BufReader`], will be more efficient.
458 /// [`File`]s implement `Read`:
462 /// use std::io::prelude::*;
463 /// use std::fs::File;
465 /// fn main() -> io::Result<()> {
466 /// let mut f = File::open("foo.txt")?;
467 /// let mut buffer = [0; 10];
469 /// // read up to 10 bytes
470 /// f.read(&mut buffer)?;
472 /// let mut buffer = Vec::new();
473 /// // read the whole file
474 /// f.read_to_end(&mut buffer)?;
476 /// // read into a String, so that you don't need to do the conversion.
477 /// let mut buffer = String::new();
478 /// f.read_to_string(&mut buffer)?;
480 /// // and more! See the other methods for more details.
485 /// Read from [`&str`] because [`&[u8]`][prim@slice] implements `Read`:
489 /// use std::io::prelude::*;
491 /// fn main() -> io::Result<()> {
492 /// let mut b = "This string will be read".as_bytes();
493 /// let mut buffer = [0; 10];
495 /// // read up to 10 bytes
496 /// b.read(&mut buffer)?;
498 /// // etc... it works exactly as a File does!
503 /// [`read()`]: Read::read
504 /// [`&str`]: prim@str
505 /// [`std::io`]: self
506 /// [`File`]: crate::fs::File
507 #[stable(feature = "rust1", since = "1.0.0")]
510 /// Pull some bytes from this source into the specified buffer, returning
511 /// how many bytes were read.
513 /// This function does not provide any guarantees about whether it blocks
514 /// waiting for data, but if an object needs to block for a read and cannot,
515 /// it will typically signal this via an [`Err`] return value.
517 /// If the return value of this method is [`Ok(n)`], then implementations must
518 /// guarantee that `0 <= n <= buf.len()`. A nonzero `n` value indicates
519 /// that the buffer `buf` has been filled in with `n` bytes of data from this
520 /// source. If `n` is `0`, then it can indicate one of two scenarios:
522 /// 1. This reader has reached its "end of file" and will likely no longer
523 /// be able to produce bytes. Note that this does not mean that the
524 /// reader will *always* no longer be able to produce bytes.
525 /// 2. The buffer specified was 0 bytes in length.
527 /// It is not an error if the returned value `n` is smaller than the buffer size,
528 /// even when the reader is not at the end of the stream yet.
529 /// This may happen for example because fewer bytes are actually available right now
530 /// (e. g. being close to end-of-file) or because read() was interrupted by a signal.
532 /// As this trait is safe to implement, callers cannot rely on `n <= buf.len()` for safety.
533 /// Extra care needs to be taken when `unsafe` functions are used to access the read bytes.
534 /// Callers have to ensure that no unchecked out-of-bounds accesses are possible even if
537 /// No guarantees are provided about the contents of `buf` when this
538 /// function is called, implementations cannot rely on any property of the
539 /// contents of `buf` being true. It is recommended that *implementations*
540 /// only write data to `buf` instead of reading its contents.
542 /// Correspondingly, however, *callers* of this method may not assume any guarantees
543 /// about how the implementation uses `buf`. The trait is safe to implement,
544 /// so it is possible that the code that's supposed to write to the buffer might also read
545 /// from it. It is your responsibility to make sure that `buf` is initialized
546 /// before calling `read`. Calling `read` with an uninitialized `buf` (of the kind one
547 /// obtains via [`MaybeUninit<T>`]) is not safe, and can lead to undefined behavior.
549 /// [`MaybeUninit<T>`]: crate::mem::MaybeUninit
553 /// If this function encounters any form of I/O or other error, an error
554 /// variant will be returned. If an error is returned then it must be
555 /// guaranteed that no bytes were read.
557 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
558 /// operation should be retried if there is nothing else to do.
562 /// [`File`]s implement `Read`:
565 /// [`File`]: crate::fs::File
569 /// use std::io::prelude::*;
570 /// use std::fs::File;
572 /// fn main() -> io::Result<()> {
573 /// let mut f = File::open("foo.txt")?;
574 /// let mut buffer = [0; 10];
576 /// // read up to 10 bytes
577 /// let n = f.read(&mut buffer[..])?;
579 /// println!("The bytes: {:?}", &buffer[..n]);
583 #[stable(feature = "rust1", since = "1.0.0")]
584 fn read(&mut self, buf
: &mut [u8]) -> Result
<usize>;
586 /// Like `read`, except that it reads into a slice of buffers.
588 /// Data is copied to fill each buffer in order, with the final buffer
589 /// written to possibly being only partially filled. This method must
590 /// behave equivalently to a single call to `read` with concatenated
593 /// The default implementation calls `read` with either the first nonempty
594 /// buffer provided, or an empty one if none exists.
595 #[stable(feature = "iovec", since = "1.36.0")]
596 fn read_vectored(&mut self, bufs
: &mut [IoSliceMut
<'_
>]) -> Result
<usize> {
597 default_read_vectored(|b
| self.read(b
), bufs
)
600 /// Determines if this `Read`er has an efficient `read_vectored`
603 /// If a `Read`er does not override the default `read_vectored`
604 /// implementation, code using it may want to avoid the method all together
605 /// and coalesce writes into a single buffer for higher performance.
607 /// The default implementation returns `false`.
608 #[unstable(feature = "can_vector", issue = "69941")]
609 fn is_read_vectored(&self) -> bool
{
613 /// Determines if this `Read`er can work with buffers of uninitialized
616 /// The default implementation returns an initializer which will zero
619 /// If a `Read`er guarantees that it can work properly with uninitialized
620 /// memory, it should call [`Initializer::nop()`]. See the documentation for
621 /// [`Initializer`] for details.
623 /// The behavior of this method must be independent of the state of the
624 /// `Read`er - the method only takes `&self` so that it can be used through
629 /// This method is unsafe because a `Read`er could otherwise return a
630 /// non-zeroing `Initializer` from another `Read` type without an `unsafe`
632 #[unstable(feature = "read_initializer", issue = "42788")]
634 unsafe fn initializer(&self) -> Initializer
{
635 Initializer
::zeroing()
638 /// Read all bytes until EOF in this source, placing them into `buf`.
640 /// All bytes read from this source will be appended to the specified buffer
641 /// `buf`. This function will continuously call [`read()`] to append more data to
642 /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of
643 /// non-[`ErrorKind::Interrupted`] kind.
645 /// If successful, this function will return the total number of bytes read.
649 /// If this function encounters an error of the kind
650 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
653 /// If any other read error is encountered then this function immediately
654 /// returns. Any bytes which have already been read will be appended to
659 /// [`File`]s implement `Read`:
661 /// [`read()`]: Read::read
663 /// [`File`]: crate::fs::File
667 /// use std::io::prelude::*;
668 /// use std::fs::File;
670 /// fn main() -> io::Result<()> {
671 /// let mut f = File::open("foo.txt")?;
672 /// let mut buffer = Vec::new();
674 /// // read the whole file
675 /// f.read_to_end(&mut buffer)?;
680 /// (See also the [`std::fs::read`] convenience function for reading from a
683 /// [`std::fs::read`]: crate::fs::read
684 #[stable(feature = "rust1", since = "1.0.0")]
685 fn read_to_end(&mut self, buf
: &mut Vec
<u8>) -> Result
<usize> {
686 read_to_end(self, buf
)
689 /// Read all bytes until EOF in this source, appending them to `buf`.
691 /// If successful, this function returns the number of bytes which were read
692 /// and appended to `buf`.
696 /// If the data in this stream is *not* valid UTF-8 then an error is
697 /// returned and `buf` is unchanged.
699 /// See [`read_to_end`] for other error semantics.
701 /// [`read_to_end`]: Read::read_to_end
705 /// [`File`]s implement `Read`:
707 /// [`File`]: crate::fs::File
711 /// use std::io::prelude::*;
712 /// use std::fs::File;
714 /// fn main() -> io::Result<()> {
715 /// let mut f = File::open("foo.txt")?;
716 /// let mut buffer = String::new();
718 /// f.read_to_string(&mut buffer)?;
723 /// (See also the [`std::fs::read_to_string`] convenience function for
724 /// reading from a file.)
726 /// [`std::fs::read_to_string`]: crate::fs::read_to_string
727 #[stable(feature = "rust1", since = "1.0.0")]
728 fn read_to_string(&mut self, buf
: &mut String
) -> Result
<usize> {
729 // Note that we do *not* call `.read_to_end()` here. We are passing
730 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
731 // method to fill it up. An arbitrary implementation could overwrite the
732 // entire contents of the vector, not just append to it (which is what
733 // we are expecting).
735 // To prevent extraneously checking the UTF-8-ness of the entire buffer
736 // we pass it to our hardcoded `read_to_end` implementation which we
737 // know is guaranteed to only read data into the end of the buffer.
738 append_to_string(buf
, |b
| read_to_end(self, b
))
741 /// Read the exact number of bytes required to fill `buf`.
743 /// This function reads as many bytes as necessary to completely fill the
744 /// specified buffer `buf`.
746 /// No guarantees are provided about the contents of `buf` when this
747 /// function is called, implementations cannot rely on any property of the
748 /// contents of `buf` being true. It is recommended that implementations
749 /// only write data to `buf` instead of reading its contents. The
750 /// documentation on [`read`] has a more detailed explanation on this
755 /// If this function encounters an error of the kind
756 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
759 /// If this function encounters an "end of file" before completely filling
760 /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
761 /// The contents of `buf` are unspecified in this case.
763 /// If any other read error is encountered then this function immediately
764 /// returns. The contents of `buf` are unspecified in this case.
766 /// If this function returns an error, it is unspecified how many bytes it
767 /// has read, but it will never read more than would be necessary to
768 /// completely fill the buffer.
772 /// [`File`]s implement `Read`:
774 /// [`read`]: Read::read
775 /// [`File`]: crate::fs::File
779 /// use std::io::prelude::*;
780 /// use std::fs::File;
782 /// fn main() -> io::Result<()> {
783 /// let mut f = File::open("foo.txt")?;
784 /// let mut buffer = [0; 10];
786 /// // read exactly 10 bytes
787 /// f.read_exact(&mut buffer)?;
791 #[stable(feature = "read_exact", since = "1.6.0")]
792 fn read_exact(&mut self, buf
: &mut [u8]) -> Result
<()> {
793 default_read_exact(self, buf
)
796 /// Creates a "by reference" adaptor for this instance of `Read`.
798 /// The returned adaptor also implements `Read` and will simply borrow this
803 /// [`File`]s implement `Read`:
805 /// [`File`]: crate::fs::File
809 /// use std::io::Read;
810 /// use std::fs::File;
812 /// fn main() -> io::Result<()> {
813 /// let mut f = File::open("foo.txt")?;
814 /// let mut buffer = Vec::new();
815 /// let mut other_buffer = Vec::new();
818 /// let reference = f.by_ref();
820 /// // read at most 5 bytes
821 /// reference.take(5).read_to_end(&mut buffer)?;
823 /// } // drop our &mut reference so we can use f again
825 /// // original file still usable, read the rest
826 /// f.read_to_end(&mut other_buffer)?;
830 #[stable(feature = "rust1", since = "1.0.0")]
831 fn by_ref(&mut self) -> &mut Self
838 /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
840 /// The returned type implements [`Iterator`] where the `Item` is
841 /// [`Result`]`<`[`u8`]`, `[`io::Error`]`>`.
842 /// The yielded item is [`Ok`] if a byte was successfully read and [`Err`]
843 /// otherwise. EOF is mapped to returning [`None`] from this iterator.
847 /// [`File`]s implement `Read`:
849 /// [`File`]: crate::fs::File
850 /// [`Result`]: crate::result::Result
851 /// [`io::Error`]: self::Error
855 /// use std::io::prelude::*;
856 /// use std::fs::File;
858 /// fn main() -> io::Result<()> {
859 /// let mut f = File::open("foo.txt")?;
861 /// for byte in f.bytes() {
862 /// println!("{}", byte.unwrap());
867 #[stable(feature = "rust1", since = "1.0.0")]
868 fn bytes(self) -> Bytes
<Self>
872 Bytes { inner: self }
875 /// Creates an adaptor which will chain this stream with another.
877 /// The returned `Read` instance will first read all bytes from this object
878 /// until EOF is encountered. Afterwards the output is equivalent to the
879 /// output of `next`.
883 /// [`File`]s implement `Read`:
885 /// [`File`]: crate::fs::File
889 /// use std::io::prelude::*;
890 /// use std::fs::File;
892 /// fn main() -> io::Result<()> {
893 /// let mut f1 = File::open("foo.txt")?;
894 /// let mut f2 = File::open("bar.txt")?;
896 /// let mut handle = f1.chain(f2);
897 /// let mut buffer = String::new();
899 /// // read the value into a String. We could use any Read method here,
900 /// // this is just one example.
901 /// handle.read_to_string(&mut buffer)?;
905 #[stable(feature = "rust1", since = "1.0.0")]
906 fn chain
<R
: Read
>(self, next
: R
) -> Chain
<Self, R
>
910 Chain { first: self, second: next, done_first: false }
913 /// Creates an adaptor which will read at most `limit` bytes from it.
915 /// This function returns a new instance of `Read` which will read at most
916 /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
917 /// read errors will not count towards the number of bytes read and future
918 /// calls to [`read()`] may succeed.
922 /// [`File`]s implement `Read`:
924 /// [`File`]: crate::fs::File
926 /// [`read()`]: Read::read
930 /// use std::io::prelude::*;
931 /// use std::fs::File;
933 /// fn main() -> io::Result<()> {
934 /// let mut f = File::open("foo.txt")?;
935 /// let mut buffer = [0; 5];
937 /// // read at most five bytes
938 /// let mut handle = f.take(5);
940 /// handle.read(&mut buffer)?;
944 #[stable(feature = "rust1", since = "1.0.0")]
945 fn take(self, limit
: u64) -> Take
<Self>
949 Take { inner: self, limit }
953 /// Read all bytes from a [reader][Read] into a new [`String`].
955 /// This is a convenience function for [`Read::read_to_string`]. Using this
956 /// function avoids having to create a variable first and provides more type
957 /// safety since you can only get the buffer out if there were no errors. (If you
958 /// use [`Read::read_to_string`] you have to remember to check whether the read
959 /// succeeded because otherwise your buffer will be empty or only partially full.)
963 /// The downside of this function's increased ease of use and type safety is
964 /// that it gives you less control over performance. For example, you can't
965 /// pre-allocate memory like you can using [`String::with_capacity`] and
966 /// [`Read::read_to_string`]. Also, you can't re-use the buffer if an error
967 /// occurs while reading.
969 /// In many cases, this function's performance will be adequate and the ease of use
970 /// and type safety tradeoffs will be worth it. However, there are cases where you
971 /// need more control over performance, and in those cases you should definitely use
972 /// [`Read::read_to_string`] directly.
976 /// This function forces you to handle errors because the output (the `String`)
977 /// is wrapped in a [`Result`]. See [`Read::read_to_string`] for the errors
978 /// that can occur. If any error occurs, you will get an [`Err`], so you
979 /// don't have to worry about your buffer being empty or partially full.
984 /// #![feature(io_read_to_string)]
987 /// fn main() -> io::Result<()> {
988 /// let stdin = io::read_to_string(&mut io::stdin())?;
989 /// println!("Stdin was:");
990 /// println!("{}", stdin);
994 #[unstable(feature = "io_read_to_string", issue = "80218")]
995 pub fn read_to_string
<R
: Read
>(reader
: &mut R
) -> Result
<String
> {
996 let mut buf
= String
::new();
997 reader
.read_to_string(&mut buf
)?
;
1001 /// A buffer type used with `Read::read_vectored`.
1003 /// It is semantically a wrapper around an `&mut [u8]`, but is guaranteed to be
1004 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
1006 #[stable(feature = "iovec", since = "1.36.0")]
1007 #[repr(transparent)]
1008 pub struct IoSliceMut
<'a
>(sys
::io
::IoSliceMut
<'a
>);
1010 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1011 unsafe impl<'a
> Send
for IoSliceMut
<'a
> {}
1013 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1014 unsafe impl<'a
> Sync
for IoSliceMut
<'a
> {}
1016 #[stable(feature = "iovec", since = "1.36.0")]
1017 impl<'a
> fmt
::Debug
for IoSliceMut
<'a
> {
1018 fn fmt(&self, fmt
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1019 fmt
::Debug
::fmt(self.0.as_slice(), fmt
)
1023 impl<'a
> IoSliceMut
<'a
> {
1024 /// Creates a new `IoSliceMut` wrapping a byte slice.
1028 /// Panics on Windows if the slice is larger than 4GB.
1029 #[stable(feature = "iovec", since = "1.36.0")]
1031 pub fn new(buf
: &'a
mut [u8]) -> IoSliceMut
<'a
> {
1032 IoSliceMut(sys
::io
::IoSliceMut
::new(buf
))
1035 /// Advance the internal cursor of the slice.
1039 /// Elements in the slice may be modified if the cursor is not advanced to
1040 /// the end of the slice. For example if we have a slice of buffers with 2
1041 /// `IoSliceMut`s, both of length 8, and we advance the cursor by 10 bytes
1042 /// the first `IoSliceMut` will be untouched however the second will be
1043 /// modified to remove the first 2 bytes (10 - 8).
1048 /// #![feature(io_slice_advance)]
1050 /// use std::io::IoSliceMut;
1051 /// use std::ops::Deref;
1053 /// let mut buf1 = [1; 8];
1054 /// let mut buf2 = [2; 16];
1055 /// let mut buf3 = [3; 8];
1056 /// let mut bufs = &mut [
1057 /// IoSliceMut::new(&mut buf1),
1058 /// IoSliceMut::new(&mut buf2),
1059 /// IoSliceMut::new(&mut buf3),
1062 /// // Mark 10 bytes as read.
1063 /// bufs = IoSliceMut::advance(bufs, 10);
1064 /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1065 /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1067 #[unstable(feature = "io_slice_advance", issue = "62726")]
1069 pub fn advance
<'b
>(bufs
: &'b
mut [IoSliceMut
<'a
>], n
: usize) -> &'b
mut [IoSliceMut
<'a
>] {
1070 // Number of buffers to remove.
1072 // Total length of all the to be removed buffers.
1073 let mut accumulated_len
= 0;
1074 for buf
in bufs
.iter() {
1075 if accumulated_len
+ buf
.len() > n
{
1078 accumulated_len
+= buf
.len();
1083 let bufs
= &mut bufs
[remove
..];
1084 if !bufs
.is_empty() {
1085 bufs
[0].0.advance(n
- accumulated_len
)
1091 #[stable(feature = "iovec", since = "1.36.0")]
1092 impl<'a
> Deref
for IoSliceMut
<'a
> {
1096 fn deref(&self) -> &[u8] {
1101 #[stable(feature = "iovec", since = "1.36.0")]
1102 impl<'a
> DerefMut
for IoSliceMut
<'a
> {
1104 fn deref_mut(&mut self) -> &mut [u8] {
1105 self.0.as_mut_slice()
1109 /// A buffer type used with `Write::write_vectored`.
1111 /// It is semantically a wrapper around an `&[u8]`, but is guaranteed to be
1112 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
1114 #[stable(feature = "iovec", since = "1.36.0")]
1115 #[derive(Copy, Clone)]
1116 #[repr(transparent)]
1117 pub struct IoSlice
<'a
>(sys
::io
::IoSlice
<'a
>);
1119 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1120 unsafe impl<'a
> Send
for IoSlice
<'a
> {}
1122 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1123 unsafe impl<'a
> Sync
for IoSlice
<'a
> {}
1125 #[stable(feature = "iovec", since = "1.36.0")]
1126 impl<'a
> fmt
::Debug
for IoSlice
<'a
> {
1127 fn fmt(&self, fmt
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1128 fmt
::Debug
::fmt(self.0.as_slice(), fmt
)
1132 impl<'a
> IoSlice
<'a
> {
1133 /// Creates a new `IoSlice` wrapping a byte slice.
1137 /// Panics on Windows if the slice is larger than 4GB.
1138 #[stable(feature = "iovec", since = "1.36.0")]
1140 pub fn new(buf
: &'a
[u8]) -> IoSlice
<'a
> {
1141 IoSlice(sys
::io
::IoSlice
::new(buf
))
1144 /// Advance the internal cursor of the slice.
1148 /// Elements in the slice may be modified if the cursor is not advanced to
1149 /// the end of the slice. For example if we have a slice of buffers with 2
1150 /// `IoSlice`s, both of length 8, and we advance the cursor by 10 bytes the
1151 /// first `IoSlice` will be untouched however the second will be modified to
1152 /// remove the first 2 bytes (10 - 8).
1157 /// #![feature(io_slice_advance)]
1159 /// use std::io::IoSlice;
1160 /// use std::ops::Deref;
1162 /// let buf1 = [1; 8];
1163 /// let buf2 = [2; 16];
1164 /// let buf3 = [3; 8];
1165 /// let mut bufs = &mut [
1166 /// IoSlice::new(&buf1),
1167 /// IoSlice::new(&buf2),
1168 /// IoSlice::new(&buf3),
1171 /// // Mark 10 bytes as written.
1172 /// bufs = IoSlice::advance(bufs, 10);
1173 /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1174 /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1175 #[unstable(feature = "io_slice_advance", issue = "62726")]
1177 pub fn advance
<'b
>(bufs
: &'b
mut [IoSlice
<'a
>], n
: usize) -> &'b
mut [IoSlice
<'a
>] {
1178 // Number of buffers to remove.
1180 // Total length of all the to be removed buffers.
1181 let mut accumulated_len
= 0;
1182 for buf
in bufs
.iter() {
1183 if accumulated_len
+ buf
.len() > n
{
1186 accumulated_len
+= buf
.len();
1191 let bufs
= &mut bufs
[remove
..];
1192 if !bufs
.is_empty() {
1193 bufs
[0].0.advance(n
- accumulated_len
)
1199 #[stable(feature = "iovec", since = "1.36.0")]
1200 impl<'a
> Deref
for IoSlice
<'a
> {
1204 fn deref(&self) -> &[u8] {
1209 /// A type used to conditionally initialize buffers passed to `Read` methods.
1210 #[unstable(feature = "read_initializer", issue = "42788")]
1212 pub struct Initializer(bool
);
1215 /// Returns a new `Initializer` which will zero out buffers.
1216 #[unstable(feature = "read_initializer", issue = "42788")]
1218 pub fn zeroing() -> Initializer
{
1222 /// Returns a new `Initializer` which will not zero out buffers.
1226 /// This may only be called by `Read`ers which guarantee that they will not
1227 /// read from buffers passed to `Read` methods, and that the return value of
1228 /// the method accurately reflects the number of bytes that have been
1229 /// written to the head of the buffer.
1230 #[unstable(feature = "read_initializer", issue = "42788")]
1232 pub unsafe fn nop() -> Initializer
{
1236 /// Indicates if a buffer should be initialized.
1237 #[unstable(feature = "read_initializer", issue = "42788")]
1239 pub fn should_initialize(&self) -> bool
{
1243 /// Initializes a buffer if necessary.
1244 #[unstable(feature = "read_initializer", issue = "42788")]
1246 pub fn initialize(&self, buf
: &mut [u8]) {
1247 if self.should_initialize() {
1248 unsafe { ptr::write_bytes(buf.as_mut_ptr(), 0, buf.len()) }
1253 /// A trait for objects which are byte-oriented sinks.
1255 /// Implementors of the `Write` trait are sometimes called 'writers'.
1257 /// Writers are defined by two required methods, [`write`] and [`flush`]:
1259 /// * The [`write`] method will attempt to write some data into the object,
1260 /// returning how many bytes were successfully written.
1262 /// * The [`flush`] method is useful for adaptors and explicit buffers
1263 /// themselves for ensuring that all buffered data has been pushed out to the
1266 /// Writers are intended to be composable with one another. Many implementors
1267 /// throughout [`std::io`] take and provide types which implement the `Write`
1270 /// [`write`]: Write::write
1271 /// [`flush`]: Write::flush
1272 /// [`std::io`]: self
1277 /// use std::io::prelude::*;
1278 /// use std::fs::File;
1280 /// fn main() -> std::io::Result<()> {
1281 /// let data = b"some bytes";
1283 /// let mut pos = 0;
1284 /// let mut buffer = File::create("foo.txt")?;
1286 /// while pos < data.len() {
1287 /// let bytes_written = buffer.write(&data[pos..])?;
1288 /// pos += bytes_written;
1294 /// The trait also provides convenience methods like [`write_all`], which calls
1295 /// `write` in a loop until its entire input has been written.
1297 /// [`write_all`]: Write::write_all
1298 #[stable(feature = "rust1", since = "1.0.0")]
1301 /// Write a buffer into this writer, returning how many bytes were written.
1303 /// This function will attempt to write the entire contents of `buf`, but
1304 /// the entire write may not succeed, or the write may also generate an
1305 /// error. A call to `write` represents *at most one* attempt to write to
1306 /// any wrapped object.
1308 /// Calls to `write` are not guaranteed to block waiting for data to be
1309 /// written, and a write which would otherwise block can be indicated through
1310 /// an [`Err`] variant.
1312 /// If the return value is [`Ok(n)`] then it must be guaranteed that
1313 /// `n <= buf.len()`. A return value of `0` typically means that the
1314 /// underlying object is no longer able to accept bytes and will likely not
1315 /// be able to in the future as well, or that the buffer provided is empty.
1319 /// Each call to `write` may generate an I/O error indicating that the
1320 /// operation could not be completed. If an error is returned then no bytes
1321 /// in the buffer were written to this writer.
1323 /// It is **not** considered an error if the entire buffer could not be
1324 /// written to this writer.
1326 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the
1327 /// write operation should be retried if there is nothing else to do.
1332 /// use std::io::prelude::*;
1333 /// use std::fs::File;
1335 /// fn main() -> std::io::Result<()> {
1336 /// let mut buffer = File::create("foo.txt")?;
1338 /// // Writes some prefix of the byte string, not necessarily all of it.
1339 /// buffer.write(b"some bytes")?;
1345 #[stable(feature = "rust1", since = "1.0.0")]
1346 fn write(&mut self, buf
: &[u8]) -> Result
<usize>;
1348 /// Like [`write`], except that it writes from a slice of buffers.
1350 /// Data is copied from each buffer in order, with the final buffer
1351 /// read from possibly being only partially consumed. This method must
1352 /// behave as a call to [`write`] with the buffers concatenated would.
1354 /// The default implementation calls [`write`] with either the first nonempty
1355 /// buffer provided, or an empty one if none exists.
1357 /// [`write`]: Write::write
1358 #[stable(feature = "iovec", since = "1.36.0")]
1359 fn write_vectored(&mut self, bufs
: &[IoSlice
<'_
>]) -> Result
<usize> {
1360 default_write_vectored(|b
| self.write(b
), bufs
)
1363 /// Determines if this `Write`r has an efficient [`write_vectored`]
1366 /// If a `Write`r does not override the default [`write_vectored`]
1367 /// implementation, code using it may want to avoid the method all together
1368 /// and coalesce writes into a single buffer for higher performance.
1370 /// The default implementation returns `false`.
1372 /// [`write_vectored`]: Write::write_vectored
1373 #[unstable(feature = "can_vector", issue = "69941")]
1374 fn is_write_vectored(&self) -> bool
{
1378 /// Flush this output stream, ensuring that all intermediately buffered
1379 /// contents reach their destination.
1383 /// It is considered an error if not all bytes could be written due to
1384 /// I/O errors or EOF being reached.
1389 /// use std::io::prelude::*;
1390 /// use std::io::BufWriter;
1391 /// use std::fs::File;
1393 /// fn main() -> std::io::Result<()> {
1394 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
1396 /// buffer.write_all(b"some bytes")?;
1397 /// buffer.flush()?;
1401 #[stable(feature = "rust1", since = "1.0.0")]
1402 fn flush(&mut self) -> Result
<()>;
1404 /// Attempts to write an entire buffer into this writer.
1406 /// This method will continuously call [`write`] until there is no more data
1407 /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is
1408 /// returned. This method will not return until the entire buffer has been
1409 /// successfully written or such an error occurs. The first error that is
1410 /// not of [`ErrorKind::Interrupted`] kind generated from this method will be
1413 /// If the buffer contains no data, this will never call [`write`].
1417 /// This function will return the first error of
1418 /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns.
1420 /// [`write`]: Write::write
1425 /// use std::io::prelude::*;
1426 /// use std::fs::File;
1428 /// fn main() -> std::io::Result<()> {
1429 /// let mut buffer = File::create("foo.txt")?;
1431 /// buffer.write_all(b"some bytes")?;
1435 #[stable(feature = "rust1", since = "1.0.0")]
1436 fn write_all(&mut self, mut buf
: &[u8]) -> Result
<()> {
1437 while !buf
.is_empty() {
1438 match self.write(buf
) {
1440 return Err(Error
::new(ErrorKind
::WriteZero
, "failed to write whole buffer"));
1442 Ok(n
) => buf
= &buf
[n
..],
1443 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> {}
1444 Err(e
) => return Err(e
),
1450 /// Attempts to write multiple buffers into this writer.
1452 /// This method will continuously call [`write_vectored`] until there is no
1453 /// more data to be written or an error of non-[`ErrorKind::Interrupted`]
1454 /// kind is returned. This method will not return until all buffers have
1455 /// been successfully written or such an error occurs. The first error that
1456 /// is not of [`ErrorKind::Interrupted`] kind generated from this method
1457 /// will be returned.
1459 /// If the buffer contains no data, this will never call [`write_vectored`].
1463 /// Unlike [`write_vectored`], this takes a *mutable* reference to
1464 /// a slice of [`IoSlice`]s, not an immutable one. That's because we need to
1465 /// modify the slice to keep track of the bytes already written.
1467 /// Once this function returns, the contents of `bufs` are unspecified, as
1468 /// this depends on how many calls to [`write_vectored`] were necessary. It is
1469 /// best to understand this function as taking ownership of `bufs` and to
1470 /// not use `bufs` afterwards. The underlying buffers, to which the
1471 /// [`IoSlice`]s point (but not the [`IoSlice`]s themselves), are unchanged and
1474 /// [`write_vectored`]: Write::write_vectored
1479 /// #![feature(write_all_vectored)]
1480 /// # fn main() -> std::io::Result<()> {
1482 /// use std::io::{Write, IoSlice};
1484 /// let mut writer = Vec::new();
1485 /// let bufs = &mut [
1486 /// IoSlice::new(&[1]),
1487 /// IoSlice::new(&[2, 3]),
1488 /// IoSlice::new(&[4, 5, 6]),
1491 /// writer.write_all_vectored(bufs)?;
1492 /// // Note: the contents of `bufs` is now undefined, see the Notes section.
1494 /// assert_eq!(writer, &[1, 2, 3, 4, 5, 6]);
1497 #[unstable(feature = "write_all_vectored", issue = "70436")]
1498 fn write_all_vectored(&mut self, mut bufs
: &mut [IoSlice
<'_
>]) -> Result
<()> {
1499 // Guarantee that bufs is empty if it contains no data,
1500 // to avoid calling write_vectored if there is no data to be written.
1501 bufs
= IoSlice
::advance(bufs
, 0);
1502 while !bufs
.is_empty() {
1503 match self.write_vectored(bufs
) {
1505 return Err(Error
::new(ErrorKind
::WriteZero
, "failed to write whole buffer"));
1507 Ok(n
) => bufs
= IoSlice
::advance(bufs
, n
),
1508 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> {}
1509 Err(e
) => return Err(e
),
1515 /// Writes a formatted string into this writer, returning any error
1518 /// This method is primarily used to interface with the
1519 /// [`format_args!()`] macro, but it is rare that this should
1520 /// explicitly be called. The [`write!()`] macro should be favored to
1521 /// invoke this method instead.
1523 /// This function internally uses the [`write_all`] method on
1524 /// this trait and hence will continuously write data so long as no errors
1525 /// are received. This also means that partial writes are not indicated in
1528 /// [`write_all`]: Write::write_all
1532 /// This function will return any I/O error reported while formatting.
1537 /// use std::io::prelude::*;
1538 /// use std::fs::File;
1540 /// fn main() -> std::io::Result<()> {
1541 /// let mut buffer = File::create("foo.txt")?;
1544 /// write!(buffer, "{:.*}", 2, 1.234567)?;
1545 /// // turns into this:
1546 /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1550 #[stable(feature = "rust1", since = "1.0.0")]
1551 fn write_fmt(&mut self, fmt
: fmt
::Arguments
<'_
>) -> Result
<()> {
1552 // Create a shim which translates a Write to a fmt::Write and saves
1553 // off I/O errors. instead of discarding them
1554 struct Adaptor
<'a
, T
: ?Sized
+ 'a
> {
1559 impl<T
: Write
+ ?Sized
> fmt
::Write
for Adaptor
<'_
, T
> {
1560 fn write_str(&mut self, s
: &str) -> fmt
::Result
{
1561 match self.inner
.write_all(s
.as_bytes()) {
1564 self.error
= Err(e
);
1571 let mut output
= Adaptor { inner: self, error: Ok(()) }
;
1572 match fmt
::write(&mut output
, fmt
) {
1575 // check if the error came from the underlying `Write` or not
1576 if output
.error
.is_err() {
1579 Err(Error
::new(ErrorKind
::Other
, "formatter error"))
1585 /// Creates a "by reference" adaptor for this instance of `Write`.
1587 /// The returned adaptor also implements `Write` and will simply borrow this
1593 /// use std::io::Write;
1594 /// use std::fs::File;
1596 /// fn main() -> std::io::Result<()> {
1597 /// let mut buffer = File::create("foo.txt")?;
1599 /// let reference = buffer.by_ref();
1601 /// // we can use reference just like our original buffer
1602 /// reference.write_all(b"some bytes")?;
1606 #[stable(feature = "rust1", since = "1.0.0")]
1607 fn by_ref(&mut self) -> &mut Self
1615 /// The `Seek` trait provides a cursor which can be moved within a stream of
1618 /// The stream typically has a fixed size, allowing seeking relative to either
1619 /// end or the current offset.
1623 /// [`File`]s implement `Seek`:
1625 /// [`File`]: crate::fs::File
1629 /// use std::io::prelude::*;
1630 /// use std::fs::File;
1631 /// use std::io::SeekFrom;
1633 /// fn main() -> io::Result<()> {
1634 /// let mut f = File::open("foo.txt")?;
1636 /// // move the cursor 42 bytes from the start of the file
1637 /// f.seek(SeekFrom::Start(42))?;
1641 #[stable(feature = "rust1", since = "1.0.0")]
1643 /// Seek to an offset, in bytes, in a stream.
1645 /// A seek beyond the end of a stream is allowed, but behavior is defined
1646 /// by the implementation.
1648 /// If the seek operation completed successfully,
1649 /// this method returns the new position from the start of the stream.
1650 /// That position can be used later with [`SeekFrom::Start`].
1654 /// Seeking to a negative offset is considered an error.
1655 #[stable(feature = "rust1", since = "1.0.0")]
1656 fn seek(&mut self, pos
: SeekFrom
) -> Result
<u64>;
1658 /// Returns the length of this stream (in bytes).
1660 /// This method is implemented using up to three seek operations. If this
1661 /// method returns successfully, the seek position is unchanged (i.e. the
1662 /// position before calling this method is the same as afterwards).
1663 /// However, if this method returns an error, the seek position is
1666 /// If you need to obtain the length of *many* streams and you don't care
1667 /// about the seek position afterwards, you can reduce the number of seek
1668 /// operations by simply calling `seek(SeekFrom::End(0))` and using its
1669 /// return value (it is also the stream length).
1671 /// Note that length of a stream can change over time (for example, when
1672 /// data is appended to a file). So calling this method multiple times does
1673 /// not necessarily return the same length each time.
1678 /// #![feature(seek_stream_len)]
1680 /// io::{self, Seek},
1684 /// fn main() -> io::Result<()> {
1685 /// let mut f = File::open("foo.txt")?;
1687 /// let len = f.stream_len()?;
1688 /// println!("The file is currently {} bytes long", len);
1692 #[unstable(feature = "seek_stream_len", issue = "59359")]
1693 fn stream_len(&mut self) -> Result
<u64> {
1694 let old_pos
= self.stream_position()?
;
1695 let len
= self.seek(SeekFrom
::End(0))?
;
1697 // Avoid seeking a third time when we were already at the end of the
1698 // stream. The branch is usually way cheaper than a seek operation.
1700 self.seek(SeekFrom
::Start(old_pos
))?
;
1706 /// Returns the current seek position from the start of the stream.
1708 /// This is equivalent to `self.seek(SeekFrom::Current(0))`.
1714 /// io::{self, BufRead, BufReader, Seek},
1718 /// fn main() -> io::Result<()> {
1719 /// let mut f = BufReader::new(File::open("foo.txt")?);
1721 /// let before = f.stream_position()?;
1722 /// f.read_line(&mut String::new())?;
1723 /// let after = f.stream_position()?;
1725 /// println!("The first line was {} bytes long", after - before);
1729 #[stable(feature = "seek_convenience", since = "1.51.0")]
1730 fn stream_position(&mut self) -> Result
<u64> {
1731 self.seek(SeekFrom
::Current(0))
1735 /// Enumeration of possible methods to seek within an I/O object.
1737 /// It is used by the [`Seek`] trait.
1738 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1739 #[stable(feature = "rust1", since = "1.0.0")]
1741 /// Sets the offset to the provided number of bytes.
1742 #[stable(feature = "rust1", since = "1.0.0")]
1743 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1745 /// Sets the offset to the size of this object plus the specified number of
1748 /// It is possible to seek beyond the end of an object, but it's an error to
1749 /// seek before byte 0.
1750 #[stable(feature = "rust1", since = "1.0.0")]
1751 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1753 /// Sets the offset to the current position plus the specified number of
1756 /// It is possible to seek beyond the end of an object, but it's an error to
1757 /// seek before byte 0.
1758 #[stable(feature = "rust1", since = "1.0.0")]
1759 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1762 fn read_until
<R
: BufRead
+ ?Sized
>(r
: &mut R
, delim
: u8, buf
: &mut Vec
<u8>) -> Result
<usize> {
1765 let (done
, used
) = {
1766 let available
= match r
.fill_buf() {
1768 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> continue,
1769 Err(e
) => return Err(e
),
1771 match memchr
::memchr(delim
, available
) {
1773 buf
.extend_from_slice(&available
[..=i
]);
1777 buf
.extend_from_slice(available
);
1778 (false, available
.len())
1784 if done
|| used
== 0 {
1790 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1791 /// to perform extra ways of reading.
1793 /// For example, reading line-by-line is inefficient without using a buffer, so
1794 /// if you want to read by line, you'll need `BufRead`, which includes a
1795 /// [`read_line`] method as well as a [`lines`] iterator.
1799 /// A locked standard input implements `BufRead`:
1803 /// use std::io::prelude::*;
1805 /// let stdin = io::stdin();
1806 /// for line in stdin.lock().lines() {
1807 /// println!("{}", line.unwrap());
1811 /// If you have something that implements [`Read`], you can use the [`BufReader`
1812 /// type][`BufReader`] to turn it into a `BufRead`.
1814 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1815 /// [`BufReader`] to the rescue!
1817 /// [`File`]: crate::fs::File
1818 /// [`read_line`]: BufRead::read_line
1819 /// [`lines`]: BufRead::lines
1822 /// use std::io::{self, BufReader};
1823 /// use std::io::prelude::*;
1824 /// use std::fs::File;
1826 /// fn main() -> io::Result<()> {
1827 /// let f = File::open("foo.txt")?;
1828 /// let f = BufReader::new(f);
1830 /// for line in f.lines() {
1831 /// println!("{}", line.unwrap());
1837 #[stable(feature = "rust1", since = "1.0.0")]
1838 pub trait BufRead
: Read
{
1839 /// Returns the contents of the internal buffer, filling it with more data
1840 /// from the inner reader if it is empty.
1842 /// This function is a lower-level call. It needs to be paired with the
1843 /// [`consume`] method to function properly. When calling this
1844 /// method, none of the contents will be "read" in the sense that later
1845 /// calling `read` may return the same contents. As such, [`consume`] must
1846 /// be called with the number of bytes that are consumed from this buffer to
1847 /// ensure that the bytes are never returned twice.
1849 /// [`consume`]: BufRead::consume
1851 /// An empty buffer returned indicates that the stream has reached EOF.
1855 /// This function will return an I/O error if the underlying reader was
1856 /// read, but returned an error.
1860 /// A locked standard input implements `BufRead`:
1864 /// use std::io::prelude::*;
1866 /// let stdin = io::stdin();
1867 /// let mut stdin = stdin.lock();
1869 /// let buffer = stdin.fill_buf().unwrap();
1871 /// // work with buffer
1872 /// println!("{:?}", buffer);
1874 /// // ensure the bytes we worked with aren't returned again later
1875 /// let length = buffer.len();
1876 /// stdin.consume(length);
1878 #[stable(feature = "rust1", since = "1.0.0")]
1879 fn fill_buf(&mut self) -> Result
<&[u8]>;
1881 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1882 /// so they should no longer be returned in calls to `read`.
1884 /// This function is a lower-level call. It needs to be paired with the
1885 /// [`fill_buf`] method to function properly. This function does
1886 /// not perform any I/O, it simply informs this object that some amount of
1887 /// its buffer, returned from [`fill_buf`], has been consumed and should
1888 /// no longer be returned. As such, this function may do odd things if
1889 /// [`fill_buf`] isn't called before calling it.
1891 /// The `amt` must be `<=` the number of bytes in the buffer returned by
1896 /// Since `consume()` is meant to be used with [`fill_buf`],
1897 /// that method's example includes an example of `consume()`.
1899 /// [`fill_buf`]: BufRead::fill_buf
1900 #[stable(feature = "rust1", since = "1.0.0")]
1901 fn consume(&mut self, amt
: usize);
1903 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
1905 /// This function will read bytes from the underlying stream until the
1906 /// delimiter or EOF is found. Once found, all bytes up to, and including,
1907 /// the delimiter (if found) will be appended to `buf`.
1909 /// If successful, this function will return the total number of bytes read.
1911 /// This function is blocking and should be used carefully: it is possible for
1912 /// an attacker to continuously send bytes without ever sending the delimiter
1917 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1918 /// will otherwise return any errors returned by [`fill_buf`].
1920 /// If an I/O error is encountered then all bytes read so far will be
1921 /// present in `buf` and its length will have been adjusted appropriately.
1923 /// [`fill_buf`]: BufRead::fill_buf
1927 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1928 /// this example, we use [`Cursor`] to read all the bytes in a byte slice
1929 /// in hyphen delimited segments:
1932 /// use std::io::{self, BufRead};
1934 /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
1935 /// let mut buf = vec![];
1937 /// // cursor is at 'l'
1938 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1939 /// .expect("reading from cursor won't fail");
1940 /// assert_eq!(num_bytes, 6);
1941 /// assert_eq!(buf, b"lorem-");
1944 /// // cursor is at 'i'
1945 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1946 /// .expect("reading from cursor won't fail");
1947 /// assert_eq!(num_bytes, 5);
1948 /// assert_eq!(buf, b"ipsum");
1951 /// // cursor is at EOF
1952 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1953 /// .expect("reading from cursor won't fail");
1954 /// assert_eq!(num_bytes, 0);
1955 /// assert_eq!(buf, b"");
1957 #[stable(feature = "rust1", since = "1.0.0")]
1958 fn read_until(&mut self, byte
: u8, buf
: &mut Vec
<u8>) -> Result
<usize> {
1959 read_until(self, byte
, buf
)
1962 /// Read all bytes until a newline (the `0xA` byte) is reached, and append
1963 /// them to the provided buffer.
1965 /// This function will read bytes from the underlying stream until the
1966 /// newline delimiter (the `0xA` byte) or EOF is found. Once found, all bytes
1967 /// up to, and including, the delimiter (if found) will be appended to
1970 /// If successful, this function will return the total number of bytes read.
1972 /// If this function returns [`Ok(0)`], the stream has reached EOF.
1974 /// This function is blocking and should be used carefully: it is possible for
1975 /// an attacker to continuously send bytes without ever sending a newline
1982 /// This function has the same error semantics as [`read_until`] and will
1983 /// also return an error if the read bytes are not valid UTF-8. If an I/O
1984 /// error is encountered then `buf` may contain some bytes already read in
1985 /// the event that all data read so far was valid UTF-8.
1987 /// [`read_until`]: BufRead::read_until
1991 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1992 /// this example, we use [`Cursor`] to read all the lines in a byte slice:
1995 /// use std::io::{self, BufRead};
1997 /// let mut cursor = io::Cursor::new(b"foo\nbar");
1998 /// let mut buf = String::new();
2000 /// // cursor is at 'f'
2001 /// let num_bytes = cursor.read_line(&mut buf)
2002 /// .expect("reading from cursor won't fail");
2003 /// assert_eq!(num_bytes, 4);
2004 /// assert_eq!(buf, "foo\n");
2007 /// // cursor is at 'b'
2008 /// let num_bytes = cursor.read_line(&mut buf)
2009 /// .expect("reading from cursor won't fail");
2010 /// assert_eq!(num_bytes, 3);
2011 /// assert_eq!(buf, "bar");
2014 /// // cursor is at EOF
2015 /// let num_bytes = cursor.read_line(&mut buf)
2016 /// .expect("reading from cursor won't fail");
2017 /// assert_eq!(num_bytes, 0);
2018 /// assert_eq!(buf, "");
2020 #[stable(feature = "rust1", since = "1.0.0")]
2021 fn read_line(&mut self, buf
: &mut String
) -> Result
<usize> {
2022 // Note that we are not calling the `.read_until` method here, but
2023 // rather our hardcoded implementation. For more details as to why, see
2024 // the comments in `read_to_end`.
2025 append_to_string(buf
, |b
| read_until(self, b'
\n'
, b
))
2028 /// Returns an iterator over the contents of this reader split on the byte
2031 /// The iterator returned from this function will return instances of
2032 /// [`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
2033 /// the delimiter byte at the end.
2035 /// This function will yield errors whenever [`read_until`] would have
2036 /// also yielded an error.
2038 /// [`io::Result`]: self::Result
2039 /// [`read_until`]: BufRead::read_until
2043 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2044 /// this example, we use [`Cursor`] to iterate over all hyphen delimited
2045 /// segments in a byte slice
2048 /// use std::io::{self, BufRead};
2050 /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
2052 /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
2053 /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
2054 /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
2055 /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
2056 /// assert_eq!(split_iter.next(), None);
2058 #[stable(feature = "rust1", since = "1.0.0")]
2059 fn split(self, byte
: u8) -> Split
<Self>
2063 Split { buf: self, delim: byte }
2066 /// Returns an iterator over the lines of this reader.
2068 /// The iterator returned from this function will yield instances of
2069 /// [`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline
2070 /// byte (the `0xA` byte) or `CRLF` (`0xD`, `0xA` bytes) at the end.
2072 /// [`io::Result`]: self::Result
2076 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2077 /// this example, we use [`Cursor`] to iterate over all the lines in a byte
2081 /// use std::io::{self, BufRead};
2083 /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
2085 /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
2086 /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
2087 /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
2088 /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
2089 /// assert_eq!(lines_iter.next(), None);
2094 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
2095 #[stable(feature = "rust1", since = "1.0.0")]
2096 fn lines(self) -> Lines
<Self>
2104 /// Adaptor to chain together two readers.
2106 /// This struct is generally created by calling [`chain`] on a reader.
2107 /// Please see the documentation of [`chain`] for more details.
2109 /// [`chain`]: Read::chain
2110 #[stable(feature = "rust1", since = "1.0.0")]
2111 pub struct Chain
<T
, U
> {
2117 impl<T
, U
> Chain
<T
, U
> {
2118 /// Consumes the `Chain`, returning the wrapped readers.
2124 /// use std::io::prelude::*;
2125 /// use std::fs::File;
2127 /// fn main() -> io::Result<()> {
2128 /// let mut foo_file = File::open("foo.txt")?;
2129 /// let mut bar_file = File::open("bar.txt")?;
2131 /// let chain = foo_file.chain(bar_file);
2132 /// let (foo_file, bar_file) = chain.into_inner();
2136 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2137 pub fn into_inner(self) -> (T
, U
) {
2138 (self.first
, self.second
)
2141 /// Gets references to the underlying readers in this `Chain`.
2147 /// use std::io::prelude::*;
2148 /// use std::fs::File;
2150 /// fn main() -> io::Result<()> {
2151 /// let mut foo_file = File::open("foo.txt")?;
2152 /// let mut bar_file = File::open("bar.txt")?;
2154 /// let chain = foo_file.chain(bar_file);
2155 /// let (foo_file, bar_file) = chain.get_ref();
2159 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2160 pub fn get_ref(&self) -> (&T
, &U
) {
2161 (&self.first
, &self.second
)
2164 /// Gets mutable references to the underlying readers in this `Chain`.
2166 /// Care should be taken to avoid modifying the internal I/O state of the
2167 /// underlying readers as doing so may corrupt the internal state of this
2174 /// use std::io::prelude::*;
2175 /// use std::fs::File;
2177 /// fn main() -> io::Result<()> {
2178 /// let mut foo_file = File::open("foo.txt")?;
2179 /// let mut bar_file = File::open("bar.txt")?;
2181 /// let mut chain = foo_file.chain(bar_file);
2182 /// let (foo_file, bar_file) = chain.get_mut();
2186 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2187 pub fn get_mut(&mut self) -> (&mut T
, &mut U
) {
2188 (&mut self.first
, &mut self.second
)
2192 #[stable(feature = "std_debug", since = "1.16.0")]
2193 impl<T
: fmt
::Debug
, U
: fmt
::Debug
> fmt
::Debug
for Chain
<T
, U
> {
2194 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2195 f
.debug_struct("Chain").field("t", &self.first
).field("u", &self.second
).finish()
2199 #[stable(feature = "rust1", since = "1.0.0")]
2200 impl<T
: Read
, U
: Read
> Read
for Chain
<T
, U
> {
2201 fn read(&mut self, buf
: &mut [u8]) -> Result
<usize> {
2202 if !self.done_first
{
2203 match self.first
.read(buf
)?
{
2204 0 if !buf
.is_empty() => self.done_first
= true,
2208 self.second
.read(buf
)
2211 fn read_vectored(&mut self, bufs
: &mut [IoSliceMut
<'_
>]) -> Result
<usize> {
2212 if !self.done_first
{
2213 match self.first
.read_vectored(bufs
)?
{
2214 0 if bufs
.iter().any(|b
| !b
.is_empty()) => self.done_first
= true,
2218 self.second
.read_vectored(bufs
)
2221 unsafe fn initializer(&self) -> Initializer
{
2222 let initializer
= self.first
.initializer();
2223 if initializer
.should_initialize() { initializer }
else { self.second.initializer() }
2227 #[stable(feature = "chain_bufread", since = "1.9.0")]
2228 impl<T
: BufRead
, U
: BufRead
> BufRead
for Chain
<T
, U
> {
2229 fn fill_buf(&mut self) -> Result
<&[u8]> {
2230 if !self.done_first
{
2231 match self.first
.fill_buf()?
{
2232 buf
if buf
.is_empty() => {
2233 self.done_first
= true;
2235 buf
=> return Ok(buf
),
2238 self.second
.fill_buf()
2241 fn consume(&mut self, amt
: usize) {
2242 if !self.done_first { self.first.consume(amt) }
else { self.second.consume(amt) }
2246 impl<T
, U
> SizeHint
for Chain
<T
, U
> {
2247 fn lower_bound(&self) -> usize {
2248 SizeHint
::lower_bound(&self.first
) + SizeHint
::lower_bound(&self.second
)
2251 fn upper_bound(&self) -> Option
<usize> {
2252 match (SizeHint
::upper_bound(&self.first
), SizeHint
::upper_bound(&self.second
)) {
2253 (Some(first
), Some(second
)) => Some(first
+ second
),
2259 /// Reader adaptor which limits the bytes read from an underlying reader.
2261 /// This struct is generally created by calling [`take`] on a reader.
2262 /// Please see the documentation of [`take`] for more details.
2264 /// [`take`]: Read::take
2265 #[stable(feature = "rust1", since = "1.0.0")]
2267 pub struct Take
<T
> {
2273 /// Returns the number of bytes that can be read before this instance will
2278 /// This instance may reach `EOF` after reading fewer bytes than indicated by
2279 /// this method if the underlying [`Read`] instance reaches EOF.
2285 /// use std::io::prelude::*;
2286 /// use std::fs::File;
2288 /// fn main() -> io::Result<()> {
2289 /// let f = File::open("foo.txt")?;
2291 /// // read at most five bytes
2292 /// let handle = f.take(5);
2294 /// println!("limit: {}", handle.limit());
2298 #[stable(feature = "rust1", since = "1.0.0")]
2299 pub fn limit(&self) -> u64 {
2303 /// Sets the number of bytes that can be read before this instance will
2304 /// return EOF. This is the same as constructing a new `Take` instance, so
2305 /// the amount of bytes read and the previous limit value don't matter when
2306 /// calling this method.
2312 /// use std::io::prelude::*;
2313 /// use std::fs::File;
2315 /// fn main() -> io::Result<()> {
2316 /// let f = File::open("foo.txt")?;
2318 /// // read at most five bytes
2319 /// let mut handle = f.take(5);
2320 /// handle.set_limit(10);
2322 /// assert_eq!(handle.limit(), 10);
2326 #[stable(feature = "take_set_limit", since = "1.27.0")]
2327 pub fn set_limit(&mut self, limit
: u64) {
2331 /// Consumes the `Take`, returning the wrapped reader.
2337 /// use std::io::prelude::*;
2338 /// use std::fs::File;
2340 /// fn main() -> io::Result<()> {
2341 /// let mut file = File::open("foo.txt")?;
2343 /// let mut buffer = [0; 5];
2344 /// let mut handle = file.take(5);
2345 /// handle.read(&mut buffer)?;
2347 /// let file = handle.into_inner();
2351 #[stable(feature = "io_take_into_inner", since = "1.15.0")]
2352 pub fn into_inner(self) -> T
{
2356 /// Gets a reference to the underlying reader.
2362 /// use std::io::prelude::*;
2363 /// use std::fs::File;
2365 /// fn main() -> io::Result<()> {
2366 /// let mut file = File::open("foo.txt")?;
2368 /// let mut buffer = [0; 5];
2369 /// let mut handle = file.take(5);
2370 /// handle.read(&mut buffer)?;
2372 /// let file = handle.get_ref();
2376 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2377 pub fn get_ref(&self) -> &T
{
2381 /// Gets a mutable reference to the underlying reader.
2383 /// Care should be taken to avoid modifying the internal I/O state of the
2384 /// underlying reader as doing so may corrupt the internal limit of this
2391 /// use std::io::prelude::*;
2392 /// use std::fs::File;
2394 /// fn main() -> io::Result<()> {
2395 /// let mut file = File::open("foo.txt")?;
2397 /// let mut buffer = [0; 5];
2398 /// let mut handle = file.take(5);
2399 /// handle.read(&mut buffer)?;
2401 /// let file = handle.get_mut();
2405 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2406 pub fn get_mut(&mut self) -> &mut T
{
2411 #[stable(feature = "rust1", since = "1.0.0")]
2412 impl<T
: Read
> Read
for Take
<T
> {
2413 fn read(&mut self, buf
: &mut [u8]) -> Result
<usize> {
2414 // Don't call into inner reader at all at EOF because it may still block
2415 if self.limit
== 0 {
2419 let max
= cmp
::min(buf
.len() as u64, self.limit
) as usize;
2420 let n
= self.inner
.read(&mut buf
[..max
])?
;
2421 self.limit
-= n
as u64;
2425 unsafe fn initializer(&self) -> Initializer
{
2426 self.inner
.initializer()
2429 fn read_to_end(&mut self, buf
: &mut Vec
<u8>) -> Result
<usize> {
2430 // Pass in a reservation_size closure that respects the current value
2431 // of limit for each read. If we hit the read limit, this prevents the
2432 // final zero-byte read from allocating again.
2433 read_to_end_with_reservation(self, buf
, |self_
| cmp
::min(self_
.limit
, 32) as usize)
2437 #[stable(feature = "rust1", since = "1.0.0")]
2438 impl<T
: BufRead
> BufRead
for Take
<T
> {
2439 fn fill_buf(&mut self) -> Result
<&[u8]> {
2440 // Don't call into inner reader at all at EOF because it may still block
2441 if self.limit
== 0 {
2445 let buf
= self.inner
.fill_buf()?
;
2446 let cap
= cmp
::min(buf
.len() as u64, self.limit
) as usize;
2450 fn consume(&mut self, amt
: usize) {
2451 // Don't let callers reset the limit by passing an overlarge value
2452 let amt
= cmp
::min(amt
as u64, self.limit
) as usize;
2453 self.limit
-= amt
as u64;
2454 self.inner
.consume(amt
);
2458 /// An iterator over `u8` values of a reader.
2460 /// This struct is generally created by calling [`bytes`] on a reader.
2461 /// Please see the documentation of [`bytes`] for more details.
2463 /// [`bytes`]: Read::bytes
2464 #[stable(feature = "rust1", since = "1.0.0")]
2466 pub struct Bytes
<R
> {
2470 #[stable(feature = "rust1", since = "1.0.0")]
2471 impl<R
: Read
> Iterator
for Bytes
<R
> {
2472 type Item
= Result
<u8>;
2474 fn next(&mut self) -> Option
<Result
<u8>> {
2477 return match self.inner
.read(slice
::from_mut(&mut byte
)) {
2479 Ok(..) => Some(Ok(byte
)),
2480 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> continue,
2481 Err(e
) => Some(Err(e
)),
2486 fn size_hint(&self) -> (usize, Option
<usize>) {
2487 SizeHint
::size_hint(&self.inner
)
2492 fn lower_bound(&self) -> usize;
2494 fn upper_bound(&self) -> Option
<usize>;
2496 fn size_hint(&self) -> (usize, Option
<usize>) {
2497 (self.lower_bound(), self.upper_bound())
2501 impl<T
> SizeHint
for T
{
2502 default fn lower_bound(&self) -> usize {
2506 default fn upper_bound(&self) -> Option
<usize> {
2511 /// An iterator over the contents of an instance of `BufRead` split on a
2512 /// particular byte.
2514 /// This struct is generally created by calling [`split`] on a `BufRead`.
2515 /// Please see the documentation of [`split`] for more details.
2517 /// [`split`]: BufRead::split
2518 #[stable(feature = "rust1", since = "1.0.0")]
2520 pub struct Split
<B
> {
2525 #[stable(feature = "rust1", since = "1.0.0")]
2526 impl<B
: BufRead
> Iterator
for Split
<B
> {
2527 type Item
= Result
<Vec
<u8>>;
2529 fn next(&mut self) -> Option
<Result
<Vec
<u8>>> {
2530 let mut buf
= Vec
::new();
2531 match self.buf
.read_until(self.delim
, &mut buf
) {
2534 if buf
[buf
.len() - 1] == self.delim
{
2539 Err(e
) => Some(Err(e
)),
2544 /// An iterator over the lines of an instance of `BufRead`.
2546 /// This struct is generally created by calling [`lines`] on a `BufRead`.
2547 /// Please see the documentation of [`lines`] for more details.
2549 /// [`lines`]: BufRead::lines
2550 #[stable(feature = "rust1", since = "1.0.0")]
2552 pub struct Lines
<B
> {
2556 #[stable(feature = "rust1", since = "1.0.0")]
2557 impl<B
: BufRead
> Iterator
for Lines
<B
> {
2558 type Item
= Result
<String
>;
2560 fn next(&mut self) -> Option
<Result
<String
>> {
2561 let mut buf
= String
::new();
2562 match self.buf
.read_line(&mut buf
) {
2565 if buf
.ends_with('
\n'
) {
2567 if buf
.ends_with('
\r'
) {
2573 Err(e
) => Some(Err(e
)),