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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
//! Using [`MaybeUninit<T>`] requires unsafe, but this is often not necessary,
//! because the type system can statically determine the initialization status.
//!
//! This module provides [`StaticUninit<T, INIT>`] a safe alternative using
//! static type checking to ensure one cannot use an uninitialized value as an
//! initialized and to prevent leaking values when initializing a value twice
//! without dropping the contents.

use core::{
    borrow::{Borrow, BorrowMut},
    cmp, hash,
    mem::MaybeUninit,
    ops::{Deref, DerefMut},
    ptr::addr_of_mut,
};

/// This type is similar to [`MaybeUninit`], but it provides a safe interface
/// for initialization which can then be used statically.
/// It represents a Value which is
/// - uninitialized iff INIT == false
/// - initialized iff INIT == true
///
/// `StaticUninit<T, true>` behaves like `T`, as it implements [`DerefMut<Target = T>`],
/// [`BorrowMut<T>`] and more, you can also take the value directly with [`StaticUninit::into_inner`].
///
/// It also gives access to an unsafe interface allowing arbitrary modifications
/// of the underlying [`MaybeUninit`] if there are more complex initialization
/// requirements.
///
/// # Safety
///
/// If at any point you use one of the unsafe methods to access and modify the
/// inner [`MaybeUninit<T>`], you need to keep track of the initialization state
/// of that particular [`StaticUninit`] until you pass it to some other part of
/// the code. It is unsound to release a [`StaticUninit`] in
/// - a partially initialized state
/// - an unknown state of initialization
/// to other code, [`StaticUninit`] always is either fully initialized, or fully
/// uninitialized.
/// To achive partial initialization, use smaller components that can be fully
/// initialized seperatly and then create a wrapper struct using multiple
/// wrapping [`StaticUninit`]s (this is achieved by the `#[pinned_init]` proc
/// macro attribute).
#[repr(transparent)]
pub struct StaticUninit<T, const INIT: bool> {
    inner: MaybeUninit<T>,
}

impl<T, const INIT: bool> Drop for StaticUninit<T, INIT> {
    fn drop(&mut self) {
        if INIT {
            unsafe {
                // SAFETY: we are statically known to be initialized, so drop our value
                self.inner.assume_init_drop();
            }
        }
    }
}

impl<T> Deref for StaticUninit<T, true> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &Self::Target {
        unsafe {
            // SAFETY: we are statically known to be initialized.
            self.inner.assume_init_ref()
        }
    }
}

impl<T> DerefMut for StaticUninit<T, true> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe {
            // SAFETY: we are statically known to be initialized.
            self.inner.assume_init_mut()
        }
    }
}

impl<T> Borrow<T> for StaticUninit<T, true> {
    #[inline]
    fn borrow(&self) -> &T {
        &*self
    }
}

impl<T> BorrowMut<T> for StaticUninit<T, true> {
    #[inline]
    fn borrow_mut(&mut self) -> &mut T {
        &mut *self
    }
}

impl<T> AsRef<T> for StaticUninit<T, true> {
    #[inline]
    fn as_ref(&self) -> &T {
        &*self
    }
}

impl<T> AsMut<T> for StaticUninit<T, true> {
    #[inline]
    fn as_mut(&mut self) -> &mut T {
        &mut *self
    }
}

impl<T> From<T> for StaticUninit<T, true> {
    #[inline]
    fn from(data: T) -> Self {
        Self::new(data)
    }
}

impl<T: Clone> Clone for StaticUninit<T, true> {
    fn clone(&self) -> Self {
        StaticUninit::new((**self).clone())
    }

    fn clone_from(&mut self, src: &Self) {
        unsafe {
            // SAFETY: `src` and `self` are initialized, so dropping the value in self and cloning
            // the value in src are valid. we also immediatly populate `self` with a value without
            // invoking a function that can panic.
            let new = src.inner.assume_init_ref().clone();
            let drop_later = self.inner.assume_init_read();
            self.inner.write(new);
            // drop here to prevent an invalid state in self
            drop(drop_later);
        }
    }
}

