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        let handle = crate::runtime::Handle::current();
28        let driver_handle = handle.inner.driver().io();
29
30        type RenameOp = Op<Rename>;
31
32        if driver_handle
33            .check_and_init(io_uring::opcode::RenameAt::CODE)
34            .await?
35        {
36            return RenameOp::rename(from, to)?.await;
37        }
38    }
39
40    rename_blocking(from, to).await
41}
42
43async fn rename_blocking(from: &Path, to: &Path) -> io::Result<()> {
44    let [from, to] = [from, to].map(Path::to_owned);
45    asyncify(move || std::fs::rename(from, to)).await
46}