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
424
425
426
427
428
429
430
431
432
use std::{
    borrow::BorrowMut,
    marker,
    mem::{self, MaybeUninit},
    num::NonZero,
    ptr, slice,
};

use crate::buffer::{
    self, storage, write,
    write::{consume, edit},
};

mod commit;
mod init;
mod sink;
mod spare;
mod spareext;

pub use spare::Spare;

/// # Safety
/// The count and disjoint spare belong to one exclusive owner. Their sum fits Len.
pub(in crate::buffer) unsafe trait Writer {
    type Len: buffer::raw::Length;

    fn parts(&mut self) -> (&mut Self::Len, &mut [MaybeUninit<u8>]);
}

/// A checked writer exposing only its initialized prefix.
pub struct Slice<'a, L = usize, N = usize> {
    base: ptr::NonNull<u8>,
    len: L,
    capacity: usize,
    borrow: marker::PhantomData<(&'a mut [MaybeUninit<u8>], N)>,
}

impl<'a> Slice<'a> {
    pub fn new(out: &'a mut [u8]) -> Self {
        let capacity = out.len();
        Self::new_parts(ptr::NonNull::from(out).cast(), 0, capacity)
    }

    pub fn uninit(out: &'a mut [MaybeUninit<u8>]) -> Self {
        let capacity = out.len();
        Self::new_parts(ptr::NonNull::from(out).cast(), 0, capacity)
    }
}

impl<'a, N: buffer::raw::Length> Slice<'a, &'a mut N, N> {
    /// # Safety
    /// `len <= out.len() <= N::MAX`; the first `len` bytes are initialized.
    pub unsafe fn from_parts(out: &'a mut [MaybeUninit<u8>], len: &'a mut N) -> Self {
        let capacity = out.len();
        Self::new_parts(ptr::NonNull::from(out).cast(), len, capacity)
    }
}

impl<'a, L, N> Slice<'a, L, N> {
    fn new_parts(base: ptr::NonNull<u8>, len: L, capacity: usize) -> Self {
        Self {
            base,
            len,
            capacity,
            borrow: marker::PhantomData,
        }
    }
}

impl<'a, L: BorrowMut<N>, N: buffer::raw::Length> Slice<'a, L, N> {
    pub fn len(&self) -> usize {
        N::into_usize(*self.len.borrow())
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    pub fn remaining(&self) -> usize {
        self.capacity - self.len()
    }

    pub fn try_limit(mut self, required: usize, tail: usize) -> Result<Self, consume::Error> {
        let used = self.len();
        let room = (self.capacity - used).saturating_sub(tail);
        consume::Error::check(required, room)?;
        self.capacity = used + required;
        Ok(self)
    }

    /// # Safety
    /// The last `width` bytes are initialized and `len` fits the unchanged suffix.
    pub unsafe fn repeat(&mut self, width: NonZero<usize>, len: usize) {
        let old = self.len();
        let start = old - width.get();
        let end = old + len;
        let mut written = old;
        while written < end {
            let copied = (written - start).min(end - written);
            // SAFETY: the initialized source and its unwritten suffix are disjoint;
            // both remain inside this writer's admitted exclusive range.
            unsafe {
                ptr::copy_nonoverlapping(
                    self.base.as_ptr().add(start),
                    self.base.as_ptr().add(written),
                    copied,
                );
            }
            written += copied;
        }
        *self.len.borrow_mut() = N::from_usize(end);
    }

    /// # Safety
    /// Advance the count only over initialized bytes within the returned suffix.
    pub unsafe fn spare_parts(&mut self) -> (&mut N, &mut [MaybeUninit<u8>]) {
        let len = self.len.borrow_mut();
        let used = N::into_usize(*len);
        // SAFETY: this writer retains its entire exclusive range and its disjoint count.
        let out = unsafe {
            slice::from_raw_parts_mut(self.base.as_ptr().add(used).cast(), self.capacity - used)
        };
        (len, out)
    }

    /// Lends this writer's actual progress without lending its identity.
    pub fn reborrow(&mut self) -> Slice<'_, &mut N, N> {
        Slice::new_parts(self.base, self.len.borrow_mut(), self.capacity)
    }

