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
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
use std::{
    convert, marker,
    mem::MaybeUninit,
    num::NonZero,
    ops, ptr,
    slice::{from_raw_parts, from_raw_parts_mut},
};

use crate::{
    base::num::bounded,
    buffer::{
        self,
        pool::owners,
        segments::{self, scatter::Take},
        storage::{self, provided, range::Error},
        write::consume::{self, scope},
    },
    mem::{self, Rejected, rc},
};

mod chunks;
mod input;
mod length;
mod limit;
mod output;
mod seal;
mod slices;
mod store;

pub use chunks::Chunks;
pub use input::Input;
pub use length::Length;
pub use limit::Limit;
pub use output::Output;
pub(in crate::buffer) use output::{Exclusive, Prefix};
pub(in crate::buffer) use seal::Seal;
pub use slices::Slices;
pub(in crate::buffer) use slices::Transfer;
pub(in crate::buffer) use store::{Header, Heap};

/// # Safety
/// The Source contract holds and `AsRef` exposes that exact initialized range.
/// Consumption must advance exactly the proved prefix and preserve the remaining bytes.
pub unsafe trait Consume: AsRef<[u8]> {
    fn consume<const MAX: u32>(prefix: Input<&mut Self, scope::Prefix<MAX>>);
}

/// One owner edge that can retain the same backing independently.
/// # Safety
/// `try_retain` preserves backing identity, access, and branded lifetimes.
pub unsafe trait Retain: Sized {
    fn try_retain(&self) -> Result<Self, rc::Error>;
}

// SAFETY: cloning this counted edge preserves its target, access, and lifetime.
unsafe impl<T: mem::raw::Target> Retain for mem::raw::Owner<T> {
    fn try_retain(&self) -> Result<Self, rc::Error> {
        self.try_clone()
    }
}

// SAFETY: Some retains the same owner and lifetime; None retains no backing.
unsafe impl<T: Retain> Retain for Option<T> {
    fn try_retain(&self) -> Result<Self, rc::Error> {
        self.as_ref().map(T::try_retain).transpose()
    }
}

/// # Safety
/// Shared access preserves its exact backing, range, and contents until exclusive mutation.
/// Writes preserve the initialized prefix; successful writes append their complete input.
pub unsafe trait Source: AsRef<[u8]> {
    /// # Safety
    /// The bounds lie within this unchanged source's initialized bytes.
    unsafe fn view(&self, bounds: ops::Range<usize>) -> buffer::View<'_, Self> {
        buffer::View {
            source: self,
            // SAFETY: the caller admits this range of the retained source.
            proof: unsafe { self.as_ref().get_unchecked(bounds) },
        }
    }

    /// # Safety
    /// This source's complete unchanged visible range is valid UTF-8.
    unsafe fn into_str(self) -> storage::Str<Self>
    where
        Self: Sized,
    {
        // SAFETY: the caller proved UTF-8 for this complete immutable source.
        unsafe { storage::Str::new(self) }
    }

    /// # Safety
    /// This source's unchanged initialized extent is nonempty.
    unsafe fn nonempty(self) -> storage::NonEmpty<Self>
    where
        Self: Sized,
    {
        // SAFETY: the caller proved nonemptiness on this retained source.
        unsafe { storage::raw::present(self) }
    }
}

/// # Safety
/// `AsMut::as_mut` returns the full Source range with its pre-call pointer and length, unchanged after the loan.
/// The call changes no owner, descriptor, extent, or bytes; caller slice writes are allowed, and other exclusive operations retain their own contracts.
pub unsafe trait Mutable: Source + AsMut<[u8]> {}

/// # Safety
/// Every `provided::Mutable::try_take` implementation returns the exact requested prefix
/// and retains its disjoint suffix, contents, owner and lifetimes; failure changes nothing.
pub unsafe trait Split: Mutable {}

/// # Safety
/// Freezing retains the exact backing, initialized range, contents, owner and lifetimes.
/// It allocates, copies and clones nothing and introduces no sharing.
pub unsafe trait Freeze: Source + Sized {
    type Output: Source;

    fn freeze(self) -> Self::Output;
}

