1#![no_std]
44#![allow(unsafe_code)]
45#![deny(missing_docs)]
46
47use core::cell::UnsafeCell;
48use core::cmp;
49use core::fmt;
50use core::fmt::{Debug, Display};
51use core::marker::PhantomData;
52use core::ops::{Deref, DerefMut};
53use core::ptr::NonNull;
54use core::sync::atomic;
55use core::sync::atomic::AtomicUsize;
56
57#[cfg(feature = "serde")]
58extern crate serde;
59#[cfg(feature = "serde")]
60use serde::{Deserialize, Serialize};
61
62pub struct AtomicRefCell<T: ?Sized> {
64    borrow: AtomicUsize,
65    value: UnsafeCell<T>,
66}
67
68pub struct BorrowError {
70    _private: (),
71}
72
73impl Debug for BorrowError {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        f.debug_struct("BorrowError").finish()
76    }
77}
78
79impl Display for BorrowError {
80    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81        Display::fmt("already mutably borrowed", f)
82    }
83}
84
85pub struct BorrowMutError {
87    _private: (),
88}
89
90impl Debug for BorrowMutError {
91    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92        f.debug_struct("BorrowMutError").finish()
93    }
94}
95
96impl Display for BorrowMutError {
97    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98        Display::fmt("already borrowed", f)
99    }
100}
101
102impl<T> AtomicRefCell<T> {
103    #[inline]
105    pub const fn new(value: T) -> AtomicRefCell<T> {
106        AtomicRefCell {
107            borrow: AtomicUsize::new(0),
108            value: UnsafeCell::new(value),
109        }
110    }
111
112    #[inline]
114    pub fn into_inner(self) -> T {
115        debug_assert!(self.borrow.load(atomic::Ordering::Acquire) == 0);
116        self.value.into_inner()
117    }
118}
119
120impl<T: ?Sized> AtomicRefCell<T> {
121    #[inline]
123    pub fn borrow(&self) -> AtomicRef<T> {
124        match AtomicBorrowRef::try_new(&self.borrow) {
125            Ok(borrow) => AtomicRef {
126                value: unsafe { NonNull::new_unchecked(self.value.get()) },
127                borrow,
128            },
129            Err(s) => panic!("{}", s),
130        }
131    }
132
133    #[inline]
136    pub fn try_borrow(&self) -> Result<AtomicRef<T>, BorrowError> {
137        match AtomicBorrowRef::try_new(&self.borrow) {
138            Ok(borrow) => Ok(AtomicRef {
139                value: unsafe { NonNull::new_unchecked(self.value.get()) },
140                borrow,
141            }),
142            Err(_) => Err(BorrowError { _private: () }),
143        }
144    }
145
146    #[inline]
148    pub fn borrow_mut(&self) -> AtomicRefMut<T> {
149        match AtomicBorrowRefMut::try_new(&self.borrow) {
150            Ok(borrow) => AtomicRefMut {
151                value: unsafe { NonNull::new_unchecked(self.value.get()) },
152                borrow,
153                marker: PhantomData,
154            },
155            Err(s) => panic!("{}", s),
156        }
157    }
158
159    #[inline]
162    pub fn try_borrow_mut(&self) -> Result<AtomicRefMut<T>, BorrowMutError> {
163        match AtomicBorrowRefMut::try_new(&self.borrow) {
164            Ok(borrow) => Ok(AtomicRefMut {
165                value: unsafe { NonNull::new_unchecked(self.value.get()) },
166                borrow,
167                marker: PhantomData,
168            }),
169            Err(_) => Err(BorrowMutError { _private: () }),
170        }
171    }
172
173    #[inline]
178    pub fn as_ptr(&self) -> *mut T {
179        self.value.get()
180    }
181
182    #[inline]
187    pub fn get_mut(&mut self) -> &mut T {
188        debug_assert!(self.borrow.load(atomic::Ordering::Acquire) == 0);
189        unsafe { &mut *self.value.get() }
190    }
191}
192
193const HIGH_BIT: usize = !(::core::usize::MAX >> 1);
198const MAX_FAILED_BORROWS: usize = HIGH_BIT + (HIGH_BIT >> 1);
199
200struct AtomicBorrowRef<'b> {
201    borrow: &'b AtomicUsize,
202}
203
204impl<'b> AtomicBorrowRef<'b> {
205    #[inline]
206    fn try_new(borrow: &'b AtomicUsize) -> Result<Self, &'static str> {
207        let new = borrow.fetch_add(1, atomic::Ordering::Acquire) + 1;
208        if new & HIGH_BIT != 0 {
209            Self::check_overflow(borrow, new);
219            Err("already mutably borrowed")
220        } else {
221            Ok(AtomicBorrowRef { borrow: borrow })
222        }
223    }
224
225    #[cold]
226    #[inline(never)]
227    fn check_overflow(borrow: &'b AtomicUsize, new: usize) {
228        if new == HIGH_BIT {
229            borrow.fetch_sub(1, atomic::Ordering::Release);
236            panic!("too many immutable borrows");
237        } else if new >= MAX_FAILED_BORROWS {
238            struct ForceAbort;
259            impl Drop for ForceAbort {
260                fn drop(&mut self) {
261                    panic!("Aborting to avoid unsound state of AtomicRefCell");
262                }
263            }
264            let _abort = ForceAbort;
265            panic!("Too many failed borrows");
266        }
267    }
268}
269
270impl<'b> Drop for AtomicBorrowRef<'b> {
271    #[inline]
272    fn drop(&mut self) {
273        let old = self.borrow.fetch_sub(1, atomic::Ordering::Release);
274        debug_assert!(old & HIGH_BIT == 0);
279    }
280}
281
282struct AtomicBorrowRefMut<'b> {
283    borrow: &'b AtomicUsize,
284}
285
286impl<'b> Drop for AtomicBorrowRefMut<'b> {
287    #[inline]
288    fn drop(&mut self) {
289        self.borrow.store(0, atomic::Ordering::Release);
290    }
291}
292
293impl<'b> AtomicBorrowRefMut<'b> {
294    #[inline]
295    fn try_new(borrow: &'b AtomicUsize) -> Result<AtomicBorrowRefMut<'b>, &'static str> {
296        let old = match borrow.compare_exchange(
299            0,
300            HIGH_BIT,
301            atomic::Ordering::Acquire,
302            atomic::Ordering::Relaxed,
303        ) {
304            Ok(x) => x,
305            Err(x) => x,
306        };
307
308        if old == 0 {
309            Ok(AtomicBorrowRefMut { borrow })
310        } else if old & HIGH_BIT == 0 {
311            Err("already immutably borrowed")
312        } else {
313            Err("already mutably borrowed")
314        }
315    }
316}
317
318unsafe impl<T: ?Sized + Send> Send for AtomicRefCell<T> {}
319unsafe impl<T: ?Sized + Send + Sync> Sync for AtomicRefCell<T> {}
320
321impl<T: Clone> Clone for AtomicRefCell<T> {
327    #[inline]
328    fn clone(&self) -> AtomicRefCell<T> {
329        AtomicRefCell::new(self.borrow().clone())
330    }
331}
332
333impl<T: Default> Default for AtomicRefCell<T> {
334    #[inline]
335    fn default() -> AtomicRefCell<T> {
336        AtomicRefCell::new(Default::default())
337    }
338}
339
340impl<T: ?Sized + PartialEq> PartialEq for AtomicRefCell<T> {
341    #[inline]
342    fn eq(&self, other: &AtomicRefCell<T>) -> bool {
343        *self.borrow() == *other.borrow()
344    }
345}
346
347impl<T: ?Sized + Eq> Eq for AtomicRefCell<T> {}
348
349impl<T: ?Sized + PartialOrd> PartialOrd for AtomicRefCell<T> {
350    #[inline]
351    fn partial_cmp(&self, other: &AtomicRefCell<T>) -> Option<cmp::Ordering> {
352        self.borrow().partial_cmp(&*other.borrow())
353    }
354}
355
356impl<T: ?Sized + Ord> Ord for AtomicRefCell<T> {
357    #[inline]
358    fn cmp(&self, other: &AtomicRefCell<T>) -> cmp::Ordering {
359        self.borrow().cmp(&*other.borrow())
360    }
361}
362
363impl<T> From<T> for AtomicRefCell<T> {
364    fn from(t: T) -> AtomicRefCell<T> {
365        AtomicRefCell::new(t)
366    }
367}
368
369impl<'b> Clone for AtomicBorrowRef<'b> {
370    #[inline]
371    fn clone(&self) -> AtomicBorrowRef<'b> {
372        AtomicBorrowRef::try_new(self.borrow).unwrap()
373    }
374}
375
376pub struct AtomicRef<'b, T: ?Sized + 'b> {
378    value: NonNull<T>,
379    borrow: AtomicBorrowRef<'b>,
380}
381
382unsafe impl<'b, T: ?Sized> Sync for AtomicRef<'b, T> where for<'a> &'a T: Sync {}
385unsafe impl<'b, T: ?Sized> Send for AtomicRef<'b, T> where for<'a> &'a T: Send {}
386
387impl<'b, T: ?Sized> Deref for AtomicRef<'b, T> {
388    type Target = T;
389
390    #[inline]
391    fn deref(&self) -> &T {
392        unsafe { self.value.as_ref() }
394    }
395}
396
397impl<'b, T: ?Sized> AtomicRef<'b, T> {
398    #[inline]
400    pub fn clone(orig: &AtomicRef<'b, T>) -> AtomicRef<'b, T> {
401        AtomicRef {
402            value: orig.value,
403            borrow: orig.borrow.clone(),
404        }
405    }
406
407    #[inline]
409    pub fn map<U: ?Sized, F>(orig: AtomicRef<'b, T>, f: F) -> AtomicRef<'b, U>
410    where
411        F: FnOnce(&T) -> &U,
412    {
413        AtomicRef {
414            value: NonNull::from(f(&*orig)),
415            borrow: orig.borrow,
416        }
417    }
418
419    #[inline]
421    pub fn filter_map<U: ?Sized, F>(orig: AtomicRef<'b, T>, f: F) -> Option<AtomicRef<'b, U>>
422    where
423        F: FnOnce(&T) -> Option<&U>,
424    {
425        Some(AtomicRef {
426            value: NonNull::from(f(&*orig)?),
427            borrow: orig.borrow,
428        })
429    }
430}
431
432impl<'b, T: ?Sized> AtomicRefMut<'b, T> {
433    #[inline]
436    pub fn map<U: ?Sized, F>(mut orig: AtomicRefMut<'b, T>, f: F) -> AtomicRefMut<'b, U>
437    where
438        F: FnOnce(&mut T) -> &mut U,
439    {
440        AtomicRefMut {
441            value: NonNull::from(f(&mut *orig)),
442            borrow: orig.borrow,
443            marker: PhantomData,
444        }
445    }
446
447    #[inline]
449    pub fn filter_map<U: ?Sized, F>(
450        mut orig: AtomicRefMut<'b, T>,
451        f: F,
452    ) -> Option<AtomicRefMut<'b, U>>
453    where
454        F: FnOnce(&mut T) -> Option<&mut U>,
455    {
456        Some(AtomicRefMut {
457            value: NonNull::from(f(&mut *orig)?),
458            borrow: orig.borrow,
459            marker: PhantomData,
460        })
461    }
462}
463
464pub struct AtomicRefMut<'b, T: ?Sized + 'b> {
466    value: NonNull<T>,
467    borrow: AtomicBorrowRefMut<'b>,
468    marker: PhantomData<&'b mut T>,
471}
472
473unsafe impl<'b, T: ?Sized> Sync for AtomicRefMut<'b, T> where for<'a> &'a mut T: Sync {}
476unsafe impl<'b, T: ?Sized> Send for AtomicRefMut<'b, T> where for<'a> &'a mut T: Send {}
477
478impl<'b, T: ?Sized> Deref for AtomicRefMut<'b, T> {
479    type Target = T;
480
481    #[inline]
482    fn deref(&self) -> &T {
483        unsafe { self.value.as_ref() }
485    }
486}
487
488impl<'b, T: ?Sized> DerefMut for AtomicRefMut<'b, T> {
489    #[inline]
490    fn deref_mut(&mut self) -> &mut T {
491        unsafe { self.value.as_mut() }
493    }
494}
495
496impl<'b, T: ?Sized + Debug + 'b> Debug for AtomicRef<'b, T> {
497    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
498        <T as Debug>::fmt(self, f)
499    }
500}
501
502impl<'b, T: ?Sized + Debug + 'b> Debug for AtomicRefMut<'b, T> {
503    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
504        <T as Debug>::fmt(self, f)
505    }
506}
507
508impl<T: ?Sized + Debug> Debug for AtomicRefCell<T>  {
509    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
510        match self.try_borrow() {
511            Ok(borrow) => f.debug_struct("AtomicRefCell").field("value", &borrow).finish(),
512            Err(_) => {
513                struct BorrowedPlaceholder;
516
517                impl Debug for BorrowedPlaceholder {
518                    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
519                        f.write_str("<borrowed>")
520                    }
521                }
522
523                f.debug_struct("AtomicRefCell").field("value", &BorrowedPlaceholder).finish()
524            }
525        }
526    }
527}
528
529#[cfg(feature = "serde")]
530impl<'de, T: Deserialize<'de>> Deserialize<'de> for AtomicRefCell<T> {
531    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
532    where
533        D: serde::Deserializer<'de>,
534    {
535        T::deserialize(deserializer).map(Self::from)
536    }
537}
538
539#[cfg(feature = "serde")]
540impl<T: Serialize> Serialize for AtomicRefCell<T> {
541    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
542    where
543        S: serde::Serializer,
544    {
545        use serde::ser::Error;
546        match self.try_borrow() {
547            Ok(value) => value.serialize(serializer),
548            Err(_err) => Err(S::Error::custom("already mutably borrowed")),
549        }
550    }
551}