esp32_nimble/utilities/
arc_unsafe_cell.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use alloc::sync::{Arc, Weak};
use core::{
  cell::UnsafeCell,
  ops::{Deref, DerefMut},
};

pub struct ArcUnsafeCell<T: ?Sized> {
  value: Arc<UnsafeCell<T>>,
}

impl<T> ArcUnsafeCell<T> {
  #[inline(always)]
  pub(crate) fn new(value: T) -> Self {
    Self {
      value: Arc::new(UnsafeCell::new(value)),
    }
  }

  pub fn downgrade(this: &Self) -> WeakUnsafeCell<T> {
    WeakUnsafeCell {
      value: Arc::downgrade(&this.value),
    }
  }
}

impl<T: ?Sized> Clone for ArcUnsafeCell<T> {
  #[inline]
  fn clone(&self) -> Self {
    Self {
      value: self.value.clone(),
    }
  }
}

impl<T: ?Sized> Deref for ArcUnsafeCell<T> {
  type Target = T;

  #[inline]
  fn deref(&self) -> &T {
    unsafe { &*self.value.get() }
  }
}

impl<T: ?Sized> DerefMut for ArcUnsafeCell<T> {
  #[inline]
  fn deref_mut(&mut self) -> &mut T {
    unsafe { &mut *self.value.get() }
  }
}

pub struct WeakUnsafeCell<T: ?Sized> {
  pub value: Weak<UnsafeCell<T>>,
}

impl<T> WeakUnsafeCell<T> {
  pub fn upgrade(&self) -> Option<ArcUnsafeCell<T>> {
    self.value.upgrade().map(|x| ArcUnsafeCell { value: x })
  }
}

impl<T: ?Sized> Clone for WeakUnsafeCell<T> {
  #[inline]
  fn clone(&self) -> Self {
    Self {
      value: self.value.clone(),
    }
  }
}