async_std/fs/copy.rs
1use crate::io;
2use crate::path::Path;
3use crate::task::spawn_blocking;
4use crate::utils::Context as _;
5
6/// Copies the contents and permissions of a file to a new location.
7///
8/// On success, the total number of bytes copied is returned and equals the length of the `to` file
9/// after this operation.
10///
11/// The old contents of `to` will be overwritten. If `from` and `to` both point to the same file,
12/// then the file will likely get truncated as a result of this operation.
13///
14/// If you're working with open [`File`]s and want to copy contents through those types, use the
15/// [`io::copy`] function.
16///
17/// This function is an async version of [`std::fs::copy`].
18///
19/// [`File`]: struct.File.html
20/// [`io::copy`]: ../io/fn.copy.html
21/// [`std::fs::copy`]: https://doc.rust-lang.org/std/fs/fn.copy.html
22///
23/// # Errors
24///
25/// An error will be returned in the following situations:
26///
27/// * `from` does not point to an existing file.
28/// * The current process lacks permissions to read `from` or write `to`.
29/// * Some other I/O error occurred.
30///
31/// # Examples
32///
33/// ```no_run
34/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
35/// #
36/// use async_std::fs;
37///
38/// let num_bytes = fs::copy("a.txt", "b.txt").await?;
39/// #
40/// # Ok(()) }) }
41/// ```
42pub async fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
43 let from = from.as_ref().to_owned();
44 let to = to.as_ref().to_owned();
45 spawn_blocking(move || {
46 std::fs::copy(&from, &to)
47 .context(|| format!("could not copy `{}` to `{}`", from.display(), to.display()))
48 })
49 .await
50}