alloc/io/read.rs
1use core::cmp;
2use core::mem::{DropGuard, MaybeUninit};
3
4use crate::io::{
5 BorrowedBuf, BorrowedCursor, Bytes, Chain, Error, IoSliceMut, Result, Take, bytes, chain, take,
6};
7use crate::string::String;
8use crate::vec::Vec;
9
10/// The `Read` trait allows for reading bytes from a source.
11///
12/// Implementors of the `Read` trait are called 'readers'.
13///
14/// Readers are defined by one required method, [`read()`]. Each call to [`read()`]
15/// will attempt to pull bytes from this source into a provided buffer. A
16/// number of other methods are implemented in terms of [`read()`], giving
17/// implementors a number of ways to read bytes while only needing to implement
18/// a single method.
19///
20/// Readers are intended to be composable with one another. Many implementors
21/// throughout [`std::io`] take and provide types which implement the `Read`
22/// trait.
23///
24/// Please note that each call to [`read()`] may involve a system call, and
25/// `BufReader`, will be more efficient.
26/// therefore, using something that implements [`BufRead`], such as
27///
28/// [`BufRead`]: crate::io::BufRead
29///
30/// Repeated calls to the reader use the same cursor, so for example
31/// calling `read_to_end` twice on a `File` will only return the file's
32/// contents once. It's recommended to first call `rewind()` in that case.
33///
34/// # Examples
35///
36/// `File`s implement `Read`:
37///
38/// ```no_run
39/// use std::io;
40/// use std::io::prelude::*;
41/// use std::fs::File;
42///
43/// fn main() -> io::Result<()> {
44/// let mut f = File::open("foo.txt")?;
45/// let mut buffer = [0; 10];
46///
47/// // read up to 10 bytes
48/// f.read(&mut buffer)?;
49///
50/// let mut buffer = Vec::new();
51/// // read the whole file
52/// f.read_to_end(&mut buffer)?;
53///
54/// // read into a String, so that you don't need to do the conversion.
55/// let mut buffer = String::new();
56/// f.read_to_string(&mut buffer)?;
57///
58/// // and more! See the other methods for more details.
59/// Ok(())
60/// }
61/// ```
62///
63/// Read from [`&str`] because [`&[u8]`][prim@slice] implements `Read`:
64///
65/// ```no_run
66/// # use std::io;
67/// use std::io::prelude::*;
68///
69/// fn main() -> io::Result<()> {
70/// let mut b = "This string will be read".as_bytes();
71/// let mut buffer = [0; 10];
72///
73/// // read up to 10 bytes
74/// b.read(&mut buffer)?;
75///
76/// // etc... it works exactly as a File does!
77/// Ok(())
78/// }
79/// ```
80///
81/// [`read()`]: Read::read
82/// [`&str`]: prim@str
83/// [`std::io`]: crate::io
84#[stable(feature = "rust1", since = "1.0.0")]
85#[doc(notable_trait)]
86#[cfg_attr(not(test), rustc_diagnostic_item = "IoRead")]
87pub trait Read {
88 /// Pull some bytes from this source into the specified buffer, returning
89 /// how many bytes were read.
90 ///
91 /// This function does not provide any guarantees about whether it blocks
92 /// waiting for data, but if an object needs to block for a read and cannot,
93 /// it will typically signal this via an [`Err`] return value.
94 ///
95 /// If the return value of this method is [`Ok(n)`], then implementations must
96 /// guarantee that `0 <= n <= buf.len()`. A nonzero `n` value indicates
97 /// that the buffer `buf` has been filled in with `n` bytes of data from this
98 /// source. If `n` is `0`, then it can indicate one of two scenarios:
99 ///
100 /// 1. This reader has reached its "end of file" and will likely no longer
101 /// be able to produce bytes. Note that this does not mean that the
102 /// reader will *always* no longer be able to produce bytes. As an example,
103 /// on Linux, this method will call the `recv` syscall for a `TcpStream`,
104 /// where returning zero indicates the connection was shut down correctly. While
105 /// for `File`, it is possible to reach the end of file and get zero as result,
106 /// but if more data is appended to the file, future calls to `read` will return
107 /// more data.
108 /// 2. The buffer specified was 0 bytes in length.
109 ///
110 /// It is not an error if the returned value `n` is smaller than the buffer size,
111 /// even when the reader is not at the end of the stream yet.
112 /// This may happen for example because fewer bytes are actually available right now
113 /// (e. g. being close to end-of-file) or because read() was interrupted by a signal.
114 ///
115 /// As this trait is safe to implement, callers in unsafe code cannot rely on
116 /// `n <= buf.len()` for safety.
117 /// Extra care needs to be taken when `unsafe` functions are used to access the read bytes.
118 /// Callers have to ensure that no unchecked out-of-bounds accesses are possible even if
119 /// `n > buf.len()`.
120 ///
121 /// *Implementations* of this method can make no assumptions about the contents of `buf` when
122 /// this function is called. It is recommended that implementations only write data to `buf`
123 /// instead of reading its contents.
124 ///
125 /// Correspondingly, however, *callers* of this method in unsafe code must not assume
126 /// any guarantees about how the implementation uses `buf`. The trait is safe to implement,
127 /// so it is possible that the code that's supposed to write to the buffer might also read
128 /// from it. It is your responsibility to make sure that `buf` is initialized
129 /// before calling `read`. Calling `read` with an uninitialized `buf` (of the kind one
130 /// obtains via [`MaybeUninit<T>`]) is not safe, and can lead to undefined behavior.
131 ///
132 /// [`MaybeUninit<T>`]: core::mem::MaybeUninit
133 ///
134 /// # Errors
135 ///
136 /// If this function encounters any form of I/O or other error, an error
137 /// variant will be returned. If an error is returned then it must be
138 /// guaranteed that no bytes were read.
139 ///
140 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
141 /// operation should be retried if there is nothing else to do.
142 ///
143 /// # Examples
144 ///
145 /// `File`s implement `Read`:
146 ///
147 /// [`Ok(n)`]: Ok
148 /// [`ErrorKind::Interrupted`]: crate::io::ErrorKind::Interrupted
149 ///
150 /// ```no_run
151 /// use std::io;
152 /// use std::io::prelude::*;
153 /// use std::fs::File;
154 ///
155 /// fn main() -> io::Result<()> {
156 /// let mut f = File::open("foo.txt")?;
157 /// let mut buffer = [0; 10];
158 ///
159 /// // read up to 10 bytes
160 /// let n = f.read(&mut buffer[..])?;
161 ///
162 /// println!("The bytes: {:?}", &buffer[..n]);
163 /// Ok(())
164 /// }
165 /// ```
166 #[stable(feature = "rust1", since = "1.0.0")]
167 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
168
169 /// Like `read`, except that it reads into a slice of buffers.
170 ///
171 /// Data is copied to fill each buffer in order, with the final buffer
172 /// written to possibly being only partially filled. This method must
173 /// behave equivalently to a single call to `read` with concatenated
174 /// buffers.
175 ///
176 /// The default implementation calls `read` with either the first nonempty
177 /// buffer provided, or an empty one if none exists.
178 #[stable(feature = "iovec", since = "1.36.0")]
179 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
180 default_read_vectored(|b| self.read(b), bufs)
181 }
182
183 /// Determines if this `Read`er has an efficient `read_vectored`
184 /// implementation.
185 ///
186 /// If a `Read`er does not override the default `read_vectored`
187 /// implementation, code using it may want to avoid the method all together
188 /// and coalesce writes into a single buffer for higher performance.
189 ///
190 /// The default implementation returns `false`.
191 #[unstable(feature = "can_vector", issue = "69941")]
192 fn is_read_vectored(&self) -> bool {
193 false
194 }
195
196 /// Reads all bytes until EOF in this source, placing them into `buf`.
197 ///
198 /// All bytes read from this source will be appended to the specified buffer
199 /// `buf`. This function will continuously call [`read()`] to append more data to
200 /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of
201 /// non-[`ErrorKind::Interrupted`] kind.
202 ///
203 /// If successful, this function will return the total number of bytes read.
204 ///
205 /// # Errors
206 ///
207 /// If this function encounters an error of the kind
208 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
209 /// will continue.
210 ///
211 /// If any other read error is encountered then this function immediately
212 /// returns. Any bytes which have already been read will be appended to
213 /// `buf`.
214 ///
215 /// # Examples
216 ///
217 /// `File`s implement `Read`:
218 ///
219 /// [`Ok(0)`]: Ok
220 /// [`ErrorKind::Interrupted`]: crate::io::ErrorKind::Interrupted
221 /// [`read()`]: Read::read
222 ///
223 /// ```no_run
224 /// use std::io;
225 /// use std::io::prelude::*;
226 /// use std::fs::File;
227 ///
228 /// fn main() -> io::Result<()> {
229 /// let mut f = File::open("foo.txt")?;
230 /// let mut buffer = Vec::new();
231 ///
232 /// // read the whole file
233 /// f.read_to_end(&mut buffer)?;
234 /// Ok(())
235 /// }
236 /// ```
237 ///
238 /// (See also the `std::fs::read` convenience function for reading from a
239 /// file.)
240 ///
241 /// ## Implementing `read_to_end`
242 ///
243 /// When implementing the `io::Read` trait, it is recommended to allocate
244 /// memory using [`Vec::try_reserve`]. However, this behavior is not guaranteed
245 /// by all implementations, and `read_to_end` may not handle out-of-memory
246 /// situations gracefully.
247 ///
248 /// ```no_run
249 /// # #![expect(dead_code)]
250 /// # use std::io::{self, BufRead};
251 /// # struct Example { example_datasource: io::Empty } impl Example {
252 /// # fn get_some_data_for_the_example(&self) -> &'static [u8] { &[] }
253 /// fn read_to_end(&mut self, dest_vec: &mut Vec<u8>) -> io::Result<usize> {
254 /// let initial_vec_len = dest_vec.len();
255 /// loop {
256 /// let src_buf = self.example_datasource.fill_buf()?;
257 /// if src_buf.is_empty() {
258 /// break;
259 /// }
260 /// dest_vec.try_reserve(src_buf.len())?;
261 /// dest_vec.extend_from_slice(src_buf);
262 ///
263 /// // Any irreversible side effects should happen after `try_reserve` succeeds,
264 /// // to avoid losing data on allocation error.
265 /// let read = src_buf.len();
266 /// self.example_datasource.consume(read);
267 /// }
268 /// Ok(dest_vec.len() - initial_vec_len)
269 /// }
270 /// # }
271 /// ```
272 ///
273 /// # Usage Notes
274 ///
275 /// `read_to_end` attempts to read a source until EOF, but many sources are continuous streams
276 /// that do not send EOF. In these cases, `read_to_end` will block indefinitely. Standard input
277 /// is one such stream which may be finite if piped, but is typically continuous. For example,
278 /// `cat file | my-rust-program` will correctly terminate with an `EOF` upon closure of cat.
279 /// Reading user input or running programs that remain open indefinitely will never terminate
280 /// the stream with `EOF` (e.g. `yes | my-rust-program`).
281 ///
282 /// Using `.lines()` with a `BufReader` or using [`read`] can provide a better solution
283 ///
284 /// [`read`]: Read::read
285 /// [`Vec::try_reserve`]: crate::vec::Vec::try_reserve
286 #[stable(feature = "rust1", since = "1.0.0")]
287 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
288 default_read_to_end(self, buf, None)
289 }
290
291 /// Reads all bytes until EOF in this source, appending them to `buf`.
292 ///
293 /// If successful, this function returns the number of bytes which were read
294 /// and appended to `buf`.
295 ///
296 /// # Errors
297 ///
298 /// If the data in this stream is *not* valid UTF-8 then an error is
299 /// returned and `buf` is unchanged.
300 ///
301 /// See [`read_to_end`] for other error semantics.
302 ///
303 /// [`read_to_end`]: Read::read_to_end
304 ///
305 /// # Examples
306 ///
307 /// `File`s implement `Read`:
308 ///
309 /// ```no_run
310 /// use std::io;
311 /// use std::io::prelude::*;
312 /// use std::fs::File;
313 ///
314 /// fn main() -> io::Result<()> {
315 /// let mut f = File::open("foo.txt")?;
316 /// let mut buffer = String::new();
317 ///
318 /// f.read_to_string(&mut buffer)?;
319 /// Ok(())
320 /// }
321 /// ```
322 ///
323 /// (See also the `std::fs::read_to_string` convenience function for
324 /// reading from a file.)
325 ///
326 /// # Usage Notes
327 ///
328 /// `read_to_string` attempts to read a source until EOF, but many sources are continuous streams
329 /// that do not send EOF. In these cases, `read_to_string` will block indefinitely. Standard input
330 /// is one such stream which may be finite if piped, but is typically continuous. For example,
331 /// `cat file | my-rust-program` will correctly terminate with an `EOF` upon closure of cat.
332 /// Reading user input or running programs that remain open indefinitely will never terminate
333 /// the stream with `EOF` (e.g. `yes | my-rust-program`).
334 ///
335 /// Using `.lines()` with a `BufReader` or using [`read`] can provide a better solution
336 ///
337 /// [`read`]: Read::read
338 #[stable(feature = "rust1", since = "1.0.0")]
339 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
340 default_read_to_string(self, buf, None)
341 }
342
343 /// Reads the exact number of bytes required to fill `buf`.
344 ///
345 /// This function reads as many bytes as necessary to completely fill the
346 /// specified buffer `buf`.
347 ///
348 /// *Implementations* of this method can make no assumptions about the contents of `buf` when
349 /// this function is called. It is recommended that implementations only write data to `buf`
350 /// instead of reading its contents. The documentation on [`read`] has a more detailed
351 /// explanation of this subject.
352 ///
353 /// # Errors
354 ///
355 /// If this function encounters an error of the kind
356 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
357 /// will continue.
358 ///
359 /// If this function encounters an "end of file" before completely filling
360 /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
361 /// The contents of `buf` are unspecified in this case.
362 ///
363 /// If any other read error is encountered then this function immediately
364 /// returns. The contents of `buf` are unspecified in this case.
365 ///
366 /// If this function returns an error, it is unspecified how many bytes it
367 /// has read, but it will never read more than would be necessary to
368 /// completely fill the buffer.
369 ///
370 /// # Examples
371 ///
372 /// `File`s implement `Read`:
373 ///
374 /// [`ErrorKind::Interrupted`]: crate::io::ErrorKind::Interrupted
375 /// [`ErrorKind::UnexpectedEof`]: crate::io::ErrorKind::UnexpectedEof
376 /// [`read`]: Read::read
377 ///
378 /// ```no_run
379 /// use std::io;
380 /// use std::io::prelude::*;
381 /// use std::fs::File;
382 ///
383 /// fn main() -> io::Result<()> {
384 /// let mut f = File::open("foo.txt")?;
385 /// let mut buffer = [0; 10];
386 ///
387 /// // read exactly 10 bytes
388 /// f.read_exact(&mut buffer)?;
389 /// Ok(())
390 /// }
391 /// ```
392 #[stable(feature = "read_exact", since = "1.6.0")]
393 fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
394 default_read_exact(self, buf)
395 }
396
397 /// Pull some bytes from this source into the specified buffer.
398 ///
399 /// This is equivalent to the [`read`](Read::read) method, except that it is passed a [`BorrowedCursor`] rather than `[u8]` to allow use
400 /// with uninitialized buffers. The new data will be appended to any existing contents of `buf`.
401 ///
402 /// The default implementation delegates to `read`.
403 ///
404 /// This method makes it possible to return both data and an error but it is advised against.
405 #[unstable(feature = "read_buf", issue = "78485")]
406 fn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> Result<()> {
407 default_read_buf(|b| self.read(b), buf)
408 }
409
410 /// Reads the exact number of bytes required to fill `cursor`.
411 ///
412 /// This is similar to the [`read_exact`](Read::read_exact) method, except
413 /// that it is passed a [`BorrowedCursor`] rather than `[u8]` to allow use
414 /// with uninitialized buffers.
415 ///
416 /// # Errors
417 ///
418 /// If this function encounters an error of the kind [`ErrorKind::Interrupted`]
419 /// then the error is ignored and the operation will continue.
420 ///
421 /// If this function encounters an "end of file" before completely filling
422 /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
423 ///
424 /// If any other read error is encountered then this function immediately
425 /// returns.
426 ///
427 /// If this function returns an error, all bytes read will be appended to `cursor`.
428 ///
429 /// [`ErrorKind::Interrupted`]: crate::io::ErrorKind::Interrupted
430 /// [`ErrorKind::UnexpectedEof`]: crate::io::ErrorKind::UnexpectedEof
431 #[unstable(feature = "read_buf", issue = "78485")]
432 fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_, u8>) -> Result<()> {
433 default_read_buf_exact(self, cursor)
434 }
435
436 /// Creates a "by reference" adapter for this instance of `Read`.
437 ///
438 /// The returned adapter also implements `Read` and will simply borrow this
439 /// current reader.
440 ///
441 /// # Examples
442 ///
443 /// `File`s implement `Read`:
444 ///
445 /// ```no_run
446 /// use std::io;
447 /// use std::io::Read;
448 /// use std::fs::File;
449 ///
450 /// fn main() -> io::Result<()> {
451 /// let mut f = File::open("foo.txt")?;
452 /// let mut buffer = Vec::new();
453 /// let mut other_buffer = Vec::new();
454 ///
455 /// {
456 /// let reference = f.by_ref();
457 ///
458 /// // read at most 5 bytes
459 /// reference.take(5).read_to_end(&mut buffer)?;
460 ///
461 /// } // drop our &mut reference so we can use f again
462 ///
463 /// // original file still usable, read the rest
464 /// f.read_to_end(&mut other_buffer)?;
465 /// Ok(())
466 /// }
467 /// ```
468 #[stable(feature = "rust1", since = "1.0.0")]
469 fn by_ref(&mut self) -> &mut Self
470 where
471 Self: Sized,
472 {
473 self
474 }
475
476 /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
477 ///
478 /// The returned type implements [`Iterator`] where the [`Item`] is
479 /// <code>[Result]<[u8], [io::Error]></code>.
480 /// The yielded item is [`Ok`] if a byte was successfully read and [`Err`]
481 /// otherwise. EOF is mapped to returning [`None`] from this iterator.
482 ///
483 /// The default implementation calls `read` for each byte,
484 /// which can be very inefficient for data that's not in memory,
485 /// such as `File`. Consider using a `BufReader` in such cases.
486 ///
487 /// # Examples
488 ///
489 /// `File`s implement `Read`:
490 ///
491 /// [`Item`]: Iterator::Item
492 /// [Result]: core::result::Result "Result"
493 /// [io::Error]: crate::io::Error "io::Error"
494 ///
495 /// ```no_run
496 /// use std::io;
497 /// use std::io::prelude::*;
498 /// use std::io::BufReader;
499 /// use std::fs::File;
500 ///
501 /// fn main() -> io::Result<()> {
502 /// let f = BufReader::new(File::open("foo.txt")?);
503 ///
504 /// for byte in f.bytes() {
505 /// println!("{}", byte?);
506 /// }
507 /// Ok(())
508 /// }
509 /// ```
510 #[stable(feature = "rust1", since = "1.0.0")]
511 fn bytes(self) -> Bytes<Self>
512 where
513 Self: Sized,
514 {
515 bytes(self)
516 }
517
518 /// Creates an adapter which will chain this stream with another.
519 ///
520 /// The returned `Read` instance will first read all bytes from this object
521 /// until EOF is encountered. Afterwards the output is equivalent to the
522 /// output of `next`.
523 ///
524 /// # Examples
525 ///
526 /// `File`s implement `Read`:
527 ///
528 /// ```no_run
529 /// use std::io;
530 /// use std::io::prelude::*;
531 /// use std::fs::File;
532 ///
533 /// fn main() -> io::Result<()> {
534 /// let f1 = File::open("foo.txt")?;
535 /// let f2 = File::open("bar.txt")?;
536 ///
537 /// let mut handle = f1.chain(f2);
538 /// let mut buffer = String::new();
539 ///
540 /// // read the value into a String. We could use any Read method here,
541 /// // this is just one example.
542 /// handle.read_to_string(&mut buffer)?;
543 /// Ok(())
544 /// }
545 /// ```
546 #[stable(feature = "rust1", since = "1.0.0")]
547 fn chain<R: Read>(self, next: R) -> Chain<Self, R>
548 where
549 Self: Sized,
550 {
551 chain(self, next)
552 }
553
554 /// Creates an adapter which will read at most `limit` bytes from it.
555 ///
556 /// This function returns a new instance of `Read` which will read at most
557 /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
558 /// read errors will not count towards the number of bytes read and future
559 /// calls to [`read()`] may succeed.
560 ///
561 /// # Examples
562 ///
563 /// `File`s implement `Read`:
564 ///
565 /// [`Ok(0)`]: Ok
566 /// [`read()`]: Read::read
567 ///
568 /// ```no_run
569 /// use std::io;
570 /// use std::io::prelude::*;
571 /// use std::fs::File;
572 ///
573 /// fn main() -> io::Result<()> {
574 /// let f = File::open("foo.txt")?;
575 /// let mut buffer = [0; 5];
576 ///
577 /// // read at most five bytes
578 /// let mut handle = f.take(5);
579 ///
580 /// handle.read(&mut buffer)?;
581 /// Ok(())
582 /// }
583 /// ```
584 #[stable(feature = "rust1", since = "1.0.0")]
585 fn take(self, limit: u64) -> Take<Self>
586 where
587 Self: Sized,
588 {
589 take(self, limit)
590 }
591
592 /// Read and return a fixed array of bytes from this source.
593 ///
594 /// This function uses an array sized based on a const generic size known at compile time. You
595 /// can specify the size with turbofish (`reader.read_array::<8>()`), or let type inference
596 /// determine the number of bytes needed based on how the return value gets used. For instance,
597 /// this function works well with functions like [`u64::from_le_bytes`] to turn an array of
598 /// bytes into an integer of the same size.
599 ///
600 /// Like `read_exact`, if this function encounters an "end of file" before reading the desired
601 /// number of bytes, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
602 ///
603 /// [`ErrorKind::UnexpectedEof`]: crate::io::ErrorKind::UnexpectedEof
604 ///
605 /// ```
606 /// #![feature(read_array)]
607 /// use std::io::Cursor;
608 /// use std::io::prelude::*;
609 ///
610 /// fn main() -> std::io::Result<()> {
611 /// let mut buf = Cursor::new([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2]);
612 /// let x = u64::from_le_bytes(buf.read_array()?);
613 /// let y = u32::from_be_bytes(buf.read_array()?);
614 /// let z = u16::from_be_bytes(buf.read_array()?);
615 /// assert_eq!(x, 0x807060504030201);
616 /// assert_eq!(y, 0x9080706);
617 /// assert_eq!(z, 0x504);
618 /// Ok(())
619 /// }
620 /// ```
621 #[unstable(feature = "read_array", issue = "148848")]
622 fn read_array<const N: usize>(&mut self) -> Result<[u8; N]>
623 where
624 Self: Sized,
625 {
626 let mut buf = [MaybeUninit::uninit(); N];
627 let mut borrowed_buf = BorrowedBuf::from(buf.as_mut_slice());
628 self.read_buf_exact(borrowed_buf.unfilled())?;
629 // Guard against incorrect `read_buf_exact` implementations.
630 assert_eq!(borrowed_buf.len(), N);
631 Ok(unsafe { MaybeUninit::array_assume_init(buf) })
632 }
633
634 /// Read and return a type (e.g. an integer) in little-endian order.
635 ///
636 /// You can specify the type with turbofish (`reader.read_le::<u64>()`), or let type inference
637 /// determine the type based on how the return value gets used.
638 ///
639 /// Like `read_exact`, if this function encounters an "end of file" before reading the desired
640 /// number of bytes, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
641 ///
642 /// [`ErrorKind::UnexpectedEof`]: crate::io::ErrorKind::UnexpectedEof
643 ///
644 /// ```
645 /// #![feature(read_le)]
646 /// use std::io::Cursor;
647 /// use std::io::prelude::*;
648 ///
649 /// fn main() -> std::io::Result<()> {
650 /// let mut buf = Cursor::new([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2]);
651 /// let x: u64 = buf.read_le()?;
652 /// let y: u32 = buf.read_le()?;
653 /// let z = buf.read_le::<u16>()?;
654 /// assert_eq!(x, 0x807060504030201);
655 /// assert_eq!(y, 0x6070809);
656 /// assert_eq!(z, 0x405);
657 /// Ok(())
658 /// }
659 /// ```
660 #[unstable(feature = "read_le", issue = "156984")]
661 #[inline]
662 fn read_le<T: FromEndianBytes>(&mut self) -> Result<T>
663 where
664 Self: Sized,
665 {
666 T::read_le_from(self)
667 }
668
669 /// Read and return a type (e.g. an integer) in big-endian order.
670 ///
671 /// You can specify the type with turbofish (`reader.read_be::<u64>()`), or let type inference
672 /// determine the type based on how the return value gets used.
673 ///
674 /// Like `read_exact`, if this function encounters an "end of file" before reading the desired
675 /// number of bytes, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
676 ///
677 /// [`ErrorKind::UnexpectedEof`]: crate::io::ErrorKind::UnexpectedEof
678 ///
679 /// ```
680 /// #![feature(read_le)]
681 /// use std::io::Cursor;
682 /// use std::io::prelude::*;
683 ///
684 /// fn main() -> std::io::Result<()> {
685 /// let mut buf = Cursor::new([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2]);
686 /// let x: u64 = buf.read_be()?;
687 /// let y: u32 = buf.read_be()?;
688 /// let z = buf.read_be::<u16>()?;
689 /// assert_eq!(x, 0x102030405060708);
690 /// assert_eq!(y, 0x9080706);
691 /// assert_eq!(z, 0x504);
692 /// Ok(())
693 /// }
694 /// ```
695 #[unstable(feature = "read_le", issue = "156984")]
696 #[inline]
697 fn read_be<T: FromEndianBytes>(&mut self) -> Result<T>
698 where
699 Self: Sized,
700 {
701 T::read_be_from(self)
702 }
703}
704
705/// Reads all bytes from a [reader][Read] into a new [`String`].
706///
707/// This is a convenience function for [`Read::read_to_string`]. Using this
708/// function avoids having to create a variable first and provides more type
709/// safety since you can only get the buffer out if there were no errors. (If you
710/// use [`Read::read_to_string`] you have to remember to check whether the read
711/// succeeded because otherwise your buffer will be empty or only partially full.)
712///
713/// # Performance
714///
715/// The downside of this function's increased ease of use and type safety is
716/// that it gives you less control over performance. For example, you can't
717/// pre-allocate memory like you can using [`String::with_capacity`] and
718/// [`Read::read_to_string`]. Also, you can't re-use the buffer if an error
719/// occurs while reading.
720///
721/// In many cases, this function's performance will be adequate and the ease of use
722/// and type safety tradeoffs will be worth it. However, there are cases where you
723/// need more control over performance, and in those cases you should definitely use
724/// [`Read::read_to_string`] directly.
725///
726/// Note that in some special cases, such as when reading files, this function will
727/// pre-allocate memory based on the size of the input it is reading. In those
728/// cases, the performance should be as good as if you had used
729/// [`Read::read_to_string`] with a manually pre-allocated buffer.
730///
731/// # Errors
732///
733/// This function forces you to handle errors because the output (the `String`)
734/// is wrapped in a [`Result`]. See [`Read::read_to_string`] for the errors
735/// that can occur. If any error occurs, you will get an [`Err`], so you
736/// don't have to worry about your buffer being empty or partially full.
737///
738/// # Examples
739///
740/// ```no_run
741/// # use std::io;
742/// fn main() -> io::Result<()> {
743/// let stdin = io::read_to_string(io::stdin())?;
744/// println!("Stdin was:");
745/// println!("{stdin}");
746/// Ok(())
747/// }
748/// ```
749///
750/// # Usage Notes
751///
752/// `read_to_string` attempts to read a source until EOF, but many sources are continuous streams
753/// that do not send EOF. In these cases, `read_to_string` will block indefinitely. Standard input
754/// is one such stream which may be finite if piped, but is typically continuous. For example,
755/// `cat file | my-rust-program` will correctly terminate with an `EOF` upon closure of cat.
756/// Reading user input or running programs that remain open indefinitely will never terminate
757/// the stream with `EOF` (e.g. `yes | my-rust-program`).
758///
759/// Using `.lines()` with a `BufReader` or using [`read`] can provide a better solution
760///
761/// [`read`]: Read::read
762///
763#[stable(feature = "io_read_to_string", since = "1.65.0")]
764pub fn read_to_string<R: Read>(mut reader: R) -> Result<String> {
765 let mut buf = String::new();
766 reader.read_to_string(&mut buf)?;
767 Ok(buf)
768}
769
770/// Bare metal platforms usually have very small amounts of RAM
771/// (in the order of hundreds of KB)
772#[doc(hidden)]
773#[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
774pub const DEFAULT_BUF_SIZE: usize = cfg_select! {
775 target_os = "espidf" => { 512 },
776 _ => { 8 * 1024 }
777};
778
779/// Several `read_to_string` and `read_line` methods in the standard library will
780/// append data into a `String` buffer, but we need to be pretty careful when
781/// doing this. The implementation will just call `.as_mut_vec()` and then
782/// delegate to a byte-oriented reading method, but we must ensure that when
783/// returning we never leave `buf` in a state such that it contains invalid UTF-8
784/// in its bounds.
785///
786/// To this end, we use an RAII guard (to protect against panics) which updates
787/// the length of the string when it is dropped. This guard initially truncates
788/// the string to the prior length and only after we've validated that the
789/// new contents are valid UTF-8 do we allow it to set a longer length.
790///
791/// The unsafety in this function is twofold:
792///
793/// 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
794/// checks.
795/// 2. We're passing a raw buffer to the function `f`, and it is expected that
796/// the function only *appends* bytes to the buffer. We'll get undefined
797/// behavior if existing bytes are overwritten to have non-UTF-8 data.
798#[doc(hidden)]
799#[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
800pub unsafe fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
801where
802 F: FnOnce(&mut Vec<u8>) -> Result<usize>,
803{
804 let len_original = buf.len();
805 // SAFETY: invalid UTF-8 discarded before return or unwind
806 let buf_vec = unsafe { buf.as_mut_vec() };
807 let mut g = DropGuard::new((len_original, buf_vec), |(len, buf)| unsafe {
808 buf.set_len(len);
809 });
810 let ret = f(g.1);
811
812 // SAFETY: the caller promises to only append data to `buf`
813 let appended = unsafe { g.1.get_unchecked(g.0..) };
814 if str::from_utf8(appended).is_err() {
815 ret.and_then(|_| Err(Error::INVALID_UTF8))
816 } else {
817 g.0 = g.1.len();
818 ret
819 }
820}
821
822/// Here we must serve many masters with conflicting goals:
823///
824/// - avoid allocating unless necessary
825/// - avoid overallocating if we know the exact size (#89165)
826/// - avoid passing large buffers to readers that always initialize the free capacity if they perform short reads (#23815, #23820)
827/// - pass large buffers to readers that do not initialize the spare capacity. this can amortize per-call overheads
828/// - and finally pass not-too-small and not-too-large buffers to Windows read APIs because they manage to suffer from both problems
829/// at the same time, i.e. small reads suffer from syscall overhead, all reads incur costs proportional to buffer size (#110650)
830#[doc(hidden)]
831#[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
832pub fn default_read_to_end<R: Read + ?Sized>(
833 r: &mut R,
834 buf: &mut Vec<u8>,
835 size_hint: Option<usize>,
836) -> Result<usize> {
837 let start_len = buf.len();
838 let start_cap = buf.capacity();
839 // Optionally limit the maximum bytes read on each iteration.
840 // This adds an arbitrary fiddle factor to allow for more data than we expect.
841 let mut max_read_size = size_hint
842 .and_then(|s| s.checked_add(1024)?.checked_next_multiple_of(DEFAULT_BUF_SIZE))
843 .unwrap_or(DEFAULT_BUF_SIZE);
844
845 const PROBE_SIZE: usize = 32;
846
847 fn small_probe_read<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
848 let mut probe = [0u8; PROBE_SIZE];
849
850 loop {
851 cfg_select! {
852 no_global_oom_handling => {
853 // Without global OOM handling we must proactively allocate the buffer
854 // to avoid failing after already reading data.
855 buf.try_reserve(PROBE_SIZE)?;
856 }
857 _ => {}
858 }
859
860 match r.read(&mut probe) {
861 Ok(n) => {
862 cfg_select! {
863 no_global_oom_handling => {
864 // there is no way to recover from allocation failure here
865 // because the data has already been read.
866 buf.try_extend_from_slice_of_bytes(&probe[..n])?;
867 }
868 _ => {
869 // there is no way to recover from allocation failure here
870 // because the data has already been read.
871 buf.extend_from_slice(&probe[..n]);
872 }
873 }
874 return Ok(n);
875 }
876 Err(ref e) if e.is_interrupted() => continue,
877 Err(e) => return Err(e),
878 }
879 }
880 }
881
882 // avoid inflating empty/small vecs before we have determined that there's anything to read
883 if (size_hint.is_none() || size_hint == Some(0)) && buf.capacity() - buf.len() < PROBE_SIZE {
884 let read = small_probe_read(r, buf)?;
885
886 if read == 0 {
887 return Ok(0);
888 }
889 }
890
891 loop {
892 if buf.len() == buf.capacity() && buf.capacity() == start_cap {
893 // The buffer might be an exact fit. Let's read into a probe buffer
894 // and see if it returns `Ok(0)`. If so, we've avoided an
895 // unnecessary doubling of the capacity. But if not, append the
896 // probe buffer to the primary buffer and let its capacity grow.
897 let read = small_probe_read(r, buf)?;
898
899 if read == 0 {
900 return Ok(buf.len() - start_len);
901 }
902 }
903
904 if buf.len() == buf.capacity() {
905 // buf is full, need more space
906 buf.try_reserve(PROBE_SIZE)?;
907 }
908
909 let mut spare = buf.spare_capacity_mut();
910 let buf_len = cmp::min(spare.len(), max_read_size);
911 spare = &mut spare[..buf_len];
912 let mut read_buf: BorrowedBuf<'_, u8> = spare.into();
913
914 // Note that we don't track already initialized bytes here, but this is fine
915 // because we explicitly limit the read size
916 let mut cursor = read_buf.unfilled();
917 let result = loop {
918 match r.read_buf(cursor.reborrow()) {
919 Err(e) if e.is_interrupted() => continue,
920 // Do not stop now in case of error: we might have received both data
921 // and an error
922 res => break res,
923 }
924 };
925
926 let bytes_read = cursor.written();
927 let is_init = read_buf.is_init();
928
929 // SAFETY: BorrowedBuf's invariants mean this much memory is initialized.
930 unsafe {
931 let new_len = bytes_read + buf.len();
932 buf.set_len(new_len);
933 }
934
935 // Now that all data is pushed to the vector, we can fail without data loss
936 result?;
937
938 if bytes_read == 0 {
939 return Ok(buf.len() - start_len);
940 }
941
942 // Use heuristics to determine the max read size if no initial size hint was provided
943 if size_hint.is_none() {
944 // The reader is returning short reads but it doesn't call ensure_init().
945 // In that case we no longer need to restrict read sizes to avoid
946 // initialization costs.
947 // When reading from disk we usually don't get any short reads except at EOF.
948 // So we wait for at least 2 short reads before uncapping the read buffer;
949 // this helps with the Windows issue.
950 if !is_init {
951 max_read_size = usize::MAX;
952 }
953 // we have passed a larger buffer than previously and the
954 // reader still hasn't returned a short read
955 else if buf_len >= max_read_size && bytes_read == buf_len {
956 max_read_size = max_read_size.saturating_mul(2);
957 }
958 }
959 }
960}
961
962#[doc(hidden)]
963#[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
964pub fn default_read_to_string<R: Read + ?Sized>(
965 r: &mut R,
966 buf: &mut String,
967 size_hint: Option<usize>,
968) -> Result<usize> {
969 // Note that we do *not* call `r.read_to_end()` here. We are passing
970 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
971 // method to fill it up. An arbitrary implementation could overwrite the
972 // entire contents of the vector, not just append to it (which is what
973 // we are expecting).
974 //
975 // To prevent extraneously checking the UTF-8-ness of the entire buffer
976 // we pass it to our hardcoded `default_read_to_end` implementation which
977 // we know is guaranteed to only read data into the end of the buffer.
978 unsafe { append_to_string(buf, |b| default_read_to_end(r, b, size_hint)) }
979}
980
981#[doc(hidden)]
982#[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
983pub fn default_read_vectored<F>(read: F, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
984where
985 F: FnOnce(&mut [u8]) -> Result<usize>,
986{
987 let buf = bufs.iter_mut().find(|b| !b.is_empty()).map_or(&mut [][..], |b| &mut **b);
988 read(buf)
989}
990
991#[doc(hidden)]
992#[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
993pub fn default_read_exact<R: Read + ?Sized>(this: &mut R, mut buf: &mut [u8]) -> Result<()> {
994 while !buf.is_empty() {
995 match this.read(buf) {
996 Ok(0) => break,
997 Ok(n) => {
998 buf = &mut buf[n..];
999 }
1000 Err(ref e) if e.is_interrupted() => {}
1001 Err(e) => return Err(e),
1002 }
1003 }
1004 if !buf.is_empty() { Err(Error::READ_EXACT_EOF) } else { Ok(()) }
1005}
1006
1007#[doc(hidden)]
1008#[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
1009pub fn default_read_buf<F>(read: F, mut cursor: BorrowedCursor<'_, u8>) -> Result<()>
1010where
1011 F: FnOnce(&mut [u8]) -> Result<usize>,
1012{
1013 let n = read(cursor.ensure_init())?;
1014 cursor.advance_checked(n);
1015 Ok(())
1016}
1017
1018#[doc(hidden)]
1019#[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
1020pub fn default_read_buf_exact<R: Read + ?Sized>(
1021 this: &mut R,
1022 mut cursor: BorrowedCursor<'_, u8>,
1023) -> Result<()> {
1024 while cursor.capacity() > 0 {
1025 let prev_written = cursor.written();
1026 match this.read_buf(cursor.reborrow()) {
1027 Ok(()) => {}
1028 Err(e) if e.is_interrupted() => continue,
1029 Err(e) => return Err(e),
1030 }
1031
1032 if cursor.written() == prev_written {
1033 return Err(Error::READ_EXACT_EOF);
1034 }
1035 }
1036
1037 Ok(())
1038}
1039
1040mod sealed {
1041 /// This trait being unreachable from outside the crate
1042 /// prevents outside implementations of our extension traits.
1043 /// This allows adding more trait methods in the future.
1044 #[unstable(feature = "sealed", issue = "none")]
1045 pub trait Sealed {}
1046}
1047
1048/// Trait for types that can be converted from a fixed-size byte array with a specified endianness
1049#[unstable(feature = "read_le_be_internals", reason = "internals", issue = "none")]
1050// Once we can use associated consts in the types of method parameters, rewrite this to have
1051// `from_le_bytes` and `from_be_bytes` methods, move it to `core`, and make it public.
1052pub trait FromEndianBytes: sealed::Sealed + Sized {
1053 #[doc(hidden)]
1054 fn read_le_from(r: &mut impl Read) -> Result<Self>;
1055
1056 #[doc(hidden)]
1057 fn read_be_from(r: &mut impl Read) -> Result<Self>;
1058}
1059
1060macro_rules! impl_from_endian_bytes {
1061 ($($t:ty),*$(,)?) => {$(
1062 #[unstable(feature = "sealed", issue = "none")]
1063 impl sealed::Sealed for $t {}
1064
1065 #[unstable(feature = "read_le_be_internals", reason = "internals", issue = "none")]
1066 impl FromEndianBytes for $t {
1067 #[inline]
1068 fn read_le_from(r: &mut impl Read) -> Result<Self> {
1069 Ok(<$t>::from_le_bytes(r.read_array()?))
1070 }
1071
1072 #[inline]
1073 fn read_be_from(r: &mut impl Read) -> Result<Self> {
1074 Ok(<$t>::from_be_bytes(r.read_array()?))
1075 }
1076 }
1077 )*};
1078}
1079
1080impl_from_endian_bytes!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize, f32, f64);