std/sync/nonpoison/rwlock.rs
1use crate::cell::UnsafeCell;
2use crate::fmt;
3use crate::marker::PhantomData;
4use crate::mem::{self, ManuallyDrop, forget};
5use crate::ops::{Deref, DerefMut};
6use crate::ptr::NonNull;
7use crate::sync::nonpoison::{TryLockResult, WouldBlock};
8use crate::sys::sync as sys;
9
10/// A reader-writer lock that does not keep track of lock poisoning.
11///
12/// For more information about reader-writer locks, check out the documentation for the poisoning
13/// variant of this lock (which can be found at [`poison::RwLock`]).
14///
15/// [`poison::RwLock`]: crate::sync::poison::RwLock
16///
17/// # Examples
18///
19/// ```
20/// #![feature(nonpoison_rwlock)]
21///
22/// use std::sync::nonpoison::RwLock;
23///
24/// let lock = RwLock::new(5);
25///
26/// // many reader locks can be held at once
27/// {
28/// let r1 = lock.read();
29/// let r2 = lock.read();
30/// assert_eq!(*r1, 5);
31/// assert_eq!(*r2, 5);
32/// } // read locks are dropped at this point
33///
34/// // only one write lock may be held, however
35/// {
36/// let mut w = lock.write();
37/// *w += 1;
38/// assert_eq!(*w, 6);
39/// } // write lock is dropped here
40/// ```
41#[unstable(feature = "nonpoison_rwlock", issue = "134645")]
42#[cfg_attr(not(test), rustc_diagnostic_item = "NonPoisonRwLock")]
43pub struct RwLock<#[rustc_assert_variance(invariant)] T: ?Sized> {
44 /// The inner [`sys::RwLock`] that synchronizes thread access to the protected data.
45 inner: sys::RwLock,
46 /// The lock-protected data.
47 data: UnsafeCell<T>,
48}
49
50#[unstable(feature = "nonpoison_rwlock", issue = "134645")]
51unsafe impl<T: ?Sized + Send> Send for RwLock<T> {}
52
53#[unstable(feature = "nonpoison_rwlock", issue = "134645")]
54unsafe impl<T: ?Sized + Send + Sync> Sync for RwLock<T> {}
55
56////////////////////////////////////////////////////////////////////////////////////////////////////
57// Guards
58////////////////////////////////////////////////////////////////////////////////////////////////////
59
60/// RAII structure used to release the shared read access of a lock when
61/// dropped.
62///
63/// This structure is created by the [`read`] and [`try_read`] methods on
64/// [`RwLock`].
65///
66/// [`read`]: RwLock::read
67/// [`try_read`]: RwLock::try_read
68#[must_use = "if unused the RwLock will immediately unlock"]
69#[must_not_suspend = "holding a RwLockReadGuard across suspend \
70 points can cause deadlocks, delays, \
71 and cause Futures to not implement `Send`"]
72#[unstable(feature = "nonpoison_rwlock", issue = "134645")]
73#[clippy::has_significant_drop]
74#[cfg_attr(not(test), rustc_diagnostic_item = "NonPoisonRwLockReadGuard")]
75pub struct RwLockReadGuard<
76 #[rustc_assert_variance(covariant)] 'rwlock,
77 #[rustc_assert_variance(covariant)] T: ?Sized + 'rwlock,
78> {
79 /// A pointer to the data protected by the `RwLock`. Note that we use a pointer here instead of
80 /// `&'rwlock T` to avoid `noalias` violations, because a `RwLockReadGuard` instance only holds
81 /// immutability until it drops, not for its whole scope.
82 /// `NonNull` is preferable over `*const T` to allow for niche optimizations. `NonNull` is also
83 /// covariant over `T`, just like we would have with `&T`.
84 data: NonNull<T>,
85 /// A reference to the internal [`sys::RwLock`] that we have read-locked.
86 inner_lock: &'rwlock sys::RwLock,
87}
88
89#[unstable(feature = "nonpoison_rwlock", issue = "134645")]
90impl<T: ?Sized> !Send for RwLockReadGuard<'_, T> {}
91
92#[unstable(feature = "nonpoison_rwlock", issue = "134645")]
93unsafe impl<T: ?Sized + Sync> Sync for RwLockReadGuard<'_, T> {}
94
95/// RAII structure used to release the exclusive write access of a lock when
96/// dropped.
97///
98/// This structure is created by the [`write`] and [`try_write`] methods
99/// on [`RwLock`].
100///
101/// [`write`]: RwLock::write
102/// [`try_write`]: RwLock::try_write
103#[must_use = "if unused the RwLock will immediately unlock"]
104#[must_not_suspend = "holding a RwLockWriteGuard across suspend \
105 points can cause deadlocks, delays, \
106 and cause Future's to not implement `Send`"]
107#[unstable(feature = "nonpoison_rwlock", issue = "134645")]
108#[clippy::has_significant_drop]
109#[cfg_attr(not(test), rustc_diagnostic_item = "NonPoisonRwLockWriteGuard")]
110pub struct RwLockWriteGuard<
111 #[rustc_assert_variance(covariant)] 'rwlock,
112 #[rustc_assert_variance(invariant)] T: ?Sized + 'rwlock,
113> {
114 /// A reference to the [`RwLock`] that we have write-locked.
115 lock: &'rwlock RwLock<T>,
116}
117
118#[unstable(feature = "nonpoison_rwlock", issue = "134645")]
119impl<T: ?Sized> !Send for RwLockWriteGuard<'_, T> {}
120
121#[unstable(feature = "nonpoison_rwlock", issue = "134645")]
122unsafe impl<T: ?Sized + Sync> Sync for RwLockWriteGuard<'_, T> {}
123
124/// RAII structure used to release the shared read access of a lock when
125/// dropped, which can point to a subfield of the protected data.
126///
127/// This structure is created by the [`map`] and [`filter_map`] methods
128/// on [`RwLockReadGuard`].
129///
130/// [`map`]: RwLockReadGuard::map
131/// [`filter_map`]: RwLockReadGuard::filter_map
132#[must_use = "if unused the RwLock will immediately unlock"]
133#[must_not_suspend = "holding a MappedRwLockReadGuard across suspend \
134 points can cause deadlocks, delays, \
135 and cause Futures to not implement `Send`"]
136#[unstable(feature = "mapped_lock_guards", issue = "117108")]
137// #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
138#[clippy::has_significant_drop]
139pub struct MappedRwLockReadGuard<
140 #[rustc_assert_variance(covariant)] 'rwlock,
141 #[rustc_assert_variance(covariant)] T: ?Sized + 'rwlock,
142> {
143 /// A pointer to the data protected by the `RwLock`. Note that we use a pointer here instead of
144 /// `&'rwlock T` to avoid `noalias` violations, because a `MappedRwLockReadGuard` instance only
145 /// holds immutability until it drops, not for its whole scope.
146 /// `NonNull` is preferable over `*const T` to allow for niche optimizations. `NonNull` is also
147 /// covariant over `T`, just like we would have with `&T`.
148 data: NonNull<T>,
149 /// A reference to the internal [`sys::RwLock`] that we have read-locked.
150 inner_lock: &'rwlock sys::RwLock,
151}
152
153#[unstable(feature = "mapped_lock_guards", issue = "117108")]
154// #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
155impl<T: ?Sized> !Send for MappedRwLockReadGuard<'_, T> {}
156
157#[unstable(feature = "mapped_lock_guards", issue = "117108")]
158// #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
159unsafe impl<T: ?Sized + Sync> Sync for MappedRwLockReadGuard<'_, T> {}
160
161/// RAII structure used to release the exclusive write access of a lock when
162/// dropped, which can point to a subfield of the protected data.
163///
164/// This structure is created by the [`map`] and [`filter_map`] methods
165/// on [`RwLockWriteGuard`].
166///
167/// [`map`]: RwLockWriteGuard::map
168/// [`filter_map`]: RwLockWriteGuard::filter_map
169#[must_use = "if unused the RwLock will immediately unlock"]
170#[must_not_suspend = "holding a MappedRwLockWriteGuard across suspend \
171 points can cause deadlocks, delays, \
172 and cause Future's to not implement `Send`"]
173#[unstable(feature = "mapped_lock_guards", issue = "117108")]
174// #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
175#[clippy::has_significant_drop]
176pub struct MappedRwLockWriteGuard<
177 #[rustc_assert_variance(covariant)] 'rwlock,
178 #[rustc_assert_variance(invariant)] T: ?Sized + 'rwlock,
179> {
180 /// A pointer to the data protected by the `RwLock`. Note that we use a pointer here instead of
181 /// `&'rwlock T` to avoid `noalias` violations, because a `MappedRwLockWriteGuard` instance only
182 /// holds uniquneness until it drops, not for its whole scope.
183 /// `NonNull` is preferable over `*const T` to allow for niche optimizations.
184 data: NonNull<T>,
185 /// `NonNull` is covariant over `T`, so we add a `PhantomData<&'rwlock mut T>` field here to
186 /// enforce the correct invariance over `T`.
187 _variance: PhantomData<&'rwlock mut T>,
188 /// A reference to the internal [`sys::RwLock`] that we have write-locked.
189 inner_lock: &'rwlock sys::RwLock,
190}
191
192#[unstable(feature = "mapped_lock_guards", issue = "117108")]
193// #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
194impl<T: ?Sized> !Send for MappedRwLockWriteGuard<'_, T> {}
195
196#[unstable(feature = "mapped_lock_guards", issue = "117108")]
197// #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
198unsafe impl<T: ?Sized + Sync> Sync for MappedRwLockWriteGuard<'_, T> {}
199
200////////////////////////////////////////////////////////////////////////////////////////////////////
201// Implementations
202////////////////////////////////////////////////////////////////////////////////////////////////////
203
204impl<T> RwLock<T> {
205 /// Creates a new instance of an `RwLock<T>` which is unlocked.
206 ///
207 /// # Examples
208 ///
209 /// ```
210 /// #![feature(nonpoison_rwlock)]
211 ///
212 /// use std::sync::nonpoison::RwLock;
213 ///
214 /// let lock = RwLock::new(5);
215 /// ```
216 #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
217 #[inline]
218 pub const fn new(t: T) -> RwLock<T> {
219 RwLock { inner: sys::RwLock::new(), data: UnsafeCell::new(t) }
220 }
221
222 /// Returns the contained value by cloning it.
223 ///
224 /// # Examples
225 ///
226 /// ```
227 /// #![feature(nonpoison_rwlock)]
228 /// #![feature(lock_value_accessors)]
229 ///
230 /// use std::sync::nonpoison::RwLock;
231 ///
232 /// let mut lock = RwLock::new(7);
233 ///
234 /// assert_eq!(lock.get_cloned(), 7);
235 /// ```
236 #[unstable(feature = "lock_value_accessors", issue = "133407")]
237 // #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
238 pub fn get_cloned(&self) -> T
239 where
240 T: Clone,
241 {
242 self.read().clone()
243 }
244
245 /// Sets the contained value.
246 ///
247 /// # Examples
248 ///
249 /// ```
250 /// #![feature(nonpoison_rwlock)]
251 /// #![feature(lock_value_accessors)]
252 ///
253 /// use std::sync::nonpoison::RwLock;
254 ///
255 /// let mut lock = RwLock::new(7);
256 ///
257 /// assert_eq!(lock.get_cloned(), 7);
258 /// lock.set(11);
259 /// assert_eq!(lock.get_cloned(), 11);
260 /// ```
261 #[unstable(feature = "lock_value_accessors", issue = "133407")]
262 // #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
263 pub fn set(&self, value: T) {
264 if mem::needs_drop::<T>() {
265 // If the contained value has a non-trivial destructor, we
266 // call that destructor after the lock has been released.
267 drop(self.replace(value))
268 } else {
269 *self.write() = value;
270 }
271 }
272
273 /// Replaces the contained value with `value`, and returns the old contained value.
274 ///
275 /// # Examples
276 ///
277 /// ```
278 /// #![feature(nonpoison_rwlock)]
279 /// #![feature(lock_value_accessors)]
280 ///
281 /// use std::sync::nonpoison::RwLock;
282 ///
283 /// let mut lock = RwLock::new(7);
284 ///
285 /// assert_eq!(lock.replace(11), 7);
286 /// assert_eq!(lock.get_cloned(), 11);
287 /// ```
288 #[unstable(feature = "lock_value_accessors", issue = "133407")]
289 // #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
290 pub fn replace(&self, value: T) -> T {
291 let mut guard = self.write();
292 mem::replace(&mut *guard, value)
293 }
294}
295
296impl<T: ?Sized> RwLock<T> {
297 /// Locks this `RwLock` with shared read access, blocking the current thread
298 /// until it can be acquired.
299 ///
300 /// The calling thread will be blocked until there are no more writers which
301 /// hold the lock. There may be other readers currently inside the lock when
302 /// this method returns. This method does not provide any guarantees with
303 /// respect to the ordering of whether contentious readers or writers will
304 /// acquire the lock first.
305 ///
306 /// Returns an RAII guard which will release this thread's shared access
307 /// once it is dropped.
308 ///
309 /// # Panics
310 ///
311 /// This function might panic when called if the lock is already held by the current thread.
312 ///
313 /// # Examples
314 ///
315 /// ```
316 /// #![feature(nonpoison_rwlock)]
317 ///
318 /// use std::sync::Arc;
319 /// use std::sync::nonpoison::RwLock;
320 /// use std::thread;
321 ///
322 /// let lock = Arc::new(RwLock::new(1));
323 /// let c_lock = Arc::clone(&lock);
324 ///
325 /// let n = lock.read();
326 /// assert_eq!(*n, 1);
327 ///
328 /// thread::spawn(move || {
329 /// let r = c_lock.read();
330 /// }).join().unwrap();
331 /// ```
332 #[inline]
333 #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
334 pub fn read(&self) -> RwLockReadGuard<'_, T> {
335 unsafe {
336 self.inner.read();
337 RwLockReadGuard::new(self)
338 }
339 }
340
341 /// Attempts to acquire this `RwLock` with shared read access.
342 ///
343 /// If the access could not be granted at this time, then `Err` is returned.
344 /// Otherwise, an RAII guard is returned which will release the shared access
345 /// when it is dropped.
346 ///
347 /// This function does not block.
348 ///
349 /// This function does not provide any guarantees with respect to the ordering
350 /// of whether contentious readers or writers will acquire the lock first.
351 ///
352 /// # Errors
353 ///
354 /// This function will return the [`WouldBlock`] error if the `RwLock` could
355 /// not be acquired because it was already locked exclusively.
356 ///
357 /// # Examples
358 ///
359 /// ```
360 /// #![feature(nonpoison_rwlock)]
361 ///
362 /// use std::sync::nonpoison::RwLock;
363 ///
364 /// let lock = RwLock::new(1);
365 ///
366 /// match lock.try_read() {
367 /// Ok(n) => assert_eq!(*n, 1),
368 /// Err(_) => unreachable!(),
369 /// };
370 /// ```
371 #[inline]
372 #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
373 pub fn try_read(&self) -> TryLockResult<RwLockReadGuard<'_, T>> {
374 unsafe {
375 if self.inner.try_read() { Ok(RwLockReadGuard::new(self)) } else { Err(WouldBlock) }
376 }
377 }
378
379 /// Locks this `RwLock` with exclusive write access, blocking the current
380 /// thread until it can be acquired.
381 ///
382 /// This function will not return while other writers or other readers
383 /// currently have access to the lock.
384 ///
385 /// Returns an RAII guard which will drop the write access of this `RwLock`
386 /// when dropped.
387 ///
388 /// # Panics
389 ///
390 /// This function might panic when called if the lock is already held by the current thread.
391 ///
392 /// # Examples
393 ///
394 /// ```
395 /// #![feature(nonpoison_rwlock)]
396 ///
397 /// use std::sync::nonpoison::RwLock;
398 ///
399 /// let lock = RwLock::new(1);
400 ///
401 /// let mut n = lock.write();
402 /// *n = 2;
403 ///
404 /// assert!(lock.try_read().is_err());
405 /// ```
406 #[inline]
407 #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
408 pub fn write(&self) -> RwLockWriteGuard<'_, T> {
409 unsafe {
410 self.inner.write();
411 RwLockWriteGuard::new(self)
412 }
413 }
414
415 /// Attempts to lock this `RwLock` with exclusive write access.
416 ///
417 /// If the lock could not be acquired at this time, then `Err` is returned.
418 /// Otherwise, an RAII guard is returned which will release the lock when
419 /// 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.
425 ///
426 /// # Errors
427 ///
428 /// This function will return the [`WouldBlock`] error if the `RwLock` could
429 /// not be acquired because it was already locked.
430 ///
431 /// [`WouldBlock`]: WouldBlock
432 ///
433 /// # Examples
434 ///
435 /// ```
436 /// #![feature(nonpoison_rwlock)]
437 ///
438 /// use std::sync::nonpoison::RwLock;
439 ///
440 /// let lock = RwLock::new(1);
441 ///
442 /// let n = lock.read();
443 /// assert_eq!(*n, 1);
444 ///
445 /// assert!(lock.try_write().is_err());
446 /// ```
447 #[inline]
448 #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
449 pub fn try_write(&self) -> TryLockResult<RwLockWriteGuard<'_, T>> {
450 unsafe {
451 if self.inner.try_write() { Ok(RwLockWriteGuard::new(self)) } else { Err(WouldBlock) }
452 }
453 }
454
455 /// Consumes this `RwLock`, returning the underlying data.
456 ///
457 /// # Examples
458 ///
459 /// ```
460 /// #![feature(nonpoison_rwlock)]
461 ///
462 /// use std::sync::nonpoison::RwLock;
463 ///
464 /// let lock = RwLock::new(String::new());
465 /// {
466 /// let mut s = lock.write();
467 /// *s = "modified".to_owned();
468 /// }
469 /// assert_eq!(lock.into_inner(), "modified");
470 /// ```
471 #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
472 pub fn into_inner(self) -> T
473 where
474 T: Sized,
475 {
476 self.data.into_inner()
477 }
478
479 /// Returns a mutable reference to the underlying data.
480 ///
481 /// Since this call borrows the `RwLock` mutably, no actual locking needs to
482 /// take place -- the mutable borrow statically guarantees no new locks can be acquired
483 /// while this reference exists. Note that this method does not clear any previously abandoned
484 /// locks (e.g., via [`forget()`] on a [`RwLockReadGuard`] or [`RwLockWriteGuard`]).
485 ///
486 /// # Examples
487 ///
488 /// ```
489 /// #![feature(nonpoison_rwlock)]
490 ///
491 /// use std::sync::nonpoison::RwLock;
492 ///
493 /// let mut lock = RwLock::new(0);
494 /// *lock.get_mut() = 10;
495 /// assert_eq!(*lock.read(), 10);
496 /// ```
497 #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
498 pub fn get_mut(&mut self) -> &mut T {
499 self.data.get_mut()
500 }
501
502 /// Returns a raw pointer to the underlying data.
503 ///
504 /// The returned pointer is always non-null and properly aligned, but it is
505 /// the user's responsibility to ensure that any reads and writes through it
506 /// are properly synchronized to avoid data races, and that it is not read
507 /// or written through after the lock is dropped.
508 #[unstable(feature = "rwlock_data_ptr", issue = "140368")]
509 // #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
510 pub const fn data_ptr(&self) -> *mut T {
511 self.data.get()
512 }
513
514 /// Locks this `RwLock` with shared read access to the underlying data by passing
515 /// a reference to the given closure.
516 ///
517 /// This method acquires the lock, calls the provided closure with a reference
518 /// to the data, and returns the result of the closure. The lock is released after
519 /// the closure completes, even if it panics.
520 ///
521 /// # Examples
522 ///
523 /// ```
524 /// #![feature(lock_value_accessors, nonpoison_rwlock)]
525 ///
526 /// use std::sync::nonpoison::RwLock;
527 ///
528 /// let rwlock = RwLock::new(2);
529 /// let result = rwlock.with(|data| *data + 3);
530 ///
531 /// assert_eq!(result, 5);
532 /// ```
533 #[unstable(feature = "lock_value_accessors", issue = "133407")]
534 // #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
535 pub fn with<F, R>(&self, f: F) -> R
536 where
537 F: FnOnce(&T) -> R,
538 {
539 f(&self.read())
540 }
541
542 /// Locks this `RwLock` with exclusive write access to the underlying data by passing
543 /// a mutable reference to the given closure.
544 ///
545 /// This method acquires the lock, calls the provided closure with a mutable reference
546 /// to the data, and returns the result of the closure. The lock is released after
547 /// the closure completes, even if it panics.
548 ///
549 /// # Examples
550 ///
551 /// ```
552 /// #![feature(lock_value_accessors, nonpoison_rwlock)]
553 ///
554 /// use std::sync::nonpoison::RwLock;
555 ///
556 /// let rwlock = RwLock::new(2);
557 ///
558 /// let result = rwlock.with_mut(|data| {
559 /// *data += 3;
560 ///
561 /// *data + 5
562 /// });
563 ///
564 /// assert_eq!(*rwlock.read(), 5);
565 /// assert_eq!(result, 10);
566 /// ```
567 #[unstable(feature = "lock_value_accessors", issue = "133407")]
568 // #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
569 pub fn with_mut<F, R>(&self, f: F) -> R
570 where
571 F: FnOnce(&mut T) -> R,
572 {
573 f(&mut self.write())
574 }
575}
576
577#[unstable(feature = "nonpoison_rwlock", issue = "134645")]
578impl<T: ?Sized + fmt::Debug> fmt::Debug for RwLock<T> {
579 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
580 let mut d = f.debug_struct("RwLock");
581 match self.try_read() {
582 Ok(guard) => {
583 d.field("data", &&*guard);
584 }
585 Err(WouldBlock) => {
586 d.field("data", &format_args!("<locked>"));
587 }
588 }
589 d.finish_non_exhaustive()
590 }
591}
592
593#[unstable(feature = "nonpoison_rwlock", issue = "134645")]
594impl<T: Default> Default for RwLock<T> {
595 /// Creates a new `RwLock<T>`, with the `Default` value for T.
596 fn default() -> RwLock<T> {
597 RwLock::new(Default::default())
598 }
599}
600
601#[unstable(feature = "nonpoison_rwlock", issue = "134645")]
602impl<T> From<T> for RwLock<T> {
603 /// Creates a new instance of an `RwLock<T>` which is unlocked.
604 /// This is equivalent to [`RwLock::new`].
605 fn from(t: T) -> Self {
606 RwLock::new(t)
607 }
608}
609
610impl<'rwlock, T: ?Sized> RwLockReadGuard<'rwlock, T> {
611 /// Creates a new instance of `RwLockReadGuard<T>` from a `RwLock<T>`.
612 ///
613 /// # Safety
614 ///
615 /// This function is safe if and only if the same thread has successfully and safely called
616 /// `lock.inner.read()`, `lock.inner.try_read()`, or `lock.inner.downgrade()` before
617 /// instantiating this object.
618 unsafe fn new(lock: &'rwlock RwLock<T>) -> RwLockReadGuard<'rwlock, T> {
619 RwLockReadGuard {
620 data: unsafe { NonNull::new_unchecked(lock.data.get()) },
621 inner_lock: &lock.inner,
622 }
623 }
624
625 /// Makes a [`MappedRwLockReadGuard`] for a component of the borrowed data, e.g.
626 /// an enum variant.
627 ///
628 /// The `RwLock` is already locked for reading, so this cannot fail.
629 ///
630 /// This is an associated function that needs to be used as
631 /// `RwLockReadGuard::map(...)`. A method would interfere with methods of
632 /// the same name on the contents of the `RwLockReadGuard` used through
633 /// `Deref`.
634 ///
635 /// # Panics
636 ///
637 /// If the closure panics, the guard will be dropped (unlocked).
638 #[unstable(feature = "mapped_lock_guards", issue = "117108")]
639 // #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
640 pub fn map<U, F>(orig: Self, f: F) -> MappedRwLockReadGuard<'rwlock, U>
641 where
642 F: FnOnce(&T) -> &U,
643 U: ?Sized,
644 {
645 // SAFETY: the conditions of `RwLockReadGuard::new` were satisfied when the original guard
646 // was created, and have been upheld throughout `map` and/or `filter_map`.
647 // The signature of the closure guarantees that it will not "leak" the lifetime of the
648 // reference passed to it. If the closure panics, the guard will be dropped.
649 let data = NonNull::from(f(unsafe { orig.data.as_ref() }));
650 let orig = ManuallyDrop::new(orig);
651 MappedRwLockReadGuard { data, inner_lock: orig.inner_lock }
652 }
653
654 /// Makes a [`MappedRwLockReadGuard`] for a component of the borrowed data. The
655 /// original guard is returned as an `Err(...)` if the closure returns
656 /// `None`.
657 ///
658 /// The `RwLock` is already locked for reading, so this cannot fail.
659 ///
660 /// This is an associated function that needs to be used as
661 /// `RwLockReadGuard::filter_map(...)`. A method would interfere with methods
662 /// of the same name on the contents of the `RwLockReadGuard` used through
663 /// `Deref`.
664 ///
665 /// # Panics
666 ///
667 /// If the closure panics, the guard will be dropped (unlocked).
668 #[unstable(feature = "mapped_lock_guards", issue = "117108")]
669 // #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
670 pub fn filter_map<U, F>(orig: Self, f: F) -> Result<MappedRwLockReadGuard<'rwlock, U>, Self>
671 where
672 F: FnOnce(&T) -> Option<&U>,
673 U: ?Sized,
674 {
675 // SAFETY: the conditions of `RwLockReadGuard::new` were satisfied when the original guard
676 // was created, and have been upheld throughout `map` and/or `filter_map`.
677 // The signature of the closure guarantees that it will not "leak" the lifetime of the
678 // reference passed to it. If the closure panics, the guard will be dropped.
679 match f(unsafe { orig.data.as_ref() }) {
680 Some(data) => {
681 let data = NonNull::from(data);
682 let orig = ManuallyDrop::new(orig);
683 Ok(MappedRwLockReadGuard { data, inner_lock: orig.inner_lock })
684 }
685 None => Err(orig),
686 }
687 }
688}
689
690impl<'rwlock, T: ?Sized> RwLockWriteGuard<'rwlock, T> {
691 /// Creates a new instance of `RwLockWriteGuard<T>` from a `RwLock<T>`.
692 ///
693 /// # Safety
694 ///
695 /// This function is safe if and only if the same thread has successfully and safely called
696 /// `lock.inner.write()`, `lock.inner.try_write()`, or `lock.inner.try_upgrade` before
697 /// instantiating this object.
698 unsafe fn new(lock: &'rwlock RwLock<T>) -> RwLockWriteGuard<'rwlock, T> {
699 RwLockWriteGuard { lock }
700 }
701
702 /// Downgrades a write-locked `RwLockWriteGuard` into a read-locked [`RwLockReadGuard`].
703 ///
704 /// Since we have the `RwLockWriteGuard`, the [`RwLock`] must already be locked for writing, so
705 /// this method cannot fail.
706 ///
707 /// After downgrading, other readers will be allowed to read the protected data.
708 ///
709 /// # Examples
710 ///
711 /// `downgrade` takes ownership of the `RwLockWriteGuard` and returns a [`RwLockReadGuard`].
712 ///
713 /// ```
714 /// #![feature(nonpoison_rwlock)]
715 ///
716 /// use std::sync::nonpoison::{RwLock, RwLockWriteGuard};
717 ///
718 /// let rw = RwLock::new(0);
719 ///
720 /// let mut write_guard = rw.write();
721 /// *write_guard = 42;
722 ///
723 /// let read_guard = RwLockWriteGuard::downgrade(write_guard);
724 /// assert_eq!(42, *read_guard);
725 /// ```
726 ///
727 /// `downgrade` will _atomically_ change the state of the [`RwLock`] from exclusive mode into
728 /// shared mode. This means that it is impossible for another writing thread to get in between a
729 /// thread calling `downgrade` and any reads it performs after downgrading.
730 ///
731 /// ```
732 /// #![feature(nonpoison_rwlock)]
733 ///
734 /// use std::sync::Arc;
735 /// use std::sync::nonpoison::{RwLock, RwLockWriteGuard};
736 ///
737 /// let rw = Arc::new(RwLock::new(1));
738 ///
739 /// // Put the lock in write mode.
740 /// let mut main_write_guard = rw.write();
741 ///
742 /// let rw_clone = rw.clone();
743 /// let evil_handle = std::thread::spawn(move || {
744 /// // This will not return until the main thread drops the `main_read_guard`.
745 /// let mut evil_guard = rw_clone.write();
746 ///
747 /// assert_eq!(*evil_guard, 2);
748 /// *evil_guard = 3;
749 /// });
750 ///
751 /// *main_write_guard = 2;
752 ///
753 /// // Atomically downgrade the write guard into a read guard.
754 /// let main_read_guard = RwLockWriteGuard::downgrade(main_write_guard);
755 ///
756 /// // Since `downgrade` is atomic, the writer thread cannot have changed the protected data.
757 /// assert_eq!(*main_read_guard, 2, "`downgrade` was not atomic");
758 /// #
759 /// # drop(main_read_guard);
760 /// # evil_handle.join().unwrap();
761 /// #
762 /// # let final_check = rw.read();
763 /// # assert_eq!(*final_check, 3);
764 /// ```
765 #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
766 pub fn downgrade(s: Self) -> RwLockReadGuard<'rwlock, T> {
767 let lock = s.lock;
768
769 // We don't want to call the destructor since that calls `write_unlock`.
770 forget(s);
771
772 // SAFETY: We take ownership of a write guard, so we must already have the `RwLock` in write
773 // mode, satisfying the `downgrade` contract.
774 unsafe { lock.inner.downgrade() };
775
776 // SAFETY: We have just successfully called `downgrade`, so we fulfill the safety contract.
777 unsafe { RwLockReadGuard::new(lock) }
778 }
779
780 /// Makes a [`MappedRwLockWriteGuard`] for a component of the borrowed data, e.g.
781 /// an enum variant.
782 ///
783 /// The `RwLock` is already locked for writing, so this cannot fail.
784 ///
785 /// This is an associated function that needs to be used as
786 /// `RwLockWriteGuard::map(...)`. A method would interfere with methods of
787 /// the same name on the contents of the `RwLockWriteGuard` used through
788 /// `Deref`.
789 ///
790 /// # Panics
791 ///
792 /// If the closure panics, the guard will be dropped (unlocked).
793 #[unstable(feature = "mapped_lock_guards", issue = "117108")]
794 // #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
795 pub fn map<U, F>(orig: Self, f: F) -> MappedRwLockWriteGuard<'rwlock, U>
796 where
797 F: FnOnce(&mut T) -> &mut U,
798 U: ?Sized,
799 {
800 // SAFETY: the conditions of `RwLockWriteGuard::new` were satisfied when the original guard
801 // was created, and have been upheld throughout `map` and/or `filter_map`.
802 // The signature of the closure guarantees that it will not "leak" the lifetime of the
803 // reference passed to it. If the closure panics, the guard will be dropped.
804 let data = NonNull::from(f(unsafe { &mut *orig.lock.data.get() }));
805 let orig = ManuallyDrop::new(orig);
806 MappedRwLockWriteGuard { data, inner_lock: &orig.lock.inner, _variance: PhantomData }
807 }
808
809 /// Makes a [`MappedRwLockWriteGuard`] for a component of the borrowed data. The
810 /// original guard is returned as an `Err(...)` if the closure returns
811 /// `None`.
812 ///
813 /// The `RwLock` is already locked for writing, so this cannot fail.
814 ///
815 /// This is an associated function that needs to be used as
816 /// `RwLockWriteGuard::filter_map(...)`. A method would interfere with methods
817 /// of the same name on the contents of the `RwLockWriteGuard` used through
818 /// `Deref`.
819 ///
820 /// # Panics
821 ///
822 /// If the closure panics, the guard will be dropped (unlocked).
823 #[unstable(feature = "mapped_lock_guards", issue = "117108")]
824 // #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
825 pub fn filter_map<U, F>(orig: Self, f: F) -> Result<MappedRwLockWriteGuard<'rwlock, U>, Self>
826 where
827 F: FnOnce(&mut T) -> Option<&mut U>,
828 U: ?Sized,
829 {
830 // SAFETY: the conditions of `RwLockWriteGuard::new` were satisfied when the original guard
831 // was created, and have been upheld throughout `map` and/or `filter_map`.
832 // The signature of the closure guarantees that it will not "leak" the lifetime of the
833 // reference passed to it. If the closure panics, the guard will be dropped.
834 match f(unsafe { &mut *orig.lock.data.get() }) {
835 Some(data) => {
836 let data = NonNull::from(data);
837 let orig = ManuallyDrop::new(orig);
838 Ok(MappedRwLockWriteGuard {
839 data,
840 inner_lock: &orig.lock.inner,
841 _variance: PhantomData,
842 })
843 }
844 None => Err(orig),
845 }
846 }
847}
848
849impl<'rwlock, T: ?Sized> MappedRwLockReadGuard<'rwlock, T> {
850 /// Makes a [`MappedRwLockReadGuard`] for a component of the borrowed data,
851 /// e.g. an enum variant.
852 ///
853 /// The `RwLock` is already locked for reading, so this cannot fail.
854 ///
855 /// This is an associated function that needs to be used as
856 /// `MappedRwLockReadGuard::map(...)`. A method would interfere with
857 /// methods of the same name on the contents of the `MappedRwLockReadGuard`
858 /// used through `Deref`.
859 ///
860 /// # Panics
861 ///
862 /// If the closure panics, the guard will be dropped (unlocked).
863 #[unstable(feature = "mapped_lock_guards", issue = "117108")]
864 // #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
865 pub fn map<U, F>(orig: Self, f: F) -> MappedRwLockReadGuard<'rwlock, U>
866 where
867 F: FnOnce(&T) -> &U,
868 U: ?Sized,
869 {
870 // SAFETY: the conditions of `RwLockReadGuard::new` were satisfied when the original guard
871 // was created, and have been upheld throughout `map` and/or `filter_map`.
872 // The signature of the closure guarantees that it will not "leak" the lifetime of the
873 // reference passed to it. If the closure panics, the guard will be dropped.
874 let data = NonNull::from(f(unsafe { orig.data.as_ref() }));
875 let orig = ManuallyDrop::new(orig);
876 MappedRwLockReadGuard { data, inner_lock: orig.inner_lock }
877 }
878
879 /// Makes a [`MappedRwLockReadGuard`] for a component of the borrowed data.
880 /// The original guard is returned as an `Err(...)` if the closure returns
881 /// `None`.
882 ///
883 /// The `RwLock` is already locked for reading, so this cannot fail.
884 ///
885 /// This is an associated function that needs to be used as
886 /// `MappedRwLockReadGuard::filter_map(...)`. A method would interfere with
887 /// methods of the same name on the contents of the `MappedRwLockReadGuard`
888 /// used through `Deref`.
889 ///
890 /// # Panics
891 ///
892 /// If the closure panics, the guard will be dropped (unlocked).
893 #[unstable(feature = "mapped_lock_guards", issue = "117108")]
894 // #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
895 pub fn filter_map<U, F>(orig: Self, f: F) -> Result<MappedRwLockReadGuard<'rwlock, U>, Self>
896 where
897 F: FnOnce(&T) -> Option<&U>,
898 U: ?Sized,
899 {
900 // SAFETY: the conditions of `RwLockReadGuard::new` were satisfied when the original guard
901 // was created, and have been upheld throughout `map` and/or `filter_map`.
902 // The signature of the closure guarantees that it will not "leak" the lifetime of the
903 // reference passed to it. If the closure panics, the guard will be dropped.
904 match f(unsafe { orig.data.as_ref() }) {
905 Some(data) => {
906 let data = NonNull::from(data);
907 let orig = ManuallyDrop::new(orig);
908 Ok(MappedRwLockReadGuard { data, inner_lock: orig.inner_lock })
909 }
910 None => Err(orig),
911 }
912 }
913}
914
915impl<'rwlock, T: ?Sized> MappedRwLockWriteGuard<'rwlock, T> {
916 /// Makes a [`MappedRwLockWriteGuard`] for a component of the borrowed data,
917 /// e.g. an enum variant.
918 ///
919 /// The `RwLock` is already locked for writing, so this cannot fail.
920 ///
921 /// This is an associated function that needs to be used as
922 /// `MappedRwLockWriteGuard::map(...)`. A method would interfere with
923 /// methods of the same name on the contents of the `MappedRwLockWriteGuard`
924 /// used through `Deref`.
925 ///
926 /// # Panics
927 ///
928 /// If the closure panics, the guard will be dropped (unlocked).
929 #[unstable(feature = "mapped_lock_guards", issue = "117108")]
930 // #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
931 pub fn map<U, F>(mut orig: Self, f: F) -> MappedRwLockWriteGuard<'rwlock, U>
932 where
933 F: FnOnce(&mut T) -> &mut U,
934 U: ?Sized,
935 {
936 // SAFETY: the conditions of `RwLockWriteGuard::new` were satisfied when the original guard
937 // was created, and have been upheld throughout `map` and/or `filter_map`.
938 // The signature of the closure guarantees that it will not "leak" the lifetime of the
939 // reference passed to it. If the closure panics, the guard will be dropped.
940 let data = NonNull::from(f(unsafe { orig.data.as_mut() }));
941 let orig = ManuallyDrop::new(orig);
942 MappedRwLockWriteGuard { data, inner_lock: orig.inner_lock, _variance: PhantomData }
943 }
944
945 /// Makes a [`MappedRwLockWriteGuard`] for a component of the borrowed data.
946 /// The original guard is returned as an `Err(...)` if the closure returns
947 /// `None`.
948 ///
949 /// The `RwLock` is already locked for writing, so this cannot fail.
950 ///
951 /// This is an associated function that needs to be used as
952 /// `MappedRwLockWriteGuard::filter_map(...)`. A method would interfere with
953 /// methods of the same name on the contents of the `MappedRwLockWriteGuard`
954 /// used through `Deref`.
955 ///
956 /// # Panics
957 ///
958 /// If the closure panics, the guard will be dropped (unlocked).
959 #[unstable(feature = "mapped_lock_guards", issue = "117108")]
960 // #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
961 pub fn filter_map<U, F>(
962 mut orig: Self,
963 f: F,
964 ) -> Result<MappedRwLockWriteGuard<'rwlock, U>, Self>
965 where
966 F: FnOnce(&mut T) -> Option<&mut U>,
967 U: ?Sized,
968 {
969 // SAFETY: the conditions of `RwLockWriteGuard::new` were satisfied when the original guard
970 // was created, and have been upheld throughout `map` and/or `filter_map`.
971 // The signature of the closure guarantees that it will not "leak" the lifetime of the
972 // reference passed to it. If the closure panics, the guard will be dropped.
973 match f(unsafe { orig.data.as_mut() }) {
974 Some(data) => {
975 let data = NonNull::from(data);
976 let orig = ManuallyDrop::new(orig);
977 Ok(MappedRwLockWriteGuard {
978 data,
979 inner_lock: orig.inner_lock,
980 _variance: PhantomData,
981 })
982 }
983 None => Err(orig),
984 }
985 }
986}
987
988#[unstable(feature = "nonpoison_rwlock", issue = "134645")]
989impl<T: ?Sized> Drop for RwLockReadGuard<'_, T> {
990 fn drop(&mut self) {
991 // SAFETY: the conditions of `RwLockReadGuard::new` were satisfied when created.
992 unsafe {
993 self.inner_lock.read_unlock();
994 }
995 }
996}
997
998#[unstable(feature = "nonpoison_rwlock", issue = "134645")]
999impl<T: ?Sized> Drop for RwLockWriteGuard<'_, T> {
1000 fn drop(&mut self) {
1001 // SAFETY: the conditions of `RwLockWriteGuard::new` were satisfied when created.
1002 unsafe {
1003 self.lock.inner.write_unlock();
1004 }
1005 }
1006}
1007
1008#[unstable(feature = "mapped_lock_guards", issue = "117108")]
1009// #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
1010impl<T: ?Sized> Drop for MappedRwLockReadGuard<'_, T> {
1011 fn drop(&mut self) {
1012 // SAFETY: the conditions of `RwLockReadGuard::new` were satisfied when the original guard
1013 // was created, and have been upheld throughout `map` and/or `filter_map`.
1014 unsafe {
1015 self.inner_lock.read_unlock();
1016 }
1017 }
1018}
1019
1020#[unstable(feature = "mapped_lock_guards", issue = "117108")]
1021// #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
1022impl<T: ?Sized> Drop for MappedRwLockWriteGuard<'_, T> {
1023 fn drop(&mut self) {
1024 // SAFETY: the conditions of `RwLockWriteGuard::new` were satisfied when the original guard
1025 // was created, and have been upheld throughout `map` and/or `filter_map`.
1026 unsafe {
1027 self.inner_lock.write_unlock();
1028 }
1029 }
1030}
1031
1032#[unstable(feature = "nonpoison_rwlock", issue = "134645")]
1033impl<T: ?Sized> Deref for RwLockReadGuard<'_, T> {
1034 type Target = T;
1035
1036 fn deref(&self) -> &T {
1037 // SAFETY: the conditions of `RwLockReadGuard::new` were satisfied when created.
1038 unsafe { self.data.as_ref() }
1039 }
1040}
1041
1042#[unstable(feature = "nonpoison_rwlock", issue = "134645")]
1043impl<T: ?Sized> Deref for RwLockWriteGuard<'_, T> {
1044 type Target = T;
1045
1046 fn deref(&self) -> &T {
1047 // SAFETY: the conditions of `RwLockWriteGuard::new` were satisfied when created.
1048 unsafe { &*self.lock.data.get() }
1049 }
1050}
1051
1052#[unstable(feature = "nonpoison_rwlock", issue = "134645")]
1053impl<T: ?Sized> DerefMut for RwLockWriteGuard<'_, T> {
1054 fn deref_mut(&mut self) -> &mut T {
1055 // SAFETY: the conditions of `RwLockWriteGuard::new` were satisfied when created.
1056 unsafe { &mut *self.lock.data.get() }
1057 }
1058}
1059
1060#[unstable(feature = "mapped_lock_guards", issue = "117108")]
1061// #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
1062impl<T: ?Sized> Deref for MappedRwLockReadGuard<'_, T> {
1063 type Target = T;
1064
1065 fn deref(&self) -> &T {
1066 // SAFETY: the conditions of `RwLockReadGuard::new` were satisfied when the original guard
1067 // was created, and have been upheld throughout `map` and/or `filter_map`.
1068 unsafe { self.data.as_ref() }
1069 }
1070}
1071
1072#[unstable(feature = "mapped_lock_guards", issue = "117108")]
1073// #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
1074impl<T: ?Sized> Deref for MappedRwLockWriteGuard<'_, T> {
1075 type Target = T;
1076
1077 fn deref(&self) -> &T {
1078 // SAFETY: the conditions of `RwLockWriteGuard::new` were satisfied when the original guard
1079 // was created, and have been upheld throughout `map` and/or `filter_map`.
1080 unsafe { self.data.as_ref() }
1081 }
1082}
1083
1084#[unstable(feature = "mapped_lock_guards", issue = "117108")]
1085// #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
1086impl<T: ?Sized> DerefMut for MappedRwLockWriteGuard<'_, T> {
1087 fn deref_mut(&mut self) -> &mut T {
1088 // SAFETY: the conditions of `RwLockWriteGuard::new` were satisfied when the original guard
1089 // was created, and have been upheld throughout `map` and/or `filter_map`.
1090 unsafe { self.data.as_mut() }
1091 }
1092}
1093
1094#[unstable(feature = "nonpoison_rwlock", issue = "134645")]
1095impl<T: ?Sized + fmt::Debug> fmt::Debug for RwLockReadGuard<'_, T> {
1096 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1097 (**self).fmt(f)
1098 }
1099}
1100
1101#[unstable(feature = "nonpoison_rwlock", issue = "134645")]
1102impl<T: ?Sized + fmt::Display> fmt::Display for RwLockReadGuard<'_, T> {
1103 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1104 (**self).fmt(f)
1105 }
1106}
1107
1108#[unstable(feature = "nonpoison_rwlock", issue = "134645")]
1109impl<T: ?Sized + fmt::Debug> fmt::Debug for RwLockWriteGuard<'_, T> {
1110 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1111 (**self).fmt(f)
1112 }
1113}
1114
1115#[unstable(feature = "nonpoison_rwlock", issue = "134645")]
1116impl<T: ?Sized + fmt::Display> fmt::Display for RwLockWriteGuard<'_, T> {
1117 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1118 (**self).fmt(f)
1119 }
1120}
1121
1122#[unstable(feature = "mapped_lock_guards", issue = "117108")]
1123// #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
1124impl<T: ?Sized + fmt::Debug> fmt::Debug for MappedRwLockReadGuard<'_, T> {
1125 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1126 (**self).fmt(f)
1127 }
1128}
1129
1130#[unstable(feature = "mapped_lock_guards", issue = "117108")]
1131// #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
1132impl<T: ?Sized + fmt::Display> fmt::Display for MappedRwLockReadGuard<'_, T> {
1133 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1134 (**self).fmt(f)
1135 }
1136}
1137
1138#[unstable(feature = "mapped_lock_guards", issue = "117108")]
1139// #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
1140impl<T: ?Sized + fmt::Debug> fmt::Debug for MappedRwLockWriteGuard<'_, T> {
1141 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1142 (**self).fmt(f)
1143 }
1144}
1145
1146#[unstable(feature = "mapped_lock_guards", issue = "117108")]
1147// #[unstable(feature = "nonpoison_rwlock", issue = "134645")]
1148impl<T: ?Sized + fmt::Display> fmt::Display for MappedRwLockWriteGuard<'_, T> {
1149 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1150 (**self).fmt(f)
1151 }
1152}