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
use core::cell::UnsafeCell;
use core::fmt::{self, Debug};
use core::marker::Sync;
use core::ops::Deref;
pub struct UnsafeContainer<T: ?Sized>(UnsafeCell<T>);
unsafe impl<T: ?Sized + Send> Sync for UnsafeContainer<T> {}
unsafe impl<T: ?Sized + Send> Send for UnsafeContainer<T> {}
impl<T> UnsafeContainer<T> {
pub const fn new(t: T) -> UnsafeContainer<T> {
UnsafeContainer(UnsafeCell::new(t))
}
pub fn into_inner(self) -> T {
self.0.into_inner()
}
pub fn replace(&self, t: T) -> T {
return core::mem::replace(self.get(), t);
}
pub fn get<'a>(&self) -> &'a mut T {
unsafe { &mut *self.0.get() }
}
}
impl<T: ?Sized> Deref for UnsafeContainer<T> {
type Target = T;
fn deref<'a>(&'a self) -> &'a T {
unsafe { &*self.0.get() }
}
}
impl<T> Default for UnsafeContainer<T>
where
T: Default,
{
fn default() -> UnsafeContainer<T> {
Self::new(Default::default())
}
}
impl<T> Debug for UnsafeContainer<T>
where
T: Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("UnsafeContainer").field(self.get()).finish()
}
}