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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Provides an `Option`-like type for constructing values in place.

use std::mem::MaybeUninit;
use std::sync::Arc;

/// A type with methods like `Option` but that operates on a mutable reference
/// to possibly-initialized data.
///
/// This is used to initialize data in place without copying to/from `Option`
/// types.
pub struct InplaceOption<'a, T> {
    val: &'a mut MaybeUninit<T>,
    init: bool,
}

impl<'a, T> InplaceOption<'a, T> {
    /// Creates an option in the uninitialized state.
    pub fn uninit(val: &'a mut MaybeUninit<T>) -> Self {
        Self { val, init: false }
    }

    /// Creates an option in the initialized state.
    ///
    /// # Safety
    ///
    /// The caller must guarantee that the value referenced by `val` is
    /// initialized.
    pub unsafe fn new_init_unchecked(val: &'a mut MaybeUninit<T>) -> Self {
        Self { val, init: true }
    }

    /// Sets the value to the initialized state.
    ///
    /// # Safety
    ///
    /// The caller must guarantee that the underlying data has been fully
    /// initialized.
    pub unsafe fn set_init_unchecked(&mut self) -> &mut T {
        self.init = true;
        // SAFETY: the caller guarantees val is initialized.
        unsafe { self.val.assume_init_mut() }
    }

    /// Takes the value, returning `Some(_)` if the value is initialized and
    /// `None` otherwise.
    pub fn take(&mut self) -> Option<T> {
        if self.init {
            self.init = false;
            // SAFETY: val is initialized
            unsafe {
                let val = std::ptr::read(&*self.val);
                Some(val.assume_init())
            }
        } else {
            None
        }
    }

    /// Returns a reference to the data if it's initialized.
    pub fn as_ref(&self) -> Option<&T> {
        if self.init {
            // SAFETY: We have just checked that val is initialized
            unsafe { self.val.as_ptr().as_ref() }
        } else {
            None
        }
    }

    /// Returns a mutable reference to the data if it's initialized.
    pub fn as_mut(&mut self) -> Option<&mut T> {
        if self.init {
            // SAFETY: val is initialized
            Some(unsafe { self.val.assume_init_mut() })
        } else {
            None
        }
    }

    /// Clears the data to the uninitialized state.
    pub fn clear(&mut self) {
        if self.init {
            self.init = false;
            // SAFETY: val is initialized
            unsafe { self.val.assume_init_drop() };
        }
    }

    /// Resets the data to the uninitialized state without dropping any
    /// initialized value.
    pub fn forget(&mut self) -> bool {
        core::mem::take(&mut self.init)
    }

    /// Initializes the value to `v`, dropping any existing value first.
    pub fn set(&mut self, v: T) -> &mut T {
        self.clear();
        self.init = true;
        self.val.write(v)
    }

    /// Gets a mutable reference to the value, setting it to `v` first if it's
    /// not initialized.
    pub fn get_or_insert(&mut self, v: T) -> &mut T {
        self.get_or_insert_with(|| v)
    }

    /// Gets a mutable reference to the value, setting it to `f()` first if it's
    /// not initialized.
    pub fn get_or_insert_with(&mut self, f: impl FnOnce() -> T) -> &mut T {
        if self.init {
            // SAFETY: val is initialized
            unsafe { self.val.assume_init_mut() }
        } else {
            self.init = true;
            self.val.write(f())
        }
    }

    /// Returns whether the value is initialized.
    pub fn is_some(&self) -> bool {
        self.init
    }

    /// Returns whether the value is uninitialized.
    pub fn is_none(&self) -> bool {
        !self.init
    }

    /// Returns a const pointer to the underlying value (initialized or not).
    pub fn as_ptr(&self) -> *const T {
        self.val.as_ptr()
    }

    /// Returns a mut pointer to the underlying value (initialized or not).
    pub fn as_mut_ptr(&mut self) -> *mut T {
        self.val.as_mut_ptr()
    }
}

