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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
|
//! Async read-write lock.
//!
//! This module provides a read-write lock that can be used to synchronize data between asynchronous tasks.
use core::cell::{RefCell, UnsafeCell};
use core::future::{poll_fn, Future};
use core::ops::{Deref, DerefMut};
use core::task::Poll;
use core::{fmt, mem};
use crate::blocking_mutex::raw::RawMutex;
use crate::blocking_mutex::Mutex as BlockingMutex;
use crate::waitqueue::WakerRegistration;
/// Error returned by [`RwLock::try_read`] and [`RwLock::try_write`] when the lock is already held.
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct TryLockError;
struct State {
readers: usize,
writer: bool,
waker: WakerRegistration,
}
/// Async read-write lock.
///
/// The read-write lock is generic over the raw mutex implementation `M` and the data `T` it protects.
/// The raw read-write lock is used to guard access to the internal state. It
/// is held for very short periods only, while locking and unlocking. It is *not* held
/// for the entire time the async RwLock is locked.
///
/// Which implementation you select depends on the context in which you're using the read-write lock.
///
/// Use [`CriticalSectionRawMutex`](crate::blocking_mutex::raw::CriticalSectionRawMutex) when data can be shared between threads and interrupts.
///
/// Use [`NoopRawMutex`](crate::blocking_mutex::raw::NoopRawMutex) when data is only shared between tasks running on the same executor.
///
/// Use [`ThreadModeRawMutex`](crate::blocking_mutex::raw::ThreadModeRawMutex) when data is shared between tasks running on the same executor but you want a singleton.
///
pub struct RwLock<M, T>
where
M: RawMutex,
T: ?Sized,
{
state: BlockingMutex<M, RefCell<State>>,
inner: UnsafeCell<T>,
}
unsafe impl<M: RawMutex + Send, T: ?Sized + Send> Send for RwLock<M, T> {}
unsafe impl<M: RawMutex + Sync, T: ?Sized + Send> Sync for RwLock<M, T> {}
/// Async read-write lock.
impl<M, T> RwLock<M, T>
where
M: RawMutex,
{
/// Create a new read-write lock with the given value.
pub const fn new(value: T) -> Self {
Self {
inner: UnsafeCell::new(value),
state: BlockingMutex::new(RefCell::new(State {
readers: 0,
writer: false,
waker: WakerRegistration::new(),
})),
}
}
}
impl<M, T> RwLock<M, T>
where
M: RawMutex,
T: ?Sized,
{
/// Lock the read-write lock for reading.
///
/// This will wait for the lock to be available if it's already locked for writing.
pub fn read(&self) -> impl Future<Output = RwLockReadGuard<'_, M, T>> {
poll_fn(|cx| {
let ready = self.state.lock(|s| {
let mut s = s.borrow_mut();
if s.writer {
s.waker.register(cx.waker());
false
} else {
s.readers += 1;
true
}
});
if ready {
Poll::Ready(RwLockReadGuard { rwlock: self })
} else {
Poll::Pending
}
})
}
/// Lock the read-write lock for writing.
///
/// This will wait for the lock to be available if it's already locked for reading or writing.
pub fn write(&self) -> impl Future<Output = RwLockWriteGuard<'_, M, T>> {
poll_fn(|cx| {
let ready = self.state.lock(|s| {
let mut s = s.borrow_mut();
if s.writer || s.readers > 0 {
s.waker.register(cx.waker());
false
} else {
s.writer = true;
true
}
});
if ready {
Poll::Ready(RwLockWriteGuard { rwlock: self })
} else {
Poll::Pending
}
})
}
/// Attempt to immediately lock the rwlock.
///
/// If the rwlock is already locked, this will return an error instead of waiting.
pub fn try_read(&self) -> Result<RwLockReadGuard<'_, M, T>, TryLockError> {
self.state
.lock(|s| {
let mut s = s.borrow_mut();
if s.writer {
return Err(());
}
s.readers += 1;
Ok(())
})
.map_err(|_| TryLockError)?;
Ok(RwLockReadGuard { rwlock: self })
}
/// Attempt to immediately lock the rwlock.
///
/// If the rwlock is already locked, this will return an error instead of waiting.
pub fn try_write(&self) -> Result<RwLockWriteGuard<'_, M, T>, TryLockError> {
self.state
.lock(|s| {
let mut s = s.borrow_mut();
if s.writer || s.readers > 0 {
return Err(());
}
s.writer = true;
Ok(())
})
.map_err(|_| TryLockError)?;
Ok(RwLockWriteGuard { rwlock: self })
}
/// Consumes this read-write lock, returning the underlying data.
pub fn into_inner(self) -> T
where
T: Sized,
{
self.inner.into_inner()
}
/// Returns a mutable reference to the underlying data.
///
/// Since this call borrows the RwLock mutably, no actual locking needs to
/// take place -- the mutable borrow statically guarantees no locks exist.
pub fn get_mut(&mut self) -> &mut T {
self.inner.get_mut()
}
}
impl<M: RawMutex, T> From<T> for RwLock<M, T> {
fn from(from: T) -> Self {
Self::new(from)
}
}
impl<M, T> Default for RwLock<M, T>
where
M: RawMutex,
T: Default,
{
fn default() -> Self {
Self::new(Default::default())
}
}
impl<M, T> fmt::Debug for RwLock<M, T>
where
M: RawMutex,
T: ?Sized + fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut d = f.debug_struct("RwLock");
match self.try_read() {
Ok(guard) => d.field("inner", &&*guard),
Err(TryLockError) => d.field("inner", &"Locked"),
}
.finish_non_exhaustive()
}
}
/// Async read lock guard.
///
/// Owning an instance of this type indicates having
/// successfully locked the read-write lock for reading, and grants access to the contents.
///
/// Dropping it unlocks the read-write lock.
#[clippy::has_significant_drop]
#[must_use = "if unused the RwLock will immediately unlock"]
pub struct RwLockReadGuard<'a, R, T>
where
R: RawMutex,
T: ?Sized,
{
rwlock: &'a RwLock<R, T>,
}
impl<'a, M, T> RwLockReadGuard<'a, M, T>
where
M: RawMutex,
T: ?Sized,
{
/// Map the contents of the `RwLockReadGuard` to a different type.
///
/// This is useful for calling methods on the contents of the `RwLockReadGuard` without
/// moving out of the guard.
pub fn map<U>(this: Self, fun: impl FnOnce(&T) -> &U) -> MappedRwLockReadGuard<'a, M, U> {
let rwlock = this.rwlock;
let value = fun(unsafe { &mut *this.rwlock.inner.get() });
mem::forget(this);
MappedRwLockReadGuard {
state: &rwlock.state,
value,
}
}
}
impl<'a, M, T> Drop for RwLockReadGuard<'a, M, T>
where
M: RawMutex,
T: ?Sized,
{
fn drop(&mut self) {
self.rwlock.state.lock(|s| {
let mut s = unwrap!(s.try_borrow_mut());
s.readers -= 1;
if s.readers == 0 {
s.waker.wake();
}
})
}
}
impl<'a, M, T> Deref for RwLockReadGuard<'a, M, T>
where
M: RawMutex,
T: ?Sized,
{
type Target = T;
fn deref(&self) -> &Self::Target {
// Safety: the RwLockReadGuard represents shared access to the contents
// of the read-write lock, so it's OK to get it.
unsafe { &*(self.rwlock.inner.get() as *const T) }
}
}
impl<'a, M, T> fmt::Debug for RwLockReadGuard<'a, M, T>
where
M: RawMutex,
T: ?Sized + fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
impl<'a, M, T> fmt::Display for RwLockReadGuard<'a, M, T>
where
M: RawMutex,
T: ?Sized + fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
/// Async write lock guard.
///
/// Owning an instance of this type indicates having
/// successfully locked the read-write lock for writing, and grants access to the contents.
///
/// Dropping it unlocks the read-write lock.
#[clippy::has_significant_drop]
#[must_use = "if unused the RwLock will immediately unlock"]
pub struct RwLockWriteGuard<'a, R, T>
where
R: RawMutex,
T: ?Sized,
{
rwlock: &'a RwLock<R, T>,
}
impl<'a, R, T> RwLockWriteGuard<'a, R, T>
where
R: RawMutex,
T: ?Sized,
{
/// Returns a locked view over a portion of the locked data.
pub fn map<U>(this: Self, fun: impl FnOnce(&mut T) -> &mut U) -> MappedRwLockWriteGuard<'a, R, U> {
let rwlock = this.rwlock;
let value = fun(unsafe { &mut *this.rwlock.inner.get() });
// Dont run the `drop` method for RwLockWriteGuard. The ownership of the underlying
// locked state is being moved to the returned MappedRwLockWriteGuard.
mem::forget(this);
MappedRwLockWriteGuard {
state: &rwlock.state,
value,
}
}
}
impl<'a, R, T> Drop for RwLockWriteGuard<'a, R, T>
where
R: RawMutex,
T: ?Sized,
{
fn drop(&mut self) {
self.rwlock.state.lock(|s| {
let mut s = unwrap!(s.try_borrow_mut());
s.writer = false;
s.waker.wake();
})
}
}
impl<'a, R, T> Deref for RwLockWriteGuard<'a, R, T>
where
R: RawMutex,
T: ?Sized,
{
type Target = T;
fn deref(&self) -> &Self::Target {
// Safety: the RwLockWriteGuard represents exclusive access to the contents
// of the read-write lock, so it's OK to get it.
unsafe { &*(self.rwlock.inner.get() as *mut T) }
}
}
impl<'a, R, T> DerefMut for RwLockWriteGuard<'a, R, T>
where
R: RawMutex,
T: ?Sized,
{
fn deref_mut(&mut self) -> &mut Self::Target {
// Safety: the RwLockWriteGuard represents exclusive access to the contents
// of the read-write lock, so it's OK to get it.
unsafe { &mut *(self.rwlock.inner.get()) }
}
}
impl<'a, R, T> fmt::Debug for RwLockWriteGuard<'a, R, T>
where
R: RawMutex,
T: ?Sized + fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
impl<'a, R, T> fmt::Display for RwLockWriteGuard<'a, R, T>
where
R: RawMutex,
T: ?Sized + fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
/// A handle to a held `RwLock` that has had a function applied to it via [`RwLockReadGuard::map`] or
/// [`MappedRwLockReadGuard::map`].
///
/// This can be used to hold a subfield of the protected data.
#[clippy::has_significant_drop]
pub struct MappedRwLockReadGuard<'a, M, T>
where
M: RawMutex,
T: ?Sized,
{
state: &'a BlockingMutex<M, RefCell<State>>,
value: *const T,
}
impl<'a, M, T> MappedRwLockReadGuard<'a, M, T>
where
M: RawMutex,
T: ?Sized,
{
/// Returns a locked view over a portion of the locked data.
pub fn map<U>(this: Self, fun: impl FnOnce(&T) -> &U) -> MappedRwLockReadGuard<'a, M, U> {
let rwlock = this.state;
let value = fun(unsafe { &*this.value });
// Dont run the `drop` method for RwLockReadGuard. The ownership of the underlying
// locked state is being moved to the returned MappedRwLockReadGuard.
mem::forget(this);
MappedRwLockReadGuard { state: rwlock, value }
}
}
impl<'a, M, T> Deref for MappedRwLockReadGuard<'a, M, T>
where
M: RawMutex,
T: ?Sized,
{
type Target = T;
fn deref(&self) -> &Self::Target {
// Safety: the MappedRwLockReadGuard represents shared access to the contents
// of the read-write lock, so it's OK to get it.
unsafe { &*self.value }
}
}
impl<'a, M, T> Drop for MappedRwLockReadGuard<'a, M, T>
where
M: RawMutex,
T: ?Sized,
{
fn drop(&mut self) {
self.state.lock(|s| {
let mut s = unwrap!(s.try_borrow_mut());
s.readers -= 1;
if s.readers == 0 {
s.waker.wake();
}
})
}
}
unsafe impl<'a, M, T> Send for MappedRwLockReadGuard<'a, M, T>
where
M: RawMutex,
T: ?Sized,
{
}
unsafe impl<'a, M, T> Sync for MappedRwLockReadGuard<'a, M, T>
where
M: RawMutex,
T: ?Sized,
{
}
impl<'a, M, T> fmt::Debug for MappedRwLockReadGuard<'a, M, T>
where
M: RawMutex,
T: ?Sized + fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
impl<'a, M, T> fmt::Display for MappedRwLockReadGuard<'a, M, T>
where
M: RawMutex,
T: ?Sized + fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
/// A handle to a held `RwLock` that has had a function applied to it via [`RwLockWriteGuard::map`] or
/// [`MappedRwLockWriteGuard::map`].
///
/// This can be used to hold a subfield of the protected data.
#[clippy::has_significant_drop]
pub struct MappedRwLockWriteGuard<'a, M, T>
where
M: RawMutex,
T: ?Sized,
{
state: &'a BlockingMutex<M, RefCell<State>>,
value: *mut T,
}
impl<'a, M, T> MappedRwLockWriteGuard<'a, M, T>
where
M: RawMutex,
T: ?Sized,
{
/// Returns a locked view over a portion of the locked data.
pub fn map<U>(this: Self, fun: impl FnOnce(&mut T) -> &mut U) -> MappedRwLockWriteGuard<'a, M, U> {
let rwlock = this.state;
let value = fun(unsafe { &mut *this.value });
// Dont run the `drop` method for RwLockWriteGuard. The ownership of the underlying
// locked state is being moved to the returned MappedRwLockWriteGuard.
mem::forget(this);
MappedRwLockWriteGuard { state: rwlock, value }
}
}
impl<'a, M, T> Deref for MappedRwLockWriteGuard<'a, M, T>
where
M: RawMutex,
T: ?Sized,
{
type Target = T;
fn deref(&self) -> &Self::Target {
// Safety: the MappedRwLockWriteGuard represents exclusive access to the contents
// of the read-write lock, so it's OK to get it.
unsafe { &*self.value }
}
}
impl<'a, M, T> DerefMut for MappedRwLockWriteGuard<'a, M, T>
where
M: RawMutex,
T: ?Sized,
{
fn deref_mut(&mut self) -> &mut Self::Target {
// Safety: the MappedRwLockWriteGuard represents exclusive access to the contents
// of the read-write lock, so it's OK to get it.
unsafe { &mut *self.value }
}
}
impl<'a, M, T> Drop for MappedRwLockWriteGuard<'a, M, T>
where
M: RawMutex,
T: ?Sized,
{
fn drop(&mut self) {
self.state.lock(|s| {
let mut s = unwrap!(s.try_borrow_mut());
s.writer = false;
s.waker.wake();
})
}
}
unsafe impl<'a, M, T> Send for MappedRwLockWriteGuard<'a, M, T>
where
M: RawMutex,
T: ?Sized,
{
}
unsafe impl<'a, M, T> Sync for MappedRwLockWriteGuard<'a, M, T>
where
M: RawMutex,
T: ?Sized,
{
}
impl<'a, M, T> fmt::Debug for MappedRwLockWriteGuard<'a, M, T>
where
M: RawMutex,
T: ?Sized + fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
impl<'a, M, T> fmt::Display for MappedRwLockWriteGuard<'a, M, T>
where
M: RawMutex,
T: ?Sized + fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
#[cfg(test)]
mod tests {
use crate::blocking_mutex::raw::NoopRawMutex;
use crate::rwlock::RwLock;
#[futures_test::test]
async fn read_guard_releases_lock_when_dropped() {
let rwlock: RwLock<NoopRawMutex, [i32; 2]> = RwLock::new([0, 1]);
{
let guard = rwlock.read().await;
assert_eq!(*guard, [0, 1]);
}
{
let guard = rwlock.read().await;
assert_eq!(*guard, [0, 1]);
}
assert_eq!(*rwlock.read().await, [0, 1]);
}
#[futures_test::test]
async fn write_guard_releases_lock_when_dropped() {
let rwlock: RwLock<NoopRawMutex, [i32; 2]> = RwLock::new([0, 1]);
{
let mut guard = rwlock.write().await;
assert_eq!(*guard, [0, 1]);
guard[1] = 2;
}
{
let guard = rwlock.read().await;
assert_eq!(*guard, [0, 2]);
}
assert_eq!(*rwlock.read().await, [0, 2]);
}
}
|