1 use crate::fs::asyncify;
2 
3 use std::{io, path::Path};
4 
5 /// Reads the entire contents of a file into a bytes vector.
6 ///
7 /// This is an async version of [`std::fs::read`][std]
8 ///
9 /// [std]: std::fs::read
10 ///
11 /// This is a convenience function for using [`File::open`] and [`read_to_end`]
12 /// with fewer imports and without an intermediate variable. It pre-allocates a
13 /// buffer based on the file size when available, so it is generally faster than
14 /// reading into a vector created with `Vec::new()`.
15 ///
16 /// [`File::open`]: super::File::open
17 /// [`read_to_end`]: crate::io::AsyncReadExt::read_to_end
18 ///
19 /// # Errors
20 ///
21 /// This function will return an error if `path` does not already exist.
22 /// Other errors may also be returned according to [`OpenOptions::open`].
23 ///
24 /// [`OpenOptions::open`]: super::OpenOptions::open
25 ///
26 /// It will also return an error if it encounters while reading an error
27 /// of a kind other than [`ErrorKind::Interrupted`].
28 ///
29 /// [`ErrorKind::Interrupted`]: std::io::ErrorKind::Interrupted
30 ///
31 /// # Examples
32 ///
33 /// ```no_run
34 /// use tokio::fs;
35 /// use std::net::SocketAddr;
36 ///
37 /// #[tokio::main]
38 /// async fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
39 ///     let contents = fs::read("address.txt").await?;
40 ///     let foo: SocketAddr = String::from_utf8_lossy(&contents).parse()?;
41 ///     Ok(())
42 /// }
43 /// ```
read(path: impl AsRef<Path>) -> io::Result<Vec<u8>>44 pub async fn read(path: impl AsRef<Path>) -> io::Result<Vec<u8>> {
45     let path = path.as_ref().to_owned();
46     asyncify(move || std::fs::read(path)).await
47 }
48