impl<'a, T> InplaceOption<'a, Box<T>> {
    /// Updates a boxed value in place.
    ///
    /// N.B. This will allocate space for a value if one is not already present,
    ///      which is wasteful if `f` does not actually initialize the value.
    pub fn update_box<F, R>(&mut self, f: F) -> R
    where
        F: FnOnce(&mut InplaceOption<'_, T>) -> R,
    {
        let mut boxed;
        let mut inplace;

        if let Some(b) = self.take() {
            // SAFETY: MaybeUninit<T> has the same layout as T.
            boxed = unsafe { Box::from_raw(Box::into_raw(b).cast::<MaybeUninit<T>>()) };
            // SAFETY: the value is known to be initialized.
            inplace = unsafe { InplaceOption::new_init_unchecked(&mut *boxed) };
        } else {
            boxed = Box::new(MaybeUninit::uninit());
            inplace = InplaceOption::uninit(&mut *boxed);
        }

        let r = f(&mut inplace);
        if inplace.forget() {
            drop(inplace);
            // SAFETY: T has the same layout as MaybeUninit<T>, and the value is
            // known to be initialized.
            let b = unsafe { Box::from_raw(Box::into_raw(boxed).cast::<T>()) };
            self.set(b);
        }
        r
    }
}

impl<'a, T: Clone> InplaceOption<'a, Arc<T>> {
    /// Updates a reference counted value in place.
    ///
    /// N.B. This will allocate space for a value if one is not already present,
    ///      which is wasteful if `f` does not actually initialize the value.
    pub fn update_arc<F, R>(&mut self, f: F) -> R
    where
        F: FnOnce(&mut InplaceOption<'_, T>) -> R,
    {
        let mut arced;
        let mut inplace;

        if let Some(mut a) = self.take() {
            // Ensure there is only a single reference.
            Arc::make_mut(&mut a);
            // SAFETY: MaybeUninit<T> has the same layout as T.
            arced = unsafe { Arc::from_raw(Arc::into_raw(a).cast::<MaybeUninit<T>>()) };
            // SAFETY: the value is known to be initialized.
            unsafe {
                inplace = InplaceOption::new_init_unchecked(Arc::get_mut(&mut arced).unwrap())
            };
        } else {
            arced = Arc::new(MaybeUninit::uninit());
            inplace = InplaceOption::uninit(Arc::get_mut(&mut arced).unwrap());
        }

        let r = f(&mut inplace);
        if inplace.forget() {
            drop(inplace);
            // SAFETY: T has the same layout as MaybeUninit<T>, and the value is
            // known to be initialized.
            let a = unsafe { Arc::from_raw(Arc::into_raw(arced).cast::<T>()) };
            self.set(a);
        }
        r
    }
}

impl<T> Drop for InplaceOption<'_, T> {
    fn drop(&mut self) {
        self.clear();
    }
}

/// Constructs a possibly-initialized [`crate::inplace::InplaceOption`] on the stack
/// from an `Option<T>`.
#[macro_export]
macro_rules! inplace {
    ($v:ident) => {
        let opt = $v;
        let mut $v;
        let mut $v = match opt {
            Some(v) => {
                $v = std::mem::MaybeUninit::new(v);
                // SAFETY: We just initialized the value.
                unsafe { $crate::inplace::InplaceOption::new_init_unchecked(&mut $v) }
            }
            None => {
                $v = std::mem::MaybeUninit::uninit();
                $crate::inplace::InplaceOption::uninit(&mut $v)
            }
        };
    };
}

/// Constructs an initialized [`crate::inplace::InplaceOption`] on the stack from a `T`.
#[macro_export]
macro_rules! inplace_some {
    ($v:ident) => {
        let mut $v = std::mem::MaybeUninit::new($v);
        #[allow(unused_mut)]
        // SAFETY: We just initialized the value.
        let mut $v = unsafe { $crate::inplace::InplaceOption::new_init_unchecked(&mut $v) };
    };
}

/// Constructs an uninitialized [`crate::inplace::InplaceOption`] on the stack.
#[macro_export]
macro_rules! inplace_none {
    ($v:ident) => {
        let mut $v = std::mem::MaybeUninit::uninit();
        #[allow(unused_mut)]
        let mut $v = $crate::inplace::InplaceOption::uninit(&mut $v);
    };
    ($v:ident : $t:ty) => {
        let mut $v = std::mem::MaybeUninit::<$t>::uninit();
        #[allow(unused_mut)]
        let mut $v = $crate::inplace::InplaceOption::uninit(&mut $v);
    };
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    #[test]
    fn test_inplace_some() {
        let v = "test".to_string();
        inplace_some!(v);
        assert_eq!(&v.take().unwrap(), "test");
    }

    #[test]
    fn test_inplace_none() {
        inplace_none!(v: String);
        v.set("test".to_string());
        assert_eq!(&v.take().unwrap(), "test");
    }

    #[test]
    fn test_inplace() {
        let v = Some("test".to_string());
        inplace!(v);
        assert_eq!(&v.take().unwrap(), "test");
    }

    #[test]
    fn test_inplace_replace() {
        let v = "old".to_string();
        inplace_some!(v);
        v.set("new".to_string());
        assert_eq!(&v.take().unwrap(), "new");
    }

    #[test]
    fn test_updates() {
        let v = Arc::new(Box::new(1234));
        inplace_some!(v);
        v.update_arc(|v| {
            v.update_box(|v| {
                v.set(5678);
            });
        });
        assert_eq!(**v.take().unwrap(), 5678);
    }
}