mirror of
https://github.com/cargo-bins/cargo-binstall.git
synced 2025-05-07 20:50:03 +00:00
Impl new RAII type helpers::flock::FileLock
that locks a file exclusive or shared Signed-off-by: Jiahao XU <Jiahao_XU@outlook.com>
This commit is contained in:
parent
751cf47716
commit
9e45ba1032
2 changed files with 48 additions and 0 deletions
|
@ -42,6 +42,9 @@ pub use tls_version::TLSVersion;
|
|||
mod crate_name;
|
||||
pub use crate_name::CrateName;
|
||||
|
||||
mod flock;
|
||||
pub use flock::FileLock;
|
||||
|
||||
pub fn cargo_home() -> Result<&'static Path, io::Error> {
|
||||
static CARGO_HOME: OnceCell<PathBuf> = OnceCell::new();
|
||||
|
||||
|
|
45
src/helpers/flock.rs
Normal file
45
src/helpers/flock.rs
Normal file
|
@ -0,0 +1,45 @@
|
|||
use std::fs::File;
|
||||
use std::io;
|
||||
use std::ops;
|
||||
|
||||
use fs4::FileExt;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct FileLock(File);
|
||||
|
||||
impl FileLock {
|
||||
/// NOTE that this function blocks, so it cannot
|
||||
/// be called in async context.
|
||||
pub fn new_exclusive(file: File) -> io::Result<Self> {
|
||||
file.lock_exclusive()?;
|
||||
|
||||
Ok(Self(file))
|
||||
}
|
||||
|
||||
/// NOTE that this function blocks, so it cannot
|
||||
/// be called in async context.
|
||||
pub fn new_shared(file: File) -> io::Result<Self> {
|
||||
file.lock_shared()?;
|
||||
|
||||
Ok(Self(file))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for FileLock {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
impl ops::Deref for FileLock {
|
||||
type Target = File;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
impl ops::DerefMut for FileLock {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.0
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue