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
69
70
71
72
73
74
75
76
use alloc::boxed::Box;
use core::ops::{Deref, DerefMut};
use core::mem::ManuallyDrop;
#[repr(transparent)]
#[derive(Debug)]
pub struct ZeroBox<T> {
owned_box: Box<T>
}
impl<T> ZeroBox<T> {
pub fn new(x: T) -> ZeroBox<T> {
ZeroBox { owned_box: Box::new(x) }
}
pub fn new_zeroed() -> ZeroBox<T>
where T: ZeroInitialized {
#[doc(hidden)]
#[repr(C)]
union ZeroedBuilder<X> {
empty: (),
t: ManuallyDrop<X>
}
#[doc(hidden)]
unsafe fn zeroed<T>() -> Box<T> {
let alloc: Box<ZeroedBuilder<T>> = box ZeroedBuilder {
empty: ()
};
let alloc = Box::into_raw(alloc);
::core::ptr::write_bytes(alloc, 0x00, 1);
Box::<T>::from_raw(alloc as *mut T)
}
ZeroBox { owned_box: unsafe { zeroed() } }
}
}
impl<T> Deref for ZeroBox<T> {
type Target = T;
fn deref(&self) -> &<Self as Deref>::Target { &*self.owned_box }
}
impl<T> DerefMut for ZeroBox<T> {
fn deref_mut(&mut self) -> &mut <Self as Deref>::Target { &mut *self.owned_box }
}
impl<T> AsRef<T> for ZeroBox<T> {
fn as_ref(&self) -> &T {
&self.owned_box
}
}
impl<T> AsMut<T> for ZeroBox<T> {
fn as_mut(&mut self) -> &mut T {
&mut self.owned_box
}
}
pub unsafe trait ZeroInitialized {}