1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
//! Advisory reader-writer locks for files.
//!
//! # Notes on Advisory Locks
//!
//! "advisory locks" are locks which programs must opt-in to adhere to. This
//! means that they can be used to coordinate file access, but not prevent
//! access. Use this to coordinate file access between multiple instances of the
//! same program. But do not use this to prevent actors from accessing or
//! modifying files.
//!
//! # Example
//!
//! ```
//! use std::path::PathBuf;
//! use tokio::fs::File;
//! use tokio::io::{AsyncReadExt, AsyncWriteExt};
//! use async_fd_lock::{LockRead, LockWrite};
//!
//! # tokio_test::block_on(async {
//! 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?;
//! }
//! # std::io::Result::Ok(())
//! # }).unwrap();
//! ```
#![forbid(future_incompatible)]
#![deny(missing_debug_implementations, nonstandard_style)]
#![cfg_attr(doc, warn(missing_docs, rustdoc::missing_doc_code_examples))]

use std::io;
use sys::AsOpenFileExt;

mod read_guard;
mod write_guard;

pub(crate) mod sys;

#[cfg(feature = "async")]
pub use nonblocking::*;
pub use read_guard::RwLockReadGuard;
pub use sys::AsOpenFile;
pub use write_guard::RwLockWriteGuard;

pub type LockReadResult<T> = Result<RwLockReadGuard<T>, (T, io::Error)>;
pub type LockWriteResult<T> = Result<RwLockWriteGuard<T>, (T, io::Error)>;

pub mod blocking {
    use super::*;

    pub trait LockRead: AsOpenFile + std::io::Read {
        fn lock_read(self) -> LockReadResult<Self>
        where
            Self: Sized;

        fn try_lock_read(self) -> LockReadResult<Self>
        where
            Self: Sized;
    }

    pub trait LockWrite: AsOpenFile + std::io::Write {
        fn lock_write(self) -> LockWriteResult<Self>
        where
            Self: Sized;

        fn try_lock_write(self) -> LockWriteResult<Self>
        where
            Self: Sized;
    }

    impl<T> LockRead for T
    where
        T: AsOpenFile + std::io::Read,
    {
        fn lock_read(self) -> LockReadResult<Self> {
            match self.acquire_lock_blocking::<false, true>() {
                Ok(guard) => Ok(RwLockReadGuard::new(self, guard)),
                Err(error) => Err((self, error)),
            }
        }

        fn try_lock_read(self) -> LockReadResult<Self> {
            match self.acquire_lock_blocking::<false, false>() {
                Ok(guard) => Ok(RwLockReadGuard::new(self, guard)),
                Err(error) => Err((self, error)),
            }
        }
    }

    impl<T> LockWrite for T
    where
        T: AsOpenFile + std::io::Write,
    {
        fn lock_write(self) -> LockWriteResult<Self> {
            match self.acquire_lock_blocking::<true, true>() {
                Ok(guard) => Ok(RwLockWriteGuard::new(self, guard)),
                Err(error) => Err((self, error)),
            }
        }

        fn try_lock_write(self) -> LockWriteResult<Self> {
            match self.acquire_lock_blocking::<true, false>() {
                Ok(guard) => Ok(RwLockWriteGuard::new(self, guard)),
                Err(error) => Err((self, error)),
            }
        }
    }
}

#[cfg(feature = "async")]
pub mod nonblocking {
    use super::*;
    use async_trait::async_trait;
    use sys::{AsOpenFileExt, RwLockGuard};

    async fn lock<const WRITE: bool, const BLOCK: bool, T>(
        file: &T,
    ) -> Result<RwLockGuard<<T as AsOpenFileExt>::OwnedOpenFile>, io::Error>
    where
        T: AsOpenFile + Sync + 'static,
    {
        let handle = file.borrow_open_file().try_clone_to_owned()?;
        let (sync_send, async_recv) = tokio::sync::oneshot::channel();
        tokio::task::spawn_blocking(move || {
            let guard = handle.acquire_lock_blocking::<WRITE, BLOCK>();
            let result = sync_send.send(guard);
            drop(result); // If the guard cannot be sent to the async task, release the lock immediately.
        });
        async_recv
            .await
            .expect("the blocking task is not cancelable")
    }

    #[async_trait]
    pub trait LockRead: AsOpenFile + tokio::io::AsyncRead {
        async fn lock_read(self) -> LockReadResult<Self>
        where
            Self: Sized;

        async fn try_lock_read(self) -> LockReadResult<Self>
        where
            Self: Sized;
    }

    #[async_trait]
    pub trait LockWrite: AsOpenFile + tokio::io::AsyncWrite {
        async fn lock_write(self) -> LockWriteResult<Self>
        where
            Self: Sized;

        async fn try_lock_write(self) -> LockWriteResult<Self>
        where
            Self: Sized;
    }

    #[async_trait]
    impl<T> LockRead for T
    where
        T: AsOpenFile + tokio::io::AsyncRead + Send + Sync + 'static,
    {
        async fn lock_read(self) -> LockReadResult<Self> {
            match lock::<false, true, _>(&self).await {
                Ok(guard) => Ok(RwLockReadGuard::new(self, guard)),
                Err(error) => Err((self, error)),
            }
        }

        async fn try_lock_read(self) -> LockReadResult<Self> {
            match lock::<false, false, _>(&self).await {
                Ok(guard) => Ok(RwLockReadGuard::new(self, guard)),
                Err(error) => Err((self, error)),
            }
        }
    }

    #[async_trait]
    impl<T> LockWrite for T
    where
        T: AsOpenFile + tokio::io::AsyncWrite + Send + Sync + 'static,
    {
        async fn lock_write(self) -> LockWriteResult<Self> {
            match lock::<true, true, _>(&self).await {
                Ok(guard) => Ok(RwLockWriteGuard::new(self, guard)),
                Err(error) => Err((self, error)),
            }
        }

        async fn try_lock_write(self) -> LockWriteResult<Self> {
            match lock::<true, false, _>(&self).await {
                Ok(guard) => Ok(RwLockWriteGuard::new(self, guard)),
                Err(error) => return Err((self, error)),
            }
        }
    }
}