    pub fn stage(&mut self) -> Stage<'_, 'a, L, N> {
        Stage {
            parent: self,
            len: 0,
        }
    }

    /// Returns exactly the written prefix under the original exclusive borrow.
    pub fn into_mut(self) -> &'a mut [u8] {
        // SAFETY: only successful writes extend this exact initialized prefix;
        // a lent count retains its parent's exclusive borrow for the returned slice.
        unsafe { buffer::raw::range_mut(self.base.as_ptr(), 0, self.len()) }
    }

    /// Succeeds only after the complete original output slice was written.
    pub fn try_complete(self) -> Result<(), consume::Error> {
        consume::Error::check(self.capacity, self.len())
    }

    /// Stages adjacent head and body regions without advancing this writer.
    pub fn try_split(
        &mut self,
        head: usize,
        body: usize,
    ) -> Result<Split<'_, 'a, L, N>, consume::Error> {
        let room = self.remaining();
        consume::Error::check(head, room)?;
        consume::Error::check(body, room - head)?;
        Ok(Split {
            parent: self,
            head,
            capacity: head + body,
            head_len: 0,
            body_len: 0,
        })
    }
}

impl<L: BorrowMut<N>, N: buffer::raw::Length> AsRef<[u8]> for Slice<'_, L, N> {
    fn as_ref(&self) -> &[u8] {
        // SAFETY: the original exclusive loan retains this initialized prefix.
        unsafe { buffer::raw::range(self.base.as_ptr(), 0, self.len()) }
    }
}

// SAFETY: the slice retains its own initialized count and bounded spare.
unsafe impl<L: BorrowMut<N>, N: buffer::raw::Length> Writer for Slice<'_, L, N> {
    type Len = N;

    fn parts(&mut self) -> (&mut N, &mut [MaybeUninit<u8>]) {
        // SAFETY: the caller receives this writer's original paired parts.
        unsafe { self.spare_parts() }
    }
}

impl<L: BorrowMut<N>, N: buffer::raw::Length> write::Init for Slice<'_, L, N> {
    fn try_init<I: buffer::raw::Initializer>(&mut self, source: I) -> Result<(), consume::Error> {
        initialize(self, source)
    }
}

/// An unpublished suffix retained by its original writer.
pub struct Stage<'writer, 'target, L = usize, N = usize> {
    parent: &'writer mut Slice<'target, L, N>,
    len: usize,
}

impl<L: BorrowMut<N>, N: buffer::raw::Length> Stage<'_, '_, L, N> {
    pub fn body(&mut self) -> Slice<'_, &mut usize> {
        // SAFETY: the exclusive parent loan retains its unchanged suffix.
        let base = unsafe { self.parent.base.add(self.parent.len()) };
        Slice::new_parts(base, &mut self.len, self.parent.remaining())
    }

    pub fn commit(self) {
        let len = self.parent.len.borrow_mut();
        *len = N::from_usize(N::into_usize(*len) + self.len);
    }
}

/// Unpublished adjacent regions retained by one parent writer.
pub struct Split<'writer, 'target, L = usize, N = usize> {
    parent: &'writer mut Slice<'target, L, N>,
    head: usize,
    capacity: usize,
    head_len: usize,
    body_len: usize,
}

impl<L: BorrowMut<N>, N: buffer::raw::Length> Split<'_, '_, L, N> {
    pub fn head(&mut self) -> Slice<'_, &mut usize> {
        // SAFETY: admission retained this parent's entire unpublished suffix.
        let base = unsafe { self.parent.base.add(self.parent.len()) };
        Slice::new_parts(base, &mut self.head_len, self.head)
    }

    pub fn body(&mut self) -> Slice<'_, &mut usize> {
        // SAFETY: the admitted head separates this body's exact disjoint region.
        let base = unsafe { self.parent.base.add(self.parent.len() + self.head) };
        Slice::new_parts(base, &mut self.body_len, self.capacity - self.head)
    }

    /// Publishes the contiguous prefix only after the entire head is initialized.
    pub fn try_commit(self) -> Result<(), consume::Error> {
        consume::Error::check(self.head, self.head_len)?;
        let len = self.parent.len.borrow_mut();
        *len = N::from_usize(N::into_usize(*len) + self.head + self.body_len);
        Ok(())
    }
}

