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:
Jiahao XU 2022-07-22 19:48:37 +10:00
parent 751cf47716
commit 9e45ba1032
No known key found for this signature in database
GPG key ID: 591C0B03040416D6
2 changed files with 48 additions and 0 deletions

View file

@ -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
View 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
}
}