Expand description
Cross-platform file renaming without overwriting existing destinations.
§Overview
The Rust standard library offers std::fs::rename for renaming files.
Sometimes, that’s not enough. Consider the example of renaming a file but
aborting the operation if something already exists at the destination path.
That can be achieved using the Rust standard library but ensuring that the
operation is atomic requires platform-specific APIs. Without using
platform-specific APIs, a TOCTTOU bug can be introduced. This library aims
to provide a cross-platform interface to these APIs.
§Examples
Renaming a file without the possibility of accidentally overwriting anything
can be done using rename_exclusive. It should be noted that this feature
is not supported by all combinations of operating system and file system.
rename_exclusive will fail if it can’t be done atomically.
use std::io::Result;
fn main() -> Result<()> {
renamest::rename_exclusive("old.txt", "new.txt")
}Alternatively, rename_exclusive_fallback can be used. This will try to
perform the operation atomically, and use a non-atomic fallback if that’s
not supported. The return value will indicate what happened.
use std::io::Result;
fn main() -> Result<()> {
if renamest::rename_exclusive_fallback("old.txt", "new.txt")? {
// `new.txt` was definitely not overwritten.
println!("The operation was atomic");
} else {
// `new.txt` was probably not overwritten.
println!("The operation was not atomic");
}
Ok(())
}§Platform-specific behaviour
On Linux and Android, the renameat2 syscall is used through libc. The
always-fallback feature can force these platforms to report
ErrorKind::Unsupported so rename_exclusive_fallback uses its non-atomic
fallback.
always-fallback. Assume thatrenameat2doesn’t exist on Linux or Android.
Functions§
- rename_
exclusive - Rename a file without overwriting the destination path if it exists.
- rename_
exclusive_ fallback - Rename a file without overwriting the destination path if it exists, using a non-atomic fallback if necessary.
- rename_
exclusive_ is_ atomic - Determine whether an atomic
rename_exclusiveis supported.