const _: () = {
    assert!(size_of::<Slice<'static>>() == 3 * size_of::<usize>());
    assert!(size_of::<Option<Slice<'static>>>() == size_of::<Slice<'static>>());
    assert!(size_of::<Slice<'static, &'static mut usize>>() == 3 * size_of::<usize>());
    assert!(size_of::<Stage<'static, 'static>>() == 2 * size_of::<usize>());
    assert!(size_of::<Split<'static, 'static>>() == 5 * size_of::<usize>());
};

/// # Safety
/// The original count and exclusive suffix together fit L's domain.
pub(in crate::buffer) unsafe fn try_append<L: buffer::raw::Length, const N: usize>(
    (len, out): (&mut L, &mut [mem::MaybeUninit<u8>]),
    slices: [&[u8]; N],
) -> Result<(), consume::Error> {
    let added = consume::Error::checked_end(0, out.len(), &slices)?;
    // SAFETY: admission checked every stable fragment before the first copy.
    unsafe { copy((len, out), &slices, added) };
    Ok(())
}

/// # Safety
/// The original count and exclusive suffix together fit L's domain.
pub(in crate::buffer) unsafe fn try_initialize<
    L: buffer::raw::Length,
    I: buffer::raw::Initializer,
>(
    (len, out): (&mut L, &mut [mem::MaybeUninit<u8>]),
    source: I,
) -> Result<(), consume::Error> {
    let added = source.len();
    consume::Error::check(added, out.len())?;
    // SAFETY: the exclusive suffix admits the initializer's exact stable length.
    unsafe { source.initialize(slice::from_raw_parts_mut(out.as_mut_ptr(), added)) };
    *len = L::from_usize(len.into_usize() + added);
    Ok(())
}

/// # Safety
/// The source's complete byte count fits the original disjoint suffix and L.
unsafe fn copy<L: buffer::raw::Length, T: buffer::raw::Transfer + ?Sized>(
    (len, out): (&mut L, &mut [MaybeUninit<u8>]),
    source: &T,
    added: usize,
) {
    // SAFETY: the caller admitted the complete source in this original destination.
    unsafe { source.copy_to(out.as_mut_ptr().cast()) };
    *len = L::from_usize(len.into_usize() + added);
}

pub(in crate::buffer::write) fn initialize<W: Writer, I: buffer::raw::Initializer>(
    out: &mut W,
    source: I,
) -> Result<(), consume::Error> {
    // SAFETY: Writer retains the original count and disjoint suffix.
    unsafe { try_initialize(out.parts(), source) }
}

pub(in crate::buffer::write) fn edit<'a, const N: usize>(
    mut spare: Spare<'a>,
    prefix: &[u8; N],
) -> Result<edit::Edit<'a, N>, consume::Error> {
    let start = spare.len();
    write::Sink::write_slice(&mut spare, prefix)?;
    // SAFETY: this new array is initialized; the retained spare appends only after it.
    let prefix = unsafe { &mut *spare.pointer.as_ptr().add(start).cast::<[u8; N]>() };
    Ok(edit::Edit::new(prefix, spare))
}

// SAFETY: the editable header is disjoint from the nested writer's spare.
unsafe impl<const N: usize> Writer for edit::Edit<'_, N> {
    type Len = u32;

    fn parts(&mut self) -> (&mut u32, &mut [MaybeUninit<u8>]) {
        self.spare.parts()
    }
}

// SAFETY: the owned heap keeps its exclusive length and unpublished storage together.
unsafe impl<P: buffer::raw::Policy> Writer for storage::Owned<P> {
    type Len = u32;

    fn parts(&mut self) -> (&mut u32, &mut [MaybeUninit<u8>]) {
        buffer::raw::Exclusive::spare_parts(self)
    }
}
/// # Safety
/// Exclusively retain `len` initialized bytes beyond the unchanged vector length, within capacity.
unsafe fn publish_suffix(out: &mut Vec<u8>, len: usize) -> &mut [u8] {
    let start = out.len();
    // SAFETY: the caller retained this initialized suffix within capacity.
    unsafe { out.set_len(start + len) };
    // SAFETY: publication cannot reallocate; this initialized suffix retains out's
    // exclusive borrow. An empty suffix uses the valid end or dangling empty pointer.
    unsafe { buffer::raw::range_mut(out.as_mut_ptr(), start, len) }
}

