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