]> git.proxmox.com Git - rustc.git/blob - library/std/src/io/mod.rs
Update upstream source from tag 'upstream/1.47.0_beta.2+dfsg1'
[rustc.git] / library / std / src / io / mod.rs
1 //! Traits, helpers, and type definitions for core I/O functionality.
2 //!
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.
7 //!
8 //! # Read and Write
9 //!
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
15 //! [`File`]s:
16 //!
17 //! ```no_run
18 //! use std::io;
19 //! use std::io::prelude::*;
20 //! use std::fs::File;
21 //!
22 //! fn main() -> io::Result<()> {
23 //! let mut f = File::open("foo.txt")?;
24 //! let mut buffer = [0; 10];
25 //!
26 //! // read up to 10 bytes
27 //! let n = f.read(&mut buffer)?;
28 //!
29 //! println!("The bytes: {:?}", &buffer[..n]);
30 //! Ok(())
31 //! }
32 //! ```
33 //!
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!
37 //!
38 //! ## Seek and BufRead
39 //!
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
43 //! coming from:
44 //!
45 //! ```no_run
46 //! use std::io;
47 //! use std::io::prelude::*;
48 //! use std::io::SeekFrom;
49 //! use std::fs::File;
50 //!
51 //! fn main() -> io::Result<()> {
52 //! let mut f = File::open("foo.txt")?;
53 //! let mut buffer = [0; 10];
54 //!
55 //! // skip to the last 10 bytes of the file
56 //! f.seek(SeekFrom::End(-10))?;
57 //!
58 //! // read up to 10 bytes
59 //! let n = f.read(&mut buffer)?;
60 //!
61 //! println!("The bytes: {:?}", &buffer[..n]);
62 //! Ok(())
63 //! }
64 //! ```
65 //!
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!
68 //!
69 //! ## BufReader and BufWriter
70 //!
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.
76 //!
77 //! For example, [`BufReader`] works with the [`BufRead`] trait to add extra
78 //! methods to any reader:
79 //!
80 //! ```no_run
81 //! use std::io;
82 //! use std::io::prelude::*;
83 //! use std::io::BufReader;
84 //! use std::fs::File;
85 //!
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();
90 //!
91 //! // read a line into buffer
92 //! reader.read_line(&mut buffer)?;
93 //!
94 //! println!("{}", buffer);
95 //! Ok(())
96 //! }
97 //! ```
98 //!
99 //! [`BufWriter`] doesn't add any new ways of writing; it just buffers every call
100 //! to [`write`][`Write::write`]:
101 //!
102 //! ```no_run
103 //! use std::io;
104 //! use std::io::prelude::*;
105 //! use std::io::BufWriter;
106 //! use std::fs::File;
107 //!
108 //! fn main() -> io::Result<()> {
109 //! let f = File::create("foo.txt")?;
110 //! {
111 //! let mut writer = BufWriter::new(f);
112 //!
113 //! // write a byte to the buffer
114 //! writer.write(&[42])?;
115 //!
116 //! } // the buffer is flushed once writer goes out of scope
117 //!
118 //! Ok(())
119 //! }
120 //! ```
121 //!
122 //! ## Standard input and output
123 //!
124 //! A very common source of input is standard input:
125 //!
126 //! ```no_run
127 //! use std::io;
128 //!
129 //! fn main() -> io::Result<()> {
130 //! let mut input = String::new();
131 //!
132 //! io::stdin().read_line(&mut input)?;
133 //!
134 //! println!("You typed: {}", input.trim());
135 //! Ok(())
136 //! }
137 //! ```
138 //!
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:
142 //!
143 //! ```no_run
144 //! use std::io;
145 //!
146 //! let mut input = String::new();
147 //!
148 //! io::stdin().read_line(&mut input).unwrap();
149 //! ```
150 //!
151 //! And a very common source of output is standard output:
152 //!
153 //! ```no_run
154 //! use std::io;
155 //! use std::io::prelude::*;
156 //!
157 //! fn main() -> io::Result<()> {
158 //! io::stdout().write(&[42])?;
159 //! Ok(())
160 //! }
161 //! ```
162 //!
163 //! Of course, using [`io::stdout`] directly is less common than something like
164 //! [`println!`].
165 //!
166 //! ## Iterator types
167 //!
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
170 //! lines:
171 //!
172 //! ```no_run
173 //! use std::io;
174 //! use std::io::prelude::*;
175 //! use std::io::BufReader;
176 //! use std::fs::File;
177 //!
178 //! fn main() -> io::Result<()> {
179 //! let f = File::open("foo.txt")?;
180 //! let reader = BufReader::new(f);
181 //!
182 //! for line in reader.lines() {
183 //! println!("{}", line?);
184 //! }
185 //! Ok(())
186 //! }
187 //! ```
188 //!
189 //! ## Functions
190 //!
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:
194 //!
195 //! ```no_run
196 //! use std::io;
197 //!
198 //! fn main() -> io::Result<()> {
199 //! io::copy(&mut io::stdin(), &mut io::stdout())?;
200 //! Ok(())
201 //! }
202 //! ```
203 //!
204 //! [functions-list]: #functions-1
205 //!
206 //! ## io::Result
207 //!
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]:
212 //!
213 //! ```
214 //! use std::io;
215 //!
216 //! fn read_input() -> io::Result<()> {
217 //! let mut input = String::new();
218 //!
219 //! io::stdin().read_line(&mut input)?;
220 //!
221 //! println!("You typed: {}", input.trim());
222 //!
223 //! Ok(())
224 //! }
225 //! ```
226 //!
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 `()`.
231 //!
232 //! ## Platform-specific behavior
233 //!
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.
240 //!
241 //! [`File`]: crate::fs::File
242 //! [`TcpStream`]: crate::net::TcpStream
243 //! [`Vec<T>`]: Vec
244 //! [`io::stdout`]: stdout
245 //! [`io::Result`]: self::Result
246 //! [`?` operator]: ../../book/appendix-02-operators.html
247 //! [`Result`]: crate::result::Result
248 //! [`.unwrap()`]: crate::result::Result::unwrap
249
250 #![stable(feature = "rust1", since = "1.0.0")]
251
252 use crate::cmp;
253 use crate::fmt;
254 use crate::memchr;
255 use crate::ops::{Deref, DerefMut};
256 use crate::ptr;
257 use crate::slice;
258 use crate::str;
259 use crate::sys;
260
261 #[stable(feature = "rust1", since = "1.0.0")]
262 pub use self::buffered::IntoInnerError;
263 #[stable(feature = "rust1", since = "1.0.0")]
264 pub use self::buffered::{BufReader, BufWriter, LineWriter};
265 #[stable(feature = "rust1", since = "1.0.0")]
266 pub use self::cursor::Cursor;
267 #[stable(feature = "rust1", since = "1.0.0")]
268 pub use self::error::{Error, ErrorKind, Result};
269 #[stable(feature = "rust1", since = "1.0.0")]
270 pub use self::stdio::{stderr, stdin, stdout, Stderr, Stdin, Stdout};
271 #[stable(feature = "rust1", since = "1.0.0")]
272 pub use self::stdio::{StderrLock, StdinLock, StdoutLock};
273 #[unstable(feature = "print_internals", issue = "none")]
274 pub use self::stdio::{_eprint, _print};
275 #[unstable(feature = "libstd_io_internals", issue = "42788")]
276 #[doc(no_inline, hidden)]
277 pub use self::stdio::{set_panic, set_print};
278 #[stable(feature = "rust1", since = "1.0.0")]
279 pub use self::util::{copy, empty, repeat, sink, Empty, Repeat, Sink};
280
281 mod buffered;
282 mod cursor;
283 mod error;
284 mod impls;
285 mod lazy;
286 pub mod prelude;
287 mod stdio;
288 mod util;
289
290 const DEFAULT_BUF_SIZE: usize = crate::sys_common::io::DEFAULT_BUF_SIZE;
291
292 struct Guard<'a> {
293 buf: &'a mut Vec<u8>,
294 len: usize,
295 }
296
297 impl Drop for Guard<'_> {
298 fn drop(&mut self) {
299 unsafe {
300 self.buf.set_len(self.len);
301 }
302 }
303 }
304
305 // A few methods below (read_to_string, read_line) will append data into a
306 // `String` buffer, but we need to be pretty careful when doing this. The
307 // implementation will just call `.as_mut_vec()` and then delegate to a
308 // byte-oriented reading method, but we must ensure that when returning we never
309 // leave `buf` in a state such that it contains invalid UTF-8 in its bounds.
310 //
311 // To this end, we use an RAII guard (to protect against panics) which updates
312 // the length of the string when it is dropped. This guard initially truncates
313 // the string to the prior length and only after we've validated that the
314 // new contents are valid UTF-8 do we allow it to set a longer length.
315 //
316 // The unsafety in this function is twofold:
317 //
318 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
319 // checks.
320 // 2. We're passing a raw buffer to the function `f`, and it is expected that
321 // the function only *appends* bytes to the buffer. We'll get undefined
322 // behavior if existing bytes are overwritten to have non-UTF-8 data.
323 fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
324 where
325 F: FnOnce(&mut Vec<u8>) -> Result<usize>,
326 {
327 unsafe {
328 let mut g = Guard { len: buf.len(), buf: buf.as_mut_vec() };
329 let ret = f(g.buf);
330 if str::from_utf8(&g.buf[g.len..]).is_err() {
331 ret.and_then(|_| {
332 Err(Error::new(ErrorKind::InvalidData, "stream did not contain valid UTF-8"))
333 })
334 } else {
335 g.len = g.buf.len();
336 ret
337 }
338 }
339 }
340
341 // This uses an adaptive system to extend the vector when it fills. We want to
342 // avoid paying to allocate and zero a huge chunk of memory if the reader only
343 // has 4 bytes while still making large reads if the reader does have a ton
344 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
345 // time is 4,500 times (!) slower than a default reservation size of 32 if the
346 // reader has a very small amount of data to return.
347 //
348 // Because we're extending the buffer with uninitialized data for trusted
349 // readers, we need to make sure to truncate that if any of this panics.
350 fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
351 read_to_end_with_reservation(r, buf, |_| 32)
352 }
353
354 fn read_to_end_with_reservation<R, F>(
355 r: &mut R,
356 buf: &mut Vec<u8>,
357 mut reservation_size: F,
358 ) -> Result<usize>
359 where
360 R: Read + ?Sized,
361 F: FnMut(&R) -> usize,
362 {
363 let start_len = buf.len();
364 let mut g = Guard { len: buf.len(), buf };
365 let ret;
366 loop {
367 if g.len == g.buf.len() {
368 unsafe {
369 // FIXME(danielhenrymantilla): #42788
370 //
371 // - This creates a (mut) reference to a slice of
372 // _uninitialized_ integers, which is **undefined behavior**
373 //
374 // - Only the standard library gets to soundly "ignore" this,
375 // based on its privileged knowledge of unstable rustc
376 // internals;
377 g.buf.reserve(reservation_size(r));
378 let capacity = g.buf.capacity();
379 g.buf.set_len(capacity);
380 r.initializer().initialize(&mut g.buf[g.len..]);
381 }
382 }
383
384 match r.read(&mut g.buf[g.len..]) {
385 Ok(0) => {
386 ret = Ok(g.len - start_len);
387 break;
388 }
389 Ok(n) => g.len += n,
390 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
391 Err(e) => {
392 ret = Err(e);
393 break;
394 }
395 }
396 }
397
398 ret
399 }
400
401 pub(crate) fn default_read_vectored<F>(read: F, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
402 where
403 F: FnOnce(&mut [u8]) -> Result<usize>,
404 {
405 let buf = bufs.iter_mut().find(|b| !b.is_empty()).map_or(&mut [][..], |b| &mut **b);
406 read(buf)
407 }
408
409 pub(crate) fn default_write_vectored<F>(write: F, bufs: &[IoSlice<'_>]) -> Result<usize>
410 where
411 F: FnOnce(&[u8]) -> Result<usize>,
412 {
413 let buf = bufs.iter().find(|b| !b.is_empty()).map_or(&[][..], |b| &**b);
414 write(buf)
415 }
416
417 /// The `Read` trait allows for reading bytes from a source.
418 ///
419 /// Implementors of the `Read` trait are called 'readers'.
420 ///
421 /// Readers are defined by one required method, [`read()`]. Each call to [`read()`]
422 /// will attempt to pull bytes from this source into a provided buffer. A
423 /// number of other methods are implemented in terms of [`read()`], giving
424 /// implementors a number of ways to read bytes while only needing to implement
425 /// a single method.
426 ///
427 /// Readers are intended to be composable with one another. Many implementors
428 /// throughout [`std::io`] take and provide types which implement the `Read`
429 /// trait.
430 ///
431 /// Please note that each call to [`read()`] may involve a system call, and
432 /// therefore, using something that implements [`BufRead`], such as
433 /// [`BufReader`], will be more efficient.
434 ///
435 /// # Examples
436 ///
437 /// [`File`]s implement `Read`:
438 ///
439 /// ```no_run
440 /// use std::io;
441 /// use std::io::prelude::*;
442 /// use std::fs::File;
443 ///
444 /// fn main() -> io::Result<()> {
445 /// let mut f = File::open("foo.txt")?;
446 /// let mut buffer = [0; 10];
447 ///
448 /// // read up to 10 bytes
449 /// f.read(&mut buffer)?;
450 ///
451 /// let mut buffer = Vec::new();
452 /// // read the whole file
453 /// f.read_to_end(&mut buffer)?;
454 ///
455 /// // read into a String, so that you don't need to do the conversion.
456 /// let mut buffer = String::new();
457 /// f.read_to_string(&mut buffer)?;
458 ///
459 /// // and more! See the other methods for more details.
460 /// Ok(())
461 /// }
462 /// ```
463 ///
464 /// Read from [`&str`] because [`&[u8]`][slice] implements `Read`:
465 ///
466 /// ```no_run
467 /// # use std::io;
468 /// use std::io::prelude::*;
469 ///
470 /// fn main() -> io::Result<()> {
471 /// let mut b = "This string will be read".as_bytes();
472 /// let mut buffer = [0; 10];
473 ///
474 /// // read up to 10 bytes
475 /// b.read(&mut buffer)?;
476 ///
477 /// // etc... it works exactly as a File does!
478 /// Ok(())
479 /// }
480 /// ```
481 ///
482 /// [`read()`]: Read::read
483 /// [`&str`]: prim@str
484 /// [`std::io`]: self
485 /// [`File`]: crate::fs::File
486 /// [slice]: ../../std/primitive.slice.html
487 #[stable(feature = "rust1", since = "1.0.0")]
488 #[doc(spotlight)]
489 pub trait Read {
490 /// Pull some bytes from this source into the specified buffer, returning
491 /// how many bytes were read.
492 ///
493 /// This function does not provide any guarantees about whether it blocks
494 /// waiting for data, but if an object needs to block for a read and cannot,
495 /// it will typically signal this via an [`Err`] return value.
496 ///
497 /// If the return value of this method is [`Ok(n)`], then it must be
498 /// guaranteed that `0 <= n <= buf.len()`. A nonzero `n` value indicates
499 /// that the buffer `buf` has been filled in with `n` bytes of data from this
500 /// source. If `n` is `0`, then it can indicate one of two scenarios:
501 ///
502 /// 1. This reader has reached its "end of file" and will likely no longer
503 /// be able to produce bytes. Note that this does not mean that the
504 /// reader will *always* no longer be able to produce bytes.
505 /// 2. The buffer specified was 0 bytes in length.
506 ///
507 /// It is not an error if the returned value `n` is smaller than the buffer size,
508 /// even when the reader is not at the end of the stream yet.
509 /// This may happen for example because fewer bytes are actually available right now
510 /// (e. g. being close to end-of-file) or because read() was interrupted by a signal.
511 ///
512 /// No guarantees are provided about the contents of `buf` when this
513 /// function is called, implementations cannot rely on any property of the
514 /// contents of `buf` being true. It is recommended that *implementations*
515 /// only write data to `buf` instead of reading its contents.
516 ///
517 /// Correspondingly, however, *callers* of this method may not assume any guarantees
518 /// about how the implementation uses `buf`. The trait is safe to implement,
519 /// so it is possible that the code that's supposed to write to the buffer might also read
520 /// from it. It is your responsibility to make sure that `buf` is initialized
521 /// before calling `read`. Calling `read` with an uninitialized `buf` (of the kind one
522 /// obtains via [`MaybeUninit<T>`]) is not safe, and can lead to undefined behavior.
523 ///
524 /// [`MaybeUninit<T>`]: crate::mem::MaybeUninit
525 ///
526 /// # Errors
527 ///
528 /// If this function encounters any form of I/O or other error, an error
529 /// variant will be returned. If an error is returned then it must be
530 /// guaranteed that no bytes were read.
531 ///
532 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
533 /// operation should be retried if there is nothing else to do.
534 ///
535 /// # Examples
536 ///
537 /// [`File`]s implement `Read`:
538 ///
539 /// [`Ok(n)`]: Ok
540 /// [`File`]: crate::fs::File
541 ///
542 /// ```no_run
543 /// use std::io;
544 /// use std::io::prelude::*;
545 /// use std::fs::File;
546 ///
547 /// fn main() -> io::Result<()> {
548 /// let mut f = File::open("foo.txt")?;
549 /// let mut buffer = [0; 10];
550 ///
551 /// // read up to 10 bytes
552 /// let n = f.read(&mut buffer[..])?;
553 ///
554 /// println!("The bytes: {:?}", &buffer[..n]);
555 /// Ok(())
556 /// }
557 /// ```
558 #[stable(feature = "rust1", since = "1.0.0")]
559 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
560
561 /// Like `read`, except that it reads into a slice of buffers.
562 ///
563 /// Data is copied to fill each buffer in order, with the final buffer
564 /// written to possibly being only partially filled. This method must
565 /// behave equivalently to a single call to `read` with concatenated
566 /// buffers.
567 ///
568 /// The default implementation calls `read` with either the first nonempty
569 /// buffer provided, or an empty one if none exists.
570 #[stable(feature = "iovec", since = "1.36.0")]
571 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
572 default_read_vectored(|b| self.read(b), bufs)
573 }
574
575 /// Determines if this `Read`er has an efficient `read_vectored`
576 /// implementation.
577 ///
578 /// If a `Read`er does not override the default `read_vectored`
579 /// implementation, code using it may want to avoid the method all together
580 /// and coalesce writes into a single buffer for higher performance.
581 ///
582 /// The default implementation returns `false`.
583 #[unstable(feature = "can_vector", issue = "69941")]
584 fn is_read_vectored(&self) -> bool {
585 false
586 }
587
588 /// Determines if this `Read`er can work with buffers of uninitialized
589 /// memory.
590 ///
591 /// The default implementation returns an initializer which will zero
592 /// buffers.
593 ///
594 /// If a `Read`er guarantees that it can work properly with uninitialized
595 /// memory, it should call [`Initializer::nop()`]. See the documentation for
596 /// [`Initializer`] for details.
597 ///
598 /// The behavior of this method must be independent of the state of the
599 /// `Read`er - the method only takes `&self` so that it can be used through
600 /// trait objects.
601 ///
602 /// # Safety
603 ///
604 /// This method is unsafe because a `Read`er could otherwise return a
605 /// non-zeroing `Initializer` from another `Read` type without an `unsafe`
606 /// block.
607 #[unstable(feature = "read_initializer", issue = "42788")]
608 #[inline]
609 unsafe fn initializer(&self) -> Initializer {
610 Initializer::zeroing()
611 }
612
613 /// Read all bytes until EOF in this source, placing them into `buf`.
614 ///
615 /// All bytes read from this source will be appended to the specified buffer
616 /// `buf`. This function will continuously call [`read()`] to append more data to
617 /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of
618 /// non-[`ErrorKind::Interrupted`] kind.
619 ///
620 /// If successful, this function will return the total number of bytes read.
621 ///
622 /// # Errors
623 ///
624 /// If this function encounters an error of the kind
625 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
626 /// will continue.
627 ///
628 /// If any other read error is encountered then this function immediately
629 /// returns. Any bytes which have already been read will be appended to
630 /// `buf`.
631 ///
632 /// # Examples
633 ///
634 /// [`File`]s implement `Read`:
635 ///
636 /// [`read()`]: Read::read
637 /// [`Ok(0)`]: Ok
638 /// [`File`]: crate::fs::File
639 ///
640 /// ```no_run
641 /// use std::io;
642 /// use std::io::prelude::*;
643 /// use std::fs::File;
644 ///
645 /// fn main() -> io::Result<()> {
646 /// let mut f = File::open("foo.txt")?;
647 /// let mut buffer = Vec::new();
648 ///
649 /// // read the whole file
650 /// f.read_to_end(&mut buffer)?;
651 /// Ok(())
652 /// }
653 /// ```
654 ///
655 /// (See also the [`std::fs::read`] convenience function for reading from a
656 /// file.)
657 ///
658 /// [`std::fs::read`]: crate::fs::read
659 #[stable(feature = "rust1", since = "1.0.0")]
660 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
661 read_to_end(self, buf)
662 }
663
664 /// Read all bytes until EOF in this source, appending them to `buf`.
665 ///
666 /// If successful, this function returns the number of bytes which were read
667 /// and appended to `buf`.
668 ///
669 /// # Errors
670 ///
671 /// If the data in this stream is *not* valid UTF-8 then an error is
672 /// returned and `buf` is unchanged.
673 ///
674 /// See [`read_to_end`] for other error semantics.
675 ///
676 /// [`read_to_end`]: Read::read_to_end
677 ///
678 /// # Examples
679 ///
680 /// [`File`]s implement `Read`:
681 ///
682 /// [`File`]: crate::fs::File
683 ///
684 /// ```no_run
685 /// use std::io;
686 /// use std::io::prelude::*;
687 /// use std::fs::File;
688 ///
689 /// fn main() -> io::Result<()> {
690 /// let mut f = File::open("foo.txt")?;
691 /// let mut buffer = String::new();
692 ///
693 /// f.read_to_string(&mut buffer)?;
694 /// Ok(())
695 /// }
696 /// ```
697 ///
698 /// (See also the [`std::fs::read_to_string`] convenience function for
699 /// reading from a file.)
700 ///
701 /// [`std::fs::read_to_string`]: crate::fs::read_to_string
702 #[stable(feature = "rust1", since = "1.0.0")]
703 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
704 // Note that we do *not* call `.read_to_end()` here. We are passing
705 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
706 // method to fill it up. An arbitrary implementation could overwrite the
707 // entire contents of the vector, not just append to it (which is what
708 // we are expecting).
709 //
710 // To prevent extraneously checking the UTF-8-ness of the entire buffer
711 // we pass it to our hardcoded `read_to_end` implementation which we
712 // know is guaranteed to only read data into the end of the buffer.
713 append_to_string(buf, |b| read_to_end(self, b))
714 }
715
716 /// Read the exact number of bytes required to fill `buf`.
717 ///
718 /// This function reads as many bytes as necessary to completely fill the
719 /// specified buffer `buf`.
720 ///
721 /// No guarantees are provided about the contents of `buf` when this
722 /// function is called, implementations cannot rely on any property of the
723 /// contents of `buf` being true. It is recommended that implementations
724 /// only write data to `buf` instead of reading its contents. The
725 /// documentation on [`read`] has a more detailed explanation on this
726 /// subject.
727 ///
728 /// # Errors
729 ///
730 /// If this function encounters an error of the kind
731 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
732 /// will continue.
733 ///
734 /// If this function encounters an "end of file" before completely filling
735 /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
736 /// The contents of `buf` are unspecified in this case.
737 ///
738 /// If any other read error is encountered then this function immediately
739 /// returns. The contents of `buf` are unspecified in this case.
740 ///
741 /// If this function returns an error, it is unspecified how many bytes it
742 /// has read, but it will never read more than would be necessary to
743 /// completely fill the buffer.
744 ///
745 /// # Examples
746 ///
747 /// [`File`]s implement `Read`:
748 ///
749 /// [`read`]: Read::read
750 /// [`File`]: crate::fs::File
751 ///
752 /// ```no_run
753 /// use std::io;
754 /// use std::io::prelude::*;
755 /// use std::fs::File;
756 ///
757 /// fn main() -> io::Result<()> {
758 /// let mut f = File::open("foo.txt")?;
759 /// let mut buffer = [0; 10];
760 ///
761 /// // read exactly 10 bytes
762 /// f.read_exact(&mut buffer)?;
763 /// Ok(())
764 /// }
765 /// ```
766 #[stable(feature = "read_exact", since = "1.6.0")]
767 fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
768 while !buf.is_empty() {
769 match self.read(buf) {
770 Ok(0) => break,
771 Ok(n) => {
772 let tmp = buf;
773 buf = &mut tmp[n..];
774 }
775 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
776 Err(e) => return Err(e),
777 }
778 }
779 if !buf.is_empty() {
780 Err(Error::new(ErrorKind::UnexpectedEof, "failed to fill whole buffer"))
781 } else {
782 Ok(())
783 }
784 }
785
786 /// Creates a "by reference" adaptor for this instance of `Read`.
787 ///
788 /// The returned adaptor also implements `Read` and will simply borrow this
789 /// current reader.
790 ///
791 /// # Examples
792 ///
793 /// [`File`]s implement `Read`:
794 ///
795 /// [`File`]: crate::fs::File
796 ///
797 /// ```no_run
798 /// use std::io;
799 /// use std::io::Read;
800 /// use std::fs::File;
801 ///
802 /// fn main() -> io::Result<()> {
803 /// let mut f = File::open("foo.txt")?;
804 /// let mut buffer = Vec::new();
805 /// let mut other_buffer = Vec::new();
806 ///
807 /// {
808 /// let reference = f.by_ref();
809 ///
810 /// // read at most 5 bytes
811 /// reference.take(5).read_to_end(&mut buffer)?;
812 ///
813 /// } // drop our &mut reference so we can use f again
814 ///
815 /// // original file still usable, read the rest
816 /// f.read_to_end(&mut other_buffer)?;
817 /// Ok(())
818 /// }
819 /// ```
820 #[stable(feature = "rust1", since = "1.0.0")]
821 fn by_ref(&mut self) -> &mut Self
822 where
823 Self: Sized,
824 {
825 self
826 }
827
828 /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
829 ///
830 /// The returned type implements [`Iterator`] where the `Item` is
831 /// [`Result`]`<`[`u8`]`, `[`io::Error`]`>`.
832 /// The yielded item is [`Ok`] if a byte was successfully read and [`Err`]
833 /// otherwise. EOF is mapped to returning [`None`] from this iterator.
834 ///
835 /// # Examples
836 ///
837 /// [`File`]s implement `Read`:
838 ///
839 /// [`File`]: crate::fs::File
840 /// [`Result`]: crate::result::Result
841 /// [`io::Error`]: self::Error
842 ///
843 /// ```no_run
844 /// use std::io;
845 /// use std::io::prelude::*;
846 /// use std::fs::File;
847 ///
848 /// fn main() -> io::Result<()> {
849 /// let mut f = File::open("foo.txt")?;
850 ///
851 /// for byte in f.bytes() {
852 /// println!("{}", byte.unwrap());
853 /// }
854 /// Ok(())
855 /// }
856 /// ```
857 #[stable(feature = "rust1", since = "1.0.0")]
858 fn bytes(self) -> Bytes<Self>
859 where
860 Self: Sized,
861 {
862 Bytes { inner: self }
863 }
864
865 /// Creates an adaptor which will chain this stream with another.
866 ///
867 /// The returned `Read` instance will first read all bytes from this object
868 /// until EOF is encountered. Afterwards the output is equivalent to the
869 /// output of `next`.
870 ///
871 /// # Examples
872 ///
873 /// [`File`]s implement `Read`:
874 ///
875 /// [`File`]: crate::fs::File
876 ///
877 /// ```no_run
878 /// use std::io;
879 /// use std::io::prelude::*;
880 /// use std::fs::File;
881 ///
882 /// fn main() -> io::Result<()> {
883 /// let mut f1 = File::open("foo.txt")?;
884 /// let mut f2 = File::open("bar.txt")?;
885 ///
886 /// let mut handle = f1.chain(f2);
887 /// let mut buffer = String::new();
888 ///
889 /// // read the value into a String. We could use any Read method here,
890 /// // this is just one example.
891 /// handle.read_to_string(&mut buffer)?;
892 /// Ok(())
893 /// }
894 /// ```
895 #[stable(feature = "rust1", since = "1.0.0")]
896 fn chain<R: Read>(self, next: R) -> Chain<Self, R>
897 where
898 Self: Sized,
899 {
900 Chain { first: self, second: next, done_first: false }
901 }
902
903 /// Creates an adaptor which will read at most `limit` bytes from it.
904 ///
905 /// This function returns a new instance of `Read` which will read at most
906 /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
907 /// read errors will not count towards the number of bytes read and future
908 /// calls to [`read()`] may succeed.
909 ///
910 /// # Examples
911 ///
912 /// [`File`]s implement `Read`:
913 ///
914 /// [`File`]: crate::fs::File
915 /// [`Ok(0)`]: Ok
916 /// [`read()`]: Read::read
917 ///
918 /// ```no_run
919 /// use std::io;
920 /// use std::io::prelude::*;
921 /// use std::fs::File;
922 ///
923 /// fn main() -> io::Result<()> {
924 /// let mut f = File::open("foo.txt")?;
925 /// let mut buffer = [0; 5];
926 ///
927 /// // read at most five bytes
928 /// let mut handle = f.take(5);
929 ///
930 /// handle.read(&mut buffer)?;
931 /// Ok(())
932 /// }
933 /// ```
934 #[stable(feature = "rust1", since = "1.0.0")]
935 fn take(self, limit: u64) -> Take<Self>
936 where
937 Self: Sized,
938 {
939 Take { inner: self, limit }
940 }
941 }
942
943 /// A buffer type used with `Read::read_vectored`.
944 ///
945 /// It is semantically a wrapper around an `&mut [u8]`, but is guaranteed to be
946 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
947 /// Windows.
948 #[stable(feature = "iovec", since = "1.36.0")]
949 #[repr(transparent)]
950 pub struct IoSliceMut<'a>(sys::io::IoSliceMut<'a>);
951
952 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
953 unsafe impl<'a> Send for IoSliceMut<'a> {}
954
955 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
956 unsafe impl<'a> Sync for IoSliceMut<'a> {}
957
958 #[stable(feature = "iovec", since = "1.36.0")]
959 impl<'a> fmt::Debug for IoSliceMut<'a> {
960 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
961 fmt::Debug::fmt(self.0.as_slice(), fmt)
962 }
963 }
964
965 impl<'a> IoSliceMut<'a> {
966 /// Creates a new `IoSliceMut` wrapping a byte slice.
967 ///
968 /// # Panics
969 ///
970 /// Panics on Windows if the slice is larger than 4GB.
971 #[stable(feature = "iovec", since = "1.36.0")]
972 #[inline]
973 pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> {
974 IoSliceMut(sys::io::IoSliceMut::new(buf))
975 }
976
977 /// Advance the internal cursor of the slice.
978 ///
979 /// # Notes
980 ///
981 /// Elements in the slice may be modified if the cursor is not advanced to
982 /// the end of the slice. For example if we have a slice of buffers with 2
983 /// `IoSliceMut`s, both of length 8, and we advance the cursor by 10 bytes
984 /// the first `IoSliceMut` will be untouched however the second will be
985 /// modified to remove the first 2 bytes (10 - 8).
986 ///
987 /// # Examples
988 ///
989 /// ```
990 /// #![feature(io_slice_advance)]
991 ///
992 /// use std::io::IoSliceMut;
993 /// use std::ops::Deref;
994 ///
995 /// let mut buf1 = [1; 8];
996 /// let mut buf2 = [2; 16];
997 /// let mut buf3 = [3; 8];
998 /// let mut bufs = &mut [
999 /// IoSliceMut::new(&mut buf1),
1000 /// IoSliceMut::new(&mut buf2),
1001 /// IoSliceMut::new(&mut buf3),
1002 /// ][..];
1003 ///
1004 /// // Mark 10 bytes as read.
1005 /// bufs = IoSliceMut::advance(bufs, 10);
1006 /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1007 /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1008 /// ```
1009 #[unstable(feature = "io_slice_advance", issue = "62726")]
1010 #[inline]
1011 pub fn advance<'b>(bufs: &'b mut [IoSliceMut<'a>], n: usize) -> &'b mut [IoSliceMut<'a>] {
1012 // Number of buffers to remove.
1013 let mut remove = 0;
1014 // Total length of all the to be removed buffers.
1015 let mut accumulated_len = 0;
1016 for buf in bufs.iter() {
1017 if accumulated_len + buf.len() > n {
1018 break;
1019 } else {
1020 accumulated_len += buf.len();
1021 remove += 1;
1022 }
1023 }
1024
1025 let bufs = &mut bufs[remove..];
1026 if !bufs.is_empty() {
1027 bufs[0].0.advance(n - accumulated_len)
1028 }
1029 bufs
1030 }
1031 }
1032
1033 #[stable(feature = "iovec", since = "1.36.0")]
1034 impl<'a> Deref for IoSliceMut<'a> {
1035 type Target = [u8];
1036
1037 #[inline]
1038 fn deref(&self) -> &[u8] {
1039 self.0.as_slice()
1040 }
1041 }
1042
1043 #[stable(feature = "iovec", since = "1.36.0")]
1044 impl<'a> DerefMut for IoSliceMut<'a> {
1045 #[inline]
1046 fn deref_mut(&mut self) -> &mut [u8] {
1047 self.0.as_mut_slice()
1048 }
1049 }
1050
1051 /// A buffer type used with `Write::write_vectored`.
1052 ///
1053 /// It is semantically a wrapper around an `&[u8]`, but is guaranteed to be
1054 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
1055 /// Windows.
1056 #[stable(feature = "iovec", since = "1.36.0")]
1057 #[derive(Copy, Clone)]
1058 #[repr(transparent)]
1059 pub struct IoSlice<'a>(sys::io::IoSlice<'a>);
1060
1061 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1062 unsafe impl<'a> Send for IoSlice<'a> {}
1063
1064 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1065 unsafe impl<'a> Sync for IoSlice<'a> {}
1066
1067 #[stable(feature = "iovec", since = "1.36.0")]
1068 impl<'a> fmt::Debug for IoSlice<'a> {
1069 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1070 fmt::Debug::fmt(self.0.as_slice(), fmt)
1071 }
1072 }
1073
1074 impl<'a> IoSlice<'a> {
1075 /// Creates a new `IoSlice` wrapping a byte slice.
1076 ///
1077 /// # Panics
1078 ///
1079 /// Panics on Windows if the slice is larger than 4GB.
1080 #[stable(feature = "iovec", since = "1.36.0")]
1081 #[inline]
1082 pub fn new(buf: &'a [u8]) -> IoSlice<'a> {
1083 IoSlice(sys::io::IoSlice::new(buf))
1084 }
1085
1086 /// Advance the internal cursor of the slice.
1087 ///
1088 /// # Notes
1089 ///
1090 /// Elements in the slice may be modified if the cursor is not advanced to
1091 /// the end of the slice. For example if we have a slice of buffers with 2
1092 /// `IoSlice`s, both of length 8, and we advance the cursor by 10 bytes the
1093 /// first `IoSlice` will be untouched however the second will be modified to
1094 /// remove the first 2 bytes (10 - 8).
1095 ///
1096 /// # Examples
1097 ///
1098 /// ```
1099 /// #![feature(io_slice_advance)]
1100 ///
1101 /// use std::io::IoSlice;
1102 /// use std::ops::Deref;
1103 ///
1104 /// let buf1 = [1; 8];
1105 /// let buf2 = [2; 16];
1106 /// let buf3 = [3; 8];
1107 /// let mut bufs = &mut [
1108 /// IoSlice::new(&buf1),
1109 /// IoSlice::new(&buf2),
1110 /// IoSlice::new(&buf3),
1111 /// ][..];
1112 ///
1113 /// // Mark 10 bytes as written.
1114 /// bufs = IoSlice::advance(bufs, 10);
1115 /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1116 /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1117 #[unstable(feature = "io_slice_advance", issue = "62726")]
1118 #[inline]
1119 pub fn advance<'b>(bufs: &'b mut [IoSlice<'a>], n: usize) -> &'b mut [IoSlice<'a>] {
1120 // Number of buffers to remove.
1121 let mut remove = 0;
1122 // Total length of all the to be removed buffers.
1123 let mut accumulated_len = 0;
1124 for buf in bufs.iter() {
1125 if accumulated_len + buf.len() > n {
1126 break;
1127 } else {
1128 accumulated_len += buf.len();
1129 remove += 1;
1130 }
1131 }
1132
1133 let bufs = &mut bufs[remove..];
1134 if !bufs.is_empty() {
1135 bufs[0].0.advance(n - accumulated_len)
1136 }
1137 bufs
1138 }
1139 }
1140
1141 #[stable(feature = "iovec", since = "1.36.0")]
1142 impl<'a> Deref for IoSlice<'a> {
1143 type Target = [u8];
1144
1145 #[inline]
1146 fn deref(&self) -> &[u8] {
1147 self.0.as_slice()
1148 }
1149 }
1150
1151 /// A type used to conditionally initialize buffers passed to `Read` methods.
1152 #[unstable(feature = "read_initializer", issue = "42788")]
1153 #[derive(Debug)]
1154 pub struct Initializer(bool);
1155
1156 impl Initializer {
1157 /// Returns a new `Initializer` which will zero out buffers.
1158 #[unstable(feature = "read_initializer", issue = "42788")]
1159 #[inline]
1160 pub fn zeroing() -> Initializer {
1161 Initializer(true)
1162 }
1163
1164 /// Returns a new `Initializer` which will not zero out buffers.
1165 ///
1166 /// # Safety
1167 ///
1168 /// This may only be called by `Read`ers which guarantee that they will not
1169 /// read from buffers passed to `Read` methods, and that the return value of
1170 /// the method accurately reflects the number of bytes that have been
1171 /// written to the head of the buffer.
1172 #[unstable(feature = "read_initializer", issue = "42788")]
1173 #[inline]
1174 pub unsafe fn nop() -> Initializer {
1175 Initializer(false)
1176 }
1177
1178 /// Indicates if a buffer should be initialized.
1179 #[unstable(feature = "read_initializer", issue = "42788")]
1180 #[inline]
1181 pub fn should_initialize(&self) -> bool {
1182 self.0
1183 }
1184
1185 /// Initializes a buffer if necessary.
1186 #[unstable(feature = "read_initializer", issue = "42788")]
1187 #[inline]
1188 pub fn initialize(&self, buf: &mut [u8]) {
1189 if self.should_initialize() {
1190 unsafe { ptr::write_bytes(buf.as_mut_ptr(), 0, buf.len()) }
1191 }
1192 }
1193 }
1194
1195 /// A trait for objects which are byte-oriented sinks.
1196 ///
1197 /// Implementors of the `Write` trait are sometimes called 'writers'.
1198 ///
1199 /// Writers are defined by two required methods, [`write`] and [`flush`]:
1200 ///
1201 /// * The [`write`] method will attempt to write some data into the object,
1202 /// returning how many bytes were successfully written.
1203 ///
1204 /// * The [`flush`] method is useful for adaptors and explicit buffers
1205 /// themselves for ensuring that all buffered data has been pushed out to the
1206 /// 'true sink'.
1207 ///
1208 /// Writers are intended to be composable with one another. Many implementors
1209 /// throughout [`std::io`] take and provide types which implement the `Write`
1210 /// trait.
1211 ///
1212 /// [`write`]: Write::write
1213 /// [`flush`]: Write::flush
1214 /// [`std::io`]: self
1215 ///
1216 /// # Examples
1217 ///
1218 /// ```no_run
1219 /// use std::io::prelude::*;
1220 /// use std::fs::File;
1221 ///
1222 /// fn main() -> std::io::Result<()> {
1223 /// let data = b"some bytes";
1224 ///
1225 /// let mut pos = 0;
1226 /// let mut buffer = File::create("foo.txt")?;
1227 ///
1228 /// while pos < data.len() {
1229 /// let bytes_written = buffer.write(&data[pos..])?;
1230 /// pos += bytes_written;
1231 /// }
1232 /// Ok(())
1233 /// }
1234 /// ```
1235 ///
1236 /// The trait also provides convenience methods like [`write_all`], which calls
1237 /// `write` in a loop until its entire input has been written.
1238 ///
1239 /// [`write_all`]: Write::write_all
1240 #[stable(feature = "rust1", since = "1.0.0")]
1241 #[doc(spotlight)]
1242 pub trait Write {
1243 /// Write a buffer into this writer, returning how many bytes were written.
1244 ///
1245 /// This function will attempt to write the entire contents of `buf`, but
1246 /// the entire write may not succeed, or the write may also generate an
1247 /// error. A call to `write` represents *at most one* attempt to write to
1248 /// any wrapped object.
1249 ///
1250 /// Calls to `write` are not guaranteed to block waiting for data to be
1251 /// written, and a write which would otherwise block can be indicated through
1252 /// an [`Err`] variant.
1253 ///
1254 /// If the return value is [`Ok(n)`] then it must be guaranteed that
1255 /// `n <= buf.len()`. A return value of `0` typically means that the
1256 /// underlying object is no longer able to accept bytes and will likely not
1257 /// be able to in the future as well, or that the buffer provided is empty.
1258 ///
1259 /// # Errors
1260 ///
1261 /// Each call to `write` may generate an I/O error indicating that the
1262 /// operation could not be completed. If an error is returned then no bytes
1263 /// in the buffer were written to this writer.
1264 ///
1265 /// It is **not** considered an error if the entire buffer could not be
1266 /// written to this writer.
1267 ///
1268 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the
1269 /// write operation should be retried if there is nothing else to do.
1270 ///
1271 /// # Examples
1272 ///
1273 /// ```no_run
1274 /// use std::io::prelude::*;
1275 /// use std::fs::File;
1276 ///
1277 /// fn main() -> std::io::Result<()> {
1278 /// let mut buffer = File::create("foo.txt")?;
1279 ///
1280 /// // Writes some prefix of the byte string, not necessarily all of it.
1281 /// buffer.write(b"some bytes")?;
1282 /// Ok(())
1283 /// }
1284 /// ```
1285 ///
1286 /// [`Ok(n)`]: Ok
1287 #[stable(feature = "rust1", since = "1.0.0")]
1288 fn write(&mut self, buf: &[u8]) -> Result<usize>;
1289
1290 /// Like [`write`], except that it writes from a slice of buffers.
1291 ///
1292 /// Data is copied from each buffer in order, with the final buffer
1293 /// read from possibly being only partially consumed. This method must
1294 /// behave as a call to [`write`] with the buffers concatenated would.
1295 ///
1296 /// The default implementation calls [`write`] with either the first nonempty
1297 /// buffer provided, or an empty one if none exists.
1298 ///
1299 /// [`write`]: Write::write
1300 #[stable(feature = "iovec", since = "1.36.0")]
1301 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize> {
1302 default_write_vectored(|b| self.write(b), bufs)
1303 }
1304
1305 /// Determines if this `Write`er has an efficient [`write_vectored`]
1306 /// implementation.
1307 ///
1308 /// If a `Write`er does not override the default [`write_vectored`]
1309 /// implementation, code using it may want to avoid the method all together
1310 /// and coalesce writes into a single buffer for higher performance.
1311 ///
1312 /// The default implementation returns `false`.
1313 ///
1314 /// [`write_vectored`]: Write::write_vectored
1315 #[unstable(feature = "can_vector", issue = "69941")]
1316 fn is_write_vectored(&self) -> bool {
1317 false
1318 }
1319
1320 /// Flush this output stream, ensuring that all intermediately buffered
1321 /// contents reach their destination.
1322 ///
1323 /// # Errors
1324 ///
1325 /// It is considered an error if not all bytes could be written due to
1326 /// I/O errors or EOF being reached.
1327 ///
1328 /// # Examples
1329 ///
1330 /// ```no_run
1331 /// use std::io::prelude::*;
1332 /// use std::io::BufWriter;
1333 /// use std::fs::File;
1334 ///
1335 /// fn main() -> std::io::Result<()> {
1336 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
1337 ///
1338 /// buffer.write_all(b"some bytes")?;
1339 /// buffer.flush()?;
1340 /// Ok(())
1341 /// }
1342 /// ```
1343 #[stable(feature = "rust1", since = "1.0.0")]
1344 fn flush(&mut self) -> Result<()>;
1345
1346 /// Attempts to write an entire buffer into this writer.
1347 ///
1348 /// This method will continuously call [`write`] until there is no more data
1349 /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is
1350 /// returned. This method will not return until the entire buffer has been
1351 /// successfully written or such an error occurs. The first error that is
1352 /// not of [`ErrorKind::Interrupted`] kind generated from this method will be
1353 /// returned.
1354 ///
1355 /// If the buffer contains no data, this will never call [`write`].
1356 ///
1357 /// # Errors
1358 ///
1359 /// This function will return the first error of
1360 /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns.
1361 ///
1362 /// [`write`]: Write::write
1363 ///
1364 /// # Examples
1365 ///
1366 /// ```no_run
1367 /// use std::io::prelude::*;
1368 /// use std::fs::File;
1369 ///
1370 /// fn main() -> std::io::Result<()> {
1371 /// let mut buffer = File::create("foo.txt")?;
1372 ///
1373 /// buffer.write_all(b"some bytes")?;
1374 /// Ok(())
1375 /// }
1376 /// ```
1377 #[stable(feature = "rust1", since = "1.0.0")]
1378 fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
1379 while !buf.is_empty() {
1380 match self.write(buf) {
1381 Ok(0) => {
1382 return Err(Error::new(ErrorKind::WriteZero, "failed to write whole buffer"));
1383 }
1384 Ok(n) => buf = &buf[n..],
1385 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1386 Err(e) => return Err(e),
1387 }
1388 }
1389 Ok(())
1390 }
1391
1392 /// Attempts to write multiple buffers into this writer.
1393 ///
1394 /// This method will continuously call [`write_vectored`] until there is no
1395 /// more data to be written or an error of non-[`ErrorKind::Interrupted`]
1396 /// kind is returned. This method will not return until all buffers have
1397 /// been successfully written or such an error occurs. The first error that
1398 /// is not of [`ErrorKind::Interrupted`] kind generated from this method
1399 /// will be returned.
1400 ///
1401 /// If the buffer contains no data, this will never call [`write_vectored`].
1402 ///
1403 /// # Notes
1404 ///
1405 /// Unlike [`write_vectored`], this takes a *mutable* reference to
1406 /// a slice of [`IoSlice`]s, not an immutable one. That's because we need to
1407 /// modify the slice to keep track of the bytes already written.
1408 ///
1409 /// Once this function returns, the contents of `bufs` are unspecified, as
1410 /// this depends on how many calls to [`write_vectored`] were necessary. It is
1411 /// best to understand this function as taking ownership of `bufs` and to
1412 /// not use `bufs` afterwards. The underlying buffers, to which the
1413 /// [`IoSlice`]s point (but not the [`IoSlice`]s themselves), are unchanged and
1414 /// can be reused.
1415 ///
1416 /// [`write_vectored`]: Write::write_vectored
1417 ///
1418 /// # Examples
1419 ///
1420 /// ```
1421 /// #![feature(write_all_vectored)]
1422 /// # fn main() -> std::io::Result<()> {
1423 ///
1424 /// use std::io::{Write, IoSlice};
1425 ///
1426 /// let mut writer = Vec::new();
1427 /// let bufs = &mut [
1428 /// IoSlice::new(&[1]),
1429 /// IoSlice::new(&[2, 3]),
1430 /// IoSlice::new(&[4, 5, 6]),
1431 /// ];
1432 ///
1433 /// writer.write_all_vectored(bufs)?;
1434 /// // Note: the contents of `bufs` is now undefined, see the Notes section.
1435 ///
1436 /// assert_eq!(writer, &[1, 2, 3, 4, 5, 6]);
1437 /// # Ok(()) }
1438 /// ```
1439 #[unstable(feature = "write_all_vectored", issue = "70436")]
1440 fn write_all_vectored(&mut self, mut bufs: &mut [IoSlice<'_>]) -> Result<()> {
1441 // Guarantee that bufs is empty if it contains no data,
1442 // to avoid calling write_vectored if there is no data to be written.
1443 bufs = IoSlice::advance(bufs, 0);
1444 while !bufs.is_empty() {
1445 match self.write_vectored(bufs) {
1446 Ok(0) => {
1447 return Err(Error::new(ErrorKind::WriteZero, "failed to write whole buffer"));
1448 }
1449 Ok(n) => bufs = IoSlice::advance(bufs, n),
1450 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1451 Err(e) => return Err(e),
1452 }
1453 }
1454 Ok(())
1455 }
1456
1457 /// Writes a formatted string into this writer, returning any error
1458 /// encountered.
1459 ///
1460 /// This method is primarily used to interface with the
1461 /// [`format_args!()`] macro, but it is rare that this should
1462 /// explicitly be called. The [`write!()`] macro should be favored to
1463 /// invoke this method instead.
1464 ///
1465 /// This function internally uses the [`write_all`] method on
1466 /// this trait and hence will continuously write data so long as no errors
1467 /// are received. This also means that partial writes are not indicated in
1468 /// this signature.
1469 ///
1470 /// [`write_all`]: Write::write_all
1471 ///
1472 /// # Errors
1473 ///
1474 /// This function will return any I/O error reported while formatting.
1475 ///
1476 /// # Examples
1477 ///
1478 /// ```no_run
1479 /// use std::io::prelude::*;
1480 /// use std::fs::File;
1481 ///
1482 /// fn main() -> std::io::Result<()> {
1483 /// let mut buffer = File::create("foo.txt")?;
1484 ///
1485 /// // this call
1486 /// write!(buffer, "{:.*}", 2, 1.234567)?;
1487 /// // turns into this:
1488 /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1489 /// Ok(())
1490 /// }
1491 /// ```
1492 #[stable(feature = "rust1", since = "1.0.0")]
1493 fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> Result<()> {
1494 // Create a shim which translates a Write to a fmt::Write and saves
1495 // off I/O errors. instead of discarding them
1496 struct Adaptor<'a, T: ?Sized + 'a> {
1497 inner: &'a mut T,
1498 error: Result<()>,
1499 }
1500
1501 impl<T: Write + ?Sized> fmt::Write for Adaptor<'_, T> {
1502 fn write_str(&mut self, s: &str) -> fmt::Result {
1503 match self.inner.write_all(s.as_bytes()) {
1504 Ok(()) => Ok(()),
1505 Err(e) => {
1506 self.error = Err(e);
1507 Err(fmt::Error)
1508 }
1509 }
1510 }
1511 }
1512
1513 let mut output = Adaptor { inner: self, error: Ok(()) };
1514 match fmt::write(&mut output, fmt) {
1515 Ok(()) => Ok(()),
1516 Err(..) => {
1517 // check if the error came from the underlying `Write` or not
1518 if output.error.is_err() {
1519 output.error
1520 } else {
1521 Err(Error::new(ErrorKind::Other, "formatter error"))
1522 }
1523 }
1524 }
1525 }
1526
1527 /// Creates a "by reference" adaptor for this instance of `Write`.
1528 ///
1529 /// The returned adaptor also implements `Write` and will simply borrow this
1530 /// current writer.
1531 ///
1532 /// # Examples
1533 ///
1534 /// ```no_run
1535 /// use std::io::Write;
1536 /// use std::fs::File;
1537 ///
1538 /// fn main() -> std::io::Result<()> {
1539 /// let mut buffer = File::create("foo.txt")?;
1540 ///
1541 /// let reference = buffer.by_ref();
1542 ///
1543 /// // we can use reference just like our original buffer
1544 /// reference.write_all(b"some bytes")?;
1545 /// Ok(())
1546 /// }
1547 /// ```
1548 #[stable(feature = "rust1", since = "1.0.0")]
1549 fn by_ref(&mut self) -> &mut Self
1550 where
1551 Self: Sized,
1552 {
1553 self
1554 }
1555 }
1556
1557 /// The `Seek` trait provides a cursor which can be moved within a stream of
1558 /// bytes.
1559 ///
1560 /// The stream typically has a fixed size, allowing seeking relative to either
1561 /// end or the current offset.
1562 ///
1563 /// # Examples
1564 ///
1565 /// [`File`]s implement `Seek`:
1566 ///
1567 /// [`File`]: crate::fs::File
1568 ///
1569 /// ```no_run
1570 /// use std::io;
1571 /// use std::io::prelude::*;
1572 /// use std::fs::File;
1573 /// use std::io::SeekFrom;
1574 ///
1575 /// fn main() -> io::Result<()> {
1576 /// let mut f = File::open("foo.txt")?;
1577 ///
1578 /// // move the cursor 42 bytes from the start of the file
1579 /// f.seek(SeekFrom::Start(42))?;
1580 /// Ok(())
1581 /// }
1582 /// ```
1583 #[stable(feature = "rust1", since = "1.0.0")]
1584 pub trait Seek {
1585 /// Seek to an offset, in bytes, in a stream.
1586 ///
1587 /// A seek beyond the end of a stream is allowed, but behavior is defined
1588 /// by the implementation.
1589 ///
1590 /// If the seek operation completed successfully,
1591 /// this method returns the new position from the start of the stream.
1592 /// That position can be used later with [`SeekFrom::Start`].
1593 ///
1594 /// # Errors
1595 ///
1596 /// Seeking to a negative offset is considered an error.
1597 #[stable(feature = "rust1", since = "1.0.0")]
1598 fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1599
1600 /// Returns the length of this stream (in bytes).
1601 ///
1602 /// This method is implemented using up to three seek operations. If this
1603 /// method returns successfully, the seek position is unchanged (i.e. the
1604 /// position before calling this method is the same as afterwards).
1605 /// However, if this method returns an error, the seek position is
1606 /// unspecified.
1607 ///
1608 /// If you need to obtain the length of *many* streams and you don't care
1609 /// about the seek position afterwards, you can reduce the number of seek
1610 /// operations by simply calling `seek(SeekFrom::End(0))` and using its
1611 /// return value (it is also the stream length).
1612 ///
1613 /// Note that length of a stream can change over time (for example, when
1614 /// data is appended to a file). So calling this method multiple times does
1615 /// not necessarily return the same length each time.
1616 ///
1617 /// # Example
1618 ///
1619 /// ```no_run
1620 /// #![feature(seek_convenience)]
1621 /// use std::{
1622 /// io::{self, Seek},
1623 /// fs::File,
1624 /// };
1625 ///
1626 /// fn main() -> io::Result<()> {
1627 /// let mut f = File::open("foo.txt")?;
1628 ///
1629 /// let len = f.stream_len()?;
1630 /// println!("The file is currently {} bytes long", len);
1631 /// Ok(())
1632 /// }
1633 /// ```
1634 #[unstable(feature = "seek_convenience", issue = "59359")]
1635 fn stream_len(&mut self) -> Result<u64> {
1636 let old_pos = self.stream_position()?;
1637 let len = self.seek(SeekFrom::End(0))?;
1638
1639 // Avoid seeking a third time when we were already at the end of the
1640 // stream. The branch is usually way cheaper than a seek operation.
1641 if old_pos != len {
1642 self.seek(SeekFrom::Start(old_pos))?;
1643 }
1644
1645 Ok(len)
1646 }
1647
1648 /// Returns the current seek position from the start of the stream.
1649 ///
1650 /// This is equivalent to `self.seek(SeekFrom::Current(0))`.
1651 ///
1652 /// # Example
1653 ///
1654 /// ```no_run
1655 /// #![feature(seek_convenience)]
1656 /// use std::{
1657 /// io::{self, BufRead, BufReader, Seek},
1658 /// fs::File,
1659 /// };
1660 ///
1661 /// fn main() -> io::Result<()> {
1662 /// let mut f = BufReader::new(File::open("foo.txt")?);
1663 ///
1664 /// let before = f.stream_position()?;
1665 /// f.read_line(&mut String::new())?;
1666 /// let after = f.stream_position()?;
1667 ///
1668 /// println!("The first line was {} bytes long", after - before);
1669 /// Ok(())
1670 /// }
1671 /// ```
1672 #[unstable(feature = "seek_convenience", issue = "59359")]
1673 fn stream_position(&mut self) -> Result<u64> {
1674 self.seek(SeekFrom::Current(0))
1675 }
1676 }
1677
1678 /// Enumeration of possible methods to seek within an I/O object.
1679 ///
1680 /// It is used by the [`Seek`] trait.
1681 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1682 #[stable(feature = "rust1", since = "1.0.0")]
1683 pub enum SeekFrom {
1684 /// Sets the offset to the provided number of bytes.
1685 #[stable(feature = "rust1", since = "1.0.0")]
1686 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1687
1688 /// Sets the offset to the size of this object plus the specified number of
1689 /// bytes.
1690 ///
1691 /// It is possible to seek beyond the end of an object, but it's an error to
1692 /// seek before byte 0.
1693 #[stable(feature = "rust1", since = "1.0.0")]
1694 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1695
1696 /// Sets the offset to the current position plus the specified number of
1697 /// bytes.
1698 ///
1699 /// It is possible to seek beyond the end of an object, but it's an error to
1700 /// seek before byte 0.
1701 #[stable(feature = "rust1", since = "1.0.0")]
1702 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1703 }
1704
1705 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>) -> Result<usize> {
1706 let mut read = 0;
1707 loop {
1708 let (done, used) = {
1709 let available = match r.fill_buf() {
1710 Ok(n) => n,
1711 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1712 Err(e) => return Err(e),
1713 };
1714 match memchr::memchr(delim, available) {
1715 Some(i) => {
1716 buf.extend_from_slice(&available[..=i]);
1717 (true, i + 1)
1718 }
1719 None => {
1720 buf.extend_from_slice(available);
1721 (false, available.len())
1722 }
1723 }
1724 };
1725 r.consume(used);
1726 read += used;
1727 if done || used == 0 {
1728 return Ok(read);
1729 }
1730 }
1731 }
1732
1733 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1734 /// to perform extra ways of reading.
1735 ///
1736 /// For example, reading line-by-line is inefficient without using a buffer, so
1737 /// if you want to read by line, you'll need `BufRead`, which includes a
1738 /// [`read_line`] method as well as a [`lines`] iterator.
1739 ///
1740 /// # Examples
1741 ///
1742 /// A locked standard input implements `BufRead`:
1743 ///
1744 /// ```no_run
1745 /// use std::io;
1746 /// use std::io::prelude::*;
1747 ///
1748 /// let stdin = io::stdin();
1749 /// for line in stdin.lock().lines() {
1750 /// println!("{}", line.unwrap());
1751 /// }
1752 /// ```
1753 ///
1754 /// If you have something that implements [`Read`], you can use the [`BufReader`
1755 /// type][`BufReader`] to turn it into a `BufRead`.
1756 ///
1757 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1758 /// [`BufReader`] to the rescue!
1759 ///
1760 /// [`File`]: crate::fs::File
1761 /// [`read_line`]: BufRead::read_line
1762 /// [`lines`]: BufRead::lines
1763 ///
1764 /// ```no_run
1765 /// use std::io::{self, BufReader};
1766 /// use std::io::prelude::*;
1767 /// use std::fs::File;
1768 ///
1769 /// fn main() -> io::Result<()> {
1770 /// let f = File::open("foo.txt")?;
1771 /// let f = BufReader::new(f);
1772 ///
1773 /// for line in f.lines() {
1774 /// println!("{}", line.unwrap());
1775 /// }
1776 ///
1777 /// Ok(())
1778 /// }
1779 /// ```
1780 #[stable(feature = "rust1", since = "1.0.0")]
1781 pub trait BufRead: Read {
1782 /// Returns the contents of the internal buffer, filling it with more data
1783 /// from the inner reader if it is empty.
1784 ///
1785 /// This function is a lower-level call. It needs to be paired with the
1786 /// [`consume`] method to function properly. When calling this
1787 /// method, none of the contents will be "read" in the sense that later
1788 /// calling `read` may return the same contents. As such, [`consume`] must
1789 /// be called with the number of bytes that are consumed from this buffer to
1790 /// ensure that the bytes are never returned twice.
1791 ///
1792 /// [`consume`]: BufRead::consume
1793 ///
1794 /// An empty buffer returned indicates that the stream has reached EOF.
1795 ///
1796 /// # Errors
1797 ///
1798 /// This function will return an I/O error if the underlying reader was
1799 /// read, but returned an error.
1800 ///
1801 /// # Examples
1802 ///
1803 /// A locked standard input implements `BufRead`:
1804 ///
1805 /// ```no_run
1806 /// use std::io;
1807 /// use std::io::prelude::*;
1808 ///
1809 /// let stdin = io::stdin();
1810 /// let mut stdin = stdin.lock();
1811 ///
1812 /// let buffer = stdin.fill_buf().unwrap();
1813 ///
1814 /// // work with buffer
1815 /// println!("{:?}", buffer);
1816 ///
1817 /// // ensure the bytes we worked with aren't returned again later
1818 /// let length = buffer.len();
1819 /// stdin.consume(length);
1820 /// ```
1821 #[stable(feature = "rust1", since = "1.0.0")]
1822 fn fill_buf(&mut self) -> Result<&[u8]>;
1823
1824 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1825 /// so they should no longer be returned in calls to `read`.
1826 ///
1827 /// This function is a lower-level call. It needs to be paired with the
1828 /// [`fill_buf`] method to function properly. This function does
1829 /// not perform any I/O, it simply informs this object that some amount of
1830 /// its buffer, returned from [`fill_buf`], has been consumed and should
1831 /// no longer be returned. As such, this function may do odd things if
1832 /// [`fill_buf`] isn't called before calling it.
1833 ///
1834 /// The `amt` must be `<=` the number of bytes in the buffer returned by
1835 /// [`fill_buf`].
1836 ///
1837 /// # Examples
1838 ///
1839 /// Since `consume()` is meant to be used with [`fill_buf`],
1840 /// that method's example includes an example of `consume()`.
1841 ///
1842 /// [`fill_buf`]: BufRead::fill_buf
1843 #[stable(feature = "rust1", since = "1.0.0")]
1844 fn consume(&mut self, amt: usize);
1845
1846 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
1847 ///
1848 /// This function will read bytes from the underlying stream until the
1849 /// delimiter or EOF is found. Once found, all bytes up to, and including,
1850 /// the delimiter (if found) will be appended to `buf`.
1851 ///
1852 /// If successful, this function will return the total number of bytes read.
1853 ///
1854 /// This function is blocking and should be used carefully: it is possible for
1855 /// an attacker to continuously send bytes without ever sending the delimiter
1856 /// or EOF.
1857 ///
1858 /// # Errors
1859 ///
1860 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1861 /// will otherwise return any errors returned by [`fill_buf`].
1862 ///
1863 /// If an I/O error is encountered then all bytes read so far will be
1864 /// present in `buf` and its length will have been adjusted appropriately.
1865 ///
1866 /// [`fill_buf`]: BufRead::fill_buf
1867 ///
1868 /// # Examples
1869 ///
1870 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1871 /// this example, we use [`Cursor`] to read all the bytes in a byte slice
1872 /// in hyphen delimited segments:
1873 ///
1874 /// ```
1875 /// use std::io::{self, BufRead};
1876 ///
1877 /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
1878 /// let mut buf = vec![];
1879 ///
1880 /// // cursor is at 'l'
1881 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1882 /// .expect("reading from cursor won't fail");
1883 /// assert_eq!(num_bytes, 6);
1884 /// assert_eq!(buf, b"lorem-");
1885 /// buf.clear();
1886 ///
1887 /// // cursor is at 'i'
1888 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1889 /// .expect("reading from cursor won't fail");
1890 /// assert_eq!(num_bytes, 5);
1891 /// assert_eq!(buf, b"ipsum");
1892 /// buf.clear();
1893 ///
1894 /// // cursor is at EOF
1895 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1896 /// .expect("reading from cursor won't fail");
1897 /// assert_eq!(num_bytes, 0);
1898 /// assert_eq!(buf, b"");
1899 /// ```
1900 #[stable(feature = "rust1", since = "1.0.0")]
1901 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
1902 read_until(self, byte, buf)
1903 }
1904
1905 /// Read all bytes until a newline (the `0xA` byte) is reached, and append
1906 /// them to the provided buffer.
1907 ///
1908 /// This function will read bytes from the underlying stream until the
1909 /// newline delimiter (the `0xA` byte) or EOF is found. Once found, all bytes
1910 /// up to, and including, the delimiter (if found) will be appended to
1911 /// `buf`.
1912 ///
1913 /// If successful, this function will return the total number of bytes read.
1914 ///
1915 /// If this function returns [`Ok(0)`], the stream has reached EOF.
1916 ///
1917 /// This function is blocking and should be used carefully: it is possible for
1918 /// an attacker to continuously send bytes without ever sending a newline
1919 /// or EOF.
1920 ///
1921 /// [`Ok(0)`]: Ok
1922 ///
1923 /// # Errors
1924 ///
1925 /// This function has the same error semantics as [`read_until`] and will
1926 /// also return an error if the read bytes are not valid UTF-8. If an I/O
1927 /// error is encountered then `buf` may contain some bytes already read in
1928 /// the event that all data read so far was valid UTF-8.
1929 ///
1930 /// [`read_until`]: BufRead::read_until
1931 ///
1932 /// # Examples
1933 ///
1934 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1935 /// this example, we use [`Cursor`] to read all the lines in a byte slice:
1936 ///
1937 /// ```
1938 /// use std::io::{self, BufRead};
1939 ///
1940 /// let mut cursor = io::Cursor::new(b"foo\nbar");
1941 /// let mut buf = String::new();
1942 ///
1943 /// // cursor is at 'f'
1944 /// let num_bytes = cursor.read_line(&mut buf)
1945 /// .expect("reading from cursor won't fail");
1946 /// assert_eq!(num_bytes, 4);
1947 /// assert_eq!(buf, "foo\n");
1948 /// buf.clear();
1949 ///
1950 /// // cursor is at 'b'
1951 /// let num_bytes = cursor.read_line(&mut buf)
1952 /// .expect("reading from cursor won't fail");
1953 /// assert_eq!(num_bytes, 3);
1954 /// assert_eq!(buf, "bar");
1955 /// buf.clear();
1956 ///
1957 /// // cursor is at EOF
1958 /// let num_bytes = cursor.read_line(&mut buf)
1959 /// .expect("reading from cursor won't fail");
1960 /// assert_eq!(num_bytes, 0);
1961 /// assert_eq!(buf, "");
1962 /// ```
1963 #[stable(feature = "rust1", since = "1.0.0")]
1964 fn read_line(&mut self, buf: &mut String) -> Result<usize> {
1965 // Note that we are not calling the `.read_until` method here, but
1966 // rather our hardcoded implementation. For more details as to why, see
1967 // the comments in `read_to_end`.
1968 append_to_string(buf, |b| read_until(self, b'\n', b))
1969 }
1970
1971 /// Returns an iterator over the contents of this reader split on the byte
1972 /// `byte`.
1973 ///
1974 /// The iterator returned from this function will return instances of
1975 /// [`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
1976 /// the delimiter byte at the end.
1977 ///
1978 /// This function will yield errors whenever [`read_until`] would have
1979 /// also yielded an error.
1980 ///
1981 /// [`io::Result`]: self::Result
1982 /// [`Vec<u8>`]: Vec
1983 /// [`read_until`]: BufRead::read_until
1984 ///
1985 /// # Examples
1986 ///
1987 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1988 /// this example, we use [`Cursor`] to iterate over all hyphen delimited
1989 /// segments in a byte slice
1990 ///
1991 /// ```
1992 /// use std::io::{self, BufRead};
1993 ///
1994 /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
1995 ///
1996 /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
1997 /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
1998 /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
1999 /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
2000 /// assert_eq!(split_iter.next(), None);
2001 /// ```
2002 #[stable(feature = "rust1", since = "1.0.0")]
2003 fn split(self, byte: u8) -> Split<Self>
2004 where
2005 Self: Sized,
2006 {
2007 Split { buf: self, delim: byte }
2008 }
2009
2010 /// Returns an iterator over the lines of this reader.
2011 ///
2012 /// The iterator returned from this function will yield instances of
2013 /// [`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline
2014 /// byte (the `0xA` byte) or `CRLF` (`0xD`, `0xA` bytes) at the end.
2015 ///
2016 /// [`io::Result`]: self::Result
2017 ///
2018 /// # Examples
2019 ///
2020 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2021 /// this example, we use [`Cursor`] to iterate over all the lines in a byte
2022 /// slice.
2023 ///
2024 /// ```
2025 /// use std::io::{self, BufRead};
2026 ///
2027 /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
2028 ///
2029 /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
2030 /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
2031 /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
2032 /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
2033 /// assert_eq!(lines_iter.next(), None);
2034 /// ```
2035 ///
2036 /// # Errors
2037 ///
2038 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
2039 #[stable(feature = "rust1", since = "1.0.0")]
2040 fn lines(self) -> Lines<Self>
2041 where
2042 Self: Sized,
2043 {
2044 Lines { buf: self }
2045 }
2046 }
2047
2048 /// Adaptor to chain together two readers.
2049 ///
2050 /// This struct is generally created by calling [`chain`] on a reader.
2051 /// Please see the documentation of [`chain`] for more details.
2052 ///
2053 /// [`chain`]: Read::chain
2054 #[stable(feature = "rust1", since = "1.0.0")]
2055 pub struct Chain<T, U> {
2056 first: T,
2057 second: U,
2058 done_first: bool,
2059 }
2060
2061 impl<T, U> Chain<T, U> {
2062 /// Consumes the `Chain`, returning the wrapped readers.
2063 ///
2064 /// # Examples
2065 ///
2066 /// ```no_run
2067 /// use std::io;
2068 /// use std::io::prelude::*;
2069 /// use std::fs::File;
2070 ///
2071 /// fn main() -> io::Result<()> {
2072 /// let mut foo_file = File::open("foo.txt")?;
2073 /// let mut bar_file = File::open("bar.txt")?;
2074 ///
2075 /// let chain = foo_file.chain(bar_file);
2076 /// let (foo_file, bar_file) = chain.into_inner();
2077 /// Ok(())
2078 /// }
2079 /// ```
2080 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2081 pub fn into_inner(self) -> (T, U) {
2082 (self.first, self.second)
2083 }
2084
2085 /// Gets references to the underlying readers in this `Chain`.
2086 ///
2087 /// # Examples
2088 ///
2089 /// ```no_run
2090 /// use std::io;
2091 /// use std::io::prelude::*;
2092 /// use std::fs::File;
2093 ///
2094 /// fn main() -> io::Result<()> {
2095 /// let mut foo_file = File::open("foo.txt")?;
2096 /// let mut bar_file = File::open("bar.txt")?;
2097 ///
2098 /// let chain = foo_file.chain(bar_file);
2099 /// let (foo_file, bar_file) = chain.get_ref();
2100 /// Ok(())
2101 /// }
2102 /// ```
2103 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2104 pub fn get_ref(&self) -> (&T, &U) {
2105 (&self.first, &self.second)
2106 }
2107
2108 /// Gets mutable references to the underlying readers in this `Chain`.
2109 ///
2110 /// Care should be taken to avoid modifying the internal I/O state of the
2111 /// underlying readers as doing so may corrupt the internal state of this
2112 /// `Chain`.
2113 ///
2114 /// # Examples
2115 ///
2116 /// ```no_run
2117 /// use std::io;
2118 /// use std::io::prelude::*;
2119 /// use std::fs::File;
2120 ///
2121 /// fn main() -> io::Result<()> {
2122 /// let mut foo_file = File::open("foo.txt")?;
2123 /// let mut bar_file = File::open("bar.txt")?;
2124 ///
2125 /// let mut chain = foo_file.chain(bar_file);
2126 /// let (foo_file, bar_file) = chain.get_mut();
2127 /// Ok(())
2128 /// }
2129 /// ```
2130 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2131 pub fn get_mut(&mut self) -> (&mut T, &mut U) {
2132 (&mut self.first, &mut self.second)
2133 }
2134 }
2135
2136 #[stable(feature = "std_debug", since = "1.16.0")]
2137 impl<T: fmt::Debug, U: fmt::Debug> fmt::Debug for Chain<T, U> {
2138 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2139 f.debug_struct("Chain").field("t", &self.first).field("u", &self.second).finish()
2140 }
2141 }
2142
2143 #[stable(feature = "rust1", since = "1.0.0")]
2144 impl<T: Read, U: Read> Read for Chain<T, U> {
2145 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2146 if !self.done_first {
2147 match self.first.read(buf)? {
2148 0 if !buf.is_empty() => self.done_first = true,
2149 n => return Ok(n),
2150 }
2151 }
2152 self.second.read(buf)
2153 }
2154
2155 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
2156 if !self.done_first {
2157 match self.first.read_vectored(bufs)? {
2158 0 if bufs.iter().any(|b| !b.is_empty()) => self.done_first = true,
2159 n => return Ok(n),
2160 }
2161 }
2162 self.second.read_vectored(bufs)
2163 }
2164
2165 unsafe fn initializer(&self) -> Initializer {
2166 let initializer = self.first.initializer();
2167 if initializer.should_initialize() { initializer } else { self.second.initializer() }
2168 }
2169 }
2170
2171 #[stable(feature = "chain_bufread", since = "1.9.0")]
2172 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
2173 fn fill_buf(&mut self) -> Result<&[u8]> {
2174 if !self.done_first {
2175 match self.first.fill_buf()? {
2176 buf if buf.is_empty() => {
2177 self.done_first = true;
2178 }
2179 buf => return Ok(buf),
2180 }
2181 }
2182 self.second.fill_buf()
2183 }
2184
2185 fn consume(&mut self, amt: usize) {
2186 if !self.done_first { self.first.consume(amt) } else { self.second.consume(amt) }
2187 }
2188 }
2189
2190 /// Reader adaptor which limits the bytes read from an underlying reader.
2191 ///
2192 /// This struct is generally created by calling [`take`] on a reader.
2193 /// Please see the documentation of [`take`] for more details.
2194 ///
2195 /// [`take`]: Read::take
2196 #[stable(feature = "rust1", since = "1.0.0")]
2197 #[derive(Debug)]
2198 pub struct Take<T> {
2199 inner: T,
2200 limit: u64,
2201 }
2202
2203 impl<T> Take<T> {
2204 /// Returns the number of bytes that can be read before this instance will
2205 /// return EOF.
2206 ///
2207 /// # Note
2208 ///
2209 /// This instance may reach `EOF` after reading fewer bytes than indicated by
2210 /// this method if the underlying [`Read`] instance reaches EOF.
2211 ///
2212 /// # Examples
2213 ///
2214 /// ```no_run
2215 /// use std::io;
2216 /// use std::io::prelude::*;
2217 /// use std::fs::File;
2218 ///
2219 /// fn main() -> io::Result<()> {
2220 /// let f = File::open("foo.txt")?;
2221 ///
2222 /// // read at most five bytes
2223 /// let handle = f.take(5);
2224 ///
2225 /// println!("limit: {}", handle.limit());
2226 /// Ok(())
2227 /// }
2228 /// ```
2229 #[stable(feature = "rust1", since = "1.0.0")]
2230 pub fn limit(&self) -> u64 {
2231 self.limit
2232 }
2233
2234 /// Sets the number of bytes that can be read before this instance will
2235 /// return EOF. This is the same as constructing a new `Take` instance, so
2236 /// the amount of bytes read and the previous limit value don't matter when
2237 /// calling this method.
2238 ///
2239 /// # Examples
2240 ///
2241 /// ```no_run
2242 /// use std::io;
2243 /// use std::io::prelude::*;
2244 /// use std::fs::File;
2245 ///
2246 /// fn main() -> io::Result<()> {
2247 /// let f = File::open("foo.txt")?;
2248 ///
2249 /// // read at most five bytes
2250 /// let mut handle = f.take(5);
2251 /// handle.set_limit(10);
2252 ///
2253 /// assert_eq!(handle.limit(), 10);
2254 /// Ok(())
2255 /// }
2256 /// ```
2257 #[stable(feature = "take_set_limit", since = "1.27.0")]
2258 pub fn set_limit(&mut self, limit: u64) {
2259 self.limit = limit;
2260 }
2261
2262 /// Consumes the `Take`, returning the wrapped reader.
2263 ///
2264 /// # Examples
2265 ///
2266 /// ```no_run
2267 /// use std::io;
2268 /// use std::io::prelude::*;
2269 /// use std::fs::File;
2270 ///
2271 /// fn main() -> io::Result<()> {
2272 /// let mut file = File::open("foo.txt")?;
2273 ///
2274 /// let mut buffer = [0; 5];
2275 /// let mut handle = file.take(5);
2276 /// handle.read(&mut buffer)?;
2277 ///
2278 /// let file = handle.into_inner();
2279 /// Ok(())
2280 /// }
2281 /// ```
2282 #[stable(feature = "io_take_into_inner", since = "1.15.0")]
2283 pub fn into_inner(self) -> T {
2284 self.inner
2285 }
2286
2287 /// Gets a reference to the underlying reader.
2288 ///
2289 /// # Examples
2290 ///
2291 /// ```no_run
2292 /// use std::io;
2293 /// use std::io::prelude::*;
2294 /// use std::fs::File;
2295 ///
2296 /// fn main() -> io::Result<()> {
2297 /// let mut file = File::open("foo.txt")?;
2298 ///
2299 /// let mut buffer = [0; 5];
2300 /// let mut handle = file.take(5);
2301 /// handle.read(&mut buffer)?;
2302 ///
2303 /// let file = handle.get_ref();
2304 /// Ok(())
2305 /// }
2306 /// ```
2307 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2308 pub fn get_ref(&self) -> &T {
2309 &self.inner
2310 }
2311
2312 /// Gets a mutable reference to the underlying reader.
2313 ///
2314 /// Care should be taken to avoid modifying the internal I/O state of the
2315 /// underlying reader as doing so may corrupt the internal limit of this
2316 /// `Take`.
2317 ///
2318 /// # Examples
2319 ///
2320 /// ```no_run
2321 /// use std::io;
2322 /// use std::io::prelude::*;
2323 /// use std::fs::File;
2324 ///
2325 /// fn main() -> io::Result<()> {
2326 /// let mut file = File::open("foo.txt")?;
2327 ///
2328 /// let mut buffer = [0; 5];
2329 /// let mut handle = file.take(5);
2330 /// handle.read(&mut buffer)?;
2331 ///
2332 /// let file = handle.get_mut();
2333 /// Ok(())
2334 /// }
2335 /// ```
2336 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2337 pub fn get_mut(&mut self) -> &mut T {
2338 &mut self.inner
2339 }
2340 }
2341
2342 #[stable(feature = "rust1", since = "1.0.0")]
2343 impl<T: Read> Read for Take<T> {
2344 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2345 // Don't call into inner reader at all at EOF because it may still block
2346 if self.limit == 0 {
2347 return Ok(0);
2348 }
2349
2350 let max = cmp::min(buf.len() as u64, self.limit) as usize;
2351 let n = self.inner.read(&mut buf[..max])?;
2352 self.limit -= n as u64;
2353 Ok(n)
2354 }
2355
2356 unsafe fn initializer(&self) -> Initializer {
2357 self.inner.initializer()
2358 }
2359
2360 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
2361 // Pass in a reservation_size closure that respects the current value
2362 // of limit for each read. If we hit the read limit, this prevents the
2363 // final zero-byte read from allocating again.
2364 read_to_end_with_reservation(self, buf, |self_| cmp::min(self_.limit, 32) as usize)
2365 }
2366 }
2367
2368 #[stable(feature = "rust1", since = "1.0.0")]
2369 impl<T: BufRead> BufRead for Take<T> {
2370 fn fill_buf(&mut self) -> Result<&[u8]> {
2371 // Don't call into inner reader at all at EOF because it may still block
2372 if self.limit == 0 {
2373 return Ok(&[]);
2374 }
2375
2376 let buf = self.inner.fill_buf()?;
2377 let cap = cmp::min(buf.len() as u64, self.limit) as usize;
2378 Ok(&buf[..cap])
2379 }
2380
2381 fn consume(&mut self, amt: usize) {
2382 // Don't let callers reset the limit by passing an overlarge value
2383 let amt = cmp::min(amt as u64, self.limit) as usize;
2384 self.limit -= amt as u64;
2385 self.inner.consume(amt);
2386 }
2387 }
2388
2389 /// An iterator over `u8` values of a reader.
2390 ///
2391 /// This struct is generally created by calling [`bytes`] on a reader.
2392 /// Please see the documentation of [`bytes`] for more details.
2393 ///
2394 /// [`bytes`]: Read::bytes
2395 #[stable(feature = "rust1", since = "1.0.0")]
2396 #[derive(Debug)]
2397 pub struct Bytes<R> {
2398 inner: R,
2399 }
2400
2401 #[stable(feature = "rust1", since = "1.0.0")]
2402 impl<R: Read> Iterator for Bytes<R> {
2403 type Item = Result<u8>;
2404
2405 fn next(&mut self) -> Option<Result<u8>> {
2406 let mut byte = 0;
2407 loop {
2408 return match self.inner.read(slice::from_mut(&mut byte)) {
2409 Ok(0) => None,
2410 Ok(..) => Some(Ok(byte)),
2411 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
2412 Err(e) => Some(Err(e)),
2413 };
2414 }
2415 }
2416 }
2417
2418 /// An iterator over the contents of an instance of `BufRead` split on a
2419 /// particular byte.
2420 ///
2421 /// This struct is generally created by calling [`split`] on a `BufRead`.
2422 /// Please see the documentation of [`split`] for more details.
2423 ///
2424 /// [`split`]: BufRead::split
2425 #[stable(feature = "rust1", since = "1.0.0")]
2426 #[derive(Debug)]
2427 pub struct Split<B> {
2428 buf: B,
2429 delim: u8,
2430 }
2431
2432 #[stable(feature = "rust1", since = "1.0.0")]
2433 impl<B: BufRead> Iterator for Split<B> {
2434 type Item = Result<Vec<u8>>;
2435
2436 fn next(&mut self) -> Option<Result<Vec<u8>>> {
2437 let mut buf = Vec::new();
2438 match self.buf.read_until(self.delim, &mut buf) {
2439 Ok(0) => None,
2440 Ok(_n) => {
2441 if buf[buf.len() - 1] == self.delim {
2442 buf.pop();
2443 }
2444 Some(Ok(buf))
2445 }
2446 Err(e) => Some(Err(e)),
2447 }
2448 }
2449 }
2450
2451 /// An iterator over the lines of an instance of `BufRead`.
2452 ///
2453 /// This struct is generally created by calling [`lines`] on a `BufRead`.
2454 /// Please see the documentation of [`lines`] for more details.
2455 ///
2456 /// [`lines`]: BufRead::lines
2457 #[stable(feature = "rust1", since = "1.0.0")]
2458 #[derive(Debug)]
2459 pub struct Lines<B> {
2460 buf: B,
2461 }
2462
2463 #[stable(feature = "rust1", since = "1.0.0")]
2464 impl<B: BufRead> Iterator for Lines<B> {
2465 type Item = Result<String>;
2466
2467 fn next(&mut self) -> Option<Result<String>> {
2468 let mut buf = String::new();
2469 match self.buf.read_line(&mut buf) {
2470 Ok(0) => None,
2471 Ok(_n) => {
2472 if buf.ends_with('\n') {
2473 buf.pop();
2474 if buf.ends_with('\r') {
2475 buf.pop();
2476 }
2477 }
2478 Some(Ok(buf))
2479 }
2480 Err(e) => Some(Err(e)),
2481 }
2482 }
2483 }
2484
2485 #[cfg(test)]
2486 mod tests {
2487 use super::{repeat, Cursor, SeekFrom};
2488 use crate::cmp::{self, min};
2489 use crate::io::prelude::*;
2490 use crate::io::{self, IoSlice, IoSliceMut};
2491 use crate::ops::Deref;
2492
2493 #[test]
2494 #[cfg_attr(target_os = "emscripten", ignore)]
2495 fn read_until() {
2496 let mut buf = Cursor::new(&b"12"[..]);
2497 let mut v = Vec::new();
2498 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 2);
2499 assert_eq!(v, b"12");
2500
2501 let mut buf = Cursor::new(&b"1233"[..]);
2502 let mut v = Vec::new();
2503 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 3);
2504 assert_eq!(v, b"123");
2505 v.truncate(0);
2506 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 1);
2507 assert_eq!(v, b"3");
2508 v.truncate(0);
2509 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 0);
2510 assert_eq!(v, []);
2511 }
2512
2513 #[test]
2514 fn split() {
2515 let buf = Cursor::new(&b"12"[..]);
2516 let mut s = buf.split(b'3');
2517 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2518 assert!(s.next().is_none());
2519
2520 let buf = Cursor::new(&b"1233"[..]);
2521 let mut s = buf.split(b'3');
2522 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2523 assert_eq!(s.next().unwrap().unwrap(), vec![]);
2524 assert!(s.next().is_none());
2525 }
2526
2527 #[test]
2528 fn read_line() {
2529 let mut buf = Cursor::new(&b"12"[..]);
2530 let mut v = String::new();
2531 assert_eq!(buf.read_line(&mut v).unwrap(), 2);
2532 assert_eq!(v, "12");
2533
2534 let mut buf = Cursor::new(&b"12\n\n"[..]);
2535 let mut v = String::new();
2536 assert_eq!(buf.read_line(&mut v).unwrap(), 3);
2537 assert_eq!(v, "12\n");
2538 v.truncate(0);
2539 assert_eq!(buf.read_line(&mut v).unwrap(), 1);
2540 assert_eq!(v, "\n");
2541 v.truncate(0);
2542 assert_eq!(buf.read_line(&mut v).unwrap(), 0);
2543 assert_eq!(v, "");
2544 }
2545
2546 #[test]
2547 fn lines() {
2548 let buf = Cursor::new(&b"12\r"[..]);
2549 let mut s = buf.lines();
2550 assert_eq!(s.next().unwrap().unwrap(), "12\r".to_string());
2551 assert!(s.next().is_none());
2552
2553 let buf = Cursor::new(&b"12\r\n\n"[..]);
2554 let mut s = buf.lines();
2555 assert_eq!(s.next().unwrap().unwrap(), "12".to_string());
2556 assert_eq!(s.next().unwrap().unwrap(), "".to_string());
2557 assert!(s.next().is_none());
2558 }
2559
2560 #[test]
2561 fn read_to_end() {
2562 let mut c = Cursor::new(&b""[..]);
2563 let mut v = Vec::new();
2564 assert_eq!(c.read_to_end(&mut v).unwrap(), 0);
2565 assert_eq!(v, []);
2566
2567 let mut c = Cursor::new(&b"1"[..]);
2568 let mut v = Vec::new();
2569 assert_eq!(c.read_to_end(&mut v).unwrap(), 1);
2570 assert_eq!(v, b"1");
2571
2572 let cap = 1024 * 1024;
2573 let data = (0..cap).map(|i| (i / 3) as u8).collect::<Vec<_>>();
2574 let mut v = Vec::new();
2575 let (a, b) = data.split_at(data.len() / 2);
2576 assert_eq!(Cursor::new(a).read_to_end(&mut v).unwrap(), a.len());
2577 assert_eq!(Cursor::new(b).read_to_end(&mut v).unwrap(), b.len());
2578 assert_eq!(v, data);
2579 }
2580
2581 #[test]
2582 fn read_to_string() {
2583 let mut c = Cursor::new(&b""[..]);
2584 let mut v = String::new();
2585 assert_eq!(c.read_to_string(&mut v).unwrap(), 0);
2586 assert_eq!(v, "");
2587
2588 let mut c = Cursor::new(&b"1"[..]);
2589 let mut v = String::new();
2590 assert_eq!(c.read_to_string(&mut v).unwrap(), 1);
2591 assert_eq!(v, "1");
2592
2593 let mut c = Cursor::new(&b"\xff"[..]);
2594 let mut v = String::new();
2595 assert!(c.read_to_string(&mut v).is_err());
2596 }
2597
2598 #[test]
2599 fn read_exact() {
2600 let mut buf = [0; 4];
2601
2602 let mut c = Cursor::new(&b""[..]);
2603 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
2604
2605 let mut c = Cursor::new(&b"123"[..]).chain(Cursor::new(&b"456789"[..]));
2606 c.read_exact(&mut buf).unwrap();
2607 assert_eq!(&buf, b"1234");
2608 c.read_exact(&mut buf).unwrap();
2609 assert_eq!(&buf, b"5678");
2610 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
2611 }
2612
2613 #[test]
2614 fn read_exact_slice() {
2615 let mut buf = [0; 4];
2616
2617 let mut c = &b""[..];
2618 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
2619
2620 let mut c = &b"123"[..];
2621 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
2622 // make sure the optimized (early returning) method is being used
2623 assert_eq!(&buf, &[0; 4]);
2624
2625 let mut c = &b"1234"[..];
2626 c.read_exact(&mut buf).unwrap();
2627 assert_eq!(&buf, b"1234");
2628
2629 let mut c = &b"56789"[..];
2630 c.read_exact(&mut buf).unwrap();
2631 assert_eq!(&buf, b"5678");
2632 assert_eq!(c, b"9");
2633 }
2634
2635 #[test]
2636 fn take_eof() {
2637 struct R;
2638
2639 impl Read for R {
2640 fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
2641 Err(io::Error::new(io::ErrorKind::Other, ""))
2642 }
2643 }
2644 impl BufRead for R {
2645 fn fill_buf(&mut self) -> io::Result<&[u8]> {
2646 Err(io::Error::new(io::ErrorKind::Other, ""))
2647 }
2648 fn consume(&mut self, _amt: usize) {}
2649 }
2650
2651 let mut buf = [0; 1];
2652 assert_eq!(0, R.take(0).read(&mut buf).unwrap());
2653 assert_eq!(b"", R.take(0).fill_buf().unwrap());
2654 }
2655
2656 fn cmp_bufread<Br1: BufRead, Br2: BufRead>(mut br1: Br1, mut br2: Br2, exp: &[u8]) {
2657 let mut cat = Vec::new();
2658 loop {
2659 let consume = {
2660 let buf1 = br1.fill_buf().unwrap();
2661 let buf2 = br2.fill_buf().unwrap();
2662 let minlen = if buf1.len() < buf2.len() { buf1.len() } else { buf2.len() };
2663 assert_eq!(buf1[..minlen], buf2[..minlen]);
2664 cat.extend_from_slice(&buf1[..minlen]);
2665 minlen
2666 };
2667 if consume == 0 {
2668 break;
2669 }
2670 br1.consume(consume);
2671 br2.consume(consume);
2672 }
2673 assert_eq!(br1.fill_buf().unwrap().len(), 0);
2674 assert_eq!(br2.fill_buf().unwrap().len(), 0);
2675 assert_eq!(&cat[..], &exp[..])
2676 }
2677
2678 #[test]
2679 fn chain_bufread() {
2680 let testdata = b"ABCDEFGHIJKL";
2681 let chain1 =
2682 (&testdata[..3]).chain(&testdata[3..6]).chain(&testdata[6..9]).chain(&testdata[9..]);
2683 let chain2 = (&testdata[..4]).chain(&testdata[4..8]).chain(&testdata[8..]);
2684 cmp_bufread(chain1, chain2, &testdata[..]);
2685 }
2686
2687 #[test]
2688 fn chain_zero_length_read_is_not_eof() {
2689 let a = b"A";
2690 let b = b"B";
2691 let mut s = String::new();
2692 let mut chain = (&a[..]).chain(&b[..]);
2693 chain.read(&mut []).unwrap();
2694 chain.read_to_string(&mut s).unwrap();
2695 assert_eq!("AB", s);
2696 }
2697
2698 #[bench]
2699 #[cfg_attr(target_os = "emscripten", ignore)]
2700 fn bench_read_to_end(b: &mut test::Bencher) {
2701 b.iter(|| {
2702 let mut lr = repeat(1).take(10000000);
2703 let mut vec = Vec::with_capacity(1024);
2704 super::read_to_end(&mut lr, &mut vec)
2705 });
2706 }
2707
2708 #[test]
2709 fn seek_len() -> io::Result<()> {
2710 let mut c = Cursor::new(vec![0; 15]);
2711 assert_eq!(c.stream_len()?, 15);
2712
2713 c.seek(SeekFrom::End(0))?;
2714 let old_pos = c.stream_position()?;
2715 assert_eq!(c.stream_len()?, 15);
2716 assert_eq!(c.stream_position()?, old_pos);
2717
2718 c.seek(SeekFrom::Start(7))?;
2719 c.seek(SeekFrom::Current(2))?;
2720 let old_pos = c.stream_position()?;
2721 assert_eq!(c.stream_len()?, 15);
2722 assert_eq!(c.stream_position()?, old_pos);
2723
2724 Ok(())
2725 }
2726
2727 #[test]
2728 fn seek_position() -> io::Result<()> {
2729 // All `asserts` are duplicated here to make sure the method does not
2730 // change anything about the seek state.
2731 let mut c = Cursor::new(vec![0; 15]);
2732 assert_eq!(c.stream_position()?, 0);
2733 assert_eq!(c.stream_position()?, 0);
2734
2735 c.seek(SeekFrom::End(0))?;
2736 assert_eq!(c.stream_position()?, 15);
2737 assert_eq!(c.stream_position()?, 15);
2738
2739 c.seek(SeekFrom::Start(7))?;
2740 c.seek(SeekFrom::Current(2))?;
2741 assert_eq!(c.stream_position()?, 9);
2742 assert_eq!(c.stream_position()?, 9);
2743
2744 c.seek(SeekFrom::End(-3))?;
2745 c.seek(SeekFrom::Current(1))?;
2746 c.seek(SeekFrom::Current(-5))?;
2747 assert_eq!(c.stream_position()?, 8);
2748 assert_eq!(c.stream_position()?, 8);
2749
2750 Ok(())
2751 }
2752
2753 // A simple example reader which uses the default implementation of
2754 // read_to_end.
2755 struct ExampleSliceReader<'a> {
2756 slice: &'a [u8],
2757 }
2758
2759 impl<'a> Read for ExampleSliceReader<'a> {
2760 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
2761 let len = cmp::min(self.slice.len(), buf.len());
2762 buf[..len].copy_from_slice(&self.slice[..len]);
2763 self.slice = &self.slice[len..];
2764 Ok(len)
2765 }
2766 }
2767
2768 #[test]
2769 fn test_read_to_end_capacity() -> io::Result<()> {
2770 let input = &b"foo"[..];
2771
2772 // read_to_end() generally needs to over-allocate, both for efficiency
2773 // and so that it can distinguish EOF. Assert that this is the case
2774 // with this simple ExampleSliceReader struct, which uses the default
2775 // implementation of read_to_end. Even though vec1 is allocated with
2776 // exactly enough capacity for the read, read_to_end will allocate more
2777 // space here.
2778 let mut vec1 = Vec::with_capacity(input.len());
2779 ExampleSliceReader { slice: input }.read_to_end(&mut vec1)?;
2780 assert_eq!(vec1.len(), input.len());
2781 assert!(vec1.capacity() > input.len(), "allocated more");
2782
2783 // However, std::io::Take includes an implementation of read_to_end
2784 // that will not allocate when the limit has already been reached. In
2785 // this case, vec2 never grows.
2786 let mut vec2 = Vec::with_capacity(input.len());
2787 ExampleSliceReader { slice: input }.take(input.len() as u64).read_to_end(&mut vec2)?;
2788 assert_eq!(vec2.len(), input.len());
2789 assert_eq!(vec2.capacity(), input.len(), "did not allocate more");
2790
2791 Ok(())
2792 }
2793
2794 #[test]
2795 fn io_slice_mut_advance() {
2796 let mut buf1 = [1; 8];
2797 let mut buf2 = [2; 16];
2798 let mut buf3 = [3; 8];
2799 let mut bufs = &mut [
2800 IoSliceMut::new(&mut buf1),
2801 IoSliceMut::new(&mut buf2),
2802 IoSliceMut::new(&mut buf3),
2803 ][..];
2804
2805 // Only in a single buffer..
2806 bufs = IoSliceMut::advance(bufs, 1);
2807 assert_eq!(bufs[0].deref(), [1; 7].as_ref());
2808 assert_eq!(bufs[1].deref(), [2; 16].as_ref());
2809 assert_eq!(bufs[2].deref(), [3; 8].as_ref());
2810
2811 // Removing a buffer, leaving others as is.
2812 bufs = IoSliceMut::advance(bufs, 7);
2813 assert_eq!(bufs[0].deref(), [2; 16].as_ref());
2814 assert_eq!(bufs[1].deref(), [3; 8].as_ref());
2815
2816 // Removing a buffer and removing from the next buffer.
2817 bufs = IoSliceMut::advance(bufs, 18);
2818 assert_eq!(bufs[0].deref(), [3; 6].as_ref());
2819 }
2820
2821 #[test]
2822 fn io_slice_mut_advance_empty_slice() {
2823 let empty_bufs = &mut [][..];
2824 // Shouldn't panic.
2825 IoSliceMut::advance(empty_bufs, 1);
2826 }
2827
2828 #[test]
2829 fn io_slice_mut_advance_beyond_total_length() {
2830 let mut buf1 = [1; 8];
2831 let mut bufs = &mut [IoSliceMut::new(&mut buf1)][..];
2832
2833 // Going beyond the total length should be ok.
2834 bufs = IoSliceMut::advance(bufs, 9);
2835 assert!(bufs.is_empty());
2836 }
2837
2838 #[test]
2839 fn io_slice_advance() {
2840 let buf1 = [1; 8];
2841 let buf2 = [2; 16];
2842 let buf3 = [3; 8];
2843 let mut bufs = &mut [IoSlice::new(&buf1), IoSlice::new(&buf2), IoSlice::new(&buf3)][..];
2844
2845 // Only in a single buffer..
2846 bufs = IoSlice::advance(bufs, 1);
2847 assert_eq!(bufs[0].deref(), [1; 7].as_ref());
2848 assert_eq!(bufs[1].deref(), [2; 16].as_ref());
2849 assert_eq!(bufs[2].deref(), [3; 8].as_ref());
2850
2851 // Removing a buffer, leaving others as is.
2852 bufs = IoSlice::advance(bufs, 7);
2853 assert_eq!(bufs[0].deref(), [2; 16].as_ref());
2854 assert_eq!(bufs[1].deref(), [3; 8].as_ref());
2855
2856 // Removing a buffer and removing from the next buffer.
2857 bufs = IoSlice::advance(bufs, 18);
2858 assert_eq!(bufs[0].deref(), [3; 6].as_ref());
2859 }
2860
2861 #[test]
2862 fn io_slice_advance_empty_slice() {
2863 let empty_bufs = &mut [][..];
2864 // Shouldn't panic.
2865 IoSlice::advance(empty_bufs, 1);
2866 }
2867
2868 #[test]
2869 fn io_slice_advance_beyond_total_length() {
2870 let buf1 = [1; 8];
2871 let mut bufs = &mut [IoSlice::new(&buf1)][..];
2872
2873 // Going beyond the total length should be ok.
2874 bufs = IoSlice::advance(bufs, 9);
2875 assert!(bufs.is_empty());
2876 }
2877
2878 /// Create a new writer that reads from at most `n_bufs` and reads
2879 /// `per_call` bytes (in total) per call to write.
2880 fn test_writer(n_bufs: usize, per_call: usize) -> TestWriter {
2881 TestWriter { n_bufs, per_call, written: Vec::new() }
2882 }
2883
2884 struct TestWriter {
2885 n_bufs: usize,
2886 per_call: usize,
2887 written: Vec<u8>,
2888 }
2889
2890 impl Write for TestWriter {
2891 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
2892 self.write_vectored(&[IoSlice::new(buf)])
2893 }
2894
2895 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
2896 let mut left = self.per_call;
2897 let mut written = 0;
2898 for buf in bufs.iter().take(self.n_bufs) {
2899 let n = min(left, buf.len());
2900 self.written.extend_from_slice(&buf[0..n]);
2901 left -= n;
2902 written += n;
2903 }
2904 Ok(written)
2905 }
2906
2907 fn flush(&mut self) -> io::Result<()> {
2908 Ok(())
2909 }
2910 }
2911
2912 #[test]
2913 fn test_writer_read_from_one_buf() {
2914 let mut writer = test_writer(1, 2);
2915
2916 assert_eq!(writer.write(&[]).unwrap(), 0);
2917 assert_eq!(writer.write_vectored(&[]).unwrap(), 0);
2918
2919 // Read at most 2 bytes.
2920 assert_eq!(writer.write(&[1, 1, 1]).unwrap(), 2);
2921 let bufs = &[IoSlice::new(&[2, 2, 2])];
2922 assert_eq!(writer.write_vectored(bufs).unwrap(), 2);
2923
2924 // Only read from first buf.
2925 let bufs = &[IoSlice::new(&[3]), IoSlice::new(&[4, 4])];
2926 assert_eq!(writer.write_vectored(bufs).unwrap(), 1);
2927
2928 assert_eq!(writer.written, &[1, 1, 2, 2, 3]);
2929 }
2930
2931 #[test]
2932 fn test_writer_read_from_multiple_bufs() {
2933 let mut writer = test_writer(3, 3);
2934
2935 // Read at most 3 bytes from two buffers.
2936 let bufs = &[IoSlice::new(&[1]), IoSlice::new(&[2, 2, 2])];
2937 assert_eq!(writer.write_vectored(bufs).unwrap(), 3);
2938
2939 // Read at most 3 bytes from three buffers.
2940 let bufs = &[IoSlice::new(&[3]), IoSlice::new(&[4]), IoSlice::new(&[5, 5])];
2941 assert_eq!(writer.write_vectored(bufs).unwrap(), 3);
2942
2943 assert_eq!(writer.written, &[1, 2, 2, 3, 4, 5]);
2944 }
2945
2946 #[test]
2947 fn test_write_all_vectored() {
2948 #[rustfmt::skip] // Becomes unreadable otherwise.
2949 let tests: Vec<(_, &'static [u8])> = vec![
2950 (vec![], &[]),
2951 (vec![IoSlice::new(&[]), IoSlice::new(&[])], &[]),
2952 (vec![IoSlice::new(&[1])], &[1]),
2953 (vec![IoSlice::new(&[1, 2])], &[1, 2]),
2954 (vec![IoSlice::new(&[1, 2, 3])], &[1, 2, 3]),
2955 (vec![IoSlice::new(&[1, 2, 3, 4])], &[1, 2, 3, 4]),
2956 (vec![IoSlice::new(&[1, 2, 3, 4, 5])], &[1, 2, 3, 4, 5]),
2957 (vec![IoSlice::new(&[1]), IoSlice::new(&[2])], &[1, 2]),
2958 (vec![IoSlice::new(&[1]), IoSlice::new(&[2, 2])], &[1, 2, 2]),
2959 (vec![IoSlice::new(&[1, 1]), IoSlice::new(&[2, 2])], &[1, 1, 2, 2]),
2960 (vec![IoSlice::new(&[1, 1]), IoSlice::new(&[2, 2, 2])], &[1, 1, 2, 2, 2]),
2961 (vec![IoSlice::new(&[1, 1]), IoSlice::new(&[2, 2, 2])], &[1, 1, 2, 2, 2]),
2962 (vec![IoSlice::new(&[1, 1, 1]), IoSlice::new(&[2, 2, 2])], &[1, 1, 1, 2, 2, 2]),
2963 (vec![IoSlice::new(&[1, 1, 1]), IoSlice::new(&[2, 2, 2, 2])], &[1, 1, 1, 2, 2, 2, 2]),
2964 (vec![IoSlice::new(&[1, 1, 1, 1]), IoSlice::new(&[2, 2, 2, 2])], &[1, 1, 1, 1, 2, 2, 2, 2]),
2965 (vec![IoSlice::new(&[1]), IoSlice::new(&[2]), IoSlice::new(&[3])], &[1, 2, 3]),
2966 (vec![IoSlice::new(&[1, 1]), IoSlice::new(&[2, 2]), IoSlice::new(&[3, 3])], &[1, 1, 2, 2, 3, 3]),
2967 (vec![IoSlice::new(&[1]), IoSlice::new(&[2, 2]), IoSlice::new(&[3, 3, 3])], &[1, 2, 2, 3, 3, 3]),
2968 (vec![IoSlice::new(&[1, 1, 1]), IoSlice::new(&[2, 2, 2]), IoSlice::new(&[3, 3, 3])], &[1, 1, 1, 2, 2, 2, 3, 3, 3]),
2969 ];
2970
2971 let writer_configs = &[(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)];
2972
2973 for (n_bufs, per_call) in writer_configs.iter().copied() {
2974 for (mut input, wanted) in tests.clone().into_iter() {
2975 let mut writer = test_writer(n_bufs, per_call);
2976 assert!(writer.write_all_vectored(&mut *input).is_ok());
2977 assert_eq!(&*writer.written, &*wanted);
2978 }
2979 }
2980 }
2981 }