#lock-files #file-descriptor #async-file #async

async-fd-lock

Advisory cross-platform file locks using file descriptors with async support by spawning blocking tasks

2 unstable releases

0.2.0 Jun 23, 2024
0.1.1 Jun 23, 2024
0.1.0 Jun 23, 2024

#1498 in Filesystem

Download history 1817/week @ 2025-05-26 1139/week @ 2025-06-02 1374/week @ 2025-06-09 1908/week @ 2025-06-16 2419/week @ 2025-06-23 1920/week @ 2025-06-30 1540/week @ 2025-07-07 1120/week @ 2025-07-14 2620/week @ 2025-07-21 2163/week @ 2025-07-28 2653/week @ 2025-08-04 2176/week @ 2025-08-11 1674/week @ 2025-08-18 1630/week @ 2025-08-25 2273/week @ 2025-09-01 1862/week @ 2025-09-08

7,470 downloads per month
Used in 24 crates (2 directly)

MIT/Apache

33KB
671 lines

async-fd-lock

crates.io version downloads docs.rs docs

Advisory cross-platform file locks using file descriptors, with async support by off-loading blocking operations to newly spawned blocking tasks. Adapted from yoshuawuyts/fd-lock, which was adapted from mafintosh/fd-lock.

Note that advisory lock compliance is opt-in, and can freely be ignored by other parties. This means this crate should never be used for security purposes, but solely to coordinate file access.

Examples

Basic usage

use std::path::PathBuf;
use tokio::fs::File;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use async_fd_lock::{LockRead, LockWrite};

let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("foo.txt");

// Lock it for writing.
{
    let mut write_guard = File::options()
        .create_new(true)
        .write(true)
        .truncate(true)
        .open(&path).await?
        .lock_write().await
        .map_err(|(_, err)| err)?;
    write_guard.write(b"bongo cat").await?;
}

// Lock it for reading.
{
    let mut read_guard_1 = File::open(&path).await?.lock_read().await.map_err(|(_, err)| err)?;
    let mut read_guard_2 = File::open(&path).await?.lock_read().await.map_err(|(_, err)| err)?;
    let byte_1 = read_guard_1.read_u8().await?;
    let byte_2 = read_guard_2.read_u8().await?;
}

Installation

$ cargo add async-fd-lock

Safety

This crate uses unsafe on Windows to interface with windows-sys. All invariants have been carefully checked, and are manually enforced.

References

License

MIT OR Apache-2.0

Dependencies

~2–16MB
~230K SLoC