| 1 | use crate::fs::asyncify; |
| 2 | |
| 3 | use std::{io, path::Path}; |
| 4 | |
| 5 | /// Creates a future that will open a file for writing and write the entire |
| 6 | /// contents of `contents` to it. |
| 7 | /// |
| 8 | /// This is the async equivalent of [`std::fs::write`][std]. |
| 9 | /// |
| 10 | /// This operation is implemented by running the equivalent blocking operation |
| 11 | /// on a separate thread pool using [`spawn_blocking`]. |
| 12 | /// |
| 13 | /// [`spawn_blocking`]: crate::task::spawn_blocking |
| 14 | /// [std]: fn@std::fs::write |
| 15 | /// |
| 16 | /// # Examples |
| 17 | /// |
| 18 | /// ```no_run |
| 19 | /// use tokio::fs; |
| 20 | /// |
| 21 | /// # async fn dox() -> std::io::Result<()> { |
| 22 | /// fs::write("foo.txt" , b"Hello world!" ).await?; |
| 23 | /// # Ok(()) |
| 24 | /// # } |
| 25 | /// ``` |
| 26 | pub async fn write(path: impl AsRef<Path>, contents: impl AsRef<[u8]>) -> io::Result<()> { |
| 27 | let path: PathBuf = path.as_ref().to_owned(); |
| 28 | let contents: Vec = contents.as_ref().to_owned(); |
| 29 | |
| 30 | asyncify(move || std::fs::write(path, contents)).await |
| 31 | } |
| 32 | |