placid 0.2.0

Separated ownership and in-place construction in Rust
Documentation
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
//! Types and traits for working with uninitialized memory places.
//!
//! See the [`Uninit`] type for more details.

use core::{
    fmt,
    mem::{self, MaybeUninit},
    ops::{Deref, DerefMut},
    ptr::NonNull,
};

use crate::{
    init::{Init, InitPin, InitPinResult, InitResult, IntoInit, IntoInitPin},
    owned::Own,
    pin::{DropSlot, POwn},
    place::{Place, PlaceRef, Uninitialized},
};

/// An uninitialized reference that can hold a value of type `T`.
///
/// # Examples
///
/// ```rust
/// use placid::prelude::*;
///
/// let my_place: Uninit<i32> = uninit!();
/// ```
pub type Uninit<'a, T> = PlaceRef<'a, T, Uninitialized>;

/// Creates a new uninitialized place on the stack.
///
/// The macro returns an [`Uninit`] reference that can later be written to. A
/// typed variant is available by passing a type parameter.
///
/// # Examples
///
/// ```rust
/// use placid::prelude::*;
/// let my_uninit_place: Uninit<u32> = uninit!();
/// let my_typed_uninit_place = uninit!(u64);
/// ```
#[macro_export]
#[allow_internal_unstable(super_let)]
macro_rules! uninit {
    () => {{
        super let mut place = ::core::mem::MaybeUninit::uninit();
        $crate::uninit::Uninit::from_mut(&mut place)
    }};
    ($ty:ty) => {{
        super let mut place = ::core::mem::MaybeUninit::<$ty>::uninit();
        $crate::uninit::Uninit::from_mut(&mut place)
    }};
}

impl<'a, T> Deref for Uninit<'a, T> {
    type Target = MaybeUninit<T>;

    #[inline]
    fn deref(&self) -> &Self::Target {
        // SAFETY: We are treating the place as uninitialized.
        unsafe { self.inner.cast().as_ref() }
    }
}

impl<'a, T> DerefMut for Uninit<'a, T> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        // SAFETY: We are treating the place as uninitialized.
        unsafe { self.inner.cast().as_mut() }
    }
}

impl<'a, T> Deref for Uninit<'a, [T]> {
    type Target = [MaybeUninit<T>];

    #[inline]
    fn deref(&self) -> &Self::Target {
        // SAFETY: We are treating the place as uninitialized.
        unsafe {
            let data = self.inner.as_ptr();
            core::slice::from_raw_parts(data.cast(), data.len())
        }
    }
}

impl<'a, T> DerefMut for Uninit<'a, [T]> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        // SAFETY: We are treating the place as uninitialized.
        unsafe {
            let data = self.inner.as_ptr();
            core::slice::from_raw_parts_mut(data.cast(), data.len())
        }
    }
}

impl<'a> Deref for Uninit<'a, str> {
    type Target = [MaybeUninit<u8>];

    #[inline]
    fn deref(&self) -> &Self::Target {
        // SAFETY: We are treating the place as uninitialized.
        unsafe {
            let (addr, len) = self.inner.as_ptr().to_raw_parts();
            core::slice::from_raw_parts(addr.cast(), len)
        }
    }
}

impl<'a> DerefMut for Uninit<'a, str> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        // SAFETY: We are treating the place as uninitialized.
        unsafe {
            let (addr, len) = self.inner.as_ptr().to_raw_parts();
            core::slice::from_raw_parts_mut(addr.cast(), len)
        }
    }
}

impl<'a, T: ?Sized> Uninit<'a, T> {
    /// Converts the uninitialized reference into a raw pointer, consuming the
    /// original object.
    ///
    /// The caller is responsible for managing the memory and ensuring that the
    /// value is properly initialized and dropped when no longer needed. The
    /// memory itself remains valid for the original lifetime of the place.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use placid::prelude::*;
    ///
    /// let mut uninit: Uninit<String> = uninit!();
    /// let ptr = Uninit::into_raw(uninit);
    /// unsafe {
    ///     std::ptr::write(ptr, String::from("Hello"));
    ///     let owned = Own::from_raw(ptr);
    ///     assert_eq!(&*owned, "Hello");
    /// }
    /// ```
    #[inline]
    pub const fn into_raw(self) -> *mut T {
        let inner = self.inner;
        mem::forget(self);
        inner.as_ptr()
    }

