Skip to main content

tokio/fs/
rename.rs

1use crate::fs::asyncify;
2
3use std::io;
4use std::path::Path;
5
6/// Renames a file or directory to a new name, replacing the original file if
7/// `to` already exists.
8///
9/// This will not work if the new name is on a different mount point.
10///
11/// This is an async version of [`std::fs::rename`].
12pub async fn rename(from: impl AsRef<Path>, to: impl AsRef<Path>) -> io::Result<()> {
13    let from = from.as_ref();
14    let to = to.as_ref();
15
16    #[cfg(all(
17        tokio_unstable,
18        feature = "io-uring",
19        feature = "rt",
20        feature = "fs",
21        target_os = "linux",
22    ))]
23    {
24        use crate::io::uring::rename::Rename;
25        use crate::runtime::driver::op::Op;
26
27        type RenameOp = Op<Rename>;
28
29        if let Ok(handle) = crate::runtime::Handle::try_current() {
30            if let Some(driver_handle) = handle.inner.driver().io.as_ref() {
31                if driver_handle
32                    .check_and_init(io_uring::opcode::RenameAt::CODE)
33                    .await?
34                {
35                    return RenameOp::rename(from, to)?.await;
36                }
37            }
38        }
39    }
40
41    rename_blocking(from, to).await
42}
43
44async fn rename_blocking(from: &Path, to: &Path) -> io::Result<()> {
45    let [from, to] = [from, to].map(Path::to_owned);
46    asyncify(move || std::fs::rename(from, to)).await
47}