]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/common/poison.rs
std: Split the `std_misc` feature
[rust.git] / src / libstd / sys / common / poison.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use prelude::v1::*;
12
13 use cell::Cell;
14 use error::{Error};
15 use fmt;
16 use marker::Reflect;
17 use thread;
18
19 pub struct Flag { failed: Cell<bool> }
20
21 // This flag is only ever accessed with a lock previously held. Note that this
22 // a totally private structure.
23 unsafe impl Send for Flag {}
24 unsafe impl Sync for Flag {}
25
26 impl Flag {
27     pub const fn new() -> Flag {
28         Flag { failed: Cell::new(false) }
29     }
30
31     #[inline]
32     pub fn borrow(&self) -> LockResult<Guard> {
33         let ret = Guard { panicking: thread::panicking() };
34         if self.get() {
35             Err(PoisonError::new(ret))
36         } else {
37             Ok(ret)
38         }
39     }
40
41     #[inline]
42     pub fn done(&self, guard: &Guard) {
43         if !guard.panicking && thread::panicking() {
44             self.failed.set(true);
45         }
46     }
47
48     #[inline]
49     pub fn get(&self) -> bool {
50         self.failed.get()
51     }
52 }
53
54 pub struct Guard {
55     panicking: bool,
56 }
57
58 /// A type of error which can be returned whenever a lock is acquired.
59 ///
60 /// Both Mutexes and RwLocks are poisoned whenever a thread fails while the lock
61 /// is held. The precise semantics for when a lock is poisoned is documented on
62 /// each lock, but once a lock is poisoned then all future acquisitions will
63 /// return this error.
64 #[stable(feature = "rust1", since = "1.0.0")]
65 pub struct PoisonError<T> {
66     guard: T,
67 }
68
69 /// An enumeration of possible errors which can occur while calling the
70 /// `try_lock` method.
71 #[stable(feature = "rust1", since = "1.0.0")]
72 pub enum TryLockError<T> {
73     /// The lock could not be acquired because another thread failed while holding
74     /// the lock.
75     #[stable(feature = "rust1", since = "1.0.0")]
76     Poisoned(PoisonError<T>),
77     /// The lock could not be acquired at this time because the operation would
78     /// otherwise block.
79     #[stable(feature = "rust1", since = "1.0.0")]
80     WouldBlock,
81 }
82
83 /// A type alias for the result of a lock method which can be poisoned.
84 ///
85 /// The `Ok` variant of this result indicates that the primitive was not
86 /// poisoned, and the `Guard` is contained within. The `Err` variant indicates
87 /// that the primitive was poisoned. Note that the `Err` variant *also* carries
88 /// the associated guard, and it can be acquired through the `into_inner`
89 /// method.
90 #[stable(feature = "rust1", since = "1.0.0")]
91 pub type LockResult<Guard> = Result<Guard, PoisonError<Guard>>;
92
93 /// A type alias for the result of a nonblocking locking method.
94 ///
95 /// For more information, see `LockResult`. A `TryLockResult` doesn't
96 /// necessarily hold the associated guard in the `Err` type as the lock may not
97 /// have been acquired for other reasons.
98 #[stable(feature = "rust1", since = "1.0.0")]
99 pub type TryLockResult<Guard> = Result<Guard, TryLockError<Guard>>;
100
101 #[stable(feature = "rust1", since = "1.0.0")]
102 impl<T> fmt::Debug for PoisonError<T> {
103     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
104         "PoisonError { inner: .. }".fmt(f)
105     }
106 }
107
108 #[stable(feature = "rust1", since = "1.0.0")]
109 impl<T> fmt::Display for PoisonError<T> {
110     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
111         "poisoned lock: another task failed inside".fmt(f)
112     }
113 }
114
115 impl<T: Send + Reflect> Error for PoisonError<T> {
116     fn description(&self) -> &str {
117         "poisoned lock: another task failed inside"
118     }
119 }
120
121 impl<T> PoisonError<T> {
122     /// Creates a `PoisonError`.
123     #[unstable(feature = "sync_poison")]
124     pub fn new(guard: T) -> PoisonError<T> {
125         PoisonError { guard: guard }
126     }
127
128     /// Consumes this error indicating that a lock is poisoned, returning the
129     /// underlying guard to allow access regardless.
130     #[unstable(feature = "sync_poison")]
131     pub fn into_inner(self) -> T { self.guard }
132
133     /// Reaches into this error indicating that a lock is poisoned, returning a
134     /// reference to the underlying guard to allow access regardless.
135     #[unstable(feature = "sync_poison")]
136     pub fn get_ref(&self) -> &T { &self.guard }
137
138     /// Reaches into this error indicating that a lock is poisoned, returning a
139     /// mutable reference to the underlying guard to allow access regardless.
140     #[unstable(feature = "sync_poi")]
141     pub fn get_mut(&mut self) -> &mut T { &mut self.guard }
142 }
143
144 impl<T> From<PoisonError<T>> for TryLockError<T> {
145     fn from(err: PoisonError<T>) -> TryLockError<T> {
146         TryLockError::Poisoned(err)
147     }
148 }
149
150 #[stable(feature = "rust1", since = "1.0.0")]
151 impl<T> fmt::Debug for TryLockError<T> {
152     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
153         match *self {
154             TryLockError::Poisoned(..) => "Poisoned(..)".fmt(f),
155             TryLockError::WouldBlock => "WouldBlock".fmt(f)
156         }
157     }
158 }
159
160 #[stable(feature = "rust1", since = "1.0.0")]
161 impl<T: Send + Reflect> fmt::Display for TryLockError<T> {
162     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
163         self.description().fmt(f)
164     }
165 }
166
167 impl<T: Send + Reflect> Error for TryLockError<T> {
168     fn description(&self) -> &str {
169         match *self {
170             TryLockError::Poisoned(ref p) => p.description(),
171             TryLockError::WouldBlock => "try_lock failed because the operation would block"
172         }
173     }
174
175     fn cause(&self) -> Option<&Error> {
176         match *self {
177             TryLockError::Poisoned(ref p) => Some(p),
178             _ => None
179         }
180     }
181 }
182
183 pub fn map_result<T, U, F>(result: LockResult<T>, f: F)
184                            -> LockResult<U>
185                            where F: FnOnce(T) -> U {
186     match result {
187         Ok(t) => Ok(f(t)),
188         Err(PoisonError { guard }) => Err(PoisonError::new(f(guard)))
189     }
190 }