o3 0.62.0

shared-nothing primitives
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
use std::{alloc, marker, mem, num::NonZero, ptr, slice};

pub use bundle::Bundle;
pub use extent::Extent;
pub use layout::Layout;
pub use rows::Rows;
pub use shape::Shape;
pub use uninit::Uninit;

use crate::{
    alloc::{Exhausted, Overflow},
    base::marker::ThreadBound,
};
mod layout;
pub(crate) use layout::Root;

/// Initialization proof for an auxiliary plane reconstructed from its shape.
#[derive(Debug)]
pub struct Initialized;

mod bundle;
mod extent;
mod rows;
mod shape;
mod uninit;

/// One admitted insertion held by the original vector's exclusive loan.
pub struct Vacant<'a, T>(&'a mut Vec<T>, ThreadBound);

impl<'a, T> Vacant<'a, T> {
    /// Retains one previously admitted insertion.
    /// # Safety
    /// This vector's length is strictly below its capacity.
    pub unsafe fn new(values: &'a mut Vec<T>) -> Self {
        Self(values, ThreadBound::NEW)
    }

    pub fn insert(self, value: T) {
        let Self(values, _bound) = self;
        let len = values.len();
        // SAFETY: admission proved len + 1 fits both usize and this
        // vector's capacity. The retained exclusive loan preserves its
        // allocation and length, including aligned zero-sized storage.
        unsafe {
            values.as_mut_ptr().add(len).write(value);
            values.set_len(len + 1);
        }
    }
}

pub trait VecExt<T> {
    /// Removes one retained resident and returns the tail moved into its place.
    /// # Safety
    /// `index` is below this exclusively borrowed vector's current length.
    unsafe fn swap_remove(&mut self, index: usize) -> (T, Option<&T>);
}

impl<T> VecExt<T> for Vec<T> {
    unsafe fn swap_remove(&mut self, index: usize) -> (T, Option<&T>) {
        let last = self.len() - 1;
        let pointer = self.as_mut_ptr();
        // SAFETY: the retained resident proves nonemptiness; ownership leaves the tail once.
        let value = unsafe { pointer.add(last).read() };
        unsafe { self.set_len(last) };
        if index == last {
            return (value, None);
        }
        // SAFETY: the distinct admitted index remains initialized in the shortened vector.
        let slot = unsafe { &mut *pointer.add(index) };
        (mem::replace(slot, value), Some(slot))
    }
}

/// Proof that an extent describes a zero-length allocation.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct Empty<E: Extent>(E);

impl<E: Extent> Empty<E> {
    /// # Safety
    /// `extent` must report zero through its `Extent` implementation.
    pub const unsafe fn assume(extent: E) -> Self {
        Self(extent)
    }

    pub(in crate::alloc) const fn into_inner(self) -> E {
        self.0
    }
}

/// Exact stored extent and its canonical zero-based index domain.
///
/// # Safety
/// Copies retain immutable `len`; `indices` yields `0..len` exactly once in order.
pub unsafe trait TailExtent: Extent {
    #[doc(hidden)]
    type Index: TailIndex;

    #[doc(hidden)]
    fn indices(self) -> impl Iterator<Item = Self::Index>;
}

// SAFETY: `0..self` yields exactly `self` ordered indices.
unsafe impl TailExtent for usize {
    type Index = usize;

    fn indices(self) -> impl Iterator<Item = Self::Index> {
        0..self
    }
}

// SAFETY: the nonzero count is retained; the range yields every u32 index once.
unsafe impl TailExtent for NonZero<u32> {
    type Index = u32;

    fn indices(self) -> impl Iterator<Item = Self::Index> {
        0..self.get()
    }
}

// SAFETY: the retained count yields every u16 index once in order.
unsafe impl TailExtent for NonZero<u16> {
    type Index = u16;

    fn indices(self) -> impl Iterator<Item = Self::Index> {
        0..self.get()
    }
}

/// An immutable zero-based storage offset.
///
/// # Safety
/// Every copy must retain the same exact offset without truncation.
pub unsafe trait TailIndex: Copy {
    #[doc(hidden)]
    fn get(self) -> usize;
}

unsafe impl TailIndex for usize {
    fn get(self) -> usize {
        self
    }
}

unsafe impl TailIndex for u16 {
    fn get(self) -> usize {
        usize::from(self)
    }
}

unsafe impl TailIndex for u32 {
    fn get(self) -> usize {
        const { assert!(usize::BITS >= u32::BITS) };
        self as usize
    }
}

#[repr(C)]
pub struct Tail<S, T> {
    prior: S,
    offset: usize,
    value: marker::PhantomData<fn() -> T>,
}

pub trait Recipe: Sized {
    type Fields;

    fn try_build(self) -> Result<Bundle<Self::Fields>, Overflow>;

