shared_rwlock/poison.rs
1// SPDX-License-Identifier: Apache-2.0 OR MIT
2//
3// # Forked rust std::sync::poison(ver. 1.84.0)
4// See: https://github.com/rust-lang/rust/blob/1.84.0/library/std/src/sync/poison.rs
5// See Rust license detail: https://github.com/rust-lang/rust/pull/43498
6
7use core::error::Error;
8#[cfg(panic = "unwind")]
9use core::sync::atomic::{AtomicBool, Ordering};
10use std::fmt;
11#[cfg(panic = "unwind")]
12use std::thread;
13
14pub struct Flag {
15 #[cfg(panic = "unwind")]
16 failed: AtomicBool,
17}
18
19// Note that the Ordering uses to access the `failed` field of `Flag` below is
20// always `Relaxed`, and that's because this isn't actually protecting any data,
21// it's just a flag whether we've panicked or not.
22//
23// The actual location that this matters is when a mutex is **locked** which is
24// where we have external synchronization ensuring that we see memory
25// reads/writes to this flag.
26//
27// As a result, if it matters, we should see the correct value for `failed` in
28// all cases.
29
30impl Flag {
31 #[allow(unused)]
32 #[inline]
33 pub const fn new() -> Self {
34 Self {
35 #[cfg(panic = "unwind")]
36 failed: AtomicBool::new(false),
37 }
38 }
39
40 /// Checks the flag for an unguarded borrow, where we only care about existing poison.
41 #[inline]
42 pub fn borrow(&self) -> LockResult<()> {
43 if self.get() { Err(PoisonError::new(())) } else { Ok(()) }
44 }
45
46 /// Checks the flag for a guarded borrow, where we may also set poison when `done`.
47 #[inline]
48 pub fn guard(&self) -> LockResult<Guard> {
49 let ret = Guard {
50 #[cfg(panic = "unwind")]
51 panicking: thread::panicking(),
52 };
53 if self.get() { Err(PoisonError::new(ret)) } else { Ok(ret) }
54 }
55
56 #[inline]
57 #[cfg(panic = "unwind")]
58 pub fn done(&self, guard: &Guard) {
59 if !guard.panicking && thread::panicking() {
60 self.failed.store(true, Ordering::Relaxed);
61 }
62 }
63
64 #[inline]
65 #[cfg(not(panic = "unwind"))]
66 pub fn done(&self, _guard: &Guard) {}
67
68 #[inline]
69 #[cfg(panic = "unwind")]
70 pub fn get(&self) -> bool {
71 self.failed.load(Ordering::Relaxed)
72 }
73
74 #[inline(always)]
75 #[cfg(not(panic = "unwind"))]
76 pub fn get(&self) -> bool {
77 false
78 }
79
80 #[inline]
81 pub fn clear(&self) {
82 #[cfg(panic = "unwind")]
83 self.failed.store(false, Ordering::Relaxed);
84 }
85}
86
87#[derive(Clone)]
88pub struct Guard {
89 #[cfg(panic = "unwind")]
90 panicking: bool,
91}
92
93/// A type of error which can be returned whenever a lock is acquired.
94///
95/// Both [`Mutex`]es and [`RwLock`]s are poisoned whenever a thread fails while the lock
96/// is held. The precise semantics for when a lock is poisoned is documented on
97/// each lock, but once a lock is poisoned then all future acquisitions will
98/// return this error.
99///
100/// # Examples
101///
102/// ```
103/// use std::sync::{Arc, Mutex};
104/// use std::thread;
105///
106/// let mutex = Arc::new(Mutex::new(1));
107///
108/// // poison the mutex
109/// let c_mutex = Arc::clone(&mutex);
110/// let _ = thread::spawn(move || {
111/// let mut data = c_mutex.lock().unwrap();
112/// *data = 2;
113/// panic!();
114/// }).join();
115///
116/// match mutex.lock() {
117/// Ok(_) => unreachable!(),
118/// Err(p_err) => {
119/// let data = p_err.get_ref();
120/// println!("recovered: {data}");
121/// }
122/// };
123/// ```
124/// [`Mutex`]: crate::sync::Mutex
125/// [`RwLock`]: crate::sync::RwLock
126pub struct PoisonError<T> {
127 guard: T,
128 #[cfg(not(panic = "unwind"))]
129 _never: !,
130}
131
132#[allow(clippy::too_long_first_doc_paragraph)]
133/// An enumeration of possible errors associated with a [`TryLockResult`] which
134/// can occur while trying to acquire a lock, from the [`try_lock`] method on a
135/// [`Mutex`] or the [`try_read`] and [`try_write`] methods on an [`RwLock`].
136///
137/// [`try_lock`]: crate::sync::Mutex::try_lock
138/// [`try_read`]: crate::sync::RwLock::try_read
139/// [`try_write`]: crate::sync::RwLock::try_write
140/// [`Mutex`]: crate::sync::Mutex
141/// [`RwLock`]: crate::sync::RwLock
142pub enum TryLockError<T> {
143 /// The lock could not be acquired because another thread failed while holding
144 /// the lock.
145 Poisoned(PoisonError<T>),
146 /// The lock could not be acquired at this time because the operation would
147 /// otherwise block.
148 WouldBlock,
149}
150
151/// A type alias for the result of a lock method which can be poisoned.
152///
153/// The [`Ok`] variant of this result indicates that the primitive was not
154/// poisoned, and the `Guard` is contained within. The [`Err`] variant indicates
155/// that the primitive was poisoned. Note that the [`Err`] variant *also* carries
156/// the associated guard, and it can be acquired through the [`into_inner`]
157/// method.
158///
159/// [`into_inner`]: PoisonError::into_inner
160pub type LockResult<Guard> = Result<Guard, PoisonError<Guard>>;
161
162/// A type alias for the result of a nonblocking locking method.
163///
164/// For more information, see [`LockResult`]. A `TryLockResult` doesn't
165/// necessarily hold the associated guard in the [`Err`] type as the lock might not
166/// have been acquired for other reasons.
167pub type TryLockResult<Guard> = Result<Guard, TryLockError<Guard>>;
168
169impl<T> fmt::Debug for PoisonError<T> {
170 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171 f.debug_struct("PoisonError").finish_non_exhaustive()
172 }
173}
174
175impl<T> fmt::Display for PoisonError<T> {
176 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177 "poisoned lock: another task failed inside".fmt(f)
178 }
179}
180
181impl<T> Error for PoisonError<T> {
182 #[allow(deprecated)]
183 fn description(&self) -> &str {
184 "poisoned lock: another task failed inside"
185 }
186}
187
188impl<T> PoisonError<T> {
189 /// Creates a `PoisonError`.
190 ///
191 /// This is generally created by methods like [`Mutex::lock`](crate::sync::Mutex::lock)
192 /// or [`RwLock::read`](crate::sync::RwLock::read).
193 ///
194 /// This method may panic if std was built with `panic="abort"`.
195 #[cfg(panic = "unwind")]
196 pub const fn new(guard: T) -> Self {
197 Self { guard }
198 }
199
200 /// Creates a `PoisonError`.
201 ///
202 /// This is generally created by methods like [`Mutex::lock`](crate::sync::Mutex::lock)
203 /// or [`RwLock::read`](crate::sync::RwLock::read).
204 ///
205 /// This method may panic if std was built with `panic="abort"`.
206 #[cfg(not(panic = "unwind"))]
207 #[stable(feature = "sync_poison", since = "1.2.0")]
208 #[track_caller]
209 pub fn new(_guard: T) -> PoisonError<T> {
210 panic!("PoisonError created in a libstd built with panic=\"abort\"")
211 }
212
213 /// Consumes this error indicating that a lock is poisoned, returning the
214 /// underlying guard to allow access regardless.
215 ///
216 /// # Examples
217 ///
218 /// ```
219 /// use std::collections::HashSet;
220 /// use std::sync::{Arc, Mutex};
221 /// use std::thread;
222 ///
223 /// let mutex = Arc::new(Mutex::new(HashSet::new()));
224 ///
225 /// // poison the mutex
226 /// let c_mutex = Arc::clone(&mutex);
227 /// let _ = thread::spawn(move || {
228 /// let mut data = c_mutex.lock().unwrap();
229 /// data.insert(10);
230 /// panic!();
231 /// }).join();
232 ///
233 /// let p_err = mutex.lock().unwrap_err();
234 /// let data = p_err.into_inner();
235 /// println!("recovered {} items", data.len());
236 /// ```
237 pub fn into_inner(self) -> T {
238 self.guard
239 }
240
241 /// Reaches into this error indicating that a lock is poisoned, returning a
242 /// reference to the underlying guard to allow access regardless.
243 pub const fn get_ref(&self) -> &T {
244 &self.guard
245 }
246
247 /// Reaches into this error indicating that a lock is poisoned, returning a
248 /// mutable reference to the underlying guard to allow access regardless.
249 pub const fn get_mut(&mut self) -> &mut T {
250 &mut self.guard
251 }
252}
253
254impl<T> From<PoisonError<T>> for TryLockError<T> {
255 fn from(err: PoisonError<T>) -> Self {
256 Self::Poisoned(err)
257 }
258}
259
260impl<T> fmt::Debug for TryLockError<T> {
261 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
262 match *self {
263 #[cfg(panic = "unwind")]
264 Self::Poisoned(..) => "Poisoned(..)".fmt(f),
265 #[cfg(not(panic = "unwind"))]
266 Self::Poisoned(ref p) => match p._never {},
267 Self::WouldBlock => "WouldBlock".fmt(f),
268 }
269 }
270}
271
272impl<T> fmt::Display for TryLockError<T> {
273 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
274 match *self {
275 #[cfg(panic = "unwind")]
276 Self::Poisoned(..) => "poisoned lock: another task failed inside",
277 #[cfg(not(panic = "unwind"))]
278 Self::Poisoned(ref p) => match p._never {},
279 Self::WouldBlock => "try_lock failed because the operation would block",
280 }
281 .fmt(f)
282 }
283}
284
285impl<T> Error for TryLockError<T> {
286 #[allow(deprecated, deprecated_in_future)]
287 fn description(&self) -> &str {
288 match *self {
289 #[cfg(panic = "unwind")]
290 Self::Poisoned(ref p) => p.description(),
291 #[cfg(not(panic = "unwind"))]
292 Self::Poisoned(ref p) => match p._never {},
293 Self::WouldBlock => "try_lock failed because the operation would block",
294 }
295 }
296
297 #[allow(deprecated)]
298 fn cause(&self) -> Option<&dyn Error> {
299 match *self {
300 #[cfg(panic = "unwind")]
301 Self::Poisoned(ref p) => Some(p),
302 #[cfg(not(panic = "unwind"))]
303 Self::Poisoned(ref p) => match p._never {},
304 _ => None,
305 }
306 }
307}
308
309pub fn map_result<T, U, F>(result: LockResult<T>, f: F) -> LockResult<U>
310where
311 F: FnOnce(T) -> U,
312{
313 match result {
314 Ok(t) => Ok(f(t)),
315 #[cfg(panic = "unwind")]
316 Err(PoisonError { guard }) => Err(PoisonError::new(f(guard))),
317 }
318}