async_std/fs/rename.rs
1use crate::io;
2use crate::path::Path;
3use crate::task::spawn_blocking;
4use crate::utils::Context as _;
5
6/// Renames a file or directory to a new location.
7///
8/// If a file or directory already exists at the target location, it will be overwritten by this
9/// operation.
10///
11/// This function is an async version of [`std::fs::rename`].
12///
13/// [`std::fs::rename`]: https://doc.rust-lang.org/std/fs/fn.rename.html
14///
15/// # Errors
16///
17/// An error will be returned in the following situations:
18///
19/// * `from` does not point to an existing file or directory.
20/// * `from` and `to` are on different filesystems.
21/// * The current process lacks permissions to do the rename operation.
22/// * Some other I/O error occurred.
23///
24/// # Examples
25///
26/// ```no_run
27/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
28/// #
29/// use async_std::fs;
30///
31/// fs::rename("a.txt", "b.txt").await?;
32/// #
33/// # Ok(()) }) }
34/// ```
35pub async fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
36 let from = from.as_ref().to_owned();
37 let to = to.as_ref().to_owned();
38 spawn_blocking(move || {
39 std::fs::rename(&from, &to).context(|| {
40 format!(
41 "could not rename `{}` to `{}`",
42 from.display(),
43 to.display()
44 )
45 })
46 })
47 .await
48}