Debian Codegraph @

third_party/rust/lock_api/src/rwlock.rs

raw
1 // Copyright 2016 Amanieu d'Antras
2 //
3 // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4 // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5 // http://opensource.org/licenses/MIT>, at your option. This file may not be
6 // copied, modified, or distributed except according to those terms.
7
8 use core::cell::UnsafeCell;
9 use core::fmt;
10 use core::marker::PhantomData;
11 use core::mem;
12 use core::ops::{Deref, DerefMut};
13
14 #[cfg(feature = "arc_lock")]
15 use alloc::sync::Arc;
16 #[cfg(feature = "arc_lock")]
17 use core::mem::ManuallyDrop;
18 #[cfg(feature = "arc_lock")]
19 use core::ptr;
20
21 #[cfg(feature = "owning_ref")]
22 use owning_ref::StableAddress;
23
24 #[cfg(feature = "serde")]
25 use serde::{Deserialize, Deserializer, Serialize, Serializer};
26
27 /// Basic operations for a reader-writer lock.
28 ///
29 /// Types implementing this trait can be used by `RwLock` to form a safe and
30 /// fully-functioning `RwLock` type.
31 ///
32 /// # Safety
33 ///
34 /// Implementations of this trait must ensure that the `RwLock` is actually
35 /// exclusive: an exclusive lock can't be acquired while an exclusive or shared
36 /// lock exists, and a shared lock can't be acquire while an exclusive lock
37 /// exists.
38 pub unsafe trait RawRwLock {
39 /// Initial value for an unlocked `RwLock`.
40 // A “non-constant” const item is a legacy way to supply an initialized value to downstream
41 // static items. Can hopefully be replaced with `const fn new() -> Self` at some point.
42 #[allow(clippy::declare_interior_mutable_const)]
43 const INIT: Self;
44
45 /// Marker type which determines whether a lock guard should be `Send`. Use
46 /// one of the `GuardSend` or `GuardNoSend` helper types here.
47 type GuardMarker;
48
49 /// Acquires a shared lock, blocking the current thread until it is able to do so.
50 fn lock_shared(&self);
51
52 /// Attempts to acquire a shared lock without blocking.
53 fn try_lock_shared(&self) -> bool;
54
55 /// Releases a shared lock.
56 ///
57 /// # Safety
58 ///
59 /// This method may only be called if a shared lock is held in the current context.
60 unsafe fn unlock_shared(&self);
61
62 /// Acquires an exclusive lock, blocking the current thread until it is able to do so.
63 fn lock_exclusive(&self);
64
65 /// Attempts to acquire an exclusive lock without blocking.
66 fn try_lock_exclusive(&self) -> bool;
67
68 /// Releases an exclusive lock.
69 ///
70 /// # Safety
71 ///
72 /// This method may only be called if an exclusive lock is held in the current context.
73 unsafe fn unlock_exclusive(&self);
74
75 /// Checks if this `RwLock` is currently locked in any way.
76 #[inline]
77 fn is_locked(&self) -> bool {
78 let acquired_lock = self.try_lock_exclusive();
79 if acquired_lock {
80 // Safety: A lock was successfully acquired above.
81 unsafe {
82 self.unlock_exclusive();
83 }
84 }
85 !acquired_lock
86 }
87
88 /// Check if this `RwLock` is currently exclusively locked.
89 fn is_locked_exclusive(&self) -> bool {
90 let acquired_lock = self.try_lock_shared();
91 if acquired_lock {
92 // Safety: A shared lock was successfully acquired above.
93 unsafe {
94 self.unlock_shared();
95 }
96 }
97 !acquired_lock
98 }
99 }
100
101 /// Additional methods for RwLocks which support fair unlocking.
102 ///
103 /// Fair unlocking means that a lock is handed directly over to the next waiting
104 /// thread if there is one, without giving other threads the opportunity to
105 /// "steal" the lock in the meantime. This is typically slower than unfair
106 /// unlocking, but may be necessary in certain circumstances.
107 pub unsafe trait RawRwLockFair: RawRwLock {
108 /// Releases a shared lock using a fair unlock protocol.
109 ///
110 /// # Safety
111 ///
112 /// This method may only be called if a shared lock is held in the current context.
113 unsafe fn unlock_shared_fair(&self);
114
115 /// Releases an exclusive lock using a fair unlock protocol.
116 ///
117 /// # Safety
118 ///
119 /// This method may only be called if an exclusive lock is held in the current context.
120 unsafe fn unlock_exclusive_fair(&self);
121
122 /// Temporarily yields a shared lock to a waiting thread if there is one.
123 ///
124 /// This method is functionally equivalent to calling `unlock_shared_fair` followed
125 /// by `lock_shared`, however it can be much more efficient in the case where there
126 /// are no waiting threads.
127 ///
128 /// # Safety
129 ///
130 /// This method may only be called if a shared lock is held in the current context.
131 unsafe fn bump_shared(&self) {
132 self.unlock_shared_fair();
133 self.lock_shared();
134 }
135
136 /// Temporarily yields an exclusive lock to a waiting thread if there is one.
137 ///
138 /// This method is functionally equivalent to calling `unlock_exclusive_fair` followed
139 /// by `lock_exclusive`, however it can be much more efficient in the case where there
140 /// are no waiting threads.
141 ///
142 /// # Safety
143 ///
144 /// This method may only be called if an exclusive lock is held in the current context.
145 unsafe fn bump_exclusive(&self) {
146 self.unlock_exclusive_fair();
147 self.lock_exclusive();
148 }
149 }
150
151 /// Additional methods for RwLocks which support atomically downgrading an
152 /// exclusive lock to a shared lock.
153 pub unsafe trait RawRwLockDowngrade: RawRwLock {
154 /// Atomically downgrades an exclusive lock into a shared lock without
155 /// allowing any thread to take an exclusive lock in the meantime.
156 ///
157 /// # Safety
158 ///
159 /// This method may only be called if an exclusive lock is held in the current context.
160 unsafe fn downgrade(&self);
161 }
162
163 /// Additional methods for RwLocks which support locking with timeouts.
164 ///
165 /// The `Duration` and `Instant` types are specified as associated types so that
166 /// this trait is usable even in `no_std` environments.
167 pub unsafe trait RawRwLockTimed: RawRwLock {
168 /// Duration type used for `try_lock_for`.
169 type Duration;
170
171 /// Instant type used for `try_lock_until`.
172 type Instant;
173
174 /// Attempts to acquire a shared lock until a timeout is reached.
175 fn try_lock_shared_for(&self, timeout: Self::Duration) -> bool;
176
177 /// Attempts to acquire a shared lock until a timeout is reached.
178 fn try_lock_shared_until(&self, timeout: Self::Instant) -> bool;
179
180 /// Attempts to acquire an exclusive lock until a timeout is reached.
181 fn try_lock_exclusive_for(&self, timeout: Self::Duration) -> bool;
182
183 /// Attempts to acquire an exclusive lock until a timeout is reached.
184 fn try_lock_exclusive_until(&self, timeout: Self::Instant) -> bool;
185 }
186
187 /// Additional methods for RwLocks which support recursive read locks.
188 ///
189 /// These are guaranteed to succeed without blocking if
190 /// another read lock is held at the time of the call. This allows a thread
191 /// to recursively lock a `RwLock`. However using this method can cause
192 /// writers to starve since readers no longer block if a writer is waiting
193 /// for the lock.
194 pub unsafe trait RawRwLockRecursive: RawRwLock {
195 /// Acquires a shared lock without deadlocking in case of a recursive lock.
196 fn lock_shared_recursive(&self);
197
198 /// Attempts to acquire a shared lock without deadlocking in case of a recursive lock.
199 fn try_lock_shared_recursive(&self) -> bool;
200 }
201
202 /// Additional methods for RwLocks which support recursive read locks and timeouts.
203 pub unsafe trait RawRwLockRecursiveTimed: RawRwLockRecursive + RawRwLockTimed {
204 /// Attempts to acquire a shared lock until a timeout is reached, without
205 /// deadlocking in case of a recursive lock.
206 fn try_lock_shared_recursive_for(&self, timeout: Self::Duration) -> bool;
207
208 /// Attempts to acquire a shared lock until a timeout is reached, without
209 /// deadlocking in case of a recursive lock.
210 fn try_lock_shared_recursive_until(&self, timeout: Self::Instant) -> bool;
211 }
212
213 /// Additional methods for RwLocks which support atomically upgrading a shared
214 /// lock to an exclusive lock.
215 ///
216 /// This requires acquiring a special "upgradable read lock" instead of a
217 /// normal shared lock. There may only be one upgradable lock at any time,
218 /// otherwise deadlocks could occur when upgrading.
219 pub unsafe trait RawRwLockUpgrade: RawRwLock {
220 /// Acquires an upgradable lock, blocking the current thread until it is able to do so.
221 fn lock_upgradable(&self);
222
223 /// Attempts to acquire an upgradable lock without blocking.
224 fn try_lock_upgradable(&self) -> bool;
225
226 /// Releases an upgradable lock.
227 ///
228 /// # Safety
229 ///
230 /// This method may only be called if an upgradable lock is held in the current context.
231 unsafe fn unlock_upgradable(&self);
232
233 /// Upgrades an upgradable lock to an exclusive lock.
234 ///
235 /// # Safety
236 ///
237 /// This method may only be called if an upgradable lock is held in the current context.
238 unsafe fn upgrade(&self);
239
240 /// Attempts to upgrade an upgradable lock to an exclusive lock without
241 /// blocking.
242 ///
243 /// # Safety
244 ///
245 /// This method may only be called if an upgradable lock is held in the current context.
246 unsafe fn try_upgrade(&self) -> bool;
247 }
248
249 /// Additional methods for RwLocks which support upgradable locks and fair
250 /// unlocking.
251 pub unsafe trait RawRwLockUpgradeFair: RawRwLockUpgrade + RawRwLockFair {
252 /// Releases an upgradable lock using a fair unlock protocol.
253 ///
254 /// # Safety
255 ///
256 /// This method may only be called if an upgradable lock is held in the current context.
257 unsafe fn unlock_upgradable_fair(&self);
258
259 /// Temporarily yields an upgradable lock to a waiting thread if there is one.
260 ///
261 /// This method is functionally equivalent to calling `unlock_upgradable_fair` followed
262 /// by `lock_upgradable`, however it can be much more efficient in the case where there
263 /// are no waiting threads.
264 ///
265 /// # Safety
266 ///
267 /// This method may only be called if an upgradable lock is held in the current context.
268 unsafe fn bump_upgradable(&self) {
269 self.unlock_upgradable_fair();
270 self.lock_upgradable();
271 }
272 }
273
274 /// Additional methods for RwLocks which support upgradable locks and lock
275 /// downgrading.
276 pub unsafe trait RawRwLockUpgradeDowngrade: RawRwLockUpgrade + RawRwLockDowngrade {
277 /// Downgrades an upgradable lock to a shared lock.
278 ///
279 /// # Safety
280 ///
281 /// This method may only be called if an upgradable lock is held in the current context.
282 unsafe fn downgrade_upgradable(&self);
283
284 /// Downgrades an exclusive lock to an upgradable lock.
285 ///
286 /// # Safety
287 ///
288 /// This method may only be called if an exclusive lock is held in the current context.
289 unsafe fn downgrade_to_upgradable(&self);
290 }
291
292 /// Additional methods for RwLocks which support upgradable locks and locking
293 /// with timeouts.
294 pub unsafe trait RawRwLockUpgradeTimed: RawRwLockUpgrade + RawRwLockTimed {
295 /// Attempts to acquire an upgradable lock until a timeout is reached.
296 fn try_lock_upgradable_for(&self, timeout: Self::Duration) -> bool;
297
298 /// Attempts to acquire an upgradable lock until a timeout is reached.
299 fn try_lock_upgradable_until(&self, timeout: Self::Instant) -> bool;
300
301 /// Attempts to upgrade an upgradable lock to an exclusive lock until a
302 /// timeout is reached.
303 ///
304 /// # Safety
305 ///
306 /// This method may only be called if an upgradable lock is held in the current context.
307 unsafe fn try_upgrade_for(&self, timeout: Self::Duration) -> bool;
308
309 /// Attempts to upgrade an upgradable lock to an exclusive lock until a
310 /// timeout is reached.
311 ///
312 /// # Safety
313 ///
314 /// This method may only be called if an upgradable lock is held in the current context.
315 unsafe fn try_upgrade_until(&self, timeout: Self::Instant) -> bool;
316 }
317
318 /// A reader-writer lock
319 ///
320 /// This type of lock allows a number of readers or at most one writer at any
321 /// point in time. The write portion of this lock typically allows modification
322 /// of the underlying data (exclusive access) and the read portion of this lock
323 /// typically allows for read-only access (shared access).
324 ///
325 /// The type parameter `T` represents the data that this lock protects. It is
326 /// required that `T` satisfies `Send` to be shared across threads and `Sync` to
327 /// allow concurrent access through readers. The RAII guards returned from the
328 /// locking methods implement `Deref` (and `DerefMut` for the `write` methods)
329 /// to allow access to the contained of the lock.
330 pub struct RwLock<R, T: ?Sized> {
331 raw: R,
332 data: UnsafeCell<T>,
333 }
334
335 // Copied and modified from serde
336 #[cfg(feature = "serde")]
337 impl<R, T> Serialize for RwLock<R, T>
338 where
339 R: RawRwLock,
340 T: Serialize + ?Sized,
341 {
342 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
343 where
344 S: Serializer,
345 {
346 self.read().serialize(serializer)
347 }
348 }
349
350 #[cfg(feature = "serde")]
351 impl<'de, R, T> Deserialize<'de> for RwLock<R, T>
352 where
353 R: RawRwLock,
354 T: Deserialize<'de> + ?Sized,
355 {
356 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
357 where
358 D: Deserializer<'de>,
359 {
360 Deserialize::deserialize(deserializer).map(RwLock::new)
361 }
362 }
363
364 unsafe impl<R: RawRwLock + Send, T: ?Sized + Send> Send for RwLock<R, T> {}
365 unsafe impl<R: RawRwLock + Sync, T: ?Sized + Send + Sync> Sync for RwLock<R, T> {}
366
367 impl<R: RawRwLock, T> RwLock<R, T> {
368 /// Creates a new instance of an `RwLock<T>` which is unlocked.
369 #[cfg(has_const_fn_trait_bound)]
370 #[inline]
371 pub const fn new(val: T) -> RwLock<R, T> {
372 RwLock {
373 data: UnsafeCell::new(val),
374 raw: R::INIT,
375 }
376 }
377
378 /// Creates a new instance of an `RwLock<T>` which is unlocked.
379 #[cfg(not(has_const_fn_trait_bound))]
380 #[inline]
381 pub fn new(val: T) -> RwLock<R, T> {
382 RwLock {
383 data: UnsafeCell::new(val),
384 raw: R::INIT,
385 }
386 }
387
388 /// Consumes this `RwLock`, returning the underlying data.
389 #[inline]
390 #[allow(unused_unsafe)]
391 pub fn into_inner(self) -> T {
392 unsafe { self.data.into_inner() }
393 }
394 }
395
396 impl<R, T> RwLock<R, T> {
397 /// Creates a new new instance of an `RwLock<T>` based on a pre-existing
398 /// `RawRwLock<T>`.
399 ///
400 /// This allows creating a `RwLock<T>` in a constant context on stable
401 /// Rust.
402 #[inline]
403 pub const fn const_new(raw_rwlock: R, val: T) -> RwLock<R, T> {
404 RwLock {
405 data: UnsafeCell::new(val),
406 raw: raw_rwlock,
407 }
408 }
409 }
410
411 impl<R: RawRwLock, T: ?Sized> RwLock<R, T> {
412 /// # Safety
413 ///
414 /// The lock must be held when calling this method.
415 #[inline]
416 unsafe fn read_guard(&self) -> RwLockReadGuard<'_, R, T> {
417 RwLockReadGuard {
418 rwlock: self,
419 marker: PhantomData,
420 }
421 }
422
423 /// # Safety
424 ///
425 /// The lock must be held when calling this method.
426 #[inline]
427 unsafe fn write_guard(&self) -> RwLockWriteGuard<'_, R, T> {
428 RwLockWriteGuard {
429 rwlock: self,
430 marker: PhantomData,
431 }
432 }
433
434 /// Locks this `RwLock` with shared read access, blocking the current thread
435 /// until it can be acquired.
436 ///
437 /// The calling thread will be blocked until there are no more writers which
438 /// hold the lock. There may be other readers currently inside the lock when
439 /// this method returns.
440 ///
441 /// Note that attempts to recursively acquire a read lock on a `RwLock` when
442 /// the current thread already holds one may result in a deadlock.
443 ///
444 /// Returns an RAII guard which will release this thread's shared access
445 /// once it is dropped.
446 #[inline]
447 pub fn read(&self) -> RwLockReadGuard<'_, R, T> {
448 self.raw.lock_shared();
449 // SAFETY: The lock is held, as required.
450 unsafe { self.read_guard() }
451 }
452
453 /// Attempts to acquire this `RwLock` with shared read access.
454 ///
455 /// If the access could not be granted at this time, then `None` is returned.
456 /// Otherwise, an RAII guard is returned which will release the shared access
457 /// when it is dropped.
458 ///
459 /// This function does not block.
460 #[inline]
461 pub fn try_read(&self) -> Option<RwLockReadGuard<'_, R, T>> {
462 if self.raw.try_lock_shared() {
463 // SAFETY: The lock is held, as required.
464 Some(unsafe { self.read_guard() })
465 } else {
466 None
467 }
468 }
469
470 /// Locks this `RwLock` with exclusive write access, blocking the current
471 /// thread until it can be acquired.
472 ///
473 /// This function will not return while other writers or other readers
474 /// currently have access to the lock.
475 ///
476 /// Returns an RAII guard which will drop the write access of this `RwLock`
477 /// when dropped.
478 #[inline]
479 pub fn write(&self) -> RwLockWriteGuard<'_, R, T> {
480 self.raw.lock_exclusive();
481 // SAFETY: The lock is held, as required.
482 unsafe { self.write_guard() }
483 }
484
485 /// Attempts to lock this `RwLock` with exclusive write access.
486 ///
487 /// If the lock could not be acquired at this time, then `None` is returned.
488 /// Otherwise, an RAII guard is returned which will release the lock when
489 /// it is dropped.
490 ///
491 /// This function does not block.
492 #[inline]
493 pub fn try_write(&self) -> Option<RwLockWriteGuard<'_, R, T>> {
494 if self.raw.try_lock_exclusive() {
495 // SAFETY: The lock is held, as required.
496 Some(unsafe { self.write_guard() })
497 } else {
498 None
499 }
500 }
501
502 /// Returns a mutable reference to the underlying data.
503 ///
504 /// Since this call borrows the `RwLock` mutably, no actual locking needs to
505 /// take place---the mutable borrow statically guarantees no locks exist.
506 #[inline]
507 pub fn get_mut(&mut self) -> &mut T {
508 unsafe { &mut *self.data.get() }
509 }
510
511 /// Checks whether this `RwLock` is currently locked in any way.
512 #[inline]
513 pub fn is_locked(&self) -> bool {
514 self.raw.is_locked()
515 }
516
517 /// Check if this `RwLock` is currently exclusively locked.
518 #[inline]
519 pub fn is_locked_exclusive(&self) -> bool {
520 self.raw.is_locked_exclusive()
521 }
522
523 /// Forcibly unlocks a read lock.
524 ///
525 /// This is useful when combined with `mem::forget` to hold a lock without
526 /// the need to maintain a `RwLockReadGuard` object alive, for example when
527 /// dealing with FFI.
528 ///
529 /// # Safety
530 ///
531 /// This method must only be called if the current thread logically owns a
532 /// `RwLockReadGuard` but that guard has be discarded using `mem::forget`.
533 /// Behavior is undefined if a rwlock is read-unlocked when not read-locked.
534 #[inline]
535 pub unsafe fn force_unlock_read(&self) {
536 self.raw.unlock_shared();
537 }
538
539 /// Forcibly unlocks a write lock.
540 ///
541 /// This is useful when combined with `mem::forget` to hold a lock without
542 /// the need to maintain a `RwLockWriteGuard` object alive, for example when
543 /// dealing with FFI.
544 ///
545 /// # Safety
546 ///
547 /// This method must only be called if the current thread logically owns a
548 /// `RwLockWriteGuard` but that guard has be discarded using `mem::forget`.
549 /// Behavior is undefined if a rwlock is write-unlocked when not write-locked.
550 #[inline]
551 pub unsafe fn force_unlock_write(&self) {
552 self.raw.unlock_exclusive();
553 }
554
555 /// Returns the underlying raw reader-writer lock object.
556 ///
557 /// Note that you will most likely need to import the `RawRwLock` trait from
558 /// `lock_api` to be able to call functions on the raw
559 /// reader-writer lock.
560 ///
561 /// # Safety
562 ///
563 /// This method is unsafe because it allows unlocking a mutex while
564 /// still holding a reference to a lock guard.
565 pub unsafe fn raw(&self) -> &R {
566 &self.raw
567 }
568
569 /// Returns a raw pointer to the underlying data.
570 ///
571 /// This is useful when combined with `mem::forget` to hold a lock without
572 /// the need to maintain a `RwLockReadGuard` or `RwLockWriteGuard` object
573 /// alive, for example when dealing with FFI.
574 ///
575 /// # Safety
576 ///
577 /// You must ensure that there are no data races when dereferencing the
578 /// returned pointer, for example if the current thread logically owns a
579 /// `RwLockReadGuard` or `RwLockWriteGuard` but that guard has been discarded
580 /// using `mem::forget`.
581 #[inline]
582 pub fn data_ptr(&self) -> *mut T {
583 self.data.get()
584 }
585
586 /// # Safety
587 ///
588 /// The lock must be held when calling this method.
589 #[cfg(feature = "arc_lock")]
590 #[inline]
591 unsafe fn read_guard_arc(self: &Arc<Self>) -> ArcRwLockReadGuard<R, T> {
592 ArcRwLockReadGuard {
593 rwlock: self.clone(),
594 marker: PhantomData,
595 }
596 }
597
598 /// # Safety
599 ///
600 /// The lock must be held when calling this method.
601 #[cfg(feature = "arc_lock")]
602 #[inline]
603 unsafe fn write_guard_arc(self: &Arc<Self>) -> ArcRwLockWriteGuard<R, T> {
604 ArcRwLockWriteGuard {
605 rwlock: self.clone(),
606 marker: PhantomData,
607 }
608 }
609
610 /// Locks this `RwLock` with read access, through an `Arc`.
611 ///
612 /// This method is similar to the `read` method; however, it requires the `RwLock` to be inside of an `Arc`
613 /// and the resulting read guard has no lifetime requirements.
614 #[cfg(feature = "arc_lock")]
615 #[inline]
616 pub fn read_arc(self: &Arc<Self>) -> ArcRwLockReadGuard<R, T> {
617 self.raw.lock_shared();
618 // SAFETY: locking guarantee is upheld
619 unsafe { self.read_guard_arc() }
620 }
621
622 /// Attempts to lock this `RwLock` with read access, through an `Arc`.
623 ///
624 /// This method is similar to the `try_read` method; however, it requires the `RwLock` to be inside of an
625 /// `Arc` and the resulting read guard has no lifetime requirements.
626 #[cfg(feature = "arc_lock")]
627 #[inline]
628 pub fn try_read_arc(self: &Arc<Self>) -> Option<ArcRwLockReadGuard<R, T>> {
629 if self.raw.try_lock_shared() {
630 // SAFETY: locking guarantee is upheld
631 Some(unsafe { self.read_guard_arc() })
632 } else {
633 None
634 }
635 }
636
637 /// Locks this `RwLock` with write access, through an `Arc`.
638 ///
639 /// This method is similar to the `write` method; however, it requires the `RwLock` to be inside of an `Arc`
640 /// and the resulting write guard has no lifetime requirements.
641 #[cfg(feature = "arc_lock")]
642 #[inline]
643 pub fn write_arc(self: &Arc<Self>) -> ArcRwLockWriteGuard<R, T> {
644 self.raw.lock_exclusive();
645 // SAFETY: locking guarantee is upheld
646 unsafe { self.write_guard_arc() }
647 }
648
649 /// Attempts to lock this `RwLock` with writ access, through an `Arc`.
650 ///
651 /// This method is similar to the `try_write` method; however, it requires the `RwLock` to be inside of an
652 /// `Arc` and the resulting write guard has no lifetime requirements.
653 #[cfg(feature = "arc_lock")]
654 #[inline]
655 pub fn try_write_arc(self: &Arc<Self>) -> Option<ArcRwLockWriteGuard<R, T>> {
656 if self.raw.try_lock_exclusive() {
657 // SAFETY: locking guarantee is upheld
658 Some(unsafe { self.write_guard_arc() })
659 } else {
660 None
661 }
662 }
663 }
664
665 impl<R: RawRwLockFair, T: ?Sized> RwLock<R, T> {
666 /// Forcibly unlocks a read lock using a fair unlock procotol.
667 ///
668 /// This is useful when combined with `mem::forget` to hold a lock without
669 /// the need to maintain a `RwLockReadGuard` object alive, for example when
670 /// dealing with FFI.
671 ///
672 /// # Safety
673 ///
674 /// This method must only be called if the current thread logically owns a
675 /// `RwLockReadGuard` but that guard has be discarded using `mem::forget`.
676 /// Behavior is undefined if a rwlock is read-unlocked when not read-locked.
677 #[inline]
678 pub unsafe fn force_unlock_read_fair(&self) {
679 self.raw.unlock_shared_fair();
680 }
681
682 /// Forcibly unlocks a write lock using a fair unlock procotol.
683 ///
684 /// This is useful when combined with `mem::forget` to hold a lock without
685 /// the need to maintain a `RwLockWriteGuard` object alive, for example when
686 /// dealing with FFI.
687 ///
688 /// # Safety
689 ///
690 /// This method must only be called if the current thread logically owns a
691 /// `RwLockWriteGuard` but that guard has be discarded using `mem::forget`.
692 /// Behavior is undefined if a rwlock is write-unlocked when not write-locked.
693 #[inline]
694 pub unsafe fn force_unlock_write_fair(&self) {
695 self.raw.unlock_exclusive_fair();
696 }
697 }
698
699 impl<R: RawRwLockTimed, T: ?Sized> RwLock<R, T> {
700 /// Attempts to acquire this `RwLock` with shared read access until a timeout
701 /// is reached.
702 ///
703 /// If the access could not be granted before the timeout expires, then
704 /// `None` is returned. Otherwise, an RAII guard is returned which will
705 /// release the shared access when it is dropped.
706 #[inline]
707 pub fn try_read_for(&self, timeout: R::Duration) -> Option<RwLockReadGuard<'_, R, T>> {
708 if self.raw.try_lock_shared_for(timeout) {
709 // SAFETY: The lock is held, as required.
710 Some(unsafe { self.read_guard() })
711 } else {
712 None
713 }
714 }
715
716 /// Attempts to acquire this `RwLock` with shared read access until a timeout
717 /// is reached.
718 ///
719 /// If the access could not be granted before the timeout expires, then
720 /// `None` is returned. Otherwise, an RAII guard is returned which will
721 /// release the shared access when it is dropped.
722 #[inline]
723 pub fn try_read_until(&self, timeout: R::Instant) -> Option<RwLockReadGuard<'_, R, T>> {
724 if self.raw.try_lock_shared_until(timeout) {
725 // SAFETY: The lock is held, as required.
726 Some(unsafe { self.read_guard() })
727 } else {
728 None
729 }
730 }
731
732 /// Attempts to acquire this `RwLock` with exclusive write access until a
733 /// timeout is reached.
734 ///
735 /// If the access could not be granted before the timeout expires, then
736 /// `None` is returned. Otherwise, an RAII guard is returned which will
737 /// release the exclusive access when it is dropped.
738 #[inline]
739 pub fn try_write_for(&self, timeout: R::Duration) -> Option<RwLockWriteGuard<'_, R, T>> {
740 if self.raw.try_lock_exclusive_for(timeout) {
741 // SAFETY: The lock is held, as required.
742 Some(unsafe { self.write_guard() })
743 } else {
744 None
745 }
746 }
747
748 /// Attempts to acquire this `RwLock` with exclusive write access until a
749 /// timeout is reached.
750 ///
751 /// If the access could not be granted before the timeout expires, then
752 /// `None` is returned. Otherwise, an RAII guard is returned which will
753 /// release the exclusive access when it is dropped.
754 #[inline]
755 pub fn try_write_until(&self, timeout: R::Instant) -> Option<RwLockWriteGuard<'_, R, T>> {
756 if self.raw.try_lock_exclusive_until(timeout) {
757 // SAFETY: The lock is held, as required.
758 Some(unsafe { self.write_guard() })
759 } else {
760 None
761 }
762 }
763
764 /// Attempts to acquire this `RwLock` with read access until a timeout is reached, through an `Arc`.
765 ///
766 /// This method is similar to the `try_read_for` method; however, it requires the `RwLock` to be inside of an
767 /// `Arc` and the resulting read guard has no lifetime requirements.
768 #[cfg(feature = "arc_lock")]
769 #[inline]
770 pub fn try_read_arc_for(
771 self: &Arc<Self>,
772 timeout: R::Duration,
773 ) -> Option<ArcRwLockReadGuard<R, T>> {
774 if self.raw.try_lock_shared_for(timeout) {
775 // SAFETY: locking guarantee is upheld
776 Some(unsafe { self.read_guard_arc() })
777 } else {
778 None
779 }
780 }
781
782 /// Attempts to acquire this `RwLock` with read access until a timeout is reached, through an `Arc`.
783 ///
784 /// This method is similar to the `try_read_until` method; however, it requires the `RwLock` to be inside of
785 /// an `Arc` and the resulting read guard has no lifetime requirements.
786 #[cfg(feature = "arc_lock")]
787 #[inline]
788 pub fn try_read_arc_until(
789 self: &Arc<Self>,
790 timeout: R::Instant,
791 ) -> Option<ArcRwLockReadGuard<R, T>> {
792 if self.raw.try_lock_shared_until(timeout) {
793 // SAFETY: locking guarantee is upheld
794 Some(unsafe { self.read_guard_arc() })
795 } else {
796 None
797 }
798 }
799
800 /// Attempts to acquire this `RwLock` with write access until a timeout is reached, through an `Arc`.
801 ///
802 /// This method is similar to the `try_write_for` method; however, it requires the `RwLock` to be inside of
803 /// an `Arc` and the resulting write guard has no lifetime requirements.
804 #[cfg(feature = "arc_lock")]
805 #[inline]
806 pub fn try_write_arc_for(
807 self: &Arc<Self>,
808 timeout: R::Duration,
809 ) -> Option<ArcRwLockWriteGuard<R, T>> {
810 if self.raw.try_lock_exclusive_for(timeout) {
811 // SAFETY: locking guarantee is upheld
812 Some(unsafe { self.write_guard_arc() })
813 } else {
814 None
815 }
816 }
817
818 /// Attempts to acquire this `RwLock` with read access until a timeout is reached, through an `Arc`.
819 ///
820 /// This method is similar to the `try_write_until` method; however, it requires the `RwLock` to be inside of
821 /// an `Arc` and the resulting read guard has no lifetime requirements.
822 #[cfg(feature = "arc_lock")]
823 #[inline]
824 pub fn try_write_arc_until(
825 self: &Arc<Self>,
826 timeout: R::Instant,
827 ) -> Option<ArcRwLockWriteGuard<R, T>> {
828 if self.raw.try_lock_exclusive_until(timeout) {
829 // SAFETY: locking guarantee is upheld
830 Some(unsafe { self.write_guard_arc() })
831 } else {
832 None
833 }
834 }
835 }
836
837 impl<R: RawRwLockRecursive, T: ?Sized> RwLock<R, T> {
838 /// Locks this `RwLock` with shared read access, blocking the current thread
839 /// until it can be acquired.
840 ///
841 /// The calling thread will be blocked until there are no more writers which
842 /// hold the lock. There may be other readers currently inside the lock when
843 /// this method returns.
844 ///
845 /// Unlike `read`, this method is guaranteed to succeed without blocking if
846 /// another read lock is held at the time of the call. This allows a thread
847 /// to recursively lock a `RwLock`. However using this method can cause
848 /// writers to starve since readers no longer block if a writer is waiting
849 /// for the lock.
850 ///
851 /// Returns an RAII guard which will release this thread's shared access
852 /// once it is dropped.
853 #[inline]
854 pub fn read_recursive(&self) -> RwLockReadGuard<'_, R, T> {
855 self.raw.lock_shared_recursive();
856 // SAFETY: The lock is held, as required.
857 unsafe { self.read_guard() }
858 }
859
860 /// Attempts to acquire this `RwLock` with shared read access.
861 ///
862 /// If the access could not be granted at this time, then `None` is returned.
863 /// Otherwise, an RAII guard is returned which will release the shared access
864 /// when it is dropped.
865 ///
866 /// This method is guaranteed to succeed if another read lock is held at the
867 /// time of the call. See the documentation for `read_recursive` for details.
868 ///
869 /// This function does not block.
870 #[inline]
871 pub fn try_read_recursive(&self) -> Option<RwLockReadGuard<'_, R, T>> {
872 if self.raw.try_lock_shared_recursive() {
873 // SAFETY: The lock is held, as required.
874 Some(unsafe { self.read_guard() })
875 } else {
876 None
877 }
878 }
879
880 /// Locks this `RwLock` with shared read access, through an `Arc`.
881 ///
882 /// This method is similar to the `read_recursive` method; however, it requires the `RwLock` to be inside of
883 /// an `Arc` and the resulting read guard has no lifetime requirements.
884 #[cfg(feature = "arc_lock")]
885 #[inline]
886 pub fn read_arc_recursive(self: &Arc<Self>) -> ArcRwLockReadGuard<R, T> {
887 self.raw.lock_shared_recursive();
888 // SAFETY: locking guarantee is upheld
889 unsafe { self.read_guard_arc() }
890 }
891
892 /// Attempts to lock this `RwLock` with shared read access, through an `Arc`.
893 ///
894 /// This method is similar to the `try_read_recursive` method; however, it requires the `RwLock` to be inside
895 /// of an `Arc` and the resulting read guard has no lifetime requirements.
896 #[cfg(feature = "arc_lock")]
897 #[inline]
898 pub fn try_read_recursive_arc(self: &Arc<Self>) -> Option<ArcRwLockReadGuard<R, T>> {
899 if self.raw.try_lock_shared_recursive() {
900 // SAFETY: locking guarantee is upheld
901 Some(unsafe { self.read_guard_arc() })
902 } else {
903 None
904 }
905 }
906 }
907
908 impl<R: RawRwLockRecursiveTimed, T: ?Sized> RwLock<R, T> {
909 /// Attempts to acquire this `RwLock` with shared read access until a timeout
910 /// is reached.
911 ///
912 /// If the access could not be granted before the timeout expires, then
913 /// `None` is returned. Otherwise, an RAII guard is returned which will
914 /// release the shared access when it is dropped.
915 ///
916 /// This method is guaranteed to succeed without blocking if another read
917 /// lock is held at the time of the call. See the documentation for
918 /// `read_recursive` for details.
919 #[inline]
920 pub fn try_read_recursive_for(
921 &self,
922 timeout: R::Duration,
923 ) -> Option<RwLockReadGuard<'_, R, T>> {
924 if self.raw.try_lock_shared_recursive_for(timeout) {
925 // SAFETY: The lock is held, as required.
926 Some(unsafe { self.read_guard() })
927 } else {
928 None
929 }
930 }
931
932 /// Attempts to acquire this `RwLock` with shared read access until a timeout
933 /// is reached.
934 ///
935 /// If the access could not be granted before the timeout expires, then
936 /// `None` is returned. Otherwise, an RAII guard is returned which will
937 /// release the shared access when it is dropped.
938 #[inline]
939 pub fn try_read_recursive_until(
940 &self,
941 timeout: R::Instant,
942 ) -> Option<RwLockReadGuard<'_, R, T>> {
943 if self.raw.try_lock_shared_recursive_until(timeout) {
944 // SAFETY: The lock is held, as required.
945 Some(unsafe { self.read_guard() })
946 } else {
947 None
948 }
949 }
950
951 /// Attempts to lock this `RwLock` with read access until a timeout is reached, through an `Arc`.
952 ///
953 /// This method is similar to the `try_read_recursive_for` method; however, it requires the `RwLock` to be
954 /// inside of an `Arc` and the resulting read guard has no lifetime requirements.
955 #[cfg(feature = "arc_lock")]
956 #[inline]
957 pub fn try_read_arc_recursive_for(
958 self: &Arc<Self>,
959 timeout: R::Duration,
960 ) -> Option<ArcRwLockReadGuard<R, T>> {
961 if self.raw.try_lock_shared_recursive_for(timeout) {
962 // SAFETY: locking guarantee is upheld
963 Some(unsafe { self.read_guard_arc() })
964 } else {
965 None
966 }
967 }
968
969 /// Attempts to lock this `RwLock` with read access until a timeout is reached, through an `Arc`.
970 ///
971 /// This method is similar to the `try_read_recursive_until` method; however, it requires the `RwLock` to be
972 /// inside of an `Arc` and the resulting read guard has no lifetime requirements.
973 #[cfg(feature = "arc_lock")]
974 #[inline]
975 pub fn try_read_arc_recursive_until(
976 self: &Arc<Self>,
977 timeout: R::Instant,
978 ) -> Option<ArcRwLockReadGuard<R, T>> {
979 if self.raw.try_lock_shared_recursive_until(timeout) {
980 // SAFETY: locking guarantee is upheld
981 Some(unsafe { self.read_guard_arc() })
982 } else {
983 None
984 }
985 }
986 }
987
988 impl<R: RawRwLockUpgrade, T: ?Sized> RwLock<R, T> {
989 /// # Safety
990 ///
991 /// The lock must be held when calling this method.
992 #[inline]
993 unsafe fn upgradable_guard(&self) -> RwLockUpgradableReadGuard<'_, R, T> {
994 RwLockUpgradableReadGuard {
995 rwlock: self,
996 marker: PhantomData,
997 }
998 }
999
1000 /// Locks this `RwLock` with upgradable read access, blocking the current thread
1001 /// until it can be acquired.
1002 ///
1003 /// The calling thread will be blocked until there are no more writers or other
1004 /// upgradable reads which hold the lock. There may be other readers currently
1005 /// inside the lock when this method returns.
1006 ///
1007 /// Returns an RAII guard which will release this thread's shared access
1008 /// once it is dropped.
1009 #[inline]
1010 pub fn upgradable_read(&self) -> RwLockUpgradableReadGuard<'_, R, T> {
1011 self.raw.lock_upgradable();
1012 // SAFETY: The lock is held, as required.
1013 unsafe { self.upgradable_guard() }
1014 }
1015
1016 /// Attempts to acquire this `RwLock` with upgradable read access.
1017 ///
1018 /// If the access could not be granted at this time, then `None` is returned.
1019 /// Otherwise, an RAII guard is returned which will release the shared access
1020 /// when it is dropped.
1021 ///
1022 /// This function does not block.
1023 #[inline]
1024 pub fn try_upgradable_read(&self) -> Option<RwLockUpgradableReadGuard<'_, R, T>> {
1025 if self.raw.try_lock_upgradable() {
1026 // SAFETY: The lock is held, as required.
1027 Some(unsafe { self.upgradable_guard() })
1028 } else {
1029 None
1030 }
1031 }
1032
1033 /// # Safety
1034 ///
1035 /// The lock must be held when calling this method.
1036 #[cfg(feature = "arc_lock")]
1037 #[inline]
1038 unsafe fn upgradable_guard_arc(self: &Arc<Self>) -> ArcRwLockUpgradableReadGuard<R, T> {
1039 ArcRwLockUpgradableReadGuard {
1040 rwlock: self.clone(),
1041 marker: PhantomData,
1042 }
1043 }
1044
1045 /// Locks this `RwLock` with upgradable read access, through an `Arc`.
1046 ///
1047 /// This method is similar to the `upgradable_read` method; however, it requires the `RwLock` to be
1048 /// inside of an `Arc` and the resulting read guard has no lifetime requirements.
1049 #[cfg(feature = "arc_lock")]
1050 #[inline]
1051 pub fn upgradable_read_arc(self: &Arc<Self>) -> ArcRwLockUpgradableReadGuard<R, T> {
1052 self.raw.lock_upgradable();
1053 // SAFETY: locking guarantee is upheld
1054 unsafe { self.upgradable_guard_arc() }
1055 }
1056
1057 /// Attempts to lock this `RwLock` with upgradable read access, through an `Arc`.
1058 ///
1059 /// This method is similar to the `try_upgradable_read` method; however, it requires the `RwLock` to be
1060 /// inside of an `Arc` and the resulting read guard has no lifetime requirements.
1061 #[cfg(feature = "arc_lock")]
1062 #[inline]
1063 pub fn try_upgradable_read_arc(self: &Arc<Self>) -> Option<ArcRwLockUpgradableReadGuard<R, T>> {
1064 if self.raw.try_lock_upgradable() {
1065 // SAFETY: locking guarantee is upheld
1066 Some(unsafe { self.upgradable_guard_arc() })
1067 } else {
1068 None
1069 }
1070 }
1071 }
1072
1073 impl<R: RawRwLockUpgradeTimed, T: ?Sized> RwLock<R, T> {
1074 /// Attempts to acquire this `RwLock` with upgradable read access until a timeout
1075 /// is reached.
1076 ///
1077 /// If the access could not be granted before the timeout expires, then
1078 /// `None` is returned. Otherwise, an RAII guard is returned which will
1079 /// release the shared access when it is dropped.
1080 #[inline]
1081 pub fn try_upgradable_read_for(
1082 &self,
1083 timeout: R::Duration,
1084 ) -> Option<RwLockUpgradableReadGuard<'_, R, T>> {
1085 if self.raw.try_lock_upgradable_for(timeout) {
1086 // SAFETY: The lock is held, as required.
1087 Some(unsafe { self.upgradable_guard() })
1088 } else {
1089 None
1090 }
1091 }
1092
1093 /// Attempts to acquire this `RwLock` with upgradable read access until a timeout
1094 /// is reached.
1095 ///
1096 /// If the access could not be granted before the timeout expires, then
1097 /// `None` is returned. Otherwise, an RAII guard is returned which will
1098 /// release the shared access when it is dropped.
1099 #[inline]
1100 pub fn try_upgradable_read_until(
1101 &self,
1102 timeout: R::Instant,
1103 ) -> Option<RwLockUpgradableReadGuard<'_, R, T>> {
1104 if self.raw.try_lock_upgradable_until(timeout) {
1105 // SAFETY: The lock is held, as required.
1106 Some(unsafe { self.upgradable_guard() })
1107 } else {
1108 None
1109 }
1110 }
1111
1112 /// Attempts to lock this `RwLock` with upgradable access until a timeout is reached, through an `Arc`.
1113 ///
1114 /// This method is similar to the `try_upgradable_read_for` method; however, it requires the `RwLock` to be
1115 /// inside of an `Arc` and the resulting read guard has no lifetime requirements.
1116 #[cfg(feature = "arc_lock")]
1117 #[inline]
1118 pub fn try_upgradable_read_arc_for(
1119 self: &Arc<Self>,
1120 timeout: R::Duration,
1121 ) -> Option<ArcRwLockUpgradableReadGuard<R, T>> {
1122 if self.raw.try_lock_upgradable_for(timeout) {
1123 // SAFETY: locking guarantee is upheld
1124 Some(unsafe { self.upgradable_guard_arc() })
1125 } else {
1126 None
1127 }
1128 }
1129
1130 /// Attempts to lock this `RwLock` with upgradable access until a timeout is reached, through an `Arc`.
1131 ///
1132 /// This method is similar to the `try_upgradable_read_until` method; however, it requires the `RwLock` to be
1133 /// inside of an `Arc` and the resulting read guard has no lifetime requirements.
1134 #[cfg(feature = "arc_lock")]
1135 #[inline]
1136 pub fn try_upgradable_read_arc_until(
1137 self: &Arc<Self>,
1138 timeout: R::Instant,
1139 ) -> Option<ArcRwLockUpgradableReadGuard<R, T>> {
1140 if self.raw.try_lock_upgradable_until(timeout) {
1141 // SAFETY: locking guarantee is upheld
1142 Some(unsafe { self.upgradable_guard_arc() })
1143 } else {
1144 None
1145 }
1146 }
1147 }
1148
1149 impl<R: RawRwLock, T: ?Sized + Default> Default for RwLock<R, T> {
1150 #[inline]
1151 fn default() -> RwLock<R, T> {
1152 RwLock::new(Default::default())
1153 }
1154 }
1155
1156 impl<R: RawRwLock, T> From<T> for RwLock<R, T> {
1157 #[inline]
1158 fn from(t: T) -> RwLock<R, T> {
1159 RwLock::new(t)
1160 }
1161 }
1162
1163 impl<R: RawRwLock, T: ?Sized + fmt::Debug> fmt::Debug for RwLock<R, T> {
1164 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1165 match self.try_read() {
1166 Some(guard) => f.debug_struct("RwLock").field("data", &&*guard).finish(),
1167 None => {
1168 struct LockedPlaceholder;
1169 impl fmt::Debug for LockedPlaceholder {
1170 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1171 f.write_str("<locked>")
1172 }
1173 }
1174
1175 f.debug_struct("RwLock")
1176 .field("data", &LockedPlaceholder)
1177 .finish()
1178 }
1179 }
1180 }
1181 }
1182
1183 /// RAII structure used to release the shared read access of a lock when
1184 /// dropped.
1185 #[must_use = "if unused the RwLock will immediately unlock"]
1186 pub struct RwLockReadGuard<'a, R: RawRwLock, T: ?Sized> {
1187 rwlock: &'a RwLock<R, T>,
1188 marker: PhantomData<(&'a T, R::GuardMarker)>,
1189 }
1190
1191 impl<'a, R: RawRwLock + 'a, T: ?Sized + 'a> RwLockReadGuard<'a, R, T> {
1192 /// Returns a reference to the original reader-writer lock object.
1193 pub fn rwlock(s: &Self) -> &'a RwLock<R, T> {
1194 s.rwlock
1195 }
1196
1197 /// Make a new `MappedRwLockReadGuard` for a component of the locked data.
1198 ///
1199 /// This operation cannot fail as the `RwLockReadGuard` passed
1200 /// in already locked the data.
1201 ///
1202 /// This is an associated function that needs to be
1203 /// used as `RwLockReadGuard::map(...)`. A method would interfere with methods of
1204 /// the same name on the contents of the locked data.
1205 #[inline]
1206 pub fn map<U: ?Sized, F>(s: Self, f: F) -> MappedRwLockReadGuard<'a, R, U>
1207 where
1208 F: FnOnce(&T) -> &U,
1209 {
1210 let raw = &s.rwlock.raw;
1211 let data = f(unsafe { &*s.rwlock.data.get() });
1212 mem::forget(s);
1213 MappedRwLockReadGuard {
1214 raw,
1215 data,
1216 marker: PhantomData,
1217 }
1218 }
1219
1220 /// Attempts to make a new `MappedRwLockReadGuard` for a component of the
1221 /// locked data. Returns the original guard if the closure returns `None`.
1222 ///
1223 /// This operation cannot fail as the `RwLockReadGuard` passed
1224 /// in already locked the data.
1225 ///
1226 /// This is an associated function that needs to be
1227 /// used as `RwLockReadGuard::try_map(...)`. A method would interfere with methods of
1228 /// the same name on the contents of the locked data.
1229 #[inline]
1230 pub fn try_map<U: ?Sized, F>(s: Self, f: F) -> Result<MappedRwLockReadGuard<'a, R, U>, Self>
1231 where
1232 F: FnOnce(&T) -> Option<&U>,
1233 {
1234 let raw = &s.rwlock.raw;
1235 let data = match f(unsafe { &*s.rwlock.data.get() }) {
1236 Some(data) => data,
1237 None => return Err(s),
1238 };
1239 mem::forget(s);
1240 Ok(MappedRwLockReadGuard {
1241 raw,
1242 data,
1243 marker: PhantomData,
1244 })
1245 }
1246
1247 /// Temporarily unlocks the `RwLock` to execute the given function.
1248 ///
1249 /// The `RwLock` is unlocked a fair unlock protocol.
1250 ///
1251 /// This is safe because `&mut` guarantees that there exist no other
1252 /// references to the data protected by the `RwLock`.
1253 #[inline]
1254 pub fn unlocked<F, U>(s: &mut Self, f: F) -> U
1255 where
1256 F: FnOnce() -> U,
1257 {
1258 // Safety: An RwLockReadGuard always holds a shared lock.
1259 unsafe {
1260 s.rwlock.raw.unlock_shared();
1261 }
1262 defer!(s.rwlock.raw.lock_shared());
1263 f()
1264 }
1265 }
1266
1267 impl<'a, R: RawRwLockFair + 'a, T: ?Sized + 'a> RwLockReadGuard<'a, R, T> {
1268 /// Unlocks the `RwLock` using a fair unlock protocol.
1269 ///
1270 /// By default, `RwLock` is unfair and allow the current thread to re-lock
1271 /// the `RwLock` before another has the chance to acquire the lock, even if
1272 /// that thread has been blocked on the `RwLock` for a long time. This is
1273 /// the default because it allows much higher throughput as it avoids
1274 /// forcing a context switch on every `RwLock` unlock. This can result in one
1275 /// thread acquiring a `RwLock` many more times than other threads.
1276 ///
1277 /// However in some cases it can be beneficial to ensure fairness by forcing
1278 /// the lock to pass on to a waiting thread if there is one. This is done by
1279 /// using this method instead of dropping the `RwLockReadGuard` normally.
1280 #[inline]
1281 pub fn unlock_fair(s: Self) {
1282 // Safety: An RwLockReadGuard always holds a shared lock.
1283 unsafe {
1284 s.rwlock.raw.unlock_shared_fair();
1285 }
1286 mem::forget(s);
1287 }
1288
1289 /// Temporarily unlocks the `RwLock` to execute the given function.
1290 ///
1291 /// The `RwLock` is unlocked a fair unlock protocol.
1292 ///
1293 /// This is safe because `&mut` guarantees that there exist no other
1294 /// references to the data protected by the `RwLock`.
1295 #[inline]
1296 pub fn unlocked_fair<F, U>(s: &mut Self, f: F) -> U
1297 where
1298 F: FnOnce() -> U,
1299 {
1300 // Safety: An RwLockReadGuard always holds a shared lock.
1301 unsafe {
1302 s.rwlock.raw.unlock_shared_fair();
1303 }
1304 defer!(s.rwlock.raw.lock_shared());
1305 f()
1306 }
1307
1308 /// Temporarily yields the `RwLock` to a waiting thread if there is one.
1309 ///
1310 /// This method is functionally equivalent to calling `unlock_fair` followed
1311 /// by `read`, however it can be much more efficient in the case where there
1312 /// are no waiting threads.
1313 #[inline]
1314 pub fn bump(s: &mut Self) {
1315 // Safety: An RwLockReadGuard always holds a shared lock.
1316 unsafe {
1317 s.rwlock.raw.bump_shared();
1318 }
1319 }
1320 }
1321
1322 impl<'a, R: RawRwLock + 'a, T: ?Sized + 'a> Deref for RwLockReadGuard<'a, R, T> {
1323 type Target = T;
1324 #[inline]
1325 fn deref(&self) -> &T {
1326 unsafe { &*self.rwlock.data.get() }
1327 }
1328 }
1329
1330 impl<'a, R: RawRwLock + 'a, T: ?Sized + 'a> Drop for RwLockReadGuard<'a, R, T> {
1331 #[inline]
1332 fn drop(&mut self) {
1333 // Safety: An RwLockReadGuard always holds a shared lock.
1334 unsafe {
1335 self.rwlock.raw.unlock_shared();
1336 }
1337 }
1338 }
1339
1340 impl<'a, R: RawRwLock + 'a, T: fmt::Debug + ?Sized + 'a> fmt::Debug for RwLockReadGuard<'a, R, T> {
1341 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1342 fmt::Debug::fmt(&**self, f)
1343 }
1344 }
1345
1346 impl<'a, R: RawRwLock + 'a, T: fmt::Display + ?Sized + 'a> fmt::Display
1347 for RwLockReadGuard<'a, R, T>
1348 {
1349 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1350 (**self).fmt(f)
1351 }
1352 }
1353
1354 #[cfg(feature = "owning_ref")]
1355 unsafe impl<'a, R: RawRwLock + 'a, T: ?Sized + 'a> StableAddress for RwLockReadGuard<'a, R, T> {}
1356
1357 /// An RAII rwlock guard returned by the `Arc` locking operations on `RwLock`.
1358 ///
1359 /// This is similar to the `RwLockReadGuard` struct, except instead of using a reference to unlock the `RwLock`
1360 /// it uses an `Arc<RwLock>`. This has several advantages, most notably that it has an `'static` lifetime.
1361 #[cfg(feature = "arc_lock")]
1362 #[must_use = "if unused the RwLock will immediately unlock"]
1363 pub struct ArcRwLockReadGuard<R: RawRwLock, T: ?Sized> {
1364 rwlock: Arc<RwLock<R, T>>,
1365 marker: PhantomData<R::GuardMarker>,
1366 }
1367
1368 #[cfg(feature = "arc_lock")]
1369 impl<R: RawRwLock, T: ?Sized> ArcRwLockReadGuard<R, T> {
1370 /// Returns a reference to the rwlock, contained in its `Arc`.
1371 pub fn rwlock(s: &Self) -> &Arc<RwLock<R, T>> {
1372 &s.rwlock
1373 }
1374
1375 /// Temporarily unlocks the `RwLock` to execute the given function.
1376 ///
1377 /// This is functionally identical to the `unlocked` method on [`RwLockReadGuard`].
1378 #[inline]
1379 pub fn unlocked<F, U>(s: &mut Self, f: F) -> U
1380 where
1381 F: FnOnce() -> U,
1382 {
1383 // Safety: An RwLockReadGuard always holds a shared lock.
1384 unsafe {
1385 s.rwlock.raw.unlock_shared();
1386 }
1387 defer!(s.rwlock.raw.lock_shared());
1388 f()
1389 }
1390 }
1391
1392 #[cfg(feature = "arc_lock")]
1393 impl<R: RawRwLockFair, T: ?Sized> ArcRwLockReadGuard<R, T> {
1394 /// Unlocks the `RwLock` using a fair unlock protocol.
1395 ///
1396 /// This is functionally identical to the `unlock_fair` method on [`RwLockReadGuard`].
1397 #[inline]
1398 pub fn unlock_fair(s: Self) {
1399 // Safety: An RwLockReadGuard always holds a shared lock.
1400 unsafe {
1401 s.rwlock.raw.unlock_shared_fair();
1402 }
1403
1404 // SAFETY: ensure the Arc has its refcount decremented
1405 let mut s = ManuallyDrop::new(s);
1406 unsafe { ptr::drop_in_place(&mut s.rwlock) };
1407 }
1408
1409 /// Temporarily unlocks the `RwLock` to execute the given function.
1410 ///
1411 /// This is functionally identical to the `unlocked_fair` method on [`RwLockReadGuard`].
1412 #[inline]
1413 pub fn unlocked_fair<F, U>(s: &mut Self, f: F) -> U
1414 where
1415 F: FnOnce() -> U,
1416 {
1417 // Safety: An RwLockReadGuard always holds a shared lock.
1418 unsafe {
1419 s.rwlock.raw.unlock_shared_fair();
1420 }
1421 defer!(s.rwlock.raw.lock_shared());
1422 f()
1423 }
1424
1425 /// Temporarily yields the `RwLock` to a waiting thread if there is one.
1426 ///
1427 /// This is functionally identical to the `bump` method on [`RwLockReadGuard`].
1428 #[inline]
1429 pub fn bump(s: &mut Self) {
1430 // Safety: An RwLockReadGuard always holds a shared lock.
1431 unsafe {
1432 s.rwlock.raw.bump_shared();
1433 }
1434 }
1435 }
1436
1437 #[cfg(feature = "arc_lock")]
1438 impl<R: RawRwLock, T: ?Sized> Deref for ArcRwLockReadGuard<R, T> {
1439 type Target = T;
1440 #[inline]
1441 fn deref(&self) -> &T {
1442 unsafe { &*self.rwlock.data.get() }
1443 }
1444 }
1445
1446 #[cfg(feature = "arc_lock")]
1447 impl<R: RawRwLock, T: ?Sized> Drop for ArcRwLockReadGuard<R, T> {
1448 #[inline]
1449 fn drop(&mut self) {
1450 // Safety: An RwLockReadGuard always holds a shared lock.
1451 unsafe {
1452 self.rwlock.raw.unlock_shared();
1453 }
1454 }
1455 }
1456
1457 #[cfg(feature = "arc_lock")]
1458 impl<R: RawRwLock, T: fmt::Debug + ?Sized> fmt::Debug for ArcRwLockReadGuard<R, T> {
1459 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1460 fmt::Debug::fmt(&**self, f)
1461 }
1462 }
1463
1464 #[cfg(feature = "arc_lock")]
1465 impl<R: RawRwLock, T: fmt::Display + ?Sized> fmt::Display for ArcRwLockReadGuard<R, T> {
1466 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1467 (**self).fmt(f)
1468 }
1469 }
1470
1471 /// RAII structure used to release the exclusive write access of a lock when
1472 /// dropped.
1473 #[must_use = "if unused the RwLock will immediately unlock"]
1474 pub struct RwLockWriteGuard<'a, R: RawRwLock, T: ?Sized> {
1475 rwlock: &'a RwLock<R, T>,
1476 marker: PhantomData<(&'a mut T, R::GuardMarker)>,
1477 }
1478
1479 impl<'a, R: RawRwLock + 'a, T: ?Sized + 'a> RwLockWriteGuard<'a, R, T> {
1480 /// Returns a reference to the original reader-writer lock object.
1481 pub fn rwlock(s: &Self) -> &'a RwLock<R, T> {
1482 s.rwlock
1483 }
1484
1485 /// Make a new `MappedRwLockWriteGuard` for a component of the locked data.
1486 ///
1487 /// This operation cannot fail as the `RwLockWriteGuard` passed
1488 /// in already locked the data.
1489 ///
1490 /// This is an associated function that needs to be
1491 /// used as `RwLockWriteGuard::map(...)`. A method would interfere with methods of
1492 /// the same name on the contents of the locked data.
1493 #[inline]
1494 pub fn map<U: ?Sized, F>(s: Self, f: F) -> MappedRwLockWriteGuard<'a, R, U>
1495 where
1496 F: FnOnce(&mut T) -> &mut U,
1497 {
1498 let raw = &s.rwlock.raw;
1499 let data = f(unsafe { &mut *s.rwlock.data.get() });
1500 mem::forget(s);
1501 MappedRwLockWriteGuard {
1502 raw,
1503 data,
1504 marker: PhantomData,
1505 }
1506 }
1507
1508 /// Attempts to make a new `MappedRwLockWriteGuard` for a component of the
1509 /// locked data. The original guard is return if the closure returns `None`.
1510 ///
1511 /// This operation cannot fail as the `RwLockWriteGuard` passed
1512 /// in already locked the data.
1513 ///
1514 /// This is an associated function that needs to be
1515 /// used as `RwLockWriteGuard::try_map(...)`. A method would interfere with methods of
1516 /// the same name on the contents of the locked data.
1517 #[inline]
1518 pub fn try_map<U: ?Sized, F>(s: Self, f: F) -> Result<MappedRwLockWriteGuard<'a, R, U>, Self>
1519 where
1520 F: FnOnce(&mut T) -> Option<&mut U>,
1521 {
1522 let raw = &s.rwlock.raw;
1523 let data = match f(unsafe { &mut *s.rwlock.data.get() }) {
1524 Some(data) => data,
1525 None => return Err(s),
1526 };
1527 mem::forget(s);
1528 Ok(MappedRwLockWriteGuard {
1529 raw,
1530 data,
1531 marker: PhantomData,
1532 })
1533 }
1534
1535 /// Temporarily unlocks the `RwLock` to execute the given function.
1536 ///
1537 /// This is safe because `&mut` guarantees that there exist no other
1538 /// references to the data protected by the `RwLock`.
1539 #[inline]
1540 pub fn unlocked<F, U>(s: &mut Self, f: F) -> U
1541 where
1542 F: FnOnce() -> U,
1543 {
1544 // Safety: An RwLockReadGuard always holds a shared lock.
1545 unsafe {
1546 s.rwlock.raw.unlock_exclusive();
1547 }
1548 defer!(s.rwlock.raw.lock_exclusive());
1549 f()
1550 }
1551 }
1552
1553 impl<'a, R: RawRwLockDowngrade + 'a, T: ?Sized + 'a> RwLockWriteGuard<'a, R, T> {
1554 /// Atomically downgrades a write lock into a read lock without allowing any
1555 /// writers to take exclusive access of the lock in the meantime.
1556 ///
1557 /// Note that if there are any writers currently waiting to take the lock
1558 /// then other readers may not be able to acquire the lock even if it was
1559 /// downgraded.
1560 pub fn downgrade(s: Self) -> RwLockReadGuard<'a, R, T> {
1561 // Safety: An RwLockWriteGuard always holds an exclusive lock.
1562 unsafe {
1563 s.rwlock.raw.downgrade();
1564 }
1565 let rwlock = s.rwlock;
1566 mem::forget(s);
1567 RwLockReadGuard {
1568 rwlock,
1569 marker: PhantomData,
1570 }
1571 }
1572 }
1573
1574 impl<'a, R: RawRwLockUpgradeDowngrade + 'a, T: ?Sized + 'a> RwLockWriteGuard<'a, R, T> {
1575 /// Atomically downgrades a write lock into an upgradable read lock without allowing any
1576 /// writers to take exclusive access of the lock in the meantime.
1577 ///
1578 /// Note that if there are any writers currently waiting to take the lock
1579 /// then other readers may not be able to acquire the lock even if it was
1580 /// downgraded.
1581 pub fn downgrade_to_upgradable(s: Self) -> RwLockUpgradableReadGuard<'a, R, T> {
1582 // Safety: An RwLockWriteGuard always holds an exclusive lock.
1583 unsafe {
1584 s.rwlock.raw.downgrade_to_upgradable();
1585 }
1586 let rwlock = s.rwlock;
1587 mem::forget(s);
1588 RwLockUpgradableReadGuard {
1589 rwlock,
1590 marker: PhantomData,
1591 }
1592 }
1593 }
1594
1595 impl<'a, R: RawRwLockFair + 'a, T: ?Sized + 'a> RwLockWriteGuard<'a, R, T> {
1596 /// Unlocks the `RwLock` using a fair unlock protocol.
1597 ///
1598 /// By default, `RwLock` is unfair and allow the current thread to re-lock
1599 /// the `RwLock` before another has the chance to acquire the lock, even if
1600 /// that thread has been blocked on the `RwLock` for a long time. This is
1601 /// the default because it allows much higher throughput as it avoids
1602 /// forcing a context switch on every `RwLock` unlock. This can result in one
1603 /// thread acquiring a `RwLock` many more times than other threads.
1604 ///
1605 /// However in some cases it can be beneficial to ensure fairness by forcing
1606 /// the lock to pass on to a waiting thread if there is one. This is done by
1607 /// using this method instead of dropping the `RwLockWriteGuard` normally.
1608 #[inline]
1609 pub fn unlock_fair(s: Self) {
1610 // Safety: An RwLockWriteGuard always holds an exclusive lock.
1611 unsafe {
1612 s.rwlock.raw.unlock_exclusive_fair();
1613 }
1614 mem::forget(s);
1615 }
1616
1617 /// Temporarily unlocks the `RwLock` to execute the given function.
1618 ///
1619 /// The `RwLock` is unlocked a fair unlock protocol.
1620 ///
1621 /// This is safe because `&mut` guarantees that there exist no other
1622 /// references to the data protected by the `RwLock`.
1623 #[inline]
1624 pub fn unlocked_fair<F, U>(s: &mut Self, f: F) -> U
1625 where
1626 F: FnOnce() -> U,
1627 {
1628 // Safety: An RwLockWriteGuard always holds an exclusive lock.
1629 unsafe {
1630 s.rwlock.raw.unlock_exclusive_fair();
1631 }
1632 defer!(s.rwlock.raw.lock_exclusive());
1633 f()
1634 }
1635
1636 /// Temporarily yields the `RwLock` to a waiting thread if there is one.
1637 ///
1638 /// This method is functionally equivalent to calling `unlock_fair` followed
1639 /// by `write`, however it can be much more efficient in the case where there
1640 /// are no waiting threads.
1641 #[inline]
1642 pub fn bump(s: &mut Self) {
1643 // Safety: An RwLockWriteGuard always holds an exclusive lock.
1644 unsafe {
1645 s.rwlock.raw.bump_exclusive();
1646 }
1647 }
1648 }
1649
1650 impl<'a, R: RawRwLock + 'a, T: ?Sized + 'a> Deref for RwLockWriteGuard<'a, R, T> {
1651 type Target = T;
1652 #[inline]
1653 fn deref(&self) -> &T {
1654 unsafe { &*self.rwlock.data.get() }
1655 }
1656 }
1657
1658 impl<'a, R: RawRwLock + 'a, T: ?Sized + 'a> DerefMut for RwLockWriteGuard<'a, R, T> {
1659 #[inline]
1660 fn deref_mut(&mut self) -> &mut T {
1661 unsafe { &mut *self.rwlock.data.get() }
1662 }
1663 }
1664
1665 impl<'a, R: RawRwLock + 'a, T: ?Sized + 'a> Drop for RwLockWriteGuard<'a, R, T> {
1666 #[inline]
1667 fn drop(&mut self) {
1668 // Safety: An RwLockWriteGuard always holds an exclusive lock.
1669 unsafe {
1670 self.rwlock.raw.unlock_exclusive();
1671 }
1672 }
1673 }
1674
1675 impl<'a, R: RawRwLock + 'a, T: fmt::Debug + ?Sized + 'a> fmt::Debug for RwLockWriteGuard<'a, R, T> {
1676 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1677 fmt::Debug::fmt(&**self, f)
1678 }
1679 }
1680
1681 impl<'a, R: RawRwLock + 'a, T: fmt::Display + ?Sized + 'a> fmt::Display
1682 for RwLockWriteGuard<'a, R, T>
1683 {
1684 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1685 (**self).fmt(f)
1686 }
1687 }
1688
1689 #[cfg(feature = "owning_ref")]
1690 unsafe impl<'a, R: RawRwLock + 'a, T: ?Sized + 'a> StableAddress for RwLockWriteGuard<'a, R, T> {}
1691
1692 /// An RAII rwlock guard returned by the `Arc` locking operations on `RwLock`.
1693 /// This is similar to the `RwLockWriteGuard` struct, except instead of using a reference to unlock the `RwLock`
1694 /// it uses an `Arc<RwLock>`. This has several advantages, most notably that it has an `'static` lifetime.
1695 #[cfg(feature = "arc_lock")]
1696 #[must_use = "if unused the RwLock will immediately unlock"]
1697 pub struct ArcRwLockWriteGuard<R: RawRwLock, T: ?Sized> {
1698 rwlock: Arc<RwLock<R, T>>,
1699 marker: PhantomData<R::GuardMarker>,
1700 }
1701
1702 #[cfg(feature = "arc_lock")]
1703 impl<R: RawRwLock, T: ?Sized> ArcRwLockWriteGuard<R, T> {
1704 /// Returns a reference to the rwlock, contained in its `Arc`.
1705 pub fn rwlock(s: &Self) -> &Arc<RwLock<R, T>> {
1706 &s.rwlock
1707 }
1708
1709 /// Temporarily unlocks the `RwLock` to execute the given function.
1710 ///
1711 /// This is functionally equivalent to the `unlocked` method on [`RwLockWriteGuard`].
1712 #[inline]
1713 pub fn unlocked<F, U>(s: &mut Self, f: F) -> U
1714 where
1715 F: FnOnce() -> U,
1716 {
1717 // Safety: An RwLockWriteGuard always holds a shared lock.
1718 unsafe {
1719 s.rwlock.raw.unlock_exclusive();
1720 }
1721 defer!(s.rwlock.raw.lock_exclusive());
1722 f()
1723 }
1724 }
1725
1726 #[cfg(feature = "arc_lock")]
1727 impl<R: RawRwLockDowngrade, T: ?Sized> ArcRwLockWriteGuard<R, T> {
1728 /// Atomically downgrades a write lock into a read lock without allowing any
1729 /// writers to take exclusive access of the lock in the meantime.
1730 ///
1731 /// This is functionally equivalent to the `downgrade` method on [`RwLockWriteGuard`].
1732 pub fn downgrade(s: Self) -> ArcRwLockReadGuard<R, T> {
1733 // Safety: An RwLockWriteGuard always holds an exclusive lock.
1734 unsafe {
1735 s.rwlock.raw.downgrade();
1736 }
1737
1738 // SAFETY: prevent the arc's refcount from changing using ManuallyDrop and ptr::read
1739 let s = ManuallyDrop::new(s);
1740 let rwlock = unsafe { ptr::read(&s.rwlock) };
1741
1742 ArcRwLockReadGuard {
1743 rwlock,
1744 marker: PhantomData,
1745 }
1746 }
1747 }
1748
1749 #[cfg(feature = "arc_lock")]
1750 impl<R: RawRwLockUpgradeDowngrade, T: ?Sized> ArcRwLockWriteGuard<R, T> {
1751 /// Atomically downgrades a write lock into an upgradable read lock without allowing any
1752 /// writers to take exclusive access of the lock in the meantime.
1753 ///
1754 /// This is functionally identical to the `downgrade_to_upgradable` method on [`RwLockWriteGuard`].
1755 pub fn downgrade_to_upgradable(s: Self) -> ArcRwLockUpgradableReadGuard<R, T> {
1756 // Safety: An RwLockWriteGuard always holds an exclusive lock.
1757 unsafe {
1758 s.rwlock.raw.downgrade_to_upgradable();
1759 }
1760
1761 // SAFETY: same as above
1762 let s = ManuallyDrop::new(s);
1763 let rwlock = unsafe { ptr::read(&s.rwlock) };
1764
1765 ArcRwLockUpgradableReadGuard {
1766 rwlock,
1767 marker: PhantomData,
1768 }
1769 }
1770 }
1771
1772 #[cfg(feature = "arc_lock")]
1773 impl<R: RawRwLockFair, T: ?Sized> ArcRwLockWriteGuard<R, T> {
1774 /// Unlocks the `RwLock` using a fair unlock protocol.
1775 ///
1776 /// This is functionally equivalent to the `unlock_fair` method on [`RwLockWriteGuard`].
1777 #[inline]
1778 pub fn unlock_fair(s: Self) {
1779 // Safety: An RwLockWriteGuard always holds an exclusive lock.
1780 unsafe {
1781 s.rwlock.raw.unlock_exclusive_fair();
1782 }
1783
1784 // SAFETY: prevent the Arc from leaking memory
1785 let mut s = ManuallyDrop::new(s);
1786 unsafe { ptr::drop_in_place(&mut s.rwlock) };
1787 }
1788
1789 /// Temporarily unlocks the `RwLock` to execute the given function.
1790 ///
1791 /// This is functionally equivalent to the `unlocked_fair` method on [`RwLockWriteGuard`].
1792 #[inline]
1793 pub fn unlocked_fair<F, U>(s: &mut Self, f: F) -> U
1794 where
1795 F: FnOnce() -> U,
1796 {
1797 // Safety: An RwLockWriteGuard always holds an exclusive lock.
1798 unsafe {
1799 s.rwlock.raw.unlock_exclusive_fair();
1800 }
1801 defer!(s.rwlock.raw.lock_exclusive());
1802 f()
1803 }
1804
1805 /// Temporarily yields the `RwLock` to a waiting thread if there is one.
1806 ///
1807 /// This method is functionally equivalent to the `bump` method on [`RwLockWriteGuard`].
1808 #[inline]
1809 pub fn bump(s: &mut Self) {
1810 // Safety: An RwLockWriteGuard always holds an exclusive lock.
1811 unsafe {
1812 s.rwlock.raw.bump_exclusive();
1813 }
1814 }
1815 }
1816
1817 #[cfg(feature = "arc_lock")]
1818 impl<R: RawRwLock, T: ?Sized> Deref for ArcRwLockWriteGuard<R, T> {
1819 type Target = T;
1820 #[inline]
1821 fn deref(&self) -> &T {
1822 unsafe { &*self.rwlock.data.get() }
1823 }
1824 }
1825
1826 #[cfg(feature = "arc_lock")]
1827 impl<R: RawRwLock, T: ?Sized> DerefMut for ArcRwLockWriteGuard<R, T> {
1828 #[inline]
1829 fn deref_mut(&mut self) -> &mut T {
1830 unsafe { &mut *self.rwlock.data.get() }
1831 }
1832 }
1833
1834 #[cfg(feature = "arc_lock")]
1835 impl<R: RawRwLock, T: ?Sized> Drop for ArcRwLockWriteGuard<R, T> {
1836 #[inline]
1837 fn drop(&mut self) {
1838 // Safety: An RwLockWriteGuard always holds an exclusive lock.
1839 unsafe {
1840 self.rwlock.raw.unlock_exclusive();
1841 }
1842 }
1843 }
1844
1845 #[cfg(feature = "arc_lock")]
1846 impl<R: RawRwLock, T: fmt::Debug + ?Sized> fmt::Debug for ArcRwLockWriteGuard<R, T> {
1847 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1848 fmt::Debug::fmt(&**self, f)
1849 }
1850 }
1851
1852 #[cfg(feature = "arc_lock")]
1853 impl<R: RawRwLock, T: fmt::Display + ?Sized> fmt::Display for ArcRwLockWriteGuard<R, T> {
1854 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1855 (**self).fmt(f)
1856 }
1857 }
1858
1859 /// RAII structure used to release the upgradable read access of a lock when
1860 /// dropped.
1861 #[must_use = "if unused the RwLock will immediately unlock"]
1862 pub struct RwLockUpgradableReadGuard<'a, R: RawRwLockUpgrade, T: ?Sized> {
1863 rwlock: &'a RwLock<R, T>,
1864 marker: PhantomData<(&'a T, R::GuardMarker)>,
1865 }
1866
1867 unsafe impl<'a, R: RawRwLockUpgrade + 'a, T: ?Sized + Sync + 'a> Sync
1868 for RwLockUpgradableReadGuard<'a, R, T>
1869 {
1870 }
1871
1872 impl<'a, R: RawRwLockUpgrade + 'a, T: ?Sized + 'a> RwLockUpgradableReadGuard<'a, R, T> {
1873 /// Returns a reference to the original reader-writer lock object.
1874 pub fn rwlock(s: &Self) -> &'a RwLock<R, T> {
1875 s.rwlock
1876 }
1877
1878 /// Temporarily unlocks the `RwLock` to execute the given function.
1879 ///
1880 /// This is safe because `&mut` guarantees that there exist no other
1881 /// references to the data protected by the `RwLock`.
1882 #[inline]
1883 pub fn unlocked<F, U>(s: &mut Self, f: F) -> U
1884 where
1885 F: FnOnce() -> U,
1886 {
1887 // Safety: An RwLockUpgradableReadGuard always holds an upgradable lock.
1888 unsafe {
1889 s.rwlock.raw.unlock_upgradable();
1890 }
1891 defer!(s.rwlock.raw.lock_upgradable());
1892 f()
1893 }
1894
1895 /// Atomically upgrades an upgradable read lock lock into a exclusive write lock,
1896 /// blocking the current thread until it can be acquired.
1897 pub fn upgrade(s: Self) -> RwLockWriteGuard<'a, R, T> {
1898 // Safety: An RwLockUpgradableReadGuard always holds an upgradable lock.
1899 unsafe {
1900 s.rwlock.raw.upgrade();
1901 }
1902 let rwlock = s.rwlock;
1903 mem::forget(s);
1904 RwLockWriteGuard {
1905 rwlock,
1906 marker: PhantomData,
1907 }
1908 }
1909
1910 /// Tries to atomically upgrade an upgradable read lock into a exclusive write lock.
1911 ///
1912 /// If the access could not be granted at this time, then the current guard is returned.
1913 pub fn try_upgrade(s: Self) -> Result<RwLockWriteGuard<'a, R, T>, Self> {
1914 // Safety: An RwLockUpgradableReadGuard always holds an upgradable lock.
1915 if unsafe { s.rwlock.raw.try_upgrade() } {
1916 let rwlock = s.rwlock;
1917 mem::forget(s);
1918 Ok(RwLockWriteGuard {
1919 rwlock,
1920 marker: PhantomData,
1921 })
1922 } else {
1923 Err(s)
1924 }
1925 }
1926 }
1927
1928 impl<'a, R: RawRwLockUpgradeFair + 'a, T: ?Sized + 'a> RwLockUpgradableReadGuard<'a, R, T> {
1929 /// Unlocks the `RwLock` using a fair unlock protocol.
1930 ///
1931 /// By default, `RwLock` is unfair and allow the current thread to re-lock
1932 /// the `RwLock` before another has the chance to acquire the lock, even if
1933 /// that thread has been blocked on the `RwLock` for a long time. This is
1934 /// the default because it allows much higher throughput as it avoids
1935 /// forcing a context switch on every `RwLock` unlock. This can result in one
1936 /// thread acquiring a `RwLock` many more times than other threads.
1937 ///
1938 /// However in some cases it can be beneficial to ensure fairness by forcing
1939 /// the lock to pass on to a waiting thread if there is one. This is done by
1940 /// using this method instead of dropping the `RwLockUpgradableReadGuard` normally.
1941 #[inline]
1942 pub fn unlock_fair(s: Self) {
1943 // Safety: An RwLockUpgradableReadGuard always holds an upgradable lock.
1944 unsafe {
1945 s.rwlock.raw.unlock_upgradable_fair();
1946 }
1947 mem::forget(s);
1948 }
1949
1950 /// Temporarily unlocks the `RwLock` to execute the given function.
1951 ///
1952 /// The `RwLock` is unlocked a fair unlock protocol.
1953 ///
1954 /// This is safe because `&mut` guarantees that there exist no other
1955 /// references to the data protected by the `RwLock`.
1956 #[inline]
1957 pub fn unlocked_fair<F, U>(s: &mut Self, f: F) -> U
1958 where
1959 F: FnOnce() -> U,
1960 {
1961 // Safety: An RwLockUpgradableReadGuard always holds an upgradable lock.
1962 unsafe {
1963 s.rwlock.raw.unlock_upgradable_fair();
1964 }
1965 defer!(s.rwlock.raw.lock_upgradable());
1966 f()
1967 }
1968
1969 /// Temporarily yields the `RwLock` to a waiting thread if there is one.
1970 ///
1971 /// This method is functionally equivalent to calling `unlock_fair` followed
1972 /// by `upgradable_read`, however it can be much more efficient in the case where there
1973 /// are no waiting threads.
1974 #[inline]
1975 pub fn bump(s: &mut Self) {
1976 // Safety: An RwLockUpgradableReadGuard always holds an upgradable lock.
1977 unsafe {
1978 s.rwlock.raw.bump_upgradable();
1979 }
1980 }
1981 }
1982
1983 impl<'a, R: RawRwLockUpgradeDowngrade + 'a, T: ?Sized + 'a> RwLockUpgradableReadGuard<'a, R, T> {
1984 /// Atomically downgrades an upgradable read lock lock into a shared read lock
1985 /// without allowing any writers to take exclusive access of the lock in the
1986 /// meantime.
1987 ///
1988 /// Note that if there are any writers currently waiting to take the lock
1989 /// then other readers may not be able to acquire the lock even if it was
1990 /// downgraded.
1991 pub fn downgrade(s: Self) -> RwLockReadGuard<'a, R, T> {
1992 // Safety: An RwLockUpgradableReadGuard always holds an upgradable lock.
1993 unsafe {
1994 s.rwlock.raw.downgrade_upgradable();
1995 }
1996 let rwlock = s.rwlock;
1997 mem::forget(s);
1998 RwLockReadGuard {
1999 rwlock,
2000 marker: PhantomData,
2001 }
2002 }
2003 }
2004
2005 impl<'a, R: RawRwLockUpgradeTimed + 'a, T: ?Sized + 'a> RwLockUpgradableReadGuard<'a, R, T> {
2006 /// Tries to atomically upgrade an upgradable read lock into a exclusive
2007 /// write lock, until a timeout is reached.
2008 ///
2009 /// If the access could not be granted before the timeout expires, then
2010 /// the current guard is returned.
2011 pub fn try_upgrade_for(
2012 s: Self,
2013 timeout: R::Duration,
2014 ) -> Result<RwLockWriteGuard<'a, R, T>, Self> {
2015 // Safety: An RwLockUpgradableReadGuard always holds an upgradable lock.
2016 if unsafe { s.rwlock.raw.try_upgrade_for(timeout) } {
2017 let rwlock = s.rwlock;
2018 mem::forget(s);
2019 Ok(RwLockWriteGuard {
2020 rwlock,
2021 marker: PhantomData,
2022 })
2023 } else {
2024 Err(s)
2025 }
2026 }
2027
2028 /// Tries to atomically upgrade an upgradable read lock into a exclusive
2029 /// write lock, until a timeout is reached.
2030 ///
2031 /// If the access could not be granted before the timeout expires, then
2032 /// the current guard is returned.
2033 #[inline]
2034 pub fn try_upgrade_until(
2035 s: Self,
2036 timeout: R::Instant,
2037 ) -> Result<RwLockWriteGuard<'a, R, T>, Self> {
2038 // Safety: An RwLockUpgradableReadGuard always holds an upgradable lock.
2039 if unsafe { s.rwlock.raw.try_upgrade_until(timeout) } {
2040 let rwlock = s.rwlock;
2041 mem::forget(s);
2042 Ok(RwLockWriteGuard {
2043 rwlock,
2044 marker: PhantomData,
2045 })
2046 } else {
2047 Err(s)
2048 }
2049 }
2050 }
2051
2052 impl<'a, R: RawRwLockUpgrade + 'a, T: ?Sized + 'a> Deref for RwLockUpgradableReadGuard<'a, R, T> {
2053 type Target = T;
2054 #[inline]
2055 fn deref(&self) -> &T {
2056 unsafe { &*self.rwlock.data.get() }
2057 }
2058 }
2059
2060 impl<'a, R: RawRwLockUpgrade + 'a, T: ?Sized + 'a> Drop for RwLockUpgradableReadGuard<'a, R, T> {
2061 #[inline]
2062 fn drop(&mut self) {
2063 // Safety: An RwLockUpgradableReadGuard always holds an upgradable lock.
2064 unsafe {
2065 self.rwlock.raw.unlock_upgradable();
2066 }
2067 }
2068 }
2069
2070 impl<'a, R: RawRwLockUpgrade + 'a, T: fmt::Debug + ?Sized + 'a> fmt::Debug
2071 for RwLockUpgradableReadGuard<'a, R, T>
2072 {
2073 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2074 fmt::Debug::fmt(&**self, f)
2075 }
2076 }
2077
2078 impl<'a, R: RawRwLockUpgrade + 'a, T: fmt::Display + ?Sized + 'a> fmt::Display
2079 for RwLockUpgradableReadGuard<'a, R, T>
2080 {
2081 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2082 (**self).fmt(f)
2083 }
2084 }
2085
2086 #[cfg(feature = "owning_ref")]
2087 unsafe impl<'a, R: RawRwLockUpgrade + 'a, T: ?Sized + 'a> StableAddress
2088 for RwLockUpgradableReadGuard<'a, R, T>
2089 {
2090 }
2091
2092 /// An RAII rwlock guard returned by the `Arc` locking operations on `RwLock`.
2093 /// This is similar to the `RwLockUpgradableReadGuard` struct, except instead of using a reference to unlock the
2094 /// `RwLock` it uses an `Arc<RwLock>`. This has several advantages, most notably that it has an `'static`
2095 /// lifetime.
2096 #[cfg(feature = "arc_lock")]
2097 #[must_use = "if unused the RwLock will immediately unlock"]
2098 pub struct ArcRwLockUpgradableReadGuard<R: RawRwLockUpgrade, T: ?Sized> {
2099 rwlock: Arc<RwLock<R, T>>,
2100 marker: PhantomData<R::GuardMarker>,
2101 }
2102
2103 #[cfg(feature = "arc_lock")]
2104 impl<R: RawRwLockUpgrade, T: ?Sized> ArcRwLockUpgradableReadGuard<R, T> {
2105 /// Returns a reference to the rwlock, contained in its original `Arc`.
2106 pub fn rwlock(s: &Self) -> &Arc<RwLock<R, T>> {
2107 &s.rwlock
2108 }
2109
2110 /// Temporarily unlocks the `RwLock` to execute the given function.
2111 ///
2112 /// This is functionally identical to the `unlocked` method on [`RwLockUpgradableReadGuard`].
2113 #[inline]
2114 pub fn unlocked<F, U>(s: &mut Self, f: F) -> U
2115 where
2116 F: FnOnce() -> U,
2117 {
2118 // Safety: An RwLockUpgradableReadGuard always holds an upgradable lock.
2119 unsafe {
2120 s.rwlock.raw.unlock_upgradable();
2121 }
2122 defer!(s.rwlock.raw.lock_upgradable());
2123 f()
2124 }
2125
2126 /// Atomically upgrades an upgradable read lock lock into a exclusive write lock,
2127 /// blocking the current thread until it can be acquired.
2128 pub fn upgrade(s: Self) -> ArcRwLockWriteGuard<R, T> {
2129 // Safety: An RwLockUpgradableReadGuard always holds an upgradable lock.
2130 unsafe {
2131 s.rwlock.raw.upgrade();
2132 }
2133
2134 // SAFETY: avoid incrementing or decrementing the refcount using ManuallyDrop and reading the Arc out
2135 // of the struct
2136 let s = ManuallyDrop::new(s);
2137 let rwlock = unsafe { ptr::read(&s.rwlock) };
2138
2139 ArcRwLockWriteGuard {
2140 rwlock,
2141 marker: PhantomData,
2142 }
2143 }
2144
2145 /// Tries to atomically upgrade an upgradable read lock into a exclusive write lock.
2146 ///
2147 /// If the access could not be granted at this time, then the current guard is returned.
2148 pub fn try_upgrade(s: Self) -> Result<ArcRwLockWriteGuard<R, T>, Self> {
2149 // Safety: An RwLockUpgradableReadGuard always holds an upgradable lock.
2150 if unsafe { s.rwlock.raw.try_upgrade() } {
2151 // SAFETY: same as above
2152 let s = ManuallyDrop::new(s);
2153 let rwlock = unsafe { ptr::read(&s.rwlock) };
2154
2155 Ok(ArcRwLockWriteGuard {
2156 rwlock,
2157 marker: PhantomData,
2158 })
2159 } else {
2160 Err(s)
2161 }
2162 }
2163 }
2164
2165 #[cfg(feature = "arc_lock")]
2166 impl<R: RawRwLockUpgradeFair, T: ?Sized> ArcRwLockUpgradableReadGuard<R, T> {
2167 /// Unlocks the `RwLock` using a fair unlock protocol.
2168 ///
2169 /// This is functionally identical to the `unlock_fair` method on [`RwLockUpgradableReadGuard`].
2170 #[inline]
2171 pub fn unlock_fair(s: Self) {
2172 // Safety: An RwLockUpgradableReadGuard always holds an upgradable lock.
2173 unsafe {
2174 s.rwlock.raw.unlock_upgradable_fair();
2175 }
2176
2177 // SAFETY: make sure we decrement the refcount properly
2178 let mut s = ManuallyDrop::new(s);
2179 unsafe { ptr::drop_in_place(&mut s.rwlock) };
2180 }
2181
2182 /// Temporarily unlocks the `RwLock` to execute the given function.
2183 ///
2184 /// This is functionally equivalent to the `unlocked_fair` method on [`RwLockUpgradableReadGuard`].
2185 #[inline]
2186 pub fn unlocked_fair<F, U>(s: &mut Self, f: F) -> U
2187 where
2188 F: FnOnce() -> U,
2189 {
2190 // Safety: An RwLockUpgradableReadGuard always holds an upgradable lock.
2191 unsafe {
2192 s.rwlock.raw.unlock_upgradable_fair();
2193 }
2194 defer!(s.rwlock.raw.lock_upgradable());
2195 f()
2196 }
2197
2198 /// Temporarily yields the `RwLock` to a waiting thread if there is one.
2199 ///
2200 /// This method is functionally equivalent to calling `bump` on [`RwLockUpgradableReadGuard`].
2201 #[inline]
2202 pub fn bump(s: &mut Self) {
2203 // Safety: An RwLockUpgradableReadGuard always holds an upgradable lock.
2204 unsafe {
2205 s.rwlock.raw.bump_upgradable();
2206 }
2207 }
2208 }
2209
2210 #[cfg(feature = "arc_lock")]
2211 impl<R: RawRwLockUpgradeDowngrade, T: ?Sized> ArcRwLockUpgradableReadGuard<R, T> {
2212 /// Atomically downgrades an upgradable read lock lock into a shared read lock
2213 /// without allowing any writers to take exclusive access of the lock in the
2214 /// meantime.
2215 ///
2216 /// Note that if there are any writers currently waiting to take the lock
2217 /// then other readers may not be able to acquire the lock even if it was
2218 /// downgraded.
2219 pub fn downgrade(s: Self) -> ArcRwLockReadGuard<R, T> {
2220 // Safety: An RwLockUpgradableReadGuard always holds an upgradable lock.
2221 unsafe {
2222 s.rwlock.raw.downgrade_upgradable();
2223 }
2224
2225 // SAFETY: use ManuallyDrop and ptr::read to ensure the refcount is not changed
2226 let s = ManuallyDrop::new(s);
2227 let rwlock = unsafe { ptr::read(&s.rwlock) };
2228
2229 ArcRwLockReadGuard {
2230 rwlock,
2231 marker: PhantomData,
2232 }
2233 }
2234 }
2235
2236 #[cfg(feature = "arc_lock")]
2237 impl<R: RawRwLockUpgradeTimed, T: ?Sized> ArcRwLockUpgradableReadGuard<R, T> {
2238 /// Tries to atomically upgrade an upgradable read lock into a exclusive
2239 /// write lock, until a timeout is reached.
2240 ///
2241 /// If the access could not be granted before the timeout expires, then
2242 /// the current guard is returned.
2243 pub fn try_upgrade_for(
2244 s: Self,
2245 timeout: R::Duration,
2246 ) -> Result<ArcRwLockWriteGuard<R, T>, Self> {
2247 // Safety: An RwLockUpgradableReadGuard always holds an upgradable lock.
2248 if unsafe { s.rwlock.raw.try_upgrade_for(timeout) } {
2249 // SAFETY: same as above
2250 let s = ManuallyDrop::new(s);
2251 let rwlock = unsafe { ptr::read(&s.rwlock) };
2252
2253 Ok(ArcRwLockWriteGuard {
2254 rwlock,
2255 marker: PhantomData,
2256 })
2257 } else {
2258 Err(s)
2259 }
2260 }
2261
2262 /// Tries to atomically upgrade an upgradable read lock into a exclusive
2263 /// write lock, until a timeout is reached.
2264 ///
2265 /// If the access could not be granted before the timeout expires, then
2266 /// the current guard is returned.
2267 #[inline]
2268 pub fn try_upgrade_until(
2269 s: Self,
2270 timeout: R::Instant,
2271 ) -> Result<ArcRwLockWriteGuard<R, T>, Self> {
2272 // Safety: An RwLockUpgradableReadGuard always holds an upgradable lock.
2273 if unsafe { s.rwlock.raw.try_upgrade_until(timeout) } {
2274 // SAFETY: same as above
2275 let s = ManuallyDrop::new(s);
2276 let rwlock = unsafe { ptr::read(&s.rwlock) };
2277
2278 Ok(ArcRwLockWriteGuard {
2279 rwlock,
2280 marker: PhantomData,
2281 })
2282 } else {
2283 Err(s)
2284 }
2285 }
2286 }
2287
2288 #[cfg(feature = "arc_lock")]
2289 impl<R: RawRwLockUpgrade, T: ?Sized> Deref for ArcRwLockUpgradableReadGuard<R, T> {
2290 type Target = T;
2291 #[inline]
2292 fn deref(&self) -> &T {
2293 unsafe { &*self.rwlock.data.get() }
2294 }
2295 }
2296
2297 #[cfg(feature = "arc_lock")]
2298 impl<R: RawRwLockUpgrade, T: ?Sized> Drop for ArcRwLockUpgradableReadGuard<R, T> {
2299 #[inline]
2300 fn drop(&mut self) {
2301 // Safety: An RwLockUpgradableReadGuard always holds an upgradable lock.
2302 unsafe {
2303 self.rwlock.raw.unlock_upgradable();
2304 }
2305 }
2306 }
2307
2308 #[cfg(feature = "arc_lock")]
2309 impl<R: RawRwLockUpgrade, T: fmt::Debug + ?Sized> fmt::Debug
2310 for ArcRwLockUpgradableReadGuard<R, T>
2311 {
2312 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2313 fmt::Debug::fmt(&**self, f)
2314 }
2315 }
2316
2317 #[cfg(feature = "arc_lock")]
2318 impl<R: RawRwLockUpgrade, T: fmt::Display + ?Sized> fmt::Display
2319 for ArcRwLockUpgradableReadGuard<R, T>
2320 {
2321 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2322 (**self).fmt(f)
2323 }
2324 }
2325
2326 /// An RAII read lock guard returned by `RwLockReadGuard::map`, which can point to a
2327 /// subfield of the protected data.
2328 ///
2329 /// The main difference between `MappedRwLockReadGuard` and `RwLockReadGuard` is that the
2330 /// former doesn't support temporarily unlocking and re-locking, since that
2331 /// could introduce soundness issues if the locked object is modified by another
2332 /// thread.
2333 #[must_use = "if unused the RwLock will immediately unlock"]
2334 pub struct MappedRwLockReadGuard<'a, R: RawRwLock, T: ?Sized> {
2335 raw: &'a R,
2336 data: *const T,
2337 marker: PhantomData<&'a T>,
2338 }
2339
2340 unsafe impl<'a, R: RawRwLock + 'a, T: ?Sized + Sync + 'a> Sync for MappedRwLockReadGuard<'a, R, T> {}
2341 unsafe impl<'a, R: RawRwLock + 'a, T: ?Sized + Sync + 'a> Send for MappedRwLockReadGuard<'a, R, T> where
2342 R::GuardMarker: Send
2343 {
2344 }
2345
2346 impl<'a, R: RawRwLock + 'a, T: ?Sized + 'a> MappedRwLockReadGuard<'a, R, T> {
2347 /// Make a new `MappedRwLockReadGuard` for a component of the locked data.
2348 ///
2349 /// This operation cannot fail as the `MappedRwLockReadGuard` passed
2350 /// in already locked the data.
2351 ///
2352 /// This is an associated function that needs to be
2353 /// used as `MappedRwLockReadGuard::map(...)`. A method would interfere with methods of
2354 /// the same name on the contents of the locked data.
2355 #[inline]
2356 pub fn map<U: ?Sized, F>(s: Self, f: F) -> MappedRwLockReadGuard<'a, R, U>
2357 where
2358 F: FnOnce(&T) -> &U,
2359 {
2360 let raw = s.raw;
2361 let data = f(unsafe { &*s.data });
2362 mem::forget(s);
2363 MappedRwLockReadGuard {
2364 raw,
2365 data,
2366 marker: PhantomData,
2367 }
2368 }
2369
2370 /// Attempts to make a new `MappedRwLockReadGuard` for a component of the
2371 /// locked data. The original guard is return if the closure returns `None`.
2372 ///
2373 /// This operation cannot fail as the `MappedRwLockReadGuard` passed
2374 /// in already locked the data.
2375 ///
2376 /// This is an associated function that needs to be
2377 /// used as `MappedRwLockReadGuard::try_map(...)`. A method would interfere with methods of
2378 /// the same name on the contents of the locked data.
2379 #[inline]
2380 pub fn try_map<U: ?Sized, F>(s: Self, f: F) -> Result<MappedRwLockReadGuard<'a, R, U>, Self>
2381 where
2382 F: FnOnce(&T) -> Option<&U>,
2383 {
2384 let raw = s.raw;
2385 let data = match f(unsafe { &*s.data }) {
2386 Some(data) => data,
2387 None => return Err(s),
2388 };
2389 mem::forget(s);
2390 Ok(MappedRwLockReadGuard {
2391 raw,
2392 data,
2393 marker: PhantomData,
2394 })
2395 }
2396 }
2397
2398 impl<'a, R: RawRwLockFair + 'a, T: ?Sized + 'a> MappedRwLockReadGuard<'a, R, T> {
2399 /// Unlocks the `RwLock` using a fair unlock protocol.
2400 ///
2401 /// By default, `RwLock` is unfair and allow the current thread to re-lock
2402 /// the `RwLock` before another has the chance to acquire the lock, even if
2403 /// that thread has been blocked on the `RwLock` for a long time. This is
2404 /// the default because it allows much higher throughput as it avoids
2405 /// forcing a context switch on every `RwLock` unlock. This can result in one
2406 /// thread acquiring a `RwLock` many more times than other threads.
2407 ///
2408 /// However in some cases it can be beneficial to ensure fairness by forcing
2409 /// the lock to pass on to a waiting thread if there is one. This is done by
2410 /// using this method instead of dropping the `MappedRwLockReadGuard` normally.
2411 #[inline]
2412 pub fn unlock_fair(s: Self) {
2413 // Safety: A MappedRwLockReadGuard always holds a shared lock.
2414 unsafe {
2415 s.raw.unlock_shared_fair();
2416 }
2417 mem::forget(s);
2418 }
2419 }
2420
2421 impl<'a, R: RawRwLock + 'a, T: ?Sized + 'a> Deref for MappedRwLockReadGuard<'a, R, T> {
2422 type Target = T;
2423 #[inline]
2424 fn deref(&self) -> &T {
2425 unsafe { &*self.data }
2426 }
2427 }
2428
2429 impl<'a, R: RawRwLock + 'a, T: ?Sized + 'a> Drop for MappedRwLockReadGuard<'a, R, T> {
2430 #[inline]
2431 fn drop(&mut self) {
2432 // Safety: A MappedRwLockReadGuard always holds a shared lock.
2433 unsafe {
2434 self.raw.unlock_shared();
2435 }
2436 }
2437 }
2438
2439 impl<'a, R: RawRwLock + 'a, T: fmt::Debug + ?Sized + 'a> fmt::Debug
2440 for MappedRwLockReadGuard<'a, R, T>
2441 {
2442 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2443 fmt::Debug::fmt(&**self, f)
2444 }
2445 }
2446
2447 impl<'a, R: RawRwLock + 'a, T: fmt::Display + ?Sized + 'a> fmt::Display
2448 for MappedRwLockReadGuard<'a, R, T>
2449 {
2450 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2451 (**self).fmt(f)
2452 }
2453 }
2454
2455 #[cfg(feature = "owning_ref")]
2456 unsafe impl<'a, R: RawRwLock + 'a, T: ?Sized + 'a> StableAddress
2457 for MappedRwLockReadGuard<'a, R, T>
2458 {
2459 }
2460
2461 /// An RAII write lock guard returned by `RwLockWriteGuard::map`, which can point to a
2462 /// subfield of the protected data.
2463 ///
2464 /// The main difference between `MappedRwLockWriteGuard` and `RwLockWriteGuard` is that the
2465 /// former doesn't support temporarily unlocking and re-locking, since that
2466 /// could introduce soundness issues if the locked object is modified by another
2467 /// thread.
2468 #[must_use = "if unused the RwLock will immediately unlock"]
2469 pub struct MappedRwLockWriteGuard<'a, R: RawRwLock, T: ?Sized> {
2470 raw: &'a R,
2471 data: *mut T,
2472 marker: PhantomData<&'a mut T>,
2473 }
2474
2475 unsafe impl<'a, R: RawRwLock + 'a, T: ?Sized + Sync + 'a> Sync
2476 for MappedRwLockWriteGuard<'a, R, T>
2477 {
2478 }
2479 unsafe impl<'a, R: RawRwLock + 'a, T: ?Sized + Send + 'a> Send for MappedRwLockWriteGuard<'a, R, T> where
2480 R::GuardMarker: Send
2481 {
2482 }
2483
2484 impl<'a, R: RawRwLock + 'a, T: ?Sized + 'a> MappedRwLockWriteGuard<'a, R, T> {
2485 /// Make a new `MappedRwLockWriteGuard` for a component of the locked data.
2486 ///
2487 /// This operation cannot fail as the `MappedRwLockWriteGuard` passed
2488 /// in already locked the data.
2489 ///
2490 /// This is an associated function that needs to be
2491 /// used as `MappedRwLockWriteGuard::map(...)`. A method would interfere with methods of
2492 /// the same name on the contents of the locked data.
2493 #[inline]
2494 pub fn map<U: ?Sized, F>(s: Self, f: F) -> MappedRwLockWriteGuard<'a, R, U>
2495 where
2496 F: FnOnce(&mut T) -> &mut U,
2497 {
2498 let raw = s.raw;
2499 let data = f(unsafe { &mut *s.data });
2500 mem::forget(s);
2501 MappedRwLockWriteGuard {
2502 raw,
2503 data,
2504 marker: PhantomData,
2505 }
2506 }
2507
2508 /// Attempts to make a new `MappedRwLockWriteGuard` for a component of the
2509 /// locked data. The original guard is return if the closure returns `None`.
2510 ///
2511 /// This operation cannot fail as the `MappedRwLockWriteGuard` passed
2512 /// in already locked the data.
2513 ///
2514 /// This is an associated function that needs to be
2515 /// used as `MappedRwLockWriteGuard::try_map(...)`. A method would interfere with methods of
2516 /// the same name on the contents of the locked data.
2517 #[inline]
2518 pub fn try_map<U: ?Sized, F>(s: Self, f: F) -> Result<MappedRwLockWriteGuard<'a, R, U>, Self>
2519 where
2520 F: FnOnce(&mut T) -> Option<&mut U>,
2521 {
2522 let raw = s.raw;
2523 let data = match f(unsafe { &mut *s.data }) {
2524 Some(data) => data,
2525 None => return Err(s),
2526 };
2527 mem::forget(s);
2528 Ok(MappedRwLockWriteGuard {
2529 raw,
2530 data,
2531 marker: PhantomData,
2532 })
2533 }
2534 }
2535
2536 impl<'a, R: RawRwLockFair + 'a, T: ?Sized + 'a> MappedRwLockWriteGuard<'a, R, T> {
2537 /// Unlocks the `RwLock` using a fair unlock protocol.
2538 ///
2539 /// By default, `RwLock` is unfair and allow the current thread to re-lock
2540 /// the `RwLock` before another has the chance to acquire the lock, even if
2541 /// that thread has been blocked on the `RwLock` for a long time. This is
2542 /// the default because it allows much higher throughput as it avoids
2543 /// forcing a context switch on every `RwLock` unlock. This can result in one
2544 /// thread acquiring a `RwLock` many more times than other threads.
2545 ///
2546 /// However in some cases it can be beneficial to ensure fairness by forcing
2547 /// the lock to pass on to a waiting thread if there is one. This is done by
2548 /// using this method instead of dropping the `MappedRwLockWriteGuard` normally.
2549 #[inline]
2550 pub fn unlock_fair(s: Self) {
2551 // Safety: A MappedRwLockWriteGuard always holds an exclusive lock.
2552 unsafe {
2553 s.raw.unlock_exclusive_fair();
2554 }
2555 mem::forget(s);
2556 }
2557 }
2558
2559 impl<'a, R: RawRwLock + 'a, T: ?Sized + 'a> Deref for MappedRwLockWriteGuard<'a, R, T> {
2560 type Target = T;
2561 #[inline]
2562 fn deref(&self) -> &T {
2563 unsafe { &*self.data }
2564 }
2565 }
2566
2567 impl<'a, R: RawRwLock + 'a, T: ?Sized + 'a> DerefMut for MappedRwLockWriteGuard<'a, R, T> {
2568 #[inline]
2569 fn deref_mut(&mut self) -> &mut T {
2570 unsafe { &mut *self.data }
2571 }
2572 }
2573
2574 impl<'a, R: RawRwLock + 'a, T: ?Sized + 'a> Drop for MappedRwLockWriteGuard<'a, R, T> {
2575 #[inline]
2576 fn drop(&mut self) {
2577 // Safety: A MappedRwLockWriteGuard always holds an exclusive lock.
2578 unsafe {
2579 self.raw.unlock_exclusive();
2580 }
2581 }
2582 }
2583
2584 impl<'a, R: RawRwLock + 'a, T: fmt::Debug + ?Sized + 'a> fmt::Debug
2585 for MappedRwLockWriteGuard<'a, R, T>
2586 {
2587 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2588 fmt::Debug::fmt(&**self, f)
2589 }
2590 }
2591
2592 impl<'a, R: RawRwLock + 'a, T: fmt::Display + ?Sized + 'a> fmt::Display
2593 for MappedRwLockWriteGuard<'a, R, T>
2594 {
2595 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2596 (**self).fmt(f)
2597 }
2598 }
2599
2600 #[cfg(feature = "owning_ref")]
2601 unsafe impl<'a, R: RawRwLock + 'a, T: ?Sized + 'a> StableAddress
2602 for MappedRwLockWriteGuard<'a, R, T>
2603 {
2604 }