    /// # Safety
    /// A nominal proof must establish that this exact field sequence fits.
    unsafe fn build(self) -> Bundle<Self::Fields>;

    fn tail<T>(self, len: usize) -> impl Recipe<Fields = Tail<Self::Fields, T>> {
        layout::Tail {
            prior: self,
            len,
            value: marker::PhantomData,
        }
    }
}

/// Global allocation operations for one exact standard layout.
pub trait LayoutExt: Sized {
    /// Allocates uninitialized storage, or an aligned dangling pointer for an empty layout.
    /// The pointer's type does not establish initialization, size, or alignment for `T`.
    fn try_allocate<T>(self) -> Result<ptr::NonNull<T>, Exhausted>;

    /// # Safety
    /// `pointer` transfers a live allocation made with this exact layout.
    /// All contained values and borrows must have ended. Empty layouts need no allocation.
    unsafe fn deallocate<T>(self, pointer: ptr::NonNull<T>);
}

impl LayoutExt for alloc::Layout {
    fn try_allocate<T>(self) -> Result<ptr::NonNull<T>, Exhausted> {
        if self.size() == 0 {
            return Ok(self.dangling_ptr().cast());
        }
        // SAFETY: the layout is valid and its zero-sized case returned above.
        unsafe { try_new(self, false) }
    }

    unsafe fn deallocate<T>(self, pointer: ptr::NonNull<T>) {
        if self.size() != 0 {
            // SAFETY: the caller retains the allocation and this layout is nonzero.
            unsafe { dealloc(self, pointer) };
        }
    }
}

/// # Safety
/// This validated layout has nonzero size; zeroed selects initialization only.
pub(crate) unsafe fn try_new<T>(
    layout: alloc::Layout,
    zeroed: bool,
) -> Result<ptr::NonNull<T>, Exhausted> {
    // SAFETY: the caller proves this exact validated layout is nonzero.
    let pointer = unsafe {
        if zeroed {
            alloc::alloc_zeroed(layout)
        } else {
            alloc::alloc(layout)
        }
    };
    ptr::NonNull::new(pointer.cast()).ok_or(Exhausted)
}

/// # Safety
/// `pointer` identifies a live allocation made with this exact nonzero layout.
pub(crate) unsafe fn dealloc<T>(layout: alloc::Layout, pointer: ptr::NonNull<T>) {
    // SAFETY: the caller transfers the original nonzero pointer-layout pair.
    unsafe { alloc::dealloc(pointer.cast().as_ptr(), layout) };
}

/// # Safety
/// `pointer` identifies a live nonzero allocation made with `layout`;
/// `target` is nonzero and has the same alignment.
pub(crate) unsafe fn resize(
    layout: alloc::Layout,
    pointer: ptr::NonNull<u8>,
    target: alloc::Layout,
) -> Result<ptr::NonNull<u8>, Exhausted> {
    // SAFETY: the caller retains the exact allocation and proves a nonzero
    // target with unchanged alignment. Failure leaves the old allocation live.
    let pointer = unsafe { alloc::realloc(pointer.as_ptr(), layout, target.size()) };
    ptr::NonNull::new(pointer).ok_or(Exhausted)
}

pub(in crate::alloc) fn init<T>(
    entries: &mut [mem::MaybeUninit<T>],
    mut make: impl FnMut(usize) -> T,
) {
    for (index, entry) in entries.iter_mut().enumerate() {
        entry.write(make(index));
    }
}

pub struct Fields<'a, S> {
    fields: &'a S,
    pointer: ptr::NonNull<u8>,
}

impl<T> Fields<'_, Layout<T>> {
    pub const fn root(self) -> ptr::NonNull<T> {
        self.pointer.cast()
    }
}

impl<'a, S, T> Fields<'a, Tail<S, T>> {
    pub fn tail(self) -> ptr::NonNull<T> {
        // SAFETY: this allocation was made from the retained field sequence;
        // its admitted offset stays within the allocation and is aligned for T.
        unsafe { self.pointer.add(self.fields.offset) }.cast()
    }

    pub const fn prior(self) -> Fields<'a, S> {
        Fields {
            fields: &self.fields.prior,
            pointer: self.pointer,
        }
    }
}

impl<S> Clone for Fields<'_, S> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<S> Copy for Fields<'_, S> {}

/// One allocation retaining its plane initialization states and compact extent.
#[derive(Debug)]
#[repr(C)]
pub struct Block<E: Shape, S, X = (), R = mem::MaybeUninit<<E as Shape>::Root>> {
    root: ptr::NonNull<R>,
    tail: ptr::NonNull<E::Tail>,
    extent: E,
    pub state: S,
    extra: X,
}

impl<E: Shape<Last = ()>, S> Block<E, S, Initialized, E::Root> {
    pub fn values(&self) -> &[E::Extra] {
        // SAFETY: Shape retains this initialized plane's complete allocation offset.
        let extra = unsafe { self.as_ptr().byte_add(self.extent.extra()).cast() };
        // SAFETY: the initialized plane has the exact root length and owner borrow.
        unsafe { slice::from_raw_parts(extra, self.extent.len()) }
    }
}