impl<T: PartialEq<U>, U> PartialEq<StaticUninit<U, true>> for StaticUninit<T, true> {
    fn eq(&self, other: &StaticUninit<U, true>) -> bool {
        **self == **other
    }

    fn ne(&self, other: &StaticUninit<U, true>) -> bool {
        **self != **other
    }
}

impl<T: Eq> Eq for StaticUninit<T, true> {}

impl<T: PartialOrd<U>, U> PartialOrd<StaticUninit<U, true>> for StaticUninit<T, true> {
    fn partial_cmp(&self, other: &StaticUninit<U, true>) -> Option<cmp::Ordering> {
        (**self).partial_cmp(&**other)
    }

    fn lt(&self, other: &StaticUninit<U, true>) -> bool {
        **self < **other
    }

    fn gt(&self, other: &StaticUninit<U, true>) -> bool {
        **self > **other
    }

    fn le(&self, other: &StaticUninit<U, true>) -> bool {
        **self <= **other
    }

    fn ge(&self, other: &StaticUninit<U, true>) -> bool {
        **self >= **other
    }
}

impl<T: hash::Hash> hash::Hash for StaticUninit<T, true> {
    fn hash<H: hash::Hasher>(&self, state: &mut H) {
        (**self).hash(state)
    }
}

impl<T> StaticUninit<T, true> {
    /// Creates an already initialized `T` with its init status statically
    /// tracked.
    #[inline]
    pub fn new(data: T) -> Self {
        Self {
            inner: MaybeUninit::new(data),
        }
    }

    /// Retrieve the inner value of this `StaticUninit`.
    #[inline]
    pub fn into_inner(self) -> T {
        unsafe {
            // SAFETY: we are statically known to be initialized.
            self.inner.assume_init_read()
        }
    }

    /// Gets a mutable pointer to the initialized value. This avoids creating a reference, allowing
    /// mutable aliasing using `*mut`. This function is inspired by
    /// [raw_get](https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html#method.raw_get) from UnsafeCell.
    ///
    /// # Safety
    ///
    /// The supplied pointer must be valid.
    ///
    /// When casting the returned pointer to
    /// - `&mut T` the caller needs to ensure that no other references exist.
    /// - `&T` the caller needs to ensure that no mutable references exist.
    pub unsafe fn raw_get(this: *mut Self) -> *mut T {
        unsafe {
            // SAFETY: this is a valid pointer and we are initialized.
            // `MaybeUninit` is `repr(transparent)`, so we can cast the pointer to `T`.
            addr_of_mut!((*this).inner) as *mut T
        }
    }
}

impl<T> StaticUninit<T, false> {
    /// Creates a new uninitialized `T` with its init status statically tracked.
    #[inline]
    pub fn uninit() -> Self {
        Self {
            inner: MaybeUninit::uninit(),
        }
    }

    /// Gives access to the inner [`MaybeUninit`] immutably.
    ///
    /// # Safety
    ///
    /// You need to keep track of the initialization state of `self`, it is
    /// unsound to leave a [`StaticUninit`] in
    /// - a partially initialized state
    /// - an unknown state of initialization
    /// and allow code to observe it unknowingly.
    #[inline]
    pub unsafe fn as_uninit_ref(&self) -> &MaybeUninit<T> {
        &self.inner
    }

    /// Gives access to the inner [`MaybeUninit`] mutably.
    ///
    /// # Safety
    ///
    /// You need to keep track of the initialization state of `self`, it is
    /// unsound to leave a [`StaticUninit`] in
    /// - a partially initialized state
    /// - an unknown state of initialization
    /// and allow code to observe it unknowingly.
    #[inline]
    pub unsafe fn as_uninit_mut(&mut self) -> &mut MaybeUninit<T> {
        &mut self.inner
    }

    /// Initializes `self` using `data` and tracks that status statically.
    #[inline]
    pub fn write(self, data: T) -> StaticUninit<T, true> {
        StaticUninit::new(data)
    }
}