pub(in crate::buffer::write) fn fill(
    out: &mut Vec<u8>,
    len: usize,
    byte: u8,
) -> Result<(), crate::alloc::Error> {
    crate::alloc::VecExt::try_reserve(out, len)?;
    // SAFETY: the entire exclusively reserved region is initialized before publication.
    unsafe {
        out.spare_capacity_mut().as_mut_ptr().write_bytes(byte, len);
        publish_suffix(out, len);
    }
    Ok(())
}

pub(in crate::buffer::write) fn suffix<'a>(append: &'a write::Append<'_>) -> &'a [u8] {
    // SAFETY: nested writes cannot remove the append's initialized prefix.
    unsafe { append.out.get_unchecked(append.start..) }
}

pub(in crate::buffer::write) fn suffix_mut(append: write::Append<'_>) -> &mut [u8] {
    // SAFETY: exclusive ownership retains the saved initialized prefix for this loan.
    unsafe { append.out.get_unchecked_mut(append.start..) }
}

pub(in crate::buffer::write) fn commit<L: buffer::raw::Length>(
    stage: write::Staged<&mut Vec<u8>, L>,
) -> &mut [u8] {
    // SAFETY: the consumed reservation retains the complete initialized stage.
    unsafe { publish_suffix(stage.out, stage.len.into_usize()) }
}

pub(in crate::buffer::write) fn finish<L: buffer::raw::Length>(
    mut stage: write::Staged<Vec<u8>, L>,
) -> Vec<u8> {
    // SAFETY: the owned stage retains its unpublished initialized prefix.
    unsafe { publish_suffix(&mut stage.out, stage.len.into_usize()) };
    stage.out
}

pub(in crate::buffer::write) fn staged_bytes<B: BorrowMut<Vec<u8>>, L: buffer::raw::Length>(
    stage: &mut write::Staged<B, L>,
) -> &mut [u8] {
    let vec = stage.out.borrow_mut();
    // SAFETY: the stage alone retains and initializes this suffix.
    unsafe {
        vec.spare_capacity_mut()
            .get_unchecked_mut(..stage.len.into_usize())
            .assume_init_mut()
    }
}

// SAFETY: the vector is exclusively reserved, with unpublished writes counted in L.
unsafe impl<B: BorrowMut<Vec<u8>>, L: buffer::raw::Length> Writer for write::Staged<B, L> {
    type Len = L;

    fn parts(&mut self) -> (&mut L, &mut [MaybeUninit<u8>]) {
        let used = self.len.into_usize();
        let limit = self.capacity.into_usize();
        // SAFETY: staged progress never exceeds the admitted suffix of this vector.
        let spare = unsafe {
            self.out
                .borrow_mut()
                .spare_capacity_mut()
                .get_unchecked_mut(used..limit)
        };
        (&mut self.len, spare)
    }
}
// SAFETY: the vector's unchanged length selects the stage's exclusive suffix;
// its staged count advances only after these exact bytes are initialized.
unsafe impl<B: BorrowMut<Vec<u8>>> buffer::raw::Prefix for write::Staged<B, u32> {
    fn prefix(&self) -> (*mut MaybeUninit<u8>, u32) {
        let out: &Vec<u8> = self.out.borrow();
        (
            out.as_ptr().wrapping_add(out.len()).cast_mut().cast(),
            self.len,
        )
    }
}

// SAFETY: the retained vector cannot grow or publish during this stage. Its
// admitted suffix is exclusive, isize-bounded and disjoint from the staged count.
unsafe impl<B: BorrowMut<Vec<u8>>> buffer::raw::Exclusive for write::Staged<B, u32> {
    fn as_mut_ptr(&mut self) -> *mut MaybeUninit<u8> {
        self.out.borrow_mut().spare_capacity_mut().as_mut_ptr()
    }

    fn len_mut(&mut self) -> &mut u32 {
        &mut self.len
    }

    fn capacity(&self) -> u32 {
        self.capacity
    }
}