placid 0.1.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
use core::{
    convert::Infallible,
    mem::{self, MaybeUninit},
};

use crate::{
    init::{Init, InitError, InitPin, InitPinResult, InitResult, Initializer, IntoInitPin},
    owned::Own,
    pin::DropSlot,
    uninit::Uninit,
};

#[inline]
fn maybe_uninit_slice<T, const N: usize>(m: &mut MaybeUninit<[T; N]>) -> &mut [MaybeUninit<T>] {
    unsafe { &mut *(m.as_mut_ptr() as *mut [MaybeUninit<T>; N]) }
}

/// Error type for slice initialization failures.
///
/// This structure is returned from slice initializers when the source and
/// target slices have mismatched lengths.
#[derive(Debug, thiserror::Error, Clone, Copy, PartialEq)]
#[error("slice initialization error")]
pub struct SliceError;

trait SpecInitSlice<T> {
    fn init_slice(self, place: Uninit<'_, [T]>) -> InitResult<'_, [T], SliceError>;

    fn init_array<const N: usize>(
        self,
        place: Uninit<'_, [T; N]>,
    ) -> InitResult<'_, [T; N], SliceError>;
}

impl<T: Clone> SpecInitSlice<T> for &[T] {
    default fn init_slice(self, mut place: Uninit<'_, [T]>) -> InitResult<'_, [T], SliceError> {
        if place.len() != self.len() {
            return Err(InitError { error: SliceError, place });
        }

        place.write_clone_of_slice(self);
        // SAFETY: The place is now initialized.
        Ok(unsafe { place.assume_init() })
    }

    default fn init_array<const N: usize>(
        self,
        mut place: Uninit<'_, [T; N]>,
    ) -> InitResult<'_, [T; N], SliceError> {
        if N != self.len() {
            return Err(InitError { error: SliceError, place });
        }

        maybe_uninit_slice(&mut place).write_clone_of_slice(self);
        // SAFETY: The place is now initialized.
        Ok(unsafe { place.assume_init() })
    }
}

impl<T: Copy> SpecInitSlice<T> for &[T] {
    fn init_slice(self, mut place: Uninit<'_, [T]>) -> InitResult<'_, [T], SliceError> {
        if place.len() != self.len() {
            return Err(InitError { error: SliceError, place });
        }

        place.write_copy_of_slice(self);
        // SAFETY: The place is now initialized.
        Ok(unsafe { place.assume_init() })
    }

    fn init_array<const N: usize>(
        self,
        mut place: Uninit<'_, [T; N]>,
    ) -> InitResult<'_, [T; N], SliceError> {
        if N != self.len() {
            return Err(InitError { error: SliceError, place });
        }

        maybe_uninit_slice(&mut place).write_copy_of_slice(self);
        // SAFETY: The place is now initialized.
        Ok(unsafe { place.assume_init() })
    }
}

/// Initializes a slice by copying or cloning elements from a source slice.
///
/// This initializer is created by the [`slice()`] factory function or through
/// the [`IntoInitPin`] trait for slice types.
#[derive(Debug, PartialEq)]
pub struct Slice<'a, T>(&'a [T]);

impl<T> Initializer for Slice<'_, T> {
    type Error = SliceError;
}

impl<T: Clone> InitPin<[T]> for Slice<'_, T> {
    #[inline]
    fn init_pin<'a, 'b>(
        self,
        place: Uninit<'a, [T]>,
        slot: DropSlot<'a, 'b, [T]>,
    ) -> InitPinResult<'a, 'b, [T], SliceError> {
        match self.0.init_slice(place) {
            Ok(own) => Ok(Own::into_pin(own, slot)),
            Err(err) => Err(err.into_pin(slot)),
        }
    }
}

impl<T: Clone> Init<[T]> for Slice<'_, T> {
    #[inline]
    fn init(self, place: Uninit<'_, [T]>) -> InitResult<'_, [T], SliceError> {
        self.0.init_slice(place)
    }
}

impl<T: Clone, const N: usize> InitPin<[T; N]> for Slice<'_, T> {
    #[inline]
    fn init_pin<'a, 'b>(
        self,
        place: Uninit<'a, [T; N]>,
        slot: DropSlot<'a, 'b, [T; N]>,
    ) -> InitPinResult<'a, 'b, [T; N], SliceError> {
        match self.0.init_array(place) {
            Ok(own) => Ok(Own::into_pin(own, slot)),
            Err(err) => Err(err.into_pin(slot)),
        }
    }
}

impl<T: Clone, const N: usize> Init<[T; N]> for Slice<'_, T> {
    #[inline]
    fn init(self, place: Uninit<'_, [T; N]>) -> InitResult<'_, [T; N], SliceError> {
        self.0.init_array(place)
    }
}