impl<E: Shape, S, X, R> Drop for Block<E, S, X, R> {
    fn drop(&mut self) {
        // SAFETY: this owner drops its complete initialized root plane before
        // releasing the exact allocation retained by its immutable Shape.
        unsafe {
            ptr::drop_in_place(ptr::slice_from_raw_parts_mut(
                self.root.as_ptr(),
                self.extent.len(),
            ));
            LayoutExt::deallocate(self.extent.layout(), self.root);
        }
    }
}

impl<E: Shape, S, X, R> Block<E, S, X, R> {
    /// The root allocation pointer without borrowing its elements.
    pub(crate) const fn as_ptr(&self) -> *mut R {
        self.root.as_ptr()
    }

    pub const fn extent(&self) -> &E {
        &self.extent
    }

    pub fn tail(&self) -> &[E::Tail] {
        // SAFETY: every constructor initializes exactly `tail_len` Tail values
        // at the aligned disjoint offset retained by this Shape, and the shared
        // borrow keeps the owning allocation live.
        unsafe { slice::from_raw_parts(self.tail.as_ptr(), self.extent.tail_len()) }
    }

    /// Exclusively borrows the inline state and both disjoint initialized planes.
    pub fn parts_mut(&mut self) -> (&mut S, &mut [R], &mut [E::Tail]) {
        // SAFETY: construction retains initialized R and Tail planes in Shape's
        // disjoint allocation, separate from the exclusively borrowed inline state.
        unsafe {
            (
                &mut self.state,
                slice::from_raw_parts_mut(self.root.as_ptr(), self.extent.len()),
                slice::from_raw_parts_mut(self.tail.as_ptr(), self.extent.tail_len()),
            )
        }
    }
}

impl<E: Shape, S, X, R> AsRef<[R]> for Block<E, S, X, R> {
    fn as_ref(&self) -> &[R] {
        // SAFETY: construction initializes exactly `len` R values at `root` in
        // the Shape's first aligned, disjoint plane, and the shared borrow keeps
        // them initialized for its whole duration.
        unsafe { slice::from_raw_parts(self.root.as_ptr(), self.extent.len()) }
    }
}

impl<E: Shape, S, X, R> AsMut<[R]> for Block<E, S, X, R> {
    fn as_mut(&mut self) -> &mut [R] {
        // SAFETY: the exclusive borrow covers the initialized root plane.
        unsafe { slice::from_raw_parts_mut(self.root.as_ptr(), self.extent.len()) }
    }
}

impl<E: Shape, S> Block<E, S, ptr::NonNull<E::Extra>, mem::MaybeUninit<E::Root>> {
    pub fn values(&self) -> &[E::Extra] {
        // SAFETY: the `Uninit::finish` contract retains this initialized
        // `len`-element Extra plane at its admitted address; the borrow
        // keeps the plane and owner live.
        unsafe { slice::from_raw_parts(self.extra.as_ptr(), self.extent.len()) }
    }

    pub fn values_mut(&mut self) -> &mut [E::Extra] {
        // SAFETY: the `NonNull<E::Extra>` state proves the same initialized
        // `len`-element plane as `values`; the exclusive borrow additionally
        // excludes every other access to it.
        unsafe { slice::from_raw_parts_mut(self.extra.as_ptr(), self.extent.len()) }
    }
}

type Parts<E, S> = Block<
    E,
    S,
    (
        ptr::NonNull<<E as Shape>::Extra>,
        ptr::NonNull<<E as Shape>::Last>,
    ),
>;

impl<E: Rows, S> Parts<E, S> {
    pub fn extra(&self) -> (&[E::Extra], &[E::Last]) {
        // SAFETY: the `(NonNull<E::Extra>, NonNull<E::Last>)` state is produced
        // only by `try_parts`, which initialized both equal-length auxiliary
        // planes through Rows at these disjoint Shape offsets; the shared borrow
        // keeps the owning allocation and both planes live.
        unsafe {
            (
                slice::from_raw_parts(self.extra.0.as_ptr(), self.extent.len()),
                slice::from_raw_parts(self.extra.1.as_ptr(), self.extent.len()),
            )
        }
    }

    pub fn extra_mut(&mut self) -> (&mut [E::Extra], &mut [E::Last]) {
        // SAFETY: Shape proves both initialized auxiliary planes are disjoint
        // and each has exactly len entries in this exclusive allocation borrow.
        unsafe {
            (
                slice::from_raw_parts_mut(self.extra.0.as_ptr(), self.extent.len()),
                slice::from_raw_parts_mut(self.extra.1.as_ptr(), self.extent.len()),
            )
        }
    }
}