Debian Codegraph @

third_party/rust/atomic_refcell/src/lib.rs

raw
1 //! Implements a container type providing RefCell-like semantics for objects
2 //! shared across threads.
3 //!
4 //! RwLock is traditionally considered to be the |Sync| analogue of RefCell.
5 //! However, for consumers that can guarantee that they will never mutably
6 //! borrow the contents concurrently with immutable borrows, an RwLock is
7 //! overkill, and has key disadvantages:
8 //! * Performance: Even the fastest existing implementation of RwLock (that of
9 //! parking_lot) performs at least two atomic operations during immutable
10 //! borrows. This makes mutable borrows significantly cheaper than immutable
11 //! borrows, leading to weird incentives when writing performance-critical
12 //! code.
13 //! * Features: Implementing AtomicRefCell on top of RwLock makes it impossible
14 //! to implement useful things like AtomicRef{,Mut}::map.
15 //!
16 //! As such, we re-implement RefCell semantics from scratch with a single atomic
17 //! reference count. The primary complication of this scheme relates to keeping
18 //! things in a consistent state when one thread performs an illegal borrow and
19 //! panics. Since an AtomicRefCell can be accessed by multiple threads, and since
20 //! panics are recoverable, we need to ensure that an illegal (panicking) access by
21 //! one thread does not lead to undefined behavior on other, still-running threads.
22 //!
23 //! So we represent things as follows:
24 //! * Any value with the high bit set (so half the total refcount space) indicates
25 //! a mutable borrow.
26 //! * Mutable borrows perform an atomic compare-and-swap, swapping in the high bit
27 //! if the current value is zero. If the current value is non-zero, the thread
28 //! panics and the value is left undisturbed.
29 //! * Immutable borrows perform an atomic increment. If the new value has the high
30 //! bit set, the thread panics. The incremented refcount is left as-is, since it
31 //! still represents a valid mutable borrow. When the mutable borrow is released,
32 //! the refcount is set unconditionally to zero, clearing any stray increments by
33 //! panicked threads.
34 //!
35 //! There are a few additional purely-academic complications to handle overflow,
36 //! which are documented in the implementation.
37 //!
38 //! The rest of this module is mostly derived by copy-pasting the implementation of
39 //! RefCell and fixing things up as appropriate. Certain non-threadsafe methods
40 //! have been removed. We segment the concurrency logic from the rest of the code to
41 //! keep the tricky parts small and easy to audit.
42
43 #![no_std]
44 #![allow(unsafe_code)]
45 #![deny(missing_docs)]
46
47 use core::cell::UnsafeCell;
48 use core::cmp;
49 use core::fmt;
50 use core::fmt::{Debug, Display};
51 use core::ops::{Deref, DerefMut};
52 use core::sync::atomic;
53 use core::sync::atomic::AtomicUsize;
54
55 /// A threadsafe analogue to RefCell.
56 pub struct AtomicRefCell<T: ?Sized> {
57 borrow: AtomicUsize,
58 value: UnsafeCell<T>,
59 }
60
61 /// An error returned by [`AtomicRefCell::try_borrow`](struct.AtomicRefCell.html#method.try_borrow).
62 pub struct BorrowError {
63 _private: (),
64 }
65
66 impl Debug for BorrowError {
67 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68 f.debug_struct("BorrowError").finish()
69 }
70 }
71
72 impl Display for BorrowError {
73 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74 Display::fmt("already mutably borrowed", f)
75 }
76 }
77
78 /// An error returned by [`AtomicRefCell::try_borrow_mut`](struct.AtomicRefCell.html#method.try_borrow_mut).
79 pub struct BorrowMutError {
80 _private: (),
81 }
82
83 impl Debug for BorrowMutError {
84 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85 f.debug_struct("BorrowMutError").finish()
86 }
87 }
88
89 impl Display for BorrowMutError {
90 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91 Display::fmt("already borrowed", f)
92 }
93 }
94
95 impl<T> AtomicRefCell<T> {
96 /// Creates a new `AtomicRefCell` containing `value`.
97 #[inline]
98 pub const fn new(value: T) -> AtomicRefCell<T> {
99 AtomicRefCell {
100 borrow: AtomicUsize::new(0),
101 value: UnsafeCell::new(value),
102 }
103 }
104
105 /// Consumes the `AtomicRefCell`, returning the wrapped value.
106 #[inline]
107 pub fn into_inner(self) -> T {
108 debug_assert!(self.borrow.load(atomic::Ordering::Acquire) == 0);
109 self.value.into_inner()
110 }
111 }
112
113 impl<T: ?Sized> AtomicRefCell<T> {
114 /// Immutably borrows the wrapped value.
115 #[inline]
116 pub fn borrow(&self) -> AtomicRef<T> {
117 match AtomicBorrowRef::try_new(&self.borrow) {
118 Ok(borrow) => AtomicRef {
119 value: unsafe { &*self.value.get() },
120 borrow,
121 },
122 Err(s) => panic!("{}", s),
123 }
124 }
125
126 /// Attempts to immutably borrow the wrapped value, but instead of panicking
127 /// on a failed borrow, returns `Err`.
128 #[inline]
129 pub fn try_borrow(&self) -> Result<AtomicRef<T>, BorrowError> {
130 match AtomicBorrowRef::try_new(&self.borrow) {
131 Ok(borrow) => Ok(AtomicRef {
132 value: unsafe { &*self.value.get() },
133 borrow,
134 }),
135 Err(_) => Err(BorrowError { _private: () }),
136 }
137 }
138
139 /// Mutably borrows the wrapped value.
140 #[inline]
141 pub fn borrow_mut(&self) -> AtomicRefMut<T> {
142 match AtomicBorrowRefMut::try_new(&self.borrow) {
143 Ok(borrow) => AtomicRefMut {
144 value: unsafe { &mut *self.value.get() },
145 borrow,
146 },
147 Err(s) => panic!("{}", s),
148 }
149 }
150
151 /// Attempts to mutably borrow the wrapped value, but instead of panicking
152 /// on a failed borrow, returns `Err`.
153 #[inline]
154 pub fn try_borrow_mut(&self) -> Result<AtomicRefMut<T>, BorrowMutError> {
155 match AtomicBorrowRefMut::try_new(&self.borrow) {
156 Ok(borrow) => Ok(AtomicRefMut {
157 value: unsafe { &mut *self.value.get() },
158 borrow,
159 }),
160 Err(_) => Err(BorrowMutError { _private: () }),
161 }
162 }
163
164 /// Returns a raw pointer to the underlying data in this cell.
165 ///
166 /// External synchronization is needed to avoid data races when dereferencing
167 /// the pointer.
168 #[inline]
169 pub fn as_ptr(&self) -> *mut T {
170 self.value.get()
171 }
172
173 /// Returns a mutable reference to the wrapped value.
174 ///
175 /// No runtime checks take place (unless debug assertions are enabled)
176 /// because this call borrows `AtomicRefCell` mutably at compile-time.
177 #[inline]
178 pub fn get_mut(&mut self) -> &mut T {
179 debug_assert!(self.borrow.load(atomic::Ordering::Acquire) == 0);
180 unsafe { &mut *self.value.get() }
181 }
182 }
183
184 //
185 // Core synchronization logic. Keep this section small and easy to audit.
186 //
187
188 const HIGH_BIT: usize = !(::core::usize::MAX >> 1);
189 const MAX_FAILED_BORROWS: usize = HIGH_BIT + (HIGH_BIT >> 1);
190
191 struct AtomicBorrowRef<'b> {
192 borrow: &'b AtomicUsize,
193 }
194
195 impl<'b> AtomicBorrowRef<'b> {
196 #[inline]
197 fn try_new(borrow: &'b AtomicUsize) -> Result<Self, &'static str> {
198 let new = borrow.fetch_add(1, atomic::Ordering::Acquire) + 1;
199 if new & HIGH_BIT != 0 {
200 // If the new count has the high bit set, that almost certainly
201 // means there's an pre-existing mutable borrow. In that case,
202 // we simply leave the increment as a benign side-effect and
203 // return `Err`. Once the mutable borrow is released, the
204 // count will be reset to zero unconditionally.
205 //
206 // The overflow check here ensures that an unbounded number of
207 // immutable borrows during the scope of one mutable borrow
208 // will soundly trigger a panic (or abort) rather than UB.
209 Self::check_overflow(borrow, new);
210 Err("already mutably borrowed")
211 } else {
212 Ok(AtomicBorrowRef { borrow: borrow })
213 }
214 }
215
216 #[cold]
217 #[inline(never)]
218 fn check_overflow(borrow: &'b AtomicUsize, new: usize) {
219 if new == HIGH_BIT {
220 // We overflowed into the reserved upper half of the refcount
221 // space. Before panicking, decrement the refcount to leave things
222 // in a consistent immutable-borrow state.
223 //
224 // This can basically only happen if somebody forget()s AtomicRefs
225 // in a tight loop.
226 borrow.fetch_sub(1, atomic::Ordering::Release);
227 panic!("too many immutable borrows");
228 } else if new >= MAX_FAILED_BORROWS {
229 // During the mutable borrow, an absurd number of threads have
230 // attempted to increment the refcount with immutable borrows.
231 // To avoid hypothetically wrapping the refcount, we abort the
232 // process once a certain threshold is reached.
233 //
234 // This requires billions of borrows to fail during the scope of
235 // one mutable borrow, and so is very unlikely to happen in a real
236 // program.
237 //
238 // To avoid a potential unsound state after overflowing, we make
239 // sure the entire process aborts.
240 //
241 // Right now, there's no stable way to do that without `std`:
242 // https://github.com/rust-lang/rust/issues/67952
243 // As a workaround, we cause an abort by making this thread panic
244 // during the unwinding of another panic.
245 //
246 // On platforms where the panic strategy is already 'abort', the
247 // ForceAbort object here has no effect, as the program already
248 // panics before it is dropped.
249 struct ForceAbort;
250 impl Drop for ForceAbort {
251 fn drop(&mut self) {
252 panic!("Aborting to avoid unsound state of AtomicRefCell");
253 }
254 }
255 let _abort = ForceAbort;
256 panic!("Too many failed borrows");
257 }
258 }
259 }
260
261 impl<'b> Drop for AtomicBorrowRef<'b> {
262 #[inline]
263 fn drop(&mut self) {
264 let old = self.borrow.fetch_sub(1, atomic::Ordering::Release);
265 // This assertion is technically incorrect in the case where another
266 // thread hits the hypothetical overflow case, since we might observe
267 // the refcount before it fixes it up (and panics). But that never will
268 // never happen in a real program, and this is a debug_assert! anyway.
269 debug_assert!(old & HIGH_BIT == 0);
270 }
271 }
272
273 struct AtomicBorrowRefMut<'b> {
274 borrow: &'b AtomicUsize,
275 }
276
277 impl<'b> Drop for AtomicBorrowRefMut<'b> {
278 #[inline]
279 fn drop(&mut self) {
280 self.borrow.store(0, atomic::Ordering::Release);
281 }
282 }
283
284 impl<'b> AtomicBorrowRefMut<'b> {
285 #[inline]
286 fn try_new(borrow: &'b AtomicUsize) -> Result<AtomicBorrowRefMut<'b>, &'static str> {
287 // Use compare-and-swap to avoid corrupting the immutable borrow count
288 // on illegal mutable borrows.
289 let old = match borrow.compare_exchange(
290 0,
291 HIGH_BIT,
292 atomic::Ordering::Acquire,
293 atomic::Ordering::Relaxed,
294 ) {
295 Ok(x) => x,
296 Err(x) => x,
297 };
298
299 if old == 0 {
300 Ok(AtomicBorrowRefMut { borrow })
301 } else if old & HIGH_BIT == 0 {
302 Err("already immutably borrowed")
303 } else {
304 Err("already mutably borrowed")
305 }
306 }
307 }
308
309 unsafe impl<T: ?Sized + Send> Send for AtomicRefCell<T> {}
310 unsafe impl<T: ?Sized + Send + Sync> Sync for AtomicRefCell<T> {}
311
312 //
313 // End of core synchronization logic. No tricky thread stuff allowed below
314 // this point.
315 //
316
317 impl<T: Clone> Clone for AtomicRefCell<T> {
318 #[inline]
319 fn clone(&self) -> AtomicRefCell<T> {
320 AtomicRefCell::new(self.borrow().clone())
321 }
322 }
323
324 impl<T: Default> Default for AtomicRefCell<T> {
325 #[inline]
326 fn default() -> AtomicRefCell<T> {
327 AtomicRefCell::new(Default::default())
328 }
329 }
330
331 impl<T: ?Sized + PartialEq> PartialEq for AtomicRefCell<T> {
332 #[inline]
333 fn eq(&self, other: &AtomicRefCell<T>) -> bool {
334 *self.borrow() == *other.borrow()
335 }
336 }
337
338 impl<T: ?Sized + Eq> Eq for AtomicRefCell<T> {}
339
340 impl<T: ?Sized + PartialOrd> PartialOrd for AtomicRefCell<T> {
341 #[inline]
342 fn partial_cmp(&self, other: &AtomicRefCell<T>) -> Option<cmp::Ordering> {
343 self.borrow().partial_cmp(&*other.borrow())
344 }
345 }
346
347 impl<T: ?Sized + Ord> Ord for AtomicRefCell<T> {
348 #[inline]
349 fn cmp(&self, other: &AtomicRefCell<T>) -> cmp::Ordering {
350 self.borrow().cmp(&*other.borrow())
351 }
352 }
353
354 impl<T> From<T> for AtomicRefCell<T> {
355 fn from(t: T) -> AtomicRefCell<T> {
356 AtomicRefCell::new(t)
357 }
358 }
359
360 impl<'b> Clone for AtomicBorrowRef<'b> {
361 #[inline]
362 fn clone(&self) -> AtomicBorrowRef<'b> {
363 AtomicBorrowRef::try_new(self.borrow).unwrap()
364 }
365 }
366
367 /// A wrapper type for an immutably borrowed value from an `AtomicRefCell<T>`.
368 pub struct AtomicRef<'b, T: ?Sized + 'b> {
369 value: &'b T,
370 borrow: AtomicBorrowRef<'b>,
371 }
372
373 impl<'b, T: ?Sized> Deref for AtomicRef<'b, T> {
374 type Target = T;
375
376 #[inline]
377 fn deref(&self) -> &T {
378 self.value
379 }
380 }
381
382 impl<'b, T: ?Sized> AtomicRef<'b, T> {
383 /// Copies an `AtomicRef`.
384 #[inline]
385 pub fn clone(orig: &AtomicRef<'b, T>) -> AtomicRef<'b, T> {
386 AtomicRef {
387 value: orig.value,
388 borrow: orig.borrow.clone(),
389 }
390 }
391
392 /// Make a new `AtomicRef` for a component of the borrowed data.
393 #[inline]
394 pub fn map<U: ?Sized, F>(orig: AtomicRef<'b, T>, f: F) -> AtomicRef<'b, U>
395 where
396 F: FnOnce(&T) -> &U,
397 {
398 AtomicRef {
399 value: f(orig.value),
400 borrow: orig.borrow,
401 }
402 }
403
404 /// Make a new `AtomicRef` for an optional component of the borrowed data.
405 #[inline]
406 pub fn filter_map<U: ?Sized, F>(orig: AtomicRef<'b, T>, f: F) -> Option<AtomicRef<'b, U>>
407 where
408 F: FnOnce(&T) -> Option<&U>,
409 {
410 Some(AtomicRef {
411 value: f(orig.value)?,
412 borrow: orig.borrow,
413 })
414 }
415 }
416
417 impl<'b, T: ?Sized> AtomicRefMut<'b, T> {
418 /// Make a new `AtomicRefMut` for a component of the borrowed data, e.g. an enum
419 /// variant.
420 #[inline]
421 pub fn map<U: ?Sized, F>(orig: AtomicRefMut<'b, T>, f: F) -> AtomicRefMut<'b, U>
422 where
423 F: FnOnce(&mut T) -> &mut U,
424 {
425 AtomicRefMut {
426 value: f(orig.value),
427 borrow: orig.borrow,
428 }
429 }
430
431 /// Make a new `AtomicRefMut` for an optional component of the borrowed data.
432 #[inline]
433 pub fn filter_map<U: ?Sized, F>(orig: AtomicRefMut<'b, T>, f: F) -> Option<AtomicRefMut<'b, U>>
434 where
435 F: FnOnce(&mut T) -> Option<&mut U>,
436 {
437 Some(AtomicRefMut {
438 value: f(orig.value)?,
439 borrow: orig.borrow,
440 })
441 }
442 }
443
444 /// A wrapper type for a mutably borrowed value from an `AtomicRefCell<T>`.
445 pub struct AtomicRefMut<'b, T: ?Sized + 'b> {
446 value: &'b mut T,
447 borrow: AtomicBorrowRefMut<'b>,
448 }
449
450 impl<'b, T: ?Sized> Deref for AtomicRefMut<'b, T> {
451 type Target = T;
452
453 #[inline]
454 fn deref(&self) -> &T {
455 self.value
456 }
457 }
458
459 impl<'b, T: ?Sized> DerefMut for AtomicRefMut<'b, T> {
460 #[inline]
461 fn deref_mut(&mut self) -> &mut T {
462 self.value
463 }
464 }
465
466 impl<'b, T: ?Sized + Debug + 'b> Debug for AtomicRef<'b, T> {
467 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
468 self.value.fmt(f)
469 }
470 }
471
472 impl<'b, T: ?Sized + Debug + 'b> Debug for AtomicRefMut<'b, T> {
473 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
474 self.value.fmt(f)
475 }
476 }
477
478 impl<T: ?Sized + Debug> Debug for AtomicRefCell<T> {
479 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
480 write!(f, "AtomicRefCell {{ ... }}")
481 }
482 }