    /// Creates an uninitialized reference from a raw pointer.
    ///
    /// # Safety
    ///
    /// The caller must ensure that the pointer is valid and points to
    /// uninitialized memory for type `T`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use placid::prelude::*;
    ///
    /// let mut buffer = std::mem::MaybeUninit::uninit();
    /// let ptr = buffer.as_mut_ptr();
    /// let mut uninit: Uninit<i32> = unsafe { Uninit::from_raw(ptr) };
    /// unsafe {
    ///     std::ptr::write(uninit.as_mut_ptr(), 42);
    ///     let owned = uninit.assume_init();
    ///     assert_eq!(*owned, 42);
    /// }
    /// ```
    #[inline]
    pub const unsafe fn from_raw(ptr: *mut T) -> Self {
        let inner = unsafe { NonNull::new_unchecked(ptr) };
        unsafe { Uninit::from_inner(inner) }
    }

    /// Creates an uninitialized reference from a mutable place.
    ///
    /// This method is the de facto safe way to create an `Uninit` reference
    /// without using raw pointers or macros.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use placid::prelude::*;
    ///
    /// let mut buffer = std::mem::MaybeUninit::uninit();
    /// let mut uninit: Uninit<i32> = Uninit::from_mut(&mut buffer);
    /// unsafe {
    ///     std::ptr::write(uninit.as_mut_ptr(), 42);
    ///     let owned = uninit.assume_init();
    ///     assert_eq!(*owned, 42);
    /// }
    /// ```
    #[inline]
    pub fn from_mut(place: &'a mut impl Place<T>) -> Self {
        // SAFETY: We have a mutable reference to a place, so the memory is
        // valid for T.
        unsafe { Self::from_raw(place.as_mut_ptr()) }
    }

    /// Returns a raw mutable pointer to the uninitialized value inside the
    /// reference.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use placid::prelude::*;
    ///
    /// let mut uninit: Uninit<i32> = uninit!();
    /// let ptr = uninit.as_mut_ptr();
    /// unsafe {
    ///     std::ptr::write(ptr, 42);
    ///     // Now the value at ptr is initialized to 42
    ///     assert_eq!(*uninit.assume_init(), 42);
    /// }
    /// ```
    #[inline]
    pub const fn as_mut_ptr(&mut self) -> *mut T {
        self.inner.as_ptr()
    }

    /// Assumes that the reference is initialized and converts it into an owned
    /// reference.
    ///
    /// For the pinning variant, see [`Uninit::assume_init_pin`].
    ///
    /// # Safety
    ///
    /// The caller must ensure that the value is indeed initialized before
    /// calling this method.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use placid::prelude::*;
    ///
    /// let mut uninit: Uninit<i32> = uninit!(i32);
    /// unsafe {
    ///     std::ptr::write(uninit.as_mut_ptr(), 42);
    ///     // Now assume it's initialized and recover the owned reference
    ///     assert_eq!(*uninit.assume_init(), 42);
    /// }
    /// ```
    #[inline]
    pub const unsafe fn assume_init(self) -> Own<'a, T> {
        let inner = self.inner;
        mem::forget(self);
        unsafe { Own::from_inner(inner) }
    }

    /// Assumes that the reference is initialized and converts it into a pinned
    /// & owned reference.
    ///
    /// The pinning variant is needed when the value inside the reference is
    /// invalid if not in a pinned location. The semantics are slightly
    /// different from `Own::into_pin(place.assume_init())`, where an
    /// unpinned [`Own`]ed reference is exposed temporarily during the
    /// expression.
    ///
    /// For the non-pinning variant, see [`Uninit::assume_init`].
    ///
    /// # Safety
    ///
    /// The caller must ensure that the value is indeed initialized before
    /// calling this method.
    ///
    /// # Examples
    ///
    /// ```rust
    /// // Initialize a value in place first
    /// let mut uninit = placid::uninit!(String);
    /// let drop_slot = placid::drop_slot!();
    /// unsafe {
    ///     uninit.as_mut_ptr().write(String::from("Pinned value"));
    ///
    ///     // Then assume it's initialized and convert to pinned
    ///     let pinned = uninit.assume_init_pin(drop_slot);
    ///     assert_eq!(&*pinned, "Pinned value");
    /// }
    /// ```
    #[inline]
    pub unsafe fn assume_init_pin<'b>(self, slot: DropSlot<'a, 'b, T>) -> POwn<'b, T> {
        let inner = self.inner;
        mem::forget(self);
        POwn::new(unsafe { Own::from_inner(inner) }, slot)
    }

    /// Initializes the reference with the given initializer and returns the
    /// owned reference.
    ///
    /// # Panics
    ///
    /// This method panics if the initializer returns an error.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let uninit = placid::uninit!(String);
    /// let owned = uninit.write(String::from("Initialized!"));
    /// assert_eq!(&*owned, "Initialized!");
    /// ```
    #[inline]
    pub fn write<I, M>(self, init: I) -> Own<'a, T>
    where
        I: IntoInit<T, M>,
    {
        self.try_write(init).unwrap()
    }

    /// Tries to initialize the reference with the given initializer and returns
    /// the owned reference.
    ///
    /// # Errors
    ///
    /// This method returns an error if the initializer fails.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let uninit = placid::uninit!(i32);
    /// let result = uninit.try_write(42);
    /// assert!(result.is_ok());
    /// ```
    #[inline]
    pub fn try_write<I, M>(self, init: I) -> InitResult<'a, T, I::Error>
    where
        I: IntoInit<T, M>,
    {
        init.into_init().init(self)
    }

    /// Initializes the reference with the given initializer and returns the
    /// pinned & owned reference.
    ///
    /// # Panics
    ///
    /// This method panics if the initializer returns an error.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let uninit = placid::uninit!(String);
    /// let drop_slot = placid::drop_slot!();
    /// let pinned = uninit.write_pin(String::from("Pinned value"), drop_slot);
    /// // The value is now pinned and initialized
    /// assert_eq!(&*pinned, "Pinned value");
    /// ```
    #[inline]
    pub fn write_pin<'b, I, M>(self, init: I, slot: DropSlot<'a, 'b, T>) -> POwn<'b, T>
    where
        I: IntoInitPin<T, M>,
    {
        self.try_write_pin(init, slot).unwrap()
    }

    /// Tries to initialize the reference with the given pinning initializer and
    /// returns the pinned & owned reference.
    ///
    /// # Errors
    ///
    /// This method returns an error if the initializer fails.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let uninit = placid::uninit!(Vec<i32>);
    /// let drop_slot = placid::drop_slot!();
    /// let result = uninit.try_write_pin(vec![1, 2, 3], drop_slot);
    /// assert!(result.is_ok());
    /// ```
    #[inline]
    pub fn try_write_pin<'b, I, M>(
        self,
        init: I,
        slot: DropSlot<'a, 'b, T>,
    ) -> InitPinResult<'a, 'b, T, I::Error>
    where
        I: IntoInitPin<T, M>,
    {
        init.into_init().init_pin(self, slot)
    }
}