/// Initializes a slice by copying or cloning elements from a source slice.
///
/// This is used to initialize a pre-allocated slice by copying (for `Copy`
/// types) or cloning (for `Clone` types) elements from another slice. The
/// source and target slices must have the same length, or the initialization
/// will fail with a [`SliceError`].
///
/// This function is rarely used for direct initialization. Instead, use an
/// `&[T]` slice directly where an initializer is expected, as `&[T]` can be
/// used directly as an initializer. Use this function for combining with other
/// initializers when needed.
///
/// # Examples
///
/// ```rust
/// use placid::prelude::*;
///
/// // Initialize a slice with integers
/// let source = [1, 2, 3, 4, 5];
/// let mut uninit = uninit!([i32; 5]);
/// let owned = uninit.write(&source[..]);
/// assert_eq!(&*owned, &[1, 2, 3, 4, 5]);
/// ```
///
/// Error on length mismatch:
/// ```rust
/// use placid::prelude::*;
///
/// let source = [1, 2, 3];
/// let mut uninit = uninit!([i32; 5]); // Different size
/// let result = uninit.try_write(&source[..]);
/// assert!(result.is_err()); // Fails because lengths don't match
/// ```
#[inline]
pub const fn slice<T: Clone>(s: &[T]) -> Slice<'_, T> {
    Slice(s)
}

impl<'a, T: Clone> IntoInitPin<[T], Slice<'a, T>> for &'a [T] {
    type Init = Slice<'a, T>;
    type Error = SliceError;

    #[inline]
    fn into_init(self) -> Self::Init {
        Slice(self)
    }
}

impl<'a, T: Clone, const N: usize> IntoInitPin<[T; N], Slice<'a, T>> for &'a [T] {
    type Init = Slice<'a, T>;
    type Error = SliceError;

    #[inline]
    fn into_init(self) -> Self::Init {
        Slice(self)
    }
}

/// Initializes a `str` slice by copying from a source string slice.
///
/// This initializer is created by the [`str()`] factory function.
#[derive(Debug, PartialEq)]
pub struct Str<'a>(&'a str);

impl Initializer for Str<'_> {
    type Error = SliceError;
}

impl InitPin<str> for Str<'_> {
    fn init_pin<'a, 'b>(
        self,
        mut place: Uninit<'a, str>,
        slot: DropSlot<'a, 'b, str>,
    ) -> InitPinResult<'a, 'b, str, SliceError> {
        if place.len() != self.0.len() {
            return Err(InitError { error: SliceError, place }.into_pin(slot));
        }

        let src = unsafe { mem::transmute::<&[u8], &[MaybeUninit<u8>]>(self.0.as_bytes()) };
        place.copy_from_slice(src);
        // SAFETY: The place is now initialized.
        Ok(unsafe { place.assume_init_pin(slot) })
    }
}

impl Init<str> for Str<'_> {
    fn init(self, mut place: Uninit<'_, str>) -> InitResult<'_, str, SliceError> {
        if place.len() != self.0.len() {
            return Err(InitError { error: SliceError, place });
        }

        let src = unsafe { mem::transmute::<&[u8], &[MaybeUninit<u8>]>(self.0.as_bytes()) };
        place.copy_from_slice(src);
        // SAFETY: The place is now initialized.
        Ok(unsafe { place.assume_init() })
    }
}

/// Initializes a `str` slice by copying from a source string slice.
///
/// This is used to initialize a pre-allocated `str` slice by copying the
/// contents from another string slice. The source and target slices must have
/// the same length, or the initialization will fail with a [`SliceError`].
///
/// Users typically do not need to call this function directly, as `&str` can be
/// used directly as an initializer. Use this function when combining with other
/// initializers.
///
/// # Examples
///
/// ```rust
/// use placid::prelude::*;
///
/// let source = "Hello, world!";
/// let mut uninit: Uninit<str> = uninit!([u8; 13]); // Pre-allocated for 13 bytes
/// let owned = uninit.write(source);
/// assert_eq!(&*owned, "Hello, world!");
/// ```
#[inline]
pub const fn str(s: &str) -> Str<'_> {
    Str(s)
}

impl<'b> IntoInitPin<str, Str<'b>> for &'b str {
    type Init = Str<'b>;
    type Error = SliceError;

    #[inline]
    fn into_init(self) -> Self::Init {
        Str(self)
    }
}

/// Initializes all elements of a slice with a single repeated value.
///
/// This initializer is created by the [`repeat()`] factory function.
#[derive(Debug, PartialEq)]
pub struct Repeat<T>(T);

impl<T> Initializer for Repeat<T> {
    type Error = Infallible;
}

impl<T: Clone> InitPin<[T]> for Repeat<T> {
    fn init_pin<'a, 'b>(
        self,
        mut place: Uninit<'a, [T]>,
        slot: DropSlot<'a, 'b, [T]>,
    ) -> InitPinResult<'a, 'b, [T], Infallible> {
        place.write_filled(self.0);
        // SAFETY: The place is now initialized.
        Ok(unsafe { place.assume_init_pin(slot) })
    }
}

