1 | use crate::io; |
2 | use crate::path::Path; |
3 | use crate::task::spawn_blocking; |
4 | use crate::utils::Context as _; |
5 | |
6 | /// Writes a slice of bytes as the new contents of a file. |
7 | /// |
8 | /// This function will create a file if it does not exist, and will entirely replace its contents |
9 | /// if it does. |
10 | /// |
11 | /// This function is an async version of [`std::fs::write`]. |
12 | /// |
13 | /// [`std::fs::write`]: https://doc.rust-lang.org/std/fs/fn.write.html |
14 | /// |
15 | /// # Errors |
16 | /// |
17 | /// An error will be returned in the following situations: |
18 | /// |
19 | /// * The file's parent directory does not exist. |
20 | /// * The current process lacks permissions to write to the file. |
21 | /// * Some other I/O error occurred. |
22 | /// |
23 | /// # Examples |
24 | /// |
25 | /// ```no_run |
26 | /// # fn main() -> std::io::Result<()> { async_std::task::block_on(async { |
27 | /// # |
28 | /// use async_std::fs; |
29 | /// |
30 | /// fs::write("a.txt" , b"Hello world!" ).await?; |
31 | /// # |
32 | /// # Ok(()) }) } |
33 | /// ``` |
34 | pub async fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> { |
35 | let path: PathBuf = path.as_ref().to_owned(); |
36 | let contents: Vec = contents.as_ref().to_owned(); |
37 | spawn_blockingJoinHandle>(move || { |
38 | std::fs::write(&path, contents) |
39 | .context(|| format!("could not write to file ` {}`" , path.display())) |
40 | }) |
41 | .await |
42 | } |
43 | |