impl<'a, T: ?Sized> fmt::Debug for Uninit<'a, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Uninit<{}>", core::any::type_name::<T>())
    }
}

impl<'a, T> Uninit<'a, [T]> {
    /// Fills a slice with elements yielded by an iterator until either all
    /// elements have been initialized or the iterator is empty.
    ///
    /// Returns two slices. The first slice contains the initialized portion of
    /// the original slice. The second slice is the still-uninitialized
    /// remainder of the original slice.
    ///
    /// # Panics
    ///
    /// This function panics if the iterator's `next` function panics.
    ///
    /// If such a panic occurs, any elements previously initialized during this
    /// operation will be dropped.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use placid::prelude::*;
    ///
    /// let mut uninit: Uninit<[i32; 5]> = uninit!();
    /// let (init, uninit) = uninit.write_iter([1, 2, 4]);
    /// assert_eq!(*init, [1, 2, 4]);
    /// assert_eq!(uninit.len(), 2);
    /// ```
    pub fn write_iter<I>(mut self, iter: I) -> (Own<'a, [T]>, Uninit<'a, [T]>)
    where
        I: IntoIterator<Item = T>,
    {
        let (init, _) = (*self).write_iter(iter);
        let len = init.len();

        // SAFETY: We have just initialized the first `len` elements of the slice.
        let (init, remaining) = unsafe { self.split_at_unchecked(len) };
        (unsafe { init.assume_init() }, remaining)
    }
}

impl<'a, T, const N: usize> Uninit<'a, [T; N]> {
    /// Fills an array with elements yielded by an iterator until either all
    /// elements have been initialized or the iterator is empty.
    ///
    /// Returns a tuple containing the initialized portion of the original array
    /// and the number of elements that were initialized. The remaining elements
    /// in the original array are still uninitialized.
    ///
    /// # Panics
    ///
    /// This function panics if the iterator's `next` function panics.
    ///
    /// If such a panic occurs, any elements previously initialized during this
    /// operation will be dropped.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use placid::prelude::*;
    ///
    /// let mut uninit: Uninit<[i32; 5]> = uninit!();
    /// let (init, uninit) = uninit.write_iter([1, 2, 4]);
    /// assert_eq!(*init, [1, 2, 4]);
    /// assert_eq!(uninit.len(), 2);
    /// ```
    #[inline]
    pub fn write_iter<I>(self, iter: I) -> (Own<'a, [T]>, Uninit<'a, [T]>)
    where
        I: IntoIterator<Item = T>,
    {
        (self as Uninit<'a, [T]>).write_iter(iter)
    }
}