blob: c01ee17eecda3906a1cacc55847ec627916efe62 [file] [log] [blame]
Taiki Endo93b6d9e2019-02-11 04:23:21 +09001use crate::cell::UnsafeCell;
2use crate::fmt;
Zachary Sea97c1f2023-10-23 16:26:59 -05003use crate::marker::PhantomData;
EFanZh242c6c32024-11-30 19:33:06 +08004use crate::mem::{self, ManuallyDrop, forget};
Taiki Endo93b6d9e2019-02-11 04:23:21 +09005use crate::ops::{Deref, DerefMut};
Robin Raymond08650fb2022-05-14 07:29:02 +00006use crate::ptr::NonNull;
Connor Tsuif71ecc42024-10-16 09:31:30 -04007use crate::sync::{LockResult, PoisonError, TryLockError, TryLockResult, poison};
joboet22a52672024-03-12 14:55:06 +01008use crate::sys::sync as sys;
Alex Crichton71d4e772014-11-24 11:16:40 -08009
10/// A reader-writer lock
11///
12/// This type of lock allows a number of readers or at most one writer at any
13/// point in time. The write portion of this lock typically allows modification
14/// of the underlying data (exclusive access) and the read portion of this lock
15/// typically allows for read-only access (shared access).
16///
Lucas Moralesf2838752017-09-22 18:43:09 -040017/// In comparison, a [`Mutex`] does not distinguish between readers or writers
Matthias Krüger44524462018-02-16 15:56:50 +010018/// that acquire the lock, therefore blocking any threads waiting for the lock to
19/// become available. An `RwLock` will allow any number of readers to acquire the
Lucas Moralesf2838752017-09-22 18:43:09 -040020/// lock as long as a writer is not holding the lock.
21///
webmobster24808fa2015-06-03 13:47:07 +010022/// The priority policy of the lock is dependent on the underlying operating
23/// system's implementation, and this type does not guarantee that any
Aleksey Kladovd94b4e82021-02-27 19:07:19 +030024/// particular policy will be used. In particular, a writer which is waiting to
Aleksey Kladov261c9522021-02-27 19:44:17 +030025/// acquire the lock in `write` might or might not block concurrent calls to
Miguel Ojeda98096a92021-02-28 08:47:26 +010026/// `read`, e.g.:
27///
28/// <details><summary>Potential deadlock example</summary>
29///
30/// ```text
Trevor Gross0cd57722024-03-26 21:38:28 -040031/// // Thread 1 | // Thread 2
32/// let _rg1 = lock.read(); |
33/// | // will block
34/// | let _wg = lock.write();
35/// // may deadlock |
36/// let _rg2 = lock.read(); |
Miguel Ojeda98096a92021-02-28 08:47:26 +010037/// ```
Trevor Gross0cd57722024-03-26 21:38:28 -040038///
Miguel Ojeda98096a92021-02-28 08:47:26 +010039/// </details>
webmobster24808fa2015-06-03 13:47:07 +010040///
Alex Crichton71d4e772014-11-24 11:16:40 -080041/// The type parameter `T` represents the data that this lock protects. It is
Lucas Moralesf2838752017-09-22 18:43:09 -040042/// required that `T` satisfies [`Send`] to be shared across threads and
43/// [`Sync`] to allow concurrent access through readers. The RAII guards
Matthew Kraai2f433132019-12-26 05:27:55 -080044/// returned from the locking methods implement [`Deref`] (and [`DerefMut`]
Bulat Musind0d5db62018-01-10 08:03:10 +030045/// for the `write` methods) to allow access to the content of the lock.
Alex Crichton71d4e772014-11-24 11:16:40 -080046///
Alex Crichton76e5ed62014-12-08 20:20:03 -080047/// # Poisoning
48///
Alisa Sirenevada4687b2025-07-25 16:09:29 +030049/// An `RwLock`, like [`Mutex`], will [usually] become poisoned on a panic. Note,
Alisa Sireneva5b2c61e2025-07-19 18:18:01 +030050/// however, that an `RwLock` may only be poisoned if a panic occurs while it is
51/// locked exclusively (write mode). If a panic occurs in any reader, then the
52/// lock will not be poisoned.
Alex Crichton71d4e772014-11-24 11:16:40 -080053///
Alisa Sirenevada4687b2025-07-25 16:09:29 +030054/// [usually]: super::Mutex#poisoning
55///
Alex Crichton76e5ed62014-12-08 20:20:03 -080056/// # Examples
Alex Crichton71d4e772014-11-24 11:16:40 -080057///
58/// ```
Henner Zeller27f97d72026-02-03 07:19:56 -080059/// use std::sync::{Arc, RwLock};
60/// use std::thread;
61/// use std::time::Duration;
Alex Crichton71d4e772014-11-24 11:16:40 -080062///
Henner Zeller27f97d72026-02-03 07:19:56 -080063/// let data = Arc::new(RwLock::new(5));
Alex Crichton71d4e772014-11-24 11:16:40 -080064///
Henner Zeller27f97d72026-02-03 07:19:56 -080065/// // Multiple readers can access in parallel.
66/// for i in 0..3 {
67/// let lock_clone = Arc::clone(&data);
Alex Crichton71d4e772014-11-24 11:16:40 -080068///
Henner Zeller27f97d72026-02-03 07:19:56 -080069/// thread::spawn(move || {
70/// let value = lock_clone.read().unwrap();
71///
72/// println!("Reader {}: Read value {}, now holding lock...", i, *value);
73///
74/// // Simulating a long read operation
75/// thread::sleep(Duration::from_secs(1));
76///
77/// println!("Reader {}: Dropping lock.", i);
78/// // Read lock unlocked when going out of scope.
79/// });
80/// }
81///
82/// thread::sleep(Duration::from_millis(100)); // Wait for readers to start
83///
84/// // While all readers can proceed, a call to .write() has to wait for
85// // current active reader locks.
86/// let mut writable_data = data.write().unwrap();
87/// println!("Writer proceeds...");
88/// *writable_data += 1;
Alex Crichton71d4e772014-11-24 11:16:40 -080089/// ```
Lucas Moralesf2838752017-09-22 18:43:09 -040090///
LeSeulArtichautf3a832f2020-08-22 00:26:28 +020091/// [`Mutex`]: super::Mutex
Brian Andersonb44ee372015-01-23 21:48:20 -080092#[stable(feature = "rust1", since = "1.0.0")]
mejrsf3ac3282022-09-27 13:06:31 +020093#[cfg_attr(not(test), rustc_diagnostic_item = "RwLock")]
P1start57d82892015-04-23 22:53:54 +120094pub struct RwLock<T: ?Sized> {
Connor Tsuid710a8e2025-07-19 12:40:08 +020095 /// The inner [`sys::RwLock`] that synchronizes thread access to the protected data.
joboet98815742022-10-18 13:23:49 +020096 inner: sys::RwLock,
Connor Tsuid710a8e2025-07-19 12:40:08 +020097 /// A flag denoting if this `RwLock` has been poisoned.
Alex Crichtona7220d92016-07-07 11:46:09 -070098 poison: poison::Flag,
Connor Tsuid710a8e2025-07-19 12:40:08 +020099 /// The lock-protected data.
Alex Crichton71d4e772014-11-24 11:16:40 -0800100 data: UnsafeCell<T>,
101}
102
Vadim Petrochenkov7e2ffc72015-11-16 19:54:28 +0300103#[stable(feature = "rust1", since = "1.0.0")]
Jack O'Connorfbf68852017-10-13 18:54:49 -0400104unsafe impl<T: ?Sized + Send> Send for RwLock<T> {}
Connor Tsuid710a8e2025-07-19 12:40:08 +0200105
Vadim Petrochenkov7e2ffc72015-11-16 19:54:28 +0300106#[stable(feature = "rust1", since = "1.0.0")]
P1start57d82892015-04-23 22:53:54 +1200107unsafe impl<T: ?Sized + Send + Sync> Sync for RwLock<T> {}
Flavio Percocod35ebcb2014-12-23 20:21:14 +0100108
Connor Tsuid710a8e2025-07-19 12:40:08 +0200109////////////////////////////////////////////////////////////////////////////////////////////////////
110// Guards
111////////////////////////////////////////////////////////////////////////////////////////////////////
112
Alex Crichton71d4e772014-11-24 11:16:40 -0800113/// RAII structure used to release the shared read access of a lock when
114/// dropped.
Corey Farwell276d91d2016-11-25 17:43:06 -0500115///
Corey Farwelle7b0f2b2017-03-12 14:04:52 -0400116/// This structure is created by the [`read`] and [`try_read`] methods on
Corey Farwell276d91d2016-11-25 17:43:06 -0500117/// [`RwLock`].
118///
LeSeulArtichautf3a832f2020-08-22 00:26:28 +0200119/// [`read`]: RwLock::read
120/// [`try_read`]: RwLock::try_read
Manish Goregaokarf8b774fb2018-05-07 09:27:50 -0700121#[must_use = "if unused the RwLock will immediately unlock"]
Pietro Albini5b3462c2022-01-14 09:50:49 +0100122#[must_not_suspend = "holding a RwLockReadGuard across suspend \
Gus Wynn0f9c3492021-09-27 08:43:30 -0700123 points can cause deadlocks, delays, \
Pietro Albini5b3462c2022-01-14 09:50:49 +0100124 and cause Futures to not implement `Send`"]
Brian Andersonb44ee372015-01-23 21:48:20 -0800125#[stable(feature = "rust1", since = "1.0.0")]
Preston Frombbb1c5b2022-04-15 01:01:36 -0600126#[clippy::has_significant_drop]
Aaron Kofsky321a5982022-06-05 01:01:54 -0400127#[cfg_attr(not(test), rustc_diagnostic_item = "RwLockReadGuard")]
Connor Tsuid710a8e2025-07-19 12:40:08 +0200128pub struct RwLockReadGuard<'rwlock, T: ?Sized + 'rwlock> {
129 /// A pointer to the data protected by the `RwLock`. Note that we use a pointer here instead of
130 /// `&'rwlock T` to avoid `noalias` violations, because a `RwLockReadGuard` instance only holds
131 /// immutability until it drops, not for its whole scope.
132 /// `NonNull` is preferable over `*const T` to allow for niche optimizations. `NonNull` is also
133 /// covariant over `T`, just like we would have with `&T`.
Robin Raymond08650fb2022-05-14 07:29:02 +0000134 data: NonNull<T>,
Connor Tsuid710a8e2025-07-19 12:40:08 +0200135 /// A reference to the internal [`sys::RwLock`] that we have read-locked.
136 inner_lock: &'rwlock sys::RwLock,
Flavio Percococ6ab9a62015-01-11 11:10:04 +0100137}
138
Vadim Petrochenkov7e2ffc72015-11-16 19:54:28 +0300139#[stable(feature = "rust1", since = "1.0.0")]
Scott McMurray3bea2ca2019-02-17 19:42:36 -0800140impl<T: ?Sized> !Send for RwLockReadGuard<'_, T> {}
Ralf Jung71534c42017-11-01 13:39:44 +0100141
142#[stable(feature = "rwlock_guard_sync", since = "1.23.0")]
Scott McMurray3bea2ca2019-02-17 19:42:36 -0800143unsafe impl<T: ?Sized + Sync> Sync for RwLockReadGuard<'_, T> {}
Flavio Percococ6ab9a62015-01-11 11:10:04 +0100144
145/// RAII structure used to release the exclusive write access of a lock when
146/// dropped.
Corey Farwell6b4de8b2016-11-25 17:46:12 -0500147///
Corey Farwelle7b0f2b2017-03-12 14:04:52 -0400148/// This structure is created by the [`write`] and [`try_write`] methods
Corey Farwell6b4de8b2016-11-25 17:46:12 -0500149/// on [`RwLock`].
150///
LeSeulArtichautf3a832f2020-08-22 00:26:28 +0200151/// [`write`]: RwLock::write
152/// [`try_write`]: RwLock::try_write
Manish Goregaokarf8b774fb2018-05-07 09:27:50 -0700153#[must_use = "if unused the RwLock will immediately unlock"]
Pietro Albini5b3462c2022-01-14 09:50:49 +0100154#[must_not_suspend = "holding a RwLockWriteGuard across suspend \
Gus Wynn0f9c3492021-09-27 08:43:30 -0700155 points can cause deadlocks, delays, \
Pietro Albini5b3462c2022-01-14 09:50:49 +0100156 and cause Future's to not implement `Send`"]
Brian Andersonb44ee372015-01-23 21:48:20 -0800157#[stable(feature = "rust1", since = "1.0.0")]
Preston Frombbb1c5b2022-04-15 01:01:36 -0600158#[clippy::has_significant_drop]
Aaron Kofsky321a5982022-06-05 01:01:54 -0400159#[cfg_attr(not(test), rustc_diagnostic_item = "RwLockWriteGuard")]
Connor Tsuid710a8e2025-07-19 12:40:08 +0200160pub struct RwLockWriteGuard<'rwlock, T: ?Sized + 'rwlock> {
161 /// A reference to the [`RwLock`] that we have write-locked.
162 lock: &'rwlock RwLock<T>,
163 /// The poison guard. See the [`poison`] module for more information.
Ralf Jung49697ae2019-12-06 17:28:04 +0100164 poison: poison::Guard,
Alex Crichton71d4e772014-11-24 11:16:40 -0800165}
166
Vadim Petrochenkov7e2ffc72015-11-16 19:54:28 +0300167#[stable(feature = "rust1", since = "1.0.0")]
Scott McMurray3bea2ca2019-02-17 19:42:36 -0800168impl<T: ?Sized> !Send for RwLockWriteGuard<'_, T> {}
Ralf Jung71534c42017-11-01 13:39:44 +0100169
170#[stable(feature = "rwlock_guard_sync", since = "1.23.0")]
Scott McMurray3bea2ca2019-02-17 19:42:36 -0800171unsafe impl<T: ?Sized + Sync> Sync for RwLockWriteGuard<'_, T> {}
Flavio Percococ6ab9a62015-01-11 11:10:04 +0100172
Zachary Sea97c1f2023-10-23 16:26:59 -0500173/// RAII structure used to release the shared read access of a lock when
174/// dropped, which can point to a subfield of the protected data.
175///
Zachary Sd2068be2025-04-30 19:40:29 -0500176/// This structure is created by the [`map`] and [`filter_map`] methods
Zachary Sea97c1f2023-10-23 16:26:59 -0500177/// on [`RwLockReadGuard`].
178///
179/// [`map`]: RwLockReadGuard::map
Zachary Sd2068be2025-04-30 19:40:29 -0500180/// [`filter_map`]: RwLockReadGuard::filter_map
Zachary Sea97c1f2023-10-23 16:26:59 -0500181#[must_use = "if unused the RwLock will immediately unlock"]
182#[must_not_suspend = "holding a MappedRwLockReadGuard across suspend \
183 points can cause deadlocks, delays, \
184 and cause Futures to not implement `Send`"]
Zachary S04f86302023-10-23 16:36:13 -0500185#[unstable(feature = "mapped_lock_guards", issue = "117108")]
Zachary Sea97c1f2023-10-23 16:26:59 -0500186#[clippy::has_significant_drop]
Connor Tsuid710a8e2025-07-19 12:40:08 +0200187pub struct MappedRwLockReadGuard<'rwlock, T: ?Sized + 'rwlock> {
188 /// A pointer to the data protected by the `RwLock`. Note that we use a pointer here instead of
189 /// `&'rwlock T` to avoid `noalias` violations, because a `MappedRwLockReadGuard` instance only
190 /// holds immutability until it drops, not for its whole scope.
191 /// `NonNull` is preferable over `*const T` to allow for niche optimizations. `NonNull` is also
192 /// covariant over `T`, just like we would have with `&T`.
Zachary Sea97c1f2023-10-23 16:26:59 -0500193 data: NonNull<T>,
Connor Tsuid710a8e2025-07-19 12:40:08 +0200194 /// A reference to the internal [`sys::RwLock`] that we have read-locked.
195 inner_lock: &'rwlock sys::RwLock,
Zachary Sea97c1f2023-10-23 16:26:59 -0500196}
197
Zachary S04f86302023-10-23 16:36:13 -0500198#[unstable(feature = "mapped_lock_guards", issue = "117108")]
Zachary Sea97c1f2023-10-23 16:26:59 -0500199impl<T: ?Sized> !Send for MappedRwLockReadGuard<'_, T> {}
200
Zachary S04f86302023-10-23 16:36:13 -0500201#[unstable(feature = "mapped_lock_guards", issue = "117108")]
Zachary Sea97c1f2023-10-23 16:26:59 -0500202unsafe impl<T: ?Sized + Sync> Sync for MappedRwLockReadGuard<'_, T> {}
203
204/// RAII structure used to release the exclusive write access of a lock when
205/// dropped, which can point to a subfield of the protected data.
206///
Zachary Sd2068be2025-04-30 19:40:29 -0500207/// This structure is created by the [`map`] and [`filter_map`] methods
Zachary Sea97c1f2023-10-23 16:26:59 -0500208/// on [`RwLockWriteGuard`].
209///
210/// [`map`]: RwLockWriteGuard::map
Zachary Sd2068be2025-04-30 19:40:29 -0500211/// [`filter_map`]: RwLockWriteGuard::filter_map
Zachary Sea97c1f2023-10-23 16:26:59 -0500212#[must_use = "if unused the RwLock will immediately unlock"]
213#[must_not_suspend = "holding a MappedRwLockWriteGuard across suspend \
214 points can cause deadlocks, delays, \
215 and cause Future's to not implement `Send`"]
Zachary S04f86302023-10-23 16:36:13 -0500216#[unstable(feature = "mapped_lock_guards", issue = "117108")]
Zachary Sea97c1f2023-10-23 16:26:59 -0500217#[clippy::has_significant_drop]
Connor Tsuid710a8e2025-07-19 12:40:08 +0200218pub struct MappedRwLockWriteGuard<'rwlock, T: ?Sized + 'rwlock> {
219 /// A pointer to the data protected by the `RwLock`. Note that we use a pointer here instead of
220 /// `&'rwlock T` to avoid `noalias` violations, because a `MappedRwLockWriteGuard` instance only
221 /// holds uniquneness until it drops, not for its whole scope.
222 /// `NonNull` is preferable over `*const T` to allow for niche optimizations.
Zachary Sea97c1f2023-10-23 16:26:59 -0500223 data: NonNull<T>,
Connor Tsuid710a8e2025-07-19 12:40:08 +0200224 /// `NonNull` is covariant over `T`, so we add a `PhantomData<&'rwlock mut T>` field here to
225 /// enforce the correct invariance over `T`.
226 _variance: PhantomData<&'rwlock mut T>,
227 /// A reference to the internal [`sys::RwLock`] that we have write-locked.
228 inner_lock: &'rwlock sys::RwLock,
229 /// A reference to the original `RwLock`'s poison state.
230 poison_flag: &'rwlock poison::Flag,
231 /// The poison guard. See the [`poison`] module for more information.
232 poison_guard: poison::Guard,
Zachary Sea97c1f2023-10-23 16:26:59 -0500233}
234
Zachary S04f86302023-10-23 16:36:13 -0500235#[unstable(feature = "mapped_lock_guards", issue = "117108")]
Zachary Sea97c1f2023-10-23 16:26:59 -0500236impl<T: ?Sized> !Send for MappedRwLockWriteGuard<'_, T> {}
237
Zachary S04f86302023-10-23 16:36:13 -0500238#[unstable(feature = "mapped_lock_guards", issue = "117108")]
Zachary Sea97c1f2023-10-23 16:26:59 -0500239unsafe impl<T: ?Sized + Sync> Sync for MappedRwLockWriteGuard<'_, T> {}
240
Connor Tsuid710a8e2025-07-19 12:40:08 +0200241////////////////////////////////////////////////////////////////////////////////////////////////////
242// Implementations
243////////////////////////////////////////////////////////////////////////////////////////////////////
244
Huon Wilson25d070f2015-03-08 22:01:01 +1100245impl<T> RwLock<T> {
Steve Klabnikbbbdd102015-01-21 14:54:17 -0500246 /// Creates a new instance of an `RwLock<T>` which is unlocked.
247 ///
248 /// # Examples
249 ///
250 /// ```
251 /// use std::sync::RwLock;
252 ///
253 /// let lock = RwLock::new(5);
254 /// ```
Brian Andersonb44ee372015-01-23 21:48:20 -0800255 #[stable(feature = "rust1", since = "1.0.0")]
Mara Bosedae4952022-06-06 13:55:43 +0200256 #[rustc_const_stable(feature = "const_locks", since = "1.63.0")]
Mara Bosacc3ab42022-06-06 13:45:02 +0200257 #[inline]
258 pub const fn new(t: T) -> RwLock<T> {
joboet98815742022-10-18 13:23:49 +0200259 RwLock { inner: sys::RwLock::new(), poison: poison::Flag::new(), data: UnsafeCell::new(t) }
Alex Crichton71d4e772014-11-24 11:16:40 -0800260 }
EFanZh242c6c32024-11-30 19:33:06 +0800261
262 /// Returns the contained value by cloning it.
263 ///
264 /// # Errors
265 ///
266 /// This function will return an error if the `RwLock` is poisoned. An
267 /// `RwLock` is poisoned whenever a writer panics while holding an exclusive
268 /// lock.
269 ///
270 /// # Examples
271 ///
272 /// ```
273 /// #![feature(lock_value_accessors)]
274 ///
275 /// use std::sync::RwLock;
276 ///
277 /// let mut lock = RwLock::new(7);
278 ///
279 /// assert_eq!(lock.get_cloned().unwrap(), 7);
280 /// ```
281 #[unstable(feature = "lock_value_accessors", issue = "133407")]
282 pub fn get_cloned(&self) -> Result<T, PoisonError<()>>
283 where
284 T: Clone,
285 {
286 match self.read() {
287 Ok(guard) => Ok((*guard).clone()),
288 Err(_) => Err(PoisonError::new(())),
289 }
290 }
291
292 /// Sets the contained value.
293 ///
294 /// # Errors
295 ///
296 /// This function will return an error containing the provided `value` if
297 /// the `RwLock` is poisoned. An `RwLock` is poisoned whenever a writer
298 /// panics while holding an exclusive lock.
299 ///
300 /// # Examples
301 ///
302 /// ```
303 /// #![feature(lock_value_accessors)]
304 ///
305 /// use std::sync::RwLock;
306 ///
307 /// let mut lock = RwLock::new(7);
308 ///
309 /// assert_eq!(lock.get_cloned().unwrap(), 7);
310 /// lock.set(11).unwrap();
311 /// assert_eq!(lock.get_cloned().unwrap(), 11);
312 /// ```
313 #[unstable(feature = "lock_value_accessors", issue = "133407")]
Urgau0e8d1e12025-11-02 13:38:30 +0100314 #[rustc_should_not_be_called_on_const_items]
EFanZh242c6c32024-11-30 19:33:06 +0800315 pub fn set(&self, value: T) -> Result<(), PoisonError<T>> {
316 if mem::needs_drop::<T>() {
317 // If the contained value has non-trivial destructor, we
318 // call that destructor after the lock being released.
319 self.replace(value).map(drop)
320 } else {
321 match self.write() {
322 Ok(mut guard) => {
323 *guard = value;
324
325 Ok(())
326 }
327 Err(_) => Err(PoisonError::new(value)),
328 }
329 }
330 }
331
332 /// Replaces the contained value with `value`, and returns the old contained value.
333 ///
334 /// # Errors
335 ///
336 /// This function will return an error containing the provided `value` if
337 /// the `RwLock` is poisoned. An `RwLock` is poisoned whenever a writer
338 /// panics while holding an exclusive lock.
339 ///
340 /// # Examples
341 ///
342 /// ```
343 /// #![feature(lock_value_accessors)]
344 ///
345 /// use std::sync::RwLock;
346 ///
347 /// let mut lock = RwLock::new(7);
348 ///
349 /// assert_eq!(lock.replace(11).unwrap(), 7);
350 /// assert_eq!(lock.get_cloned().unwrap(), 11);
351 /// ```
352 #[unstable(feature = "lock_value_accessors", issue = "133407")]
Urgau0e8d1e12025-11-02 13:38:30 +0100353 #[rustc_should_not_be_called_on_const_items]
EFanZh242c6c32024-11-30 19:33:06 +0800354 pub fn replace(&self, value: T) -> LockResult<T> {
355 match self.write() {
356 Ok(mut guard) => Ok(mem::replace(&mut *guard, value)),
357 Err(_) => Err(PoisonError::new(value)),
358 }
359 }
P1start57d82892015-04-23 22:53:54 +1200360}
Alex Crichton71d4e772014-11-24 11:16:40 -0800361
P1start57d82892015-04-23 22:53:54 +1200362impl<T: ?Sized> RwLock<T> {
Martin Geislerf67184f2022-09-25 20:44:42 +0200363 /// Locks this `RwLock` with shared read access, blocking the current thread
Alex Crichton71d4e772014-11-24 11:16:40 -0800364 /// until it can be acquired.
365 ///
366 /// The calling thread will be blocked until there are no more writers which
367 /// hold the lock. There may be other readers currently inside the lock when
368 /// this method returns. This method does not provide any guarantees with
369 /// respect to the ordering of whether contentious readers or writers will
370 /// acquire the lock first.
371 ///
372 /// Returns an RAII guard which will release this thread's shared access
373 /// once it is dropped.
374 ///
Kamal Marhubi129a6232016-02-01 21:41:29 -0500375 /// # Errors
Alex Crichton71d4e772014-11-24 11:16:40 -0800376 ///
Martin Geislerf67184f2022-09-25 20:44:42 +0200377 /// This function will return an error if the `RwLock` is poisoned. An
378 /// `RwLock` is poisoned whenever a writer panics while holding an exclusive
379 /// lock. The failure will occur immediately after the lock has been
EFanZh242c6c32024-11-30 19:33:06 +0800380 /// acquired. The acquired lock guard will be contained in the returned
381 /// error.
Nabeel Omerb491ddd2016-10-13 21:07:18 +0530382 ///
383 /// # Panics
384 ///
Henner Zeller27f97d72026-02-03 07:19:56 -0800385 /// This function might panic when called if the lock is already held by the current thread
386 /// in read or write mode.
Lucas Moralesf2838752017-09-22 18:43:09 -0400387 ///
388 /// # Examples
389 ///
390 /// ```
391 /// use std::sync::{Arc, RwLock};
392 /// use std::thread;
393 ///
394 /// let lock = Arc::new(RwLock::new(1));
Alexis Bourget81e85ce2020-08-30 21:59:43 +0200395 /// let c_lock = Arc::clone(&lock);
Lucas Moralesf2838752017-09-22 18:43:09 -0400396 ///
397 /// let n = lock.read().unwrap();
398 /// assert_eq!(*n, 1);
399 ///
400 /// thread::spawn(move || {
401 /// let r = c_lock.read();
402 /// assert!(r.is_ok());
403 /// }).join().unwrap();
404 /// ```
Alex Crichton71d4e772014-11-24 11:16:40 -0800405 #[inline]
Brian Andersonb44ee372015-01-23 21:48:20 -0800406 #[stable(feature = "rust1", since = "1.0.0")]
Urgau0e8d1e12025-11-02 13:38:30 +0100407 #[rustc_should_not_be_called_on_const_items]
Mazdak Farrokhzad379c3802019-03-01 09:34:11 +0100408 pub fn read(&self) -> LockResult<RwLockReadGuard<'_, T>> {
Jonathan Reemfc875b02016-01-30 16:39:03 -0800409 unsafe {
Alex Crichtona7220d92016-07-07 11:46:09 -0700410 self.inner.read();
411 RwLockReadGuard::new(self)
Jonathan Reemfc875b02016-01-30 16:39:03 -0800412 }
Alex Crichton71d4e772014-11-24 11:16:40 -0800413 }
414
Martin Geislerf67184f2022-09-25 20:44:42 +0200415 /// Attempts to acquire this `RwLock` with shared read access.
Alex Crichton71d4e772014-11-24 11:16:40 -0800416 ///
John Gallagher833fc272015-05-06 11:47:30 -0400417 /// If the access could not be granted at this time, then `Err` is returned.
418 /// Otherwise, an RAII guard is returned which will release the shared access
419 /// when it is dropped.
420 ///
421 /// This function does not block.
422 ///
423 /// This function does not provide any guarantees with respect to the ordering
424 /// of whether contentious readers or writers will acquire the lock first.
Alex Crichton71d4e772014-11-24 11:16:40 -0800425 ///
Kamal Marhubi129a6232016-02-01 21:41:29 -0500426 /// # Errors
Alex Crichton71d4e772014-11-24 11:16:40 -0800427 ///
Martin Geislerf67184f2022-09-25 20:44:42 +0200428 /// This function will return the [`Poisoned`] error if the `RwLock` is
429 /// poisoned. An `RwLock` is poisoned whenever a writer panics while holding
430 /// an exclusive lock. `Poisoned` will only be returned if the lock would
EFanZh242c6c32024-11-30 19:33:06 +0800431 /// have otherwise been acquired. An acquired lock guard will be contained
432 /// in the returned error.
Lucas Moralesf2838752017-09-22 18:43:09 -0400433 ///
Martin Geislerf67184f2022-09-25 20:44:42 +0200434 /// This function will return the [`WouldBlock`] error if the `RwLock` could
435 /// not be acquired because it was already locked exclusively.
Taylor Yue5873662021-05-20 17:15:39 -0500436 ///
437 /// [`Poisoned`]: TryLockError::Poisoned
438 /// [`WouldBlock`]: TryLockError::WouldBlock
439 ///
Lucas Moralesf2838752017-09-22 18:43:09 -0400440 /// # Examples
441 ///
442 /// ```
443 /// use std::sync::RwLock;
444 ///
445 /// let lock = RwLock::new(1);
446 ///
447 /// match lock.try_read() {
448 /// Ok(n) => assert_eq!(*n, 1),
449 /// Err(_) => unreachable!(),
450 /// };
451 /// ```
Alex Crichton71d4e772014-11-24 11:16:40 -0800452 #[inline]
Brian Andersonb44ee372015-01-23 21:48:20 -0800453 #[stable(feature = "rust1", since = "1.0.0")]
Urgau0e8d1e12025-11-02 13:38:30 +0100454 #[rustc_should_not_be_called_on_const_items]
Mazdak Farrokhzad379c3802019-03-01 09:34:11 +0100455 pub fn try_read(&self) -> TryLockResult<RwLockReadGuard<'_, T>> {
Jonathan Reemfc875b02016-01-30 16:39:03 -0800456 unsafe {
Alex Crichtona7220d92016-07-07 11:46:09 -0700457 if self.inner.try_read() {
458 Ok(RwLockReadGuard::new(self)?)
Jonathan Reemfc875b02016-01-30 16:39:03 -0800459 } else {
460 Err(TryLockError::WouldBlock)
461 }
Alex Crichton71d4e772014-11-24 11:16:40 -0800462 }
463 }
464
Martin Geislerf67184f2022-09-25 20:44:42 +0200465 /// Locks this `RwLock` with exclusive write access, blocking the current
Alex Crichton71d4e772014-11-24 11:16:40 -0800466 /// thread until it can be acquired.
467 ///
468 /// This function will not return while other writers or other readers
469 /// currently have access to the lock.
470 ///
Martin Geislerf67184f2022-09-25 20:44:42 +0200471 /// Returns an RAII guard which will drop the write access of this `RwLock`
Alex Crichton71d4e772014-11-24 11:16:40 -0800472 /// when dropped.
473 ///
Kamal Marhubi129a6232016-02-01 21:41:29 -0500474 /// # Errors
Alex Crichton71d4e772014-11-24 11:16:40 -0800475 ///
Martin Geislerf67184f2022-09-25 20:44:42 +0200476 /// This function will return an error if the `RwLock` is poisoned. An
477 /// `RwLock` is poisoned whenever a writer panics while holding an exclusive
EFanZh242c6c32024-11-30 19:33:06 +0800478 /// lock. An error will be returned when the lock is acquired. The acquired
479 /// lock guard will be contained in the returned error.
Nabeel Omerb491ddd2016-10-13 21:07:18 +0530480 ///
481 /// # Panics
482 ///
Henner Zeller27f97d72026-02-03 07:19:56 -0800483 /// This function might panic when called if the lock is already held by the current thread
484 /// in read or write mode.
Lucas Moralesf2838752017-09-22 18:43:09 -0400485 ///
486 /// # Examples
487 ///
488 /// ```
489 /// use std::sync::RwLock;
490 ///
491 /// let lock = RwLock::new(1);
492 ///
493 /// let mut n = lock.write().unwrap();
494 /// *n = 2;
495 ///
496 /// assert!(lock.try_read().is_err());
497 /// ```
Alex Crichton71d4e772014-11-24 11:16:40 -0800498 #[inline]
Brian Andersonb44ee372015-01-23 21:48:20 -0800499 #[stable(feature = "rust1", since = "1.0.0")]
Urgau0e8d1e12025-11-02 13:38:30 +0100500 #[rustc_should_not_be_called_on_const_items]
Mazdak Farrokhzad379c3802019-03-01 09:34:11 +0100501 pub fn write(&self) -> LockResult<RwLockWriteGuard<'_, T>> {
Jonathan Reemfc875b02016-01-30 16:39:03 -0800502 unsafe {
Alex Crichtona7220d92016-07-07 11:46:09 -0700503 self.inner.write();
504 RwLockWriteGuard::new(self)
Jonathan Reemfc875b02016-01-30 16:39:03 -0800505 }
Alex Crichton71d4e772014-11-24 11:16:40 -0800506 }
507
Martin Geislerf67184f2022-09-25 20:44:42 +0200508 /// Attempts to lock this `RwLock` with exclusive write access.
Alex Crichton71d4e772014-11-24 11:16:40 -0800509 ///
John Gallagher833fc272015-05-06 11:47:30 -0400510 /// If the lock could not be acquired at this time, then `Err` is returned.
511 /// Otherwise, an RAII guard is returned which will release the lock when
512 /// it is dropped.
513 ///
514 /// This function does not block.
515 ///
516 /// This function does not provide any guarantees with respect to the ordering
517 /// of whether contentious readers or writers will acquire the lock first.
Alex Crichton71d4e772014-11-24 11:16:40 -0800518 ///
Kamal Marhubi129a6232016-02-01 21:41:29 -0500519 /// # Errors
Alex Crichton71d4e772014-11-24 11:16:40 -0800520 ///
Martin Geislerf67184f2022-09-25 20:44:42 +0200521 /// This function will return the [`Poisoned`] error if the `RwLock` is
522 /// poisoned. An `RwLock` is poisoned whenever a writer panics while holding
523 /// an exclusive lock. `Poisoned` will only be returned if the lock would
EFanZh242c6c32024-11-30 19:33:06 +0800524 /// have otherwise been acquired. An acquired lock guard will be contained
525 /// in the returned error.
Taylor Yue5873662021-05-20 17:15:39 -0500526 ///
Martin Geislerf67184f2022-09-25 20:44:42 +0200527 /// This function will return the [`WouldBlock`] error if the `RwLock` could
krikera7a70f642025-06-26 15:33:43 +0530528 /// not be acquired because it was already locked.
Taylor Yue5873662021-05-20 17:15:39 -0500529 ///
530 /// [`Poisoned`]: TryLockError::Poisoned
531 /// [`WouldBlock`]: TryLockError::WouldBlock
532 ///
Lucas Moralesf2838752017-09-22 18:43:09 -0400533 ///
534 /// # Examples
535 ///
536 /// ```
537 /// use std::sync::RwLock;
538 ///
539 /// let lock = RwLock::new(1);
540 ///
541 /// let n = lock.read().unwrap();
542 /// assert_eq!(*n, 1);
543 ///
544 /// assert!(lock.try_write().is_err());
545 /// ```
Alex Crichton71d4e772014-11-24 11:16:40 -0800546 #[inline]
Brian Andersonb44ee372015-01-23 21:48:20 -0800547 #[stable(feature = "rust1", since = "1.0.0")]
Urgau0e8d1e12025-11-02 13:38:30 +0100548 #[rustc_should_not_be_called_on_const_items]
Mazdak Farrokhzad379c3802019-03-01 09:34:11 +0100549 pub fn try_write(&self) -> TryLockResult<RwLockWriteGuard<'_, T>> {
Jonathan Reemfc875b02016-01-30 16:39:03 -0800550 unsafe {
Alex Crichtona7220d92016-07-07 11:46:09 -0700551 if self.inner.try_write() {
552 Ok(RwLockWriteGuard::new(self)?)
Jonathan Reemfc875b02016-01-30 16:39:03 -0800553 } else {
554 Err(TryLockError::WouldBlock)
555 }
Alex Crichton71d4e772014-11-24 11:16:40 -0800556 }
557 }
Keegan McAllister96c3a132015-01-23 11:47:04 -0800558
Andrew Paseltiner6fa16d62015-04-13 10:21:32 -0400559 /// Determines whether the lock is poisoned.
Keegan McAllister96c3a132015-01-23 11:47:04 -0800560 ///
561 /// If another thread is active, the lock can still become poisoned at any
Alexander Regueirob87363e2019-02-09 21:23:30 +0000562 /// time. You should not trust a `false` value for program correctness
Keegan McAllister96c3a132015-01-23 11:47:04 -0800563 /// without additional synchronization.
Lucas Moralesf2838752017-09-22 18:43:09 -0400564 ///
565 /// # Examples
566 ///
567 /// ```
568 /// use std::sync::{Arc, RwLock};
569 /// use std::thread;
570 ///
571 /// let lock = Arc::new(RwLock::new(0));
Alexis Bourget81e85ce2020-08-30 21:59:43 +0200572 /// let c_lock = Arc::clone(&lock);
Lucas Moralesf2838752017-09-22 18:43:09 -0400573 ///
574 /// let _ = thread::spawn(move || {
575 /// let _lock = c_lock.write().unwrap();
576 /// panic!(); // the lock gets poisoned
577 /// }).join();
578 /// assert_eq!(lock.is_poisoned(), true);
579 /// ```
Keegan McAllister96c3a132015-01-23 11:47:04 -0800580 #[inline]
Alex Crichtonc032d6f2015-06-10 18:43:08 -0700581 #[stable(feature = "sync_poison", since = "1.2.0")]
Keegan McAllister96c3a132015-01-23 11:47:04 -0800582 pub fn is_poisoned(&self) -> bool {
Alex Crichtona7220d92016-07-07 11:46:09 -0700583 self.poison.get()
Keegan McAllister96c3a132015-01-23 11:47:04 -0800584 }
Cristi Cobzarenco90ccefd2015-10-15 17:14:06 +0100585
MultisampledNighte853b502024-03-22 23:04:20 +0100586 /// Clear the poisoned state from a lock.
Thayne McCombsfc383882022-04-26 00:58:51 -0600587 ///
Thayne McCombsa65afd82022-05-20 00:15:26 -0600588 /// If the lock is poisoned, it will remain poisoned until this function is called. This allows
589 /// recovering from a poisoned state and marking that it has recovered. For example, if the
Kriskras99cdf25c92023-09-19 12:46:53 +0200590 /// value is overwritten by a known-good value, then the lock can be marked as un-poisoned. Or
Thayne McCombsa65afd82022-05-20 00:15:26 -0600591 /// possibly, the value could be inspected to determine if it is in a consistent state, and if
592 /// so the poison is removed.
Thayne McCombsfc383882022-04-26 00:58:51 -0600593 ///
594 /// # Examples
595 ///
596 /// ```
Thayne McCombsfc383882022-04-26 00:58:51 -0600597 /// use std::sync::{Arc, RwLock};
598 /// use std::thread;
599 ///
600 /// let lock = Arc::new(RwLock::new(0));
601 /// let c_lock = Arc::clone(&lock);
602 ///
603 /// let _ = thread::spawn(move || {
604 /// let _lock = c_lock.write().unwrap();
Kriskras99cdf25c92023-09-19 12:46:53 +0200605 /// panic!(); // the lock gets poisoned
Thayne McCombsfc383882022-04-26 00:58:51 -0600606 /// }).join();
607 ///
Thayne McCombs66d88c92022-05-19 01:53:41 -0600608 /// assert_eq!(lock.is_poisoned(), true);
609 /// let guard = lock.write().unwrap_or_else(|mut e| {
610 /// **e.get_mut() = 1;
611 /// lock.clear_poison();
612 /// e.into_inner()
613 /// });
Thayne McCombsfc383882022-04-26 00:58:51 -0600614 /// assert_eq!(lock.is_poisoned(), false);
Thayne McCombs66d88c92022-05-19 01:53:41 -0600615 /// assert_eq!(*guard, 1);
Thayne McCombsfc383882022-04-26 00:58:51 -0600616 /// ```
617 #[inline]
Mark Rousskov80438212024-02-03 16:37:58 -0500618 #[stable(feature = "mutex_unpoison", since = "1.77.0")]
Thayne McCombs66d88c92022-05-19 01:53:41 -0600619 pub fn clear_poison(&self) {
620 self.poison.clear();
Thayne McCombsfc383882022-04-26 00:58:51 -0600621 }
622
Cristi Cobzarenco90ccefd2015-10-15 17:14:06 +0100623 /// Consumes this `RwLock`, returning the underlying data.
624 ///
Kamal Marhubi129a6232016-02-01 21:41:29 -0500625 /// # Errors
Cristi Cobzarenco90ccefd2015-10-15 17:14:06 +0100626 ///
EFanZh242c6c32024-11-30 19:33:06 +0800627 /// This function will return an error containing the underlying data if
628 /// the `RwLock` is poisoned. An `RwLock` is poisoned whenever a writer
629 /// panics while holding an exclusive lock. An error will only be returned
630 /// if the lock would have otherwise been acquired.
Lucas Moralesf2838752017-09-22 18:43:09 -0400631 ///
632 /// # Examples
633 ///
634 /// ```
635 /// use std::sync::RwLock;
636 ///
637 /// let lock = RwLock::new(String::new());
638 /// {
639 /// let mut s = lock.write().unwrap();
640 /// *s = "modified".to_owned();
641 /// }
642 /// assert_eq!(lock.into_inner().unwrap(), "modified");
643 /// ```
Alex Crichton464cdff2015-12-02 17:31:49 -0800644 #[stable(feature = "rwlock_into_inner", since = "1.6.0")]
Mark Rousskova06baa52019-12-22 17:42:04 -0500645 pub fn into_inner(self) -> LockResult<T>
646 where
647 T: Sized,
648 {
Benoît du Garreauac470e92021-04-29 09:53:19 +0200649 let data = self.data.into_inner();
Josh Stone34895de2022-06-09 11:51:39 -0700650 poison::map_result(self.poison.borrow(), |()| data)
Cristi Cobzarenco90ccefd2015-10-15 17:14:06 +0100651 }
652
653 /// Returns a mutable reference to the underlying data.
654 ///
655 /// Since this call borrows the `RwLock` mutably, no actual locking needs to
xizheyin0162f292025-03-31 15:11:23 +0800656 /// take place -- the mutable borrow statically guarantees no new locks can be acquired
Connor Tsuid710a8e2025-07-19 12:40:08 +0200657 /// while this reference exists. Note that this method does not clear any previously abandoned
658 /// locks (e.g., via [`forget()`] on a [`RwLockReadGuard`] or [`RwLockWriteGuard`]).
Cristi Cobzarenco90ccefd2015-10-15 17:14:06 +0100659 ///
Kamal Marhubi129a6232016-02-01 21:41:29 -0500660 /// # Errors
Cristi Cobzarenco90ccefd2015-10-15 17:14:06 +0100661 ///
EFanZh242c6c32024-11-30 19:33:06 +0800662 /// This function will return an error containing a mutable reference to
663 /// the underlying data if the `RwLock` is poisoned. An `RwLock` is
664 /// poisoned whenever a writer panics while holding an exclusive lock.
665 /// An error will only be returned if the lock would have otherwise been
666 /// acquired.
Lucas Moralesf2838752017-09-22 18:43:09 -0400667 ///
668 /// # Examples
669 ///
670 /// ```
671 /// use std::sync::RwLock;
672 ///
673 /// let mut lock = RwLock::new(0);
674 /// *lock.get_mut().unwrap() = 10;
675 /// assert_eq!(*lock.read().unwrap(), 10);
676 /// ```
Alex Crichton464cdff2015-12-02 17:31:49 -0800677 #[stable(feature = "rwlock_get_mut", since = "1.6.0")]
Cristi Cobzarenco90ccefd2015-10-15 17:14:06 +0100678 pub fn get_mut(&mut self) -> LockResult<&mut T> {
Daniel Henry-Mantilla5886c382020-09-19 21:33:40 +0200679 let data = self.data.get_mut();
Josh Stone34895de2022-06-09 11:51:39 -0700680 poison::map_result(self.poison.borrow(), |()| data)
Cristi Cobzarenco90ccefd2015-10-15 17:14:06 +0100681 }
Jonas Platte9efad3a2025-04-27 16:18:29 +0200682
683 /// Returns a raw pointer to the underlying data.
Jonas Platte9d6c5a82025-05-21 08:05:44 +0200684 ///
685 /// The returned pointer is always non-null and properly aligned, but it is
686 /// the user's responsibility to ensure that any reads and writes through it
687 /// are properly synchronized to avoid data races, and that it is not read
688 /// or written through after the lock is dropped.
Jonas Platte9efad3a2025-04-27 16:18:29 +0200689 #[unstable(feature = "rwlock_data_ptr", issue = "140368")]
Peter Lyons Kehl819f8b02025-09-22 11:40:53 -0700690 pub const fn data_ptr(&self) -> *mut T {
Jonas Platte9efad3a2025-04-27 16:18:29 +0200691 self.data.get()
692 }
Alex Crichton71d4e772014-11-24 11:16:40 -0800693}
694
Brian Andersonb44ee372015-01-23 21:48:20 -0800695#[stable(feature = "rust1", since = "1.0.0")]
P1start57d82892015-04-23 22:53:54 +1200696impl<T: ?Sized + fmt::Debug> fmt::Debug for RwLock<T> {
Mazdak Farrokhzad379c3802019-03-01 09:34:11 +0100697 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Mara Bos5402abc2021-03-27 13:47:11 +0100698 let mut d = f.debug_struct("RwLock");
nwin36ba96e2015-02-20 13:09:29 +0100699 match self.try_read() {
Mara Bos5402abc2021-03-27 13:47:11 +0100700 Ok(guard) => {
701 d.field("data", &&*guard);
702 }
nwin36ba96e2015-02-20 13:09:29 +0100703 Err(TryLockError::Poisoned(err)) => {
Mara Bos5402abc2021-03-27 13:47:11 +0100704 d.field("data", &&**err.get_ref());
Mark Rousskova06baa52019-12-22 17:42:04 -0500705 }
Malo Jaffré679457a2017-10-09 20:09:08 +0200706 Err(TryLockError::WouldBlock) => {
joboetb7e68df2023-03-18 20:06:12 +0100707 d.field("data", &format_args!("<locked>"));
Malo Jaffré679457a2017-10-09 20:09:08 +0200708 }
nwin36ba96e2015-02-20 13:09:29 +0100709 }
Mara Bos5402abc2021-03-27 13:47:11 +0100710 d.field("poisoned", &self.poison.get());
711 d.finish_non_exhaustive()
nwin36ba96e2015-02-20 13:09:29 +0100712 }
713}
714
Oliver Middleton2f703e42017-05-20 08:38:39 +0100715#[stable(feature = "rw_lock_default", since = "1.10.0")]
Tobias Bucher3df35a02016-04-15 17:53:43 +0200716impl<T: Default> Default for RwLock<T> {
athulappadan49e77db2016-09-11 17:00:09 +0530717 /// Creates a new `RwLock<T>`, with the `Default` value for T.
Tobias Bucher3df35a02016-04-15 17:53:43 +0200718 fn default() -> RwLock<T> {
719 RwLock::new(Default::default())
720 }
721}
722
Oliver Middletona8d107b2017-12-27 14:11:05 +0000723#[stable(feature = "rw_lock_from", since = "1.24.0")]
Eduardo Pinho0855ea12017-11-18 21:05:06 +0000724impl<T> From<T> for RwLock<T> {
725 /// Creates a new instance of an `RwLock<T>` which is unlocked.
726 /// This is equivalent to [`RwLock::new`].
Eduardo Pinho0855ea12017-11-18 21:05:06 +0000727 fn from(t: T) -> Self {
728 RwLock::new(t)
729 }
730}
731
P1start57d82892015-04-23 22:53:54 +1200732impl<'rwlock, T: ?Sized> RwLockReadGuard<'rwlock, T> {
John Arundela19472a2024-07-15 12:26:30 +0100733 /// Creates a new instance of `RwLockReadGuard<T>` from a `RwLock<T>`.
Connor Tsuif71ecc42024-10-16 09:31:30 -0400734 ///
735 /// # Safety
736 ///
737 /// This function is safe if and only if the same thread has successfully and safely called
738 /// `lock.inner.read()`, `lock.inner.try_read()`, or `lock.inner.downgrade()` before
739 /// instantiating this object.
Mark Rousskova06baa52019-12-22 17:42:04 -0500740 unsafe fn new(lock: &'rwlock RwLock<T>) -> LockResult<RwLockReadGuard<'rwlock, T>> {
Robin Raymond0b6e6e32022-06-19 09:22:32 +0200741 poison::map_result(lock.poison.borrow(), |()| RwLockReadGuard {
Jubilee Younge3246022024-07-14 17:59:37 -0700742 data: unsafe { NonNull::new_unchecked(lock.data.get()) },
Robin Raymond0b6e6e32022-06-19 09:22:32 +0200743 inner_lock: &lock.inner,
Robin Raymond0b6e6e32022-06-19 09:22:32 +0200744 })
Flavio Percococ6ab9a62015-01-11 11:10:04 +0100745 }
Connor Tsuid710a8e2025-07-19 12:40:08 +0200746
747 /// Makes a [`MappedRwLockReadGuard`] for a component of the borrowed data, e.g.
748 /// an enum variant.
749 ///
750 /// The `RwLock` is already locked for reading, so this cannot fail.
751 ///
752 /// This is an associated function that needs to be used as
753 /// `RwLockReadGuard::map(...)`. A method would interfere with methods of
754 /// the same name on the contents of the `RwLockReadGuard` used through
755 /// `Deref`.
756 ///
757 /// # Panics
758 ///
759 /// If the closure panics, the guard will be dropped (unlocked) and the RwLock will not be
760 /// poisoned.
761 #[unstable(feature = "mapped_lock_guards", issue = "117108")]
762 pub fn map<U, F>(orig: Self, f: F) -> MappedRwLockReadGuard<'rwlock, U>
763 where
764 F: FnOnce(&T) -> &U,
765 U: ?Sized,
766 {
767 // SAFETY: the conditions of `RwLockReadGuard::new` were satisfied when the original guard
768 // was created, and have been upheld throughout `map` and/or `filter_map`.
769 // The signature of the closure guarantees that it will not "leak" the lifetime of the
770 // reference passed to it. If the closure panics, the guard will be dropped.
771 let data = NonNull::from(f(unsafe { orig.data.as_ref() }));
772 let orig = ManuallyDrop::new(orig);
773 MappedRwLockReadGuard { data, inner_lock: &orig.inner_lock }
774 }
775
776 /// Makes a [`MappedRwLockReadGuard`] for a component of the borrowed data. The
777 /// original guard is returned as an `Err(...)` if the closure returns
778 /// `None`.
779 ///
780 /// The `RwLock` is already locked for reading, so this cannot fail.
781 ///
782 /// This is an associated function that needs to be used as
783 /// `RwLockReadGuard::filter_map(...)`. A method would interfere with methods
784 /// of the same name on the contents of the `RwLockReadGuard` used through
785 /// `Deref`.
786 ///
787 /// # Panics
788 ///
789 /// If the closure panics, the guard will be dropped (unlocked) and the RwLock will not be
790 /// poisoned.
791 #[unstable(feature = "mapped_lock_guards", issue = "117108")]
792 pub fn filter_map<U, F>(orig: Self, f: F) -> Result<MappedRwLockReadGuard<'rwlock, U>, Self>
793 where
794 F: FnOnce(&T) -> Option<&U>,
795 U: ?Sized,
796 {
797 // SAFETY: the conditions of `RwLockReadGuard::new` were satisfied when the original guard
798 // was created, and have been upheld throughout `map` and/or `filter_map`.
799 // The signature of the closure guarantees that it will not "leak" the lifetime of the
800 // reference passed to it. If the closure panics, the guard will be dropped.
801 match f(unsafe { orig.data.as_ref() }) {
802 Some(data) => {
803 let data = NonNull::from(data);
804 let orig = ManuallyDrop::new(orig);
805 Ok(MappedRwLockReadGuard { data, inner_lock: &orig.inner_lock })
806 }
807 None => Err(orig),
808 }
809 }
Alex Crichton71d4e772014-11-24 11:16:40 -0800810}
Flavio Percococ6ab9a62015-01-11 11:10:04 +0100811
P1start57d82892015-04-23 22:53:54 +1200812impl<'rwlock, T: ?Sized> RwLockWriteGuard<'rwlock, T> {
John Arundela19472a2024-07-15 12:26:30 +0100813 /// Creates a new instance of `RwLockWriteGuard<T>` from a `RwLock<T>`.
Connor Tsuid710a8e2025-07-19 12:40:08 +0200814 ///
815 /// # Safety
816 ///
817 /// This function is safe if and only if the same thread has successfully and safely called
818 /// `lock.inner.write()`, `lock.inner.try_write()`, or `lock.inner.try_upgrade` before
819 /// instantiating this object.
Mark Rousskova06baa52019-12-22 17:42:04 -0500820 unsafe fn new(lock: &'rwlock RwLock<T>) -> LockResult<RwLockWriteGuard<'rwlock, T>> {
Josh Stone34895de2022-06-09 11:51:39 -0700821 poison::map_result(lock.poison.guard(), |guard| RwLockWriteGuard { lock, poison: guard })
Flavio Percococ6ab9a62015-01-11 11:10:04 +0100822 }
Alex Crichton71d4e772014-11-24 11:16:40 -0800823
Connor Tsuid710a8e2025-07-19 12:40:08 +0200824 /// Downgrades a write-locked `RwLockWriteGuard` into a read-locked [`RwLockReadGuard`].
825 ///
826 /// Since we have the `RwLockWriteGuard`, the [`RwLock`] must already be locked for writing, so
827 /// this method cannot fail.
828 ///
829 /// After downgrading, other readers will be allowed to read the protected data.
830 ///
831 /// # Examples
832 ///
833 /// `downgrade` takes ownership of the `RwLockWriteGuard` and returns a [`RwLockReadGuard`].
834 ///
835 /// ```
Connor Tsuid710a8e2025-07-19 12:40:08 +0200836 /// use std::sync::{RwLock, RwLockWriteGuard};
837 ///
838 /// let rw = RwLock::new(0);
839 ///
840 /// let mut write_guard = rw.write().unwrap();
841 /// *write_guard = 42;
842 ///
843 /// let read_guard = RwLockWriteGuard::downgrade(write_guard);
844 /// assert_eq!(42, *read_guard);
845 /// ```
846 ///
847 /// `downgrade` will _atomically_ change the state of the [`RwLock`] from exclusive mode into
848 /// shared mode. This means that it is impossible for another writing thread to get in between a
849 /// thread calling `downgrade` and any reads it performs after downgrading.
850 ///
851 /// ```
Connor Tsuid710a8e2025-07-19 12:40:08 +0200852 /// use std::sync::{Arc, RwLock, RwLockWriteGuard};
853 ///
854 /// let rw = Arc::new(RwLock::new(1));
855 ///
856 /// // Put the lock in write mode.
857 /// let mut main_write_guard = rw.write().unwrap();
858 ///
859 /// let rw_clone = rw.clone();
860 /// let evil_handle = std::thread::spawn(move || {
861 /// // This will not return until the main thread drops the `main_read_guard`.
862 /// let mut evil_guard = rw_clone.write().unwrap();
863 ///
864 /// assert_eq!(*evil_guard, 2);
865 /// *evil_guard = 3;
866 /// });
867 ///
868 /// *main_write_guard = 2;
869 ///
870 /// // Atomically downgrade the write guard into a read guard.
871 /// let main_read_guard = RwLockWriteGuard::downgrade(main_write_guard);
872 ///
873 /// // Since `downgrade` is atomic, the writer thread cannot have changed the protected data.
874 /// assert_eq!(*main_read_guard, 2, "`downgrade` was not atomic");
875 /// #
876 /// # drop(main_read_guard);
877 /// # evil_handle.join().unwrap();
878 /// #
879 /// # let final_check = rw.read().unwrap();
880 /// # assert_eq!(*final_check, 3);
881 /// ```
Josh Stonef25ca452025-10-27 10:27:05 -0700882 #[stable(feature = "rwlock_downgrade", since = "1.92.0")]
Connor Tsuid710a8e2025-07-19 12:40:08 +0200883 pub fn downgrade(s: Self) -> RwLockReadGuard<'rwlock, T> {
884 let lock = s.lock;
885
886 // We don't want to call the destructor since that calls `write_unlock`.
887 forget(s);
888
889 // SAFETY: We take ownership of a write guard, so we must already have the `RwLock` in write
890 // mode, satisfying the `downgrade` contract.
891 unsafe { lock.inner.downgrade() };
892
893 // SAFETY: We have just successfully called `downgrade`, so we fulfill the safety contract.
894 unsafe { RwLockReadGuard::new(lock).unwrap_or_else(PoisonError::into_inner) }
895 }
896
897 /// Makes a [`MappedRwLockWriteGuard`] for a component of the borrowed data, e.g.
898 /// an enum variant.
899 ///
900 /// The `RwLock` is already locked for writing, so this cannot fail.
901 ///
902 /// This is an associated function that needs to be used as
903 /// `RwLockWriteGuard::map(...)`. A method would interfere with methods of
904 /// the same name on the contents of the `RwLockWriteGuard` used through
905 /// `Deref`.
906 ///
907 /// # Panics
908 ///
909 /// If the closure panics, the guard will be dropped (unlocked) and the RwLock will be poisoned.
910 #[unstable(feature = "mapped_lock_guards", issue = "117108")]
911 pub fn map<U, F>(orig: Self, f: F) -> MappedRwLockWriteGuard<'rwlock, U>
912 where
913 F: FnOnce(&mut T) -> &mut U,
914 U: ?Sized,
915 {
916 // SAFETY: the conditions of `RwLockWriteGuard::new` were satisfied when the original guard
917 // was created, and have been upheld throughout `map` and/or `filter_map`.
918 // The signature of the closure guarantees that it will not "leak" the lifetime of the
919 // reference passed to it. If the closure panics, the guard will be dropped.
920 let data = NonNull::from(f(unsafe { &mut *orig.lock.data.get() }));
921 let orig = ManuallyDrop::new(orig);
922 MappedRwLockWriteGuard {
923 data,
924 inner_lock: &orig.lock.inner,
925 poison_flag: &orig.lock.poison,
926 poison_guard: orig.poison.clone(),
927 _variance: PhantomData,
928 }
929 }
930
931 /// Makes a [`MappedRwLockWriteGuard`] for a component of the borrowed data. The
932 /// original guard is returned as an `Err(...)` if the closure returns
933 /// `None`.
934 ///
935 /// The `RwLock` is already locked for writing, so this cannot fail.
936 ///
937 /// This is an associated function that needs to be used as
938 /// `RwLockWriteGuard::filter_map(...)`. A method would interfere with methods
939 /// of the same name on the contents of the `RwLockWriteGuard` used through
940 /// `Deref`.
941 ///
942 /// # Panics
943 ///
944 /// If the closure panics, the guard will be dropped (unlocked) and the RwLock will be poisoned.
945 #[unstable(feature = "mapped_lock_guards", issue = "117108")]
946 pub fn filter_map<U, F>(orig: Self, f: F) -> Result<MappedRwLockWriteGuard<'rwlock, U>, Self>
947 where
948 F: FnOnce(&mut T) -> Option<&mut U>,
949 U: ?Sized,
950 {
951 // SAFETY: the conditions of `RwLockWriteGuard::new` were satisfied when the original guard
952 // was created, and have been upheld throughout `map` and/or `filter_map`.
953 // The signature of the closure guarantees that it will not "leak" the lifetime of the
954 // reference passed to it. If the closure panics, the guard will be dropped.
955 match f(unsafe { &mut *orig.lock.data.get() }) {
956 Some(data) => {
957 let data = NonNull::from(data);
958 let orig = ManuallyDrop::new(orig);
959 Ok(MappedRwLockWriteGuard {
960 data,
961 inner_lock: &orig.lock.inner,
962 poison_flag: &orig.lock.poison,
963 poison_guard: orig.poison.clone(),
964 _variance: PhantomData,
965 })
966 }
967 None => Err(orig),
968 }
Corey Farwell86fc63e2016-11-25 13:21:49 -0500969 }
970}
971
Connor Tsuid710a8e2025-07-19 12:40:08 +0200972impl<'rwlock, T: ?Sized> MappedRwLockReadGuard<'rwlock, T> {
973 /// Makes a [`MappedRwLockReadGuard`] for a component of the borrowed data,
974 /// e.g. an enum variant.
975 ///
976 /// The `RwLock` is already locked for reading, so this cannot fail.
977 ///
978 /// This is an associated function that needs to be used as
979 /// `MappedRwLockReadGuard::map(...)`. A method would interfere with
980 /// methods of the same name on the contents of the `MappedRwLockReadGuard`
981 /// used through `Deref`.
982 ///
983 /// # Panics
984 ///
985 /// If the closure panics, the guard will be dropped (unlocked) and the RwLock will not be
986 /// poisoned.
987 #[unstable(feature = "mapped_lock_guards", issue = "117108")]
988 pub fn map<U, F>(orig: Self, f: F) -> MappedRwLockReadGuard<'rwlock, U>
989 where
990 F: FnOnce(&T) -> &U,
991 U: ?Sized,
992 {
993 // SAFETY: the conditions of `RwLockReadGuard::new` were satisfied when the original guard
994 // was created, and have been upheld throughout `map` and/or `filter_map`.
995 // The signature of the closure guarantees that it will not "leak" the lifetime of the
996 // reference passed to it. If the closure panics, the guard will be dropped.
997 let data = NonNull::from(f(unsafe { orig.data.as_ref() }));
998 let orig = ManuallyDrop::new(orig);
999 MappedRwLockReadGuard { data, inner_lock: &orig.inner_lock }
1000 }
1001
1002 /// Makes a [`MappedRwLockReadGuard`] for a component of the borrowed data.
1003 /// The original guard is returned as an `Err(...)` if the closure returns
1004 /// `None`.
1005 ///
1006 /// The `RwLock` is already locked for reading, so this cannot fail.
1007 ///
1008 /// This is an associated function that needs to be used as
1009 /// `MappedRwLockReadGuard::filter_map(...)`. A method would interfere with
1010 /// methods of the same name on the contents of the `MappedRwLockReadGuard`
1011 /// used through `Deref`.
1012 ///
1013 /// # Panics
1014 ///
1015 /// If the closure panics, the guard will be dropped (unlocked) and the RwLock will not be
1016 /// poisoned.
1017 #[unstable(feature = "mapped_lock_guards", issue = "117108")]
1018 pub fn filter_map<U, F>(orig: Self, f: F) -> Result<MappedRwLockReadGuard<'rwlock, U>, Self>
1019 where
1020 F: FnOnce(&T) -> Option<&U>,
1021 U: ?Sized,
1022 {
1023 // SAFETY: the conditions of `RwLockReadGuard::new` were satisfied when the original guard
1024 // was created, and have been upheld throughout `map` and/or `filter_map`.
1025 // The signature of the closure guarantees that it will not "leak" the lifetime of the
1026 // reference passed to it. If the closure panics, the guard will be dropped.
1027 match f(unsafe { orig.data.as_ref() }) {
1028 Some(data) => {
1029 let data = NonNull::from(data);
1030 let orig = ManuallyDrop::new(orig);
1031 Ok(MappedRwLockReadGuard { data, inner_lock: &orig.inner_lock })
1032 }
1033 None => Err(orig),
1034 }
Chris MacNaughton14df5492017-06-22 12:01:22 +02001035 }
1036}
1037
Connor Tsuid710a8e2025-07-19 12:40:08 +02001038impl<'rwlock, T: ?Sized> MappedRwLockWriteGuard<'rwlock, T> {
1039 /// Makes a [`MappedRwLockWriteGuard`] for a component of the borrowed data,
1040 /// e.g. an enum variant.
1041 ///
1042 /// The `RwLock` is already locked for writing, so this cannot fail.
1043 ///
1044 /// This is an associated function that needs to be used as
1045 /// `MappedRwLockWriteGuard::map(...)`. A method would interfere with
1046 /// methods of the same name on the contents of the `MappedRwLockWriteGuard`
1047 /// used through `Deref`.
1048 ///
1049 /// # Panics
1050 ///
1051 /// If the closure panics, the guard will be dropped (unlocked) and the RwLock will be poisoned.
1052 #[unstable(feature = "mapped_lock_guards", issue = "117108")]
1053 pub fn map<U, F>(mut orig: Self, f: F) -> MappedRwLockWriteGuard<'rwlock, U>
1054 where
1055 F: FnOnce(&mut T) -> &mut U,
1056 U: ?Sized,
1057 {
1058 // SAFETY: the conditions of `RwLockWriteGuard::new` were satisfied when the original guard
1059 // was created, and have been upheld throughout `map` and/or `filter_map`.
1060 // The signature of the closure guarantees that it will not "leak" the lifetime of the
1061 // reference passed to it. If the closure panics, the guard will be dropped.
1062 let data = NonNull::from(f(unsafe { orig.data.as_mut() }));
1063 let orig = ManuallyDrop::new(orig);
1064 MappedRwLockWriteGuard {
1065 data,
1066 inner_lock: orig.inner_lock,
1067 poison_flag: orig.poison_flag,
1068 poison_guard: orig.poison_guard.clone(),
1069 _variance: PhantomData,
1070 }
1071 }
1072
1073 /// Makes a [`MappedRwLockWriteGuard`] for a component of the borrowed data.
1074 /// The original guard is returned as an `Err(...)` if the closure returns
1075 /// `None`.
1076 ///
1077 /// The `RwLock` is already locked for writing, so this cannot fail.
1078 ///
1079 /// This is an associated function that needs to be used as
1080 /// `MappedRwLockWriteGuard::filter_map(...)`. A method would interfere with
1081 /// methods of the same name on the contents of the `MappedRwLockWriteGuard`
1082 /// used through `Deref`.
1083 ///
1084 /// # Panics
1085 ///
1086 /// If the closure panics, the guard will be dropped (unlocked) and the RwLock will be poisoned.
1087 #[unstable(feature = "mapped_lock_guards", issue = "117108")]
1088 pub fn filter_map<U, F>(
1089 mut orig: Self,
1090 f: F,
1091 ) -> Result<MappedRwLockWriteGuard<'rwlock, U>, Self>
1092 where
1093 F: FnOnce(&mut T) -> Option<&mut U>,
1094 U: ?Sized,
1095 {
1096 // SAFETY: the conditions of `RwLockWriteGuard::new` were satisfied when the original guard
1097 // was created, and have been upheld throughout `map` and/or `filter_map`.
1098 // The signature of the closure guarantees that it will not "leak" the lifetime of the
1099 // reference passed to it. If the closure panics, the guard will be dropped.
1100 match f(unsafe { orig.data.as_mut() }) {
1101 Some(data) => {
1102 let data = NonNull::from(data);
1103 let orig = ManuallyDrop::new(orig);
1104 Ok(MappedRwLockWriteGuard {
1105 data,
1106 inner_lock: orig.inner_lock,
1107 poison_flag: orig.poison_flag,
1108 poison_guard: orig.poison_guard.clone(),
1109 _variance: PhantomData,
1110 })
1111 }
1112 None => Err(orig),
1113 }
Corey Farwell86fc63e2016-11-25 13:21:49 -05001114 }
1115}
1116
Connor Tsuid710a8e2025-07-19 12:40:08 +02001117#[stable(feature = "rust1", since = "1.0.0")]
1118impl<T: ?Sized> Drop for RwLockReadGuard<'_, T> {
1119 fn drop(&mut self) {
1120 // SAFETY: the conditions of `RwLockReadGuard::new` were satisfied when created.
1121 unsafe {
1122 self.inner_lock.read_unlock();
1123 }
1124 }
1125}
1126
1127#[stable(feature = "rust1", since = "1.0.0")]
1128impl<T: ?Sized> Drop for RwLockWriteGuard<'_, T> {
1129 fn drop(&mut self) {
1130 self.lock.poison.done(&self.poison);
1131 // SAFETY: the conditions of `RwLockWriteGuard::new` were satisfied when created.
1132 unsafe {
1133 self.lock.inner.write_unlock();
1134 }
Chris MacNaughton14df5492017-06-22 12:01:22 +02001135 }
1136}
1137
Zachary S04f86302023-10-23 16:36:13 -05001138#[unstable(feature = "mapped_lock_guards", issue = "117108")]
Connor Tsuid710a8e2025-07-19 12:40:08 +02001139impl<T: ?Sized> Drop for MappedRwLockReadGuard<'_, T> {
1140 fn drop(&mut self) {
1141 // SAFETY: the conditions of `RwLockReadGuard::new` were satisfied when the original guard
1142 // was created, and have been upheld throughout `map` and/or `filter_map`.
1143 unsafe {
1144 self.inner_lock.read_unlock();
1145 }
Zachary Sea97c1f2023-10-23 16:26:59 -05001146 }
1147}
1148
Zachary S04f86302023-10-23 16:36:13 -05001149#[unstable(feature = "mapped_lock_guards", issue = "117108")]
Connor Tsuid710a8e2025-07-19 12:40:08 +02001150impl<T: ?Sized> Drop for MappedRwLockWriteGuard<'_, T> {
1151 fn drop(&mut self) {
1152 self.poison_flag.done(&self.poison_guard);
1153 // SAFETY: the conditions of `RwLockWriteGuard::new` were satisfied when the original guard
1154 // was created, and have been upheld throughout `map` and/or `filter_map`.
1155 unsafe {
1156 self.inner_lock.write_unlock();
1157 }
Zachary Sea97c1f2023-10-23 16:26:59 -05001158 }
1159}
1160
Brian Andersonb44ee372015-01-23 21:48:20 -08001161#[stable(feature = "rust1", since = "1.0.0")]
Scott McMurray3bea2ca2019-02-17 19:42:36 -08001162impl<T: ?Sized> Deref for RwLockReadGuard<'_, T> {
Jorge Aparicio64b7c222015-01-01 14:53:20 -05001163 type Target = T;
1164
Alex Crichtona7220d92016-07-07 11:46:09 -07001165 fn deref(&self) -> &T {
Zachary Sea97c1f2023-10-23 16:26:59 -05001166 // SAFETY: the conditions of `RwLockReadGuard::new` were satisfied when created.
Robin Raymond08650fb2022-05-14 07:29:02 +00001167 unsafe { self.data.as_ref() }
Alex Crichtona7220d92016-07-07 11:46:09 -07001168 }
Alex Crichton71d4e772014-11-24 11:16:40 -08001169}
P1start57d82892015-04-23 22:53:54 +12001170
Brian Andersonb44ee372015-01-23 21:48:20 -08001171#[stable(feature = "rust1", since = "1.0.0")]
Scott McMurray3bea2ca2019-02-17 19:42:36 -08001172impl<T: ?Sized> Deref for RwLockWriteGuard<'_, T> {
Jorge Aparicio64b7c222015-01-01 14:53:20 -05001173 type Target = T;
1174
Alex Crichtona7220d92016-07-07 11:46:09 -07001175 fn deref(&self) -> &T {
Robin Raymondfa1656e2022-05-26 06:38:23 +00001176 // SAFETY: the conditions of `RwLockWriteGuard::new` were satisfied when created.
Ralf Jung49697ae2019-12-06 17:28:04 +01001177 unsafe { &*self.lock.data.get() }
Alex Crichtona7220d92016-07-07 11:46:09 -07001178 }
Alex Crichton71d4e772014-11-24 11:16:40 -08001179}
P1start57d82892015-04-23 22:53:54 +12001180
Brian Andersonb44ee372015-01-23 21:48:20 -08001181#[stable(feature = "rust1", since = "1.0.0")]
Scott McMurray3bea2ca2019-02-17 19:42:36 -08001182impl<T: ?Sized> DerefMut for RwLockWriteGuard<'_, T> {
Alex Crichtoncae91d72016-05-17 11:57:07 -07001183 fn deref_mut(&mut self) -> &mut T {
Robin Raymondfa1656e2022-05-26 06:38:23 +00001184 // SAFETY: the conditions of `RwLockWriteGuard::new` were satisfied when created.
Ralf Jung49697ae2019-12-06 17:28:04 +01001185 unsafe { &mut *self.lock.data.get() }
Alex Crichton71d4e772014-11-24 11:16:40 -08001186 }
1187}
1188
Zachary S04f86302023-10-23 16:36:13 -05001189#[unstable(feature = "mapped_lock_guards", issue = "117108")]
Zachary Sea97c1f2023-10-23 16:26:59 -05001190impl<T: ?Sized> Deref for MappedRwLockReadGuard<'_, T> {
1191 type Target = T;
1192
1193 fn deref(&self) -> &T {
1194 // SAFETY: the conditions of `RwLockReadGuard::new` were satisfied when the original guard
Zachary Sd2068be2025-04-30 19:40:29 -05001195 // was created, and have been upheld throughout `map` and/or `filter_map`.
Zachary Sea97c1f2023-10-23 16:26:59 -05001196 unsafe { self.data.as_ref() }
1197 }
1198}
1199
Zachary S04f86302023-10-23 16:36:13 -05001200#[unstable(feature = "mapped_lock_guards", issue = "117108")]
Zachary Sea97c1f2023-10-23 16:26:59 -05001201impl<T: ?Sized> Deref for MappedRwLockWriteGuard<'_, T> {
1202 type Target = T;
1203
1204 fn deref(&self) -> &T {
1205 // SAFETY: the conditions of `RwLockWriteGuard::new` were satisfied when the original guard
Zachary Sd2068be2025-04-30 19:40:29 -05001206 // was created, and have been upheld throughout `map` and/or `filter_map`.
Zachary Sea97c1f2023-10-23 16:26:59 -05001207 unsafe { self.data.as_ref() }
1208 }
1209}
1210
Zachary S04f86302023-10-23 16:36:13 -05001211#[unstable(feature = "mapped_lock_guards", issue = "117108")]
Zachary Sea97c1f2023-10-23 16:26:59 -05001212impl<T: ?Sized> DerefMut for MappedRwLockWriteGuard<'_, T> {
1213 fn deref_mut(&mut self) -> &mut T {
1214 // SAFETY: the conditions of `RwLockWriteGuard::new` were satisfied when the original guard
Zachary Sd2068be2025-04-30 19:40:29 -05001215 // was created, and have been upheld throughout `map` and/or `filter_map`.
Zachary Sea97c1f2023-10-23 16:26:59 -05001216 unsafe { self.data.as_mut() }
1217 }
1218}
1219
Connor Tsuid710a8e2025-07-19 12:40:08 +02001220#[stable(feature = "std_debug", since = "1.16.0")]
1221impl<T: ?Sized + fmt::Debug> fmt::Debug for RwLockReadGuard<'_, T> {
1222 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1223 (**self).fmt(f)
Alex Crichton71d4e772014-11-24 11:16:40 -08001224 }
1225}
1226
Connor Tsuid710a8e2025-07-19 12:40:08 +02001227#[stable(feature = "std_guard_impls", since = "1.20.0")]
1228impl<T: ?Sized + fmt::Display> fmt::Display for RwLockReadGuard<'_, T> {
1229 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1230 (**self).fmt(f)
1231 }
1232}
1233
1234#[stable(feature = "std_debug", since = "1.16.0")]
1235impl<T: ?Sized + fmt::Debug> fmt::Debug for RwLockWriteGuard<'_, T> {
1236 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1237 (**self).fmt(f)
1238 }
1239}
1240
1241#[stable(feature = "std_guard_impls", since = "1.20.0")]
1242impl<T: ?Sized + fmt::Display> fmt::Display for RwLockWriteGuard<'_, T> {
1243 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1244 (**self).fmt(f)
Alex Crichton71d4e772014-11-24 11:16:40 -08001245 }
1246}
Zachary Sea97c1f2023-10-23 16:26:59 -05001247
Zachary S04f86302023-10-23 16:36:13 -05001248#[unstable(feature = "mapped_lock_guards", issue = "117108")]
Connor Tsuid710a8e2025-07-19 12:40:08 +02001249impl<T: ?Sized + fmt::Debug> fmt::Debug for MappedRwLockReadGuard<'_, T> {
1250 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1251 (**self).fmt(f)
Zachary Sea97c1f2023-10-23 16:26:59 -05001252 }
1253}
1254
Zachary S04f86302023-10-23 16:36:13 -05001255#[unstable(feature = "mapped_lock_guards", issue = "117108")]
Connor Tsuid710a8e2025-07-19 12:40:08 +02001256impl<T: ?Sized + fmt::Display> fmt::Display for MappedRwLockReadGuard<'_, T> {
1257 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1258 (**self).fmt(f)
Zachary Sea97c1f2023-10-23 16:26:59 -05001259 }
1260}
1261
Connor Tsuid710a8e2025-07-19 12:40:08 +02001262#[unstable(feature = "mapped_lock_guards", issue = "117108")]
1263impl<T: ?Sized + fmt::Debug> fmt::Debug for MappedRwLockWriteGuard<'_, T> {
1264 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1265 (**self).fmt(f)
Zachary Sea97c1f2023-10-23 16:26:59 -05001266 }
1267}
1268
Connor Tsuid710a8e2025-07-19 12:40:08 +02001269#[unstable(feature = "mapped_lock_guards", issue = "117108")]
1270impl<T: ?Sized + fmt::Display> fmt::Display for MappedRwLockWriteGuard<'_, T> {
1271 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1272 (**self).fmt(f)
Zachary Sea97c1f2023-10-23 16:26:59 -05001273 }
1274}