/// # Safety
/// The initialized range at `pointer.add(start)` stays retained for `'a`, without
/// overlapping exclusive access, and satisfies every `from_raw_parts` requirement.
pub(in crate::buffer) unsafe fn range<'a>(
    pointer: *const u8,
    start: usize,
    len: usize,
) -> &'a [u8] {
    // SAFETY: the caller proved this exact initialized subrange of one allocation.
    unsafe { from_raw_parts(pointer.add(start), len) }
}

/// # Safety
/// As [`range`], with exclusive access for `'a` and every `from_raw_parts_mut` requirement.
pub(in crate::buffer) unsafe fn range_mut<'a>(
    pointer: *mut u8,
    start: usize,
    len: usize,
) -> &'a mut [u8] {
    // SAFETY: the caller proved this exact initialized subrange and its exclusive retention.
    unsafe { from_raw_parts_mut(pointer.add(start), len) }
}

/// # Safety
/// Shared access preserves the visible range, backing and contents until mutation.
/// Projection applies the proved range and preserves the owner's empty-storage policy.
pub unsafe trait Store: AsRef<[u8]> + Sized {
    fn advance<const MAX: u32>(prefix: Input<&mut Self, scope::Prefix<MAX>>) {
        let (source, consumed) = prefix.into_parts();
        let end = source.as_ref().len();
        // SAFETY: this admitted total prefix still retains the exact exclusive source.
        Self::project(unsafe { Input::from_parts(source, consumed.count().get() as usize..end) });
    }

    /// Returns a canonical empty owner, or `None` to restrict the current owner
    /// according to its own empty-storage policy.
    /// A returned owner must expose no bytes and require no allocation.
    fn empty() -> Option<Self> {
        None
    }

    fn project(slice: Input<&mut Self, ops::Range<usize>>) {
        if slice.proof.is_empty()
            && let Some(empty) = Self::empty()
        {
            *slice.source = empty;
            return;
        }
        Self::restrict(slice);
    }

    fn try_project(mut self, bounds: ops::Range<usize>) -> Result<Self, Rejected<Self, Error>> {
        match Input::try_select(&mut self, bounds) {
            Ok(slice) => {
                Self::project(slice);
                Ok(self)
            }
            Err(error) => Err(Rejected::new(self, error)),
        }
    }

    /// Applies the selected extent. Nonempty selections must retain their original
    /// backing; empty selections preserve this owner's empty-storage policy.
    fn restrict(slice: Input<&mut Self, ops::Range<usize>>);
}

pub(in crate::buffer) fn select_max<const SUFFIX: bool, S: Store>(
    source: &mut S,
    max: usize,
) -> usize {
    let end = source.as_ref().len();
    let start = max.min(end);
    Input {
        source,
        proof: (start, end - start),
    }
    .project::<SUFFIX>()
}

/// # Safety
/// Release the same backing once after all access ends; static dimensions match its Header/Slot geometry.
/// COUNTED is true whenever a live Span can share its slot before consuming publication.
pub unsafe trait Backing {
    const COUNTED: bool = false;
    const SLOTS: Option<u32> = None;
    const CAPACITY: Option<NonZero<u32>> = None;

    /// # Safety
    /// `core` must be the terminal allocation edge for this backing kind.
    unsafe fn release<S>(core: owners::raw::Ptr<Self, S>)
    where
        Self: Sized,
    {
        // SAFETY: the caller transfers this backing's terminal allocation edge.
        unsafe { core.deallocate() };
    }
}

pub trait Policy: Copy {
    type Failure;
    type Debit: Into<Self>;

    fn available(self) -> usize;

    fn try_acquire(self, amount: NonZero<u32>) -> Result<Self::Debit, Self::Failure>;

    /// # Safety
    /// Own this policy's terminal header allocation and its exact capacity debit.
    unsafe fn deallocate(self, pointer: ptr::NonNull<u8>, capacity: NonZero<u32>);
}

impl Policy for () {
    type Failure = convert::Infallible;
    type Debit = ();

    fn available(self) -> usize {
        usize::MAX
    }

    fn try_acquire(self, _: NonZero<u32>) -> Result<Self::Debit, Self::Failure> {
        Ok(())
    }

    unsafe fn deallocate(self, pointer: ptr::NonNull<u8>, capacity: NonZero<u32>) {
        // SAFETY: this terminal plain header retains its exact original allocation.
        unsafe { Header::<Self>::free(pointer.cast(), capacity) };
    }
}