impl<T: Clone> Init<[T]> for Repeat<T> {
    fn init(self, mut place: Uninit<'_, [T]>) -> InitResult<'_, [T], Infallible> {
        place.write_filled(self.0);
        // SAFETY: The place is now initialized.
        Ok(unsafe { place.assume_init() })
    }
}

impl<T: Clone, const N: usize> InitPin<[T; N]> for Repeat<T> {
    fn init_pin<'a, 'b>(
        self,
        mut place: Uninit<'a, [T; N]>,
        slot: DropSlot<'a, 'b, [T; N]>,
    ) -> InitPinResult<'a, 'b, [T; N], Infallible> {
        maybe_uninit_slice(&mut place).write_filled(self.0);
        // SAFETY: The place is now initialized.
        Ok(unsafe { place.assume_init_pin(slot) })
    }
}

impl<T: Clone, const N: usize> Init<[T; N]> for Repeat<T> {
    fn init(self, mut place: Uninit<'_, [T; N]>) -> InitResult<'_, [T; N], Infallible> {
        maybe_uninit_slice(&mut place).write_filled(self.0);
        // SAFETY: The place is now initialized.
        Ok(unsafe { place.assume_init() })
    }
}

/// Initializes all elements of a slice with a single repeated value.
///
/// This is used to initialize a slice where all elements are the same
/// value. The value is cloned for each position in the slice.
///
/// # Examples
///
/// Filling an array with a repeated value:
///
/// ```rust
/// use placid::prelude::*;
///
/// let place = uninit!([i32; 3]);
/// let owned = place.write(init::repeat(5));
/// assert_eq!(*owned, [5, 5, 5]);
/// ```
#[inline]
pub const fn repeat<T: Clone>(value: T) -> Repeat<T> {
    Repeat(value)
}

/// Initializes a slice by calling a closure for each element.
///
/// This initializer is created by the [`repeat_with()`] factory function.
#[derive(Debug, PartialEq)]
pub struct RepeatWith<F>(F);

impl<F> Initializer for RepeatWith<F> {
    type Error = Infallible;
}

impl<T, F> InitPin<[T]> for RepeatWith<F>
where
    F: Fn(usize) -> T,
{
    fn init_pin<'a, 'b>(
        self,
        mut place: Uninit<'a, [T]>,
        slot: DropSlot<'a, 'b, [T]>,
    ) -> InitPinResult<'a, 'b, [T], Infallible> {
        place.write_with(self.0);
        // SAFETY: The place is now initialized.
        Ok(unsafe { place.assume_init_pin(slot) })
    }
}

impl<T, F> Init<[T]> for RepeatWith<F>
where
    F: Fn(usize) -> T,
{
    fn init(self, mut place: Uninit<'_, [T]>) -> InitResult<'_, [T], Infallible> {
        place.write_with(self.0);
        // SAFETY: The place is now initialized.
        Ok(unsafe { place.assume_init() })
    }
}

impl<T, F, const N: usize> InitPin<[T; N]> for RepeatWith<F>
where
    F: Fn(usize) -> T,
{
    fn init_pin<'a, 'b>(
        self,
        mut place: Uninit<'a, [T; N]>,
        slot: DropSlot<'a, 'b, [T; N]>,
    ) -> InitPinResult<'a, 'b, [T; N], Infallible> {
        maybe_uninit_slice(&mut place).write_with(self.0);
        // SAFETY: The place is now initialized.
        Ok(unsafe { place.assume_init_pin(slot) })
    }
}

impl<T, F, const N: usize> Init<[T; N]> for RepeatWith<F>
where
    F: Fn(usize) -> T,
{
    fn init(self, mut place: Uninit<'_, [T; N]>) -> InitResult<'_, [T; N], Infallible> {
        maybe_uninit_slice(&mut place).write_with(self.0);
        // SAFETY: The place is now initialized.
        Ok(unsafe { place.assume_init() })
    }
}

/// Initializes a slice by calling a closure for each element.
///
/// `RepeatWith` allows you to initialize a slice where each element is produced
/// by calling a closure with the element's index. This provides a flexible way
/// to create complex slice initializations.
///
/// # Examples
///
/// Creating an array of indices:
/// ```rust
/// use placid::prelude::*;
///
/// let mut uninit = uninit!([usize; 5]);
/// let owned = uninit.write(init::repeat_with(|i| i * 2));
/// assert_eq!(&*owned, &[0, 2, 4, 6, 8]);
/// ```
#[inline]
pub const fn repeat_with<T, F>(f: F) -> RepeatWith<F>
where
    F: Fn(usize) -> T,
{
    RepeatWith(f)
}