#file-lock #lock #file #async #locking #async-write #read-file

async-file-lock

Asynchronous file lock that can auto lock and auto seek

5 releases

0.1.4 Jul 11, 2021
0.1.3 Mar 12, 2021
0.1.2 Feb 21, 2021
0.1.1 Feb 14, 2021
0.1.0 Feb 14, 2021

#721 in Asynchronous

Download history 62/week @ 2023-12-14 44/week @ 2023-12-21 50/week @ 2023-12-28 37/week @ 2024-01-04 54/week @ 2024-01-11 43/week @ 2024-01-18 48/week @ 2024-01-25 67/week @ 2024-02-01 20/week @ 2024-02-08 46/week @ 2024-02-15 52/week @ 2024-02-22 66/week @ 2024-02-29 94/week @ 2024-03-07 114/week @ 2024-03-14 125/week @ 2024-03-21 99/week @ 2024-03-28

438 downloads per month

MIT license

22KB
395 lines

async-file-lock

version downloads docs licence

Asynchronous file lock that can auto lock and auto seek.

Features

  • async file locks (exclusive and shared)
  • auto lock before doing any read or write operation
  • auto seek before doing any read or write operation
  • manual lock/unlock

Platforms

async-file-lock should work on any platform supported by libc.

Example

use async_file_lock::FileLock;
use tokio::io::{AsyncWriteExt, SeekFrom, AsyncSeekExt, AsyncReadExt};
//...

// Create file in read/write mode
let mut file = FileLock::create(&tmp_path).await?;
// Supports any methods from AsyncReadExt, AsyncWriteExt, AsyncSeekExt
// Locks exclusive
file.write(b"a").await?;
// Releases lock
file.seek(SeekFrom::Start(0)).await?;
let mut string = String::new();
// Locks shared
file.read_to_string(&mut string).await?;
// Releases lock
file.seek(SeekFrom::Start(0)).await?;
// Locks exclusive and holds
file.lock_exclusive().await?;
file.set_seeking_mode(SeekFrom::End(0));
// Seek to end and write
file.write(b"b").await?;
file.seek(SeekFrom::Start(0)).await?;
// Seek to end and write
file.write(b"c").await?;
// Finally releases lock
file.unlock().await;
file.lock_shared().await?;
// Cursor is at the end of a file, we want to read whole file.
file.seek(SeekFrom::Start(0)).await?;
// Removing seeking mode, otherwise before reading cursor will seek
// to the end of a file.
file.set_seeking_mode(SeekFrom::Current(0));
string.clear();
file.read_to_string(&mut string).await?;
assert_eq!(string, "abc");

Dependencies

~4MB
~55K SLoC