libxch/
lib.rs

1// Copyright 2017-2019 Moritz Wanzenböck.
2//
3// Licensed under the MIT License <LICENSE or http://opensource.org/licenses/MIT>.
4// This file may not be copied, modified, or distributed except according to those terms.
5//! A library for exchanging paths
6//!
7//! This library provides a simple utility to swap files and/or directory content of two paths.
8//! When possible, this is done in an atomic fashion, so that only the full changes are observable.
9//!
10//! Currently, atomic exchange is only supported on Windows and Linux.
11
12use std::path;
13
14pub use error::Error;
15
16mod platform;
17mod non_atomic;
18mod error;
19
20/// Exchange the content of the objects pointed to by the two paths.
21///
22/// This can be used to swap the content of two files, but it also works with directories.
23/// **This operation is atomic**, meaning if the content at one path changed, the other path will
24/// also have changed. If the operation can't be done atomically, it will fail.
25pub fn xch<A: AsRef<path::Path>, B: AsRef<path::Path>>(path1: A, path2: B) -> error::Result<()> {
26    platform::xch(path1, path2)
27}
28
29/// Exchange the content of the object pointed to by the two paths.
30///
31/// This can be used to swap the content of two files, but it also works with directories.
32/// **This operation may not be atomic**. If available, it will try to use the platform specific,
33/// atomic operations. If they are not implemented, this will fallback to a non-atomic exchange.
34pub fn xch_non_atomic<A: AsRef<path::Path>, B: AsRef<path::Path>>(path1: A, path2: B) -> error::Result<()> {
35    let res = platform::xch(&path1, &path2);
36    if let Err(error::Error::NotImplemented) = res {
37        non_atomic::xch(&path1, &path2)
38    } else {
39        res
40    }
41}