/// Retained bytes that narrow without copying their payload.
/// # Safety
/// Shared access preserves the range, and consuming advances its exact prefix.
pub unsafe trait Segment:
    Seal + Source + Store + consume::Consume + buffer::Residency
{
    /// # Safety
    /// Preserve this owner's exact initialized extent and its original backing.
    unsafe fn extent(&mut self) -> &mut storage::raw::Extent;

    fn try_share(view: &storage::NonEmpty<buffer::View<'_, Self>>) -> Result<Self, rc::Error>;

    fn try_clone(&self) -> Result<Self, rc::Error> {
        buffer::View::new(self).try_retain()
    }

    fn try_get(&self, range: ops::Range<usize>) -> Result<Option<Self>, rc::Error> {
        buffer::View::new(self)
            .get(range)
            .map(buffer::View::<Self>::try_retain)
            .transpose()
    }

    /// Retains an in-bounds owner subrange without copying its payload.
    /// # Safety
    /// `range` must lie within the owner's visible bytes.
    unsafe fn try_project(&self, range: ops::Range<usize>) -> Result<Self, rc::Error> {
        // SAFETY: the caller admits this range of the unchanged owner.
        unsafe { Source::view(self, range) }.try_retain()
    }

    /// Retains at most `limit` leading bytes without copying the payload.
    fn prefix(mut self, limit: usize) -> Self {
        select_max::<false, _>(&mut self, limit);
        self
    }

    /// Splits off at most `limit` visible bytes without copying the payload.
    fn try_split(mut self, limit: usize) -> Result<(Self, Option<Self>), (rc::Error, Self)> {
        let Some(tail) = segments::Tail::new(&mut self, limit) else {
            return Ok((self, None));
        };
        let prefix = match tail.try_commit() {
            Ok(result) => result,
            Err(error) => return Err((error, self)),
        };
        Ok((prefix, Some(self)))
    }

    /// Removes at most `amount` visible bytes without copying the payload.
    fn suffix(mut self, amount: usize) -> Option<Self> {
        segments::Tail::new(&mut self, amount)?.commit();
        Some(self)
    }
}

/// Projects fixed-residency items admitted by their original native context.
pub trait Fixed<T> {
    fn resident(&self) -> NonZero<u32>;

    /// # Safety
    /// Own this context's unique item; its full retained backing fits `resident()`.
    /// Its prefix is initialized; `limit` is that ceiling and backing/layout live for `'a`.
    unsafe fn project<'a, 'id>(&'a self, item: &'a mut T, limit: Limit<'id>)
    -> Projection<'a, 'id>;

    /// # Safety
    /// Own its context's unique initialized item; full backing fits `resident()` and lives for `'d`.
    /// Its layout and `resident()` match this arena's unchanged layout and resident ceiling.
    unsafe fn insert<'d>(
        vacant: provided::raw::Vacant<'d, T, (), &'d Self>,
        item: T,
    ) -> provided::raw::Slice<&'d mut [u8], provided::raw::Owner<'d, ()>>
    where
        Self: Sized,
    {
        // SAFETY: the caller admitted this unique item for the vacancy's fixed context.
        unsafe { vacant.insert_fixed(item) }
    }
}

/// A mutable projection proven to fit its resident byte ceiling.
#[repr(transparent)]
pub struct Projection<'a, 'id> {
    bytes: &'a mut [u8],
    operation: marker::PhantomData<fn(&'id mut ()) -> &'id mut ()>,
}

impl<'a> Projection<'a, '_> {
    pub(in crate::buffer) const fn into_inner(self) -> &'a mut [u8] {
        self.bytes
    }
}

/// Copies a finite sequence into one admitted exclusive destination.
pub trait IteratorExt<'a>: IntoIterator<Item = &'a [u8]> + Sized {
    /// # Safety
    /// The byte sum fits `isize`; target is nonnull and writable in one allocation (dangling for zero).
    /// Sources stay valid and disjoint; iteration neither accesses nor invalidates the target.
    unsafe fn copy_to(self, target: *mut u8) {
        let mut offset = 0;
        for source in self {
            // SAFETY: the caller retains this source and its complete disjoint destination.
            unsafe { Transfer::copy_to(source, target.add(offset)) };
            offset += source.len();
        }
    }
}

impl<'a, I: IntoIterator<Item = &'a [u8]>> IteratorExt<'a> for I {}

/// # Safety
/// Retain source borrows and stable `len`; initialize the complete target once.
/// Never read uninitialized output, retain its access, or invalidate source borrows.
pub unsafe trait Initializer {
    fn len(&self) -> usize;

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

    /// # Safety
    /// `target.len()` equals this unchanged source's previously admitted `len()`.
    unsafe fn initialize(self, target: &mut [MaybeUninit<u8>]);
}

// SAFETY: the immutable array borrow keeps its N initialized bytes unchanged.
unsafe impl<const N: usize> Initializer for &[u8; N] {
    fn len(&self) -> usize {
        N
    }

    unsafe fn initialize(self, target: &mut [MaybeUninit<u8>]) {
        // SAFETY: the caller supplies this source's exact disjoint output extent.
        unsafe { Transfer::copy_to(self.as_slice(), target.as_mut_ptr().cast()) };
    }
}

/// One proven non-empty span borrowed from its source.
#[repr(transparent)]
pub struct Chunk<'data, const MAX: usize = { usize::MAX }> {
    bytes: &'data [u8],
}

impl<'data, const MAX: usize> Chunk<'data, MAX> {
    /// Retains one exact initialized span from its original immutable borrow.
    ///
    /// # Safety
    /// `bytes` is non-empty and `bytes.len() <= MAX`.
    pub unsafe fn new(bytes: &'data [u8]) -> Self {
        Self { bytes }
    }

    pub const fn bytes(&self) -> &'data [u8] {
        self.bytes
    }

    pub const fn len(&self) -> bounded::NonZeroUsize<1, MAX> {
        // SAFETY: construction proves the retained span is non-empty and bounded by MAX.
        unsafe { bounded::raw::nonzero_usize(self.bytes.len()) }
    }
}

impl<'a, T: AsRef<[u8]>> From<&'a storage::NonEmpty<T>> for Chunk<'a> {
    fn from(owner: &'a storage::NonEmpty<T>) -> Self {
        Self {
            bytes: owner.as_ref(),
        }
    }
}

const _: () = {
    assert!(size_of::<Chunk<'static>>() == size_of::<&[u8]>());
    assert!(size_of::<Option<Chunk<'static>>>() == size_of::<&[u8]>());
};

/// Exact-progress traversal over one immutable scattered source.
///
/// # Safety
/// Progress, cap, remaining length, and `'data` must all be exact.
pub unsafe trait Scatter<'data> {
    fn remaining(&self) -> usize;

    /// Advances to an admitted byte offset in this exact cursor.
    fn seek(mut self, offset: usize) -> Option<Self>
    where
        Self: Sized,
    {
        if offset > self.remaining() {
            return None;
        }
        Take::<_>::new(&mut self, offset).finish();
        Some(self)
    }

    /// Borrows at most the requested number of remaining bytes.
    fn take_bytes(&mut self, limit: usize) -> Take<'_, 'data, Self>
    where
        Self: Sized,
    {
        Take::<_>::new(self, limit)
    }

    /// Advances by a nonempty prefix of the admitted remaining bytes.
    ///
    /// # Safety
    /// `cap <= self.remaining()` and `cap <= MAX`; output advances exactly `1..=cap` bytes.
    unsafe fn advance<const MAX: usize>(&mut self, cap: NonZero<usize>) -> Chunk<'data, MAX>;
}

/// # Safety
/// Capacity and backing stay stable through access; the initialized prefix fits and spare is exclusive.
/// Truncation keeps min(len, current_len); completion extends by exactly amount after external access ends.
pub unsafe trait Target: AsRef<[u8]> {
    fn capacity(&self) -> usize;
    fn truncate(&mut self, len: usize);

    /// # Safety
    /// Writes may initialize bytes, but must never deinitialize the backing.
    unsafe fn spare(&mut self) -> &mut [MaybeUninit<u8>];

    /// # Safety
    /// Native access ended and initialized `amount` bytes of this unchanged suffix.
    unsafe fn complete(&mut self, amount: usize);

    /// # Safety
    /// The initialized prefix fits capacity and all external access has ended.
    unsafe fn set_len(&mut self, len: usize);
}