Skip to main content

o3/buffer/raw/
mod.rs

1use std::{
2    marker, mem,
3    num::NonZero,
4    ops,
5    slice::{from_raw_parts, from_raw_parts_mut},
6};
7
8use crate::{
9    base::num,
10    buffer,
11    buffer::{
12        pool::{self, owners, state},
13        resident, segments,
14        storage::provided,
15    },
16    mem::rc,
17};
18mod output;
19pub use output::Target;
20mod slices;
21pub use slices::Slices;
22mod store;
23pub use store::Store;
24mod segment;
25pub(in crate::buffer) use segment::Seal;
26pub use segment::Segment;
27mod scatter;
28pub use scatter::Scatter;
29pub(in crate::buffer) use slices::{Exclusive, Prefix, SliceExt};
30
31/// # Safety
32/// The `buffer::raw::Source` contract must hold. `buffer::Cursor` must expose that same range.
33/// Consumption must advance exactly the proved prefix and preserve the remaining bytes.
34pub unsafe trait Consume: AsRef<[u8]> {
35    fn consume<const MAX: u32>(prefix: Consumed<'_, Self, MAX>);
36}
37
38// SAFETY: admission retains this exact initialized slice exclusively.
39unsafe impl Consume for &mut [u8] {
40    fn consume<const MAX: u32>(prefix: Consumed<'_, Self, MAX>) {
41        let (target, end) = prefix.into_parts();
42        let bytes = mem::take(target);
43        // SAFETY: the source-bound end is within this unchanged slice.
44        *target = unsafe { bytes.get_unchecked_mut(end.count().get() as usize..) };
45    }
46}
47
48// SAFETY: the view retains its immutable byte borrow and original source;
49// consumption only selects the admitted suffix of that same borrow.
50unsafe impl<S: ?Sized> Consume for buffer::View<'_, S> {
51    fn consume<const MAX: u32>(prefix: Consumed<'_, Self, MAX>) {
52        let (view, end) = prefix.into_parts();
53        // SAFETY: the prefix owns the exact view and its validated bound.
54        view.proof = unsafe { view.proof.get_unchecked(end.count().get() as usize..) };
55    }
56}
57
58/// One owner edge that can retain the same backing independently.
59/// # Safety
60/// `try_retain` preserves backing identity, access, and branded lifetimes.
61pub unsafe trait Retain: Sized {
62    fn try_retain(&self) -> Result<Self, rc::Error>;
63}
64
65// SAFETY: cloning this counted edge preserves its target, access, and lifetime.
66unsafe impl<T: crate::mem::raw::Target> Retain for crate::mem::raw::Owner<T> {
67    fn try_retain(&self) -> Result<Self, rc::Error> {
68        self.try_clone()
69    }
70}
71
72// SAFETY: Some retains the same owner and lifetime; None retains no backing.
73unsafe impl<T: Retain> Retain for Option<T> {
74    fn try_retain(&self) -> Result<Self, rc::Error> {
75        self.as_ref().map(T::try_retain).transpose()
76    }
77}
78
79/// Retains a complete source whose UTF-8 was already validated.
80/// # Safety
81/// The source's entire unchanged visible range is valid UTF-8.
82pub unsafe fn utf8<O: Source>(owner: O) -> buffer::storage::Str<O> {
83    // SAFETY: the caller proves UTF-8 for this complete immutable source.
84    unsafe { buffer::storage::Str::new(owner) }
85}
86
87/// # Safety
88/// `owner` must expose a nonempty initialized extent retained by its Source contract.
89pub unsafe fn nonempty<O: Source>(owner: O) -> buffer::storage::NonEmpty<O> {
90    // SAFETY: the caller proves nonemptiness on this unchanged stable source.
91    unsafe { buffer::storage::NonEmpty::assume(owner) }
92}
93
94/// # Safety
95/// Preserve the owner, visible range, resident capacity, and owner lifetimes.
96/// Allocate, copy, and clone nothing; do not introduce sharing.
97pub unsafe trait Convert<T, const BRANCH: u8 = 0> {
98    fn into(self) -> T;
99}
100
101// SAFETY: identity retains the complete original value and its byte storage.
102unsafe impl<T> Convert<T> for T {
103    fn into(self) -> T {
104        self
105    }
106}
107
108// SAFETY: the selected variant owns this unchanged value and its complete storage.
109unsafe impl<L, R> Convert<crate::base::Either<L, R>, 1> for L {
110    fn into(self) -> crate::base::Either<L, R> {
111        crate::base::Either::Left(self)
112    }
113}
114
115// SAFETY: the selected variant owns this unchanged value and its complete storage.
116unsafe impl<L, R> Convert<crate::base::Either<L, R>, 2> for R {
117    fn into(self) -> crate::base::Either<L, R> {
118        crate::base::Either::Right(self)
119    }
120}
121
122/// Immutable scattered bytes with an exact length and borrowed cursor.
123///
124/// # Safety
125/// `chunks()` has `len()` remaining; offset cursors exist through the end.
126pub unsafe trait Chunks {
127    type Cursor<'data>: Scatter<'data>
128    where
129        Self: 'data;
130
131    fn is_empty(&self) -> bool {
132        self.len() == 0
133    }
134
135    fn len(&self) -> usize;
136    fn chunks(&self) -> Self::Cursor<'_>;
137    fn cursor(&self, offset: usize) -> Option<Self::Cursor<'_>> {
138        Scatter::seek(self.chunks(), offset)
139    }
140
141    /// Copies an exact array-sized suffix without changing the retained source.
142    fn suffix<const N: usize>(&self) -> Option<[u8; N]> {
143        let mut cursor = self.chunks();
144        let skipped = buffer::raw::Scatter::remaining(&cursor).checked_sub(N)?;
145        segments::scatter::Take::new(&mut cursor, skipped).finish();
146        let mut output = [0; N];
147        let source = segments::scatter::Take::new(&mut cursor, usize::MAX);
148        // SAFETY: admission and exact traversal leave N bytes in the retained
149        // source, disjoint from this exclusive array of the same length.
150        unsafe {
151            buffer::raw::copy_slices(source.map(|chunk| chunk.bytes()), output.as_mut_ptr());
152        }
153        Some(output)
154    }
155}
156
157/// An owned admission retaining its operation proof until storage accepts it.
158/// # Safety
159/// Move only the original owner; the projection must retain its lifetime and exactly `bytes()`.
160pub unsafe trait Input<T> {
161    fn bytes(&self) -> &[u8];
162    fn into_item(self) -> (T, impl for<'a> FnOnce(&'a mut T) -> &'a mut [u8]);
163}
164
165/// Projects fixed-residency items admitted by their original native context.
166pub trait Fixed<T> {
167    fn resident(&self) -> NonZero<u32>;
168
169    /// # Safety
170    /// Own this context's unique item; its full retained backing fits `resident()`.
171    /// Its prefix is initialized; `limit` is that ceiling and backing/layout live for `'a`.
172    unsafe fn project<'a, 'id>(&'a self, item: &'a mut T, limit: Limit<'id>)
173    -> Projection<'a, 'id>;
174
175    /// # Safety
176    /// Own its context's unique initialized item; full backing fits `resident()` and lives for `'d`.
177    /// Its layout and `resident()` match this arena's unchanged layout and resident ceiling.
178    unsafe fn insert<'d>(
179        vacant: provided::Vacant<'d, T, (), &'d Self>,
180        item: T,
181    ) -> provided::Unique<'d, ()>
182    where
183        Self: Sized,
184    {
185        // SAFETY: the caller admitted this unique item for the vacancy's fixed context.
186        unsafe { vacant.insert_fixed(item) }
187    }
188}
189
190/// Exact arenas entered together with their external accounting generation.
191/// # Safety
192/// Roots must borrow their original arenas. The terminal must reclaim every item and charge.
193pub unsafe trait Arenas: Unpin {
194    type Roots<'d>: 'd
195    where
196        Self: 'd;
197
198    /// # Safety
199    /// Invoke the terminal once after all issued access ends, while every charged budget lives.
200    unsafe fn enter(&mut self) -> (Self::Roots<'_>, impl FnOnce() + '_);
201}
202
203// SAFETY: disjoint owners retain their exact roots and terminate in reverse order.
204unsafe impl<A: Arenas, B: Arenas> Arenas for (A, B) {
205    type Roots<'d>
206        = (A::Roots<'d>, B::Roots<'d>)
207    where
208        Self: 'd;
209
210    unsafe fn enter(&mut self) -> (Self::Roots<'_>, impl FnOnce() + '_) {
211        // SAFETY: the caller supplies the same generation and terminal ordering for both owners.
212        let (first, finish) = unsafe { self.0.enter() };
213        let (second, end) = unsafe { self.1.enter() };
214        ((first, second), move || {
215            end();
216            finish();
217        })
218    }
219}
220
221/// A mutable projection proven to fit its resident byte ceiling.
222#[repr(transparent)]
223pub struct Projection<'a, 'id> {
224    bytes: &'a mut [u8],
225    operation: marker::PhantomData<fn(&'id mut ()) -> &'id mut ()>,
226}
227
228impl<'a> Projection<'a, '_> {
229    pub(in crate::buffer) const fn into_inner(self) -> &'a mut [u8] {
230        self.bytes
231    }
232}
233
234/// Immutable UTF-8 in one exact allocation bound to its paying domain.
235pub type Text<'d> = buffer::storage::Str<resident::Exact<'d>>;
236
237/// Exclusive initialized suffix retained through its output operation.
238pub struct Output<'a, L = pool::Layout>
239where
240    owners::Plain<L>: crate::buffer::raw::Backing,
241{
242    target: &'a mut pool::Span<owners::Plain<L>, pool::Owned, state::Initialized>,
243}
244
245impl<L> pool::Span<owners::Plain<L>, pool::Owned, state::Initialized>
246where
247    owners::Plain<L>: crate::buffer::raw::Backing,
248{
249    pub fn output(&mut self) -> Output<'_, L> {
250        Output { target: self }
251    }
252}
253
254impl<'a, L> Output<'a, L>
255where
256    owners::Plain<L>: crate::buffer::raw::Backing,
257{
258    pub fn is_empty(&self) -> bool {
259        self.len() == 0
260    }
261
262    pub fn len(&self) -> usize {
263        self.target.capacity().get() as usize - self.target.len()
264    }
265
266    pub fn as_mut_slice(&mut self) -> &mut [u8] {
267        let (data, start) = buffer::raw::Prefix::prefix(self.target);
268        // SAFETY: Initialized retains every byte of this exact exclusive suffix.
269        unsafe { range_mut(data.cast(), start as usize, self.len()) }
270    }
271
272    /// # Safety
273    /// The foreign operation must prove `len` fits this unchanged output.
274    pub unsafe fn complete(self, len: NonZero<usize>) {
275        *Exclusive::len_mut(self.target) += len.get() as u32;
276    }
277}
278
279const _: () = assert!(size_of::<Output<'_>>() == size_of::<usize>());
280
281/// # Safety
282/// Shared access preserves its exact backing, range, and contents until exclusive mutation.
283/// Writes preserve the initialized prefix; successful writes append their complete input.
284pub unsafe trait Source: AsRef<[u8]> {}
285
286/// Borrows an admitted range while retaining its original source.
287/// # Safety
288/// `range.start <= range.end <= source.as_ref().len()` at this unchanged origin.
289pub unsafe fn view<S: Source + ?Sized>(
290    source: &S,
291    range: ops::Range<usize>,
292) -> buffer::View<'_, S> {
293    buffer::View {
294        source,
295        // SAFETY: the caller admits this subrange; Source preserves its borrow.
296        proof: unsafe { source.as_ref().get_unchecked(range) },
297    }
298}
299
300// SAFETY: the stronger cursor contract requires this stable-source contract.
301unsafe impl<T: buffer::raw::Consume> Source for T {}
302
303// SAFETY: this immutable borrow preserves the owner's visible range and contents.
304unsafe impl Source for &buffer::storage::Shared {}
305
306/// # Safety
307/// `AsMut::as_mut` returns the full Source range with its pre-call pointer and length, unchanged after the loan.
308/// The call changes no owner, descriptor, extent, or bytes; caller slice writes are allowed, and other exclusive operations retain their own contracts.
309pub unsafe trait Mutable: Source + AsMut<[u8]> {}
310
311/// # Safety
312/// Every `provided::Mutable::try_take` implementation returns the exact requested prefix
313/// and retains its disjoint suffix, contents, owner and lifetimes; failure changes nothing.
314pub unsafe trait Split: Mutable {}
315
316/// # Safety
317/// Freezing retains the exact backing, initialized range, contents, owner and lifetimes.
318/// It allocates, copies and clones nothing and introduces no sharing.
319pub unsafe trait Freeze: Source + Sized {
320    type Output: Source;
321
322    fn freeze(self) -> Self::Output;
323}
324
325/// # Safety
326/// Retain source borrows and stable `len`; initialize exactly that prefix once.
327/// Never read uninitialized output, retain its access, or invalidate source borrows.
328pub unsafe trait Initializer {
329    fn len(&self) -> usize;
330
331    fn is_empty(&self) -> bool {
332        self.len() == 0
333    }
334
335    /// # Safety
336    /// `target` exclusively retains at least `self.len()` writable bytes.
337    unsafe fn initialize(self, target: *mut mem::MaybeUninit<u8>);
338}
339
340pub use store::Backing;
341pub(in crate::buffer) use store::{Debit, Header, Heap, Policy, Rc};
342
343mod length;
344pub use length::Length;
345pub(in crate::buffer) use length::truncate;
346mod limit;
347pub use limit::Limit;
348mod selection;
349pub(in crate::buffer) use selection::Selection;
350pub use selection::{Consumed, Slice};
351
352/// One proven non-empty span borrowed from its source.
353#[repr(transparent)]
354pub struct Chunk<'data, const MAX: usize = { usize::MAX }> {
355    bytes: &'data [u8],
356}
357
358/// Borrows exactly `len` initialized bytes at `start` of one allocation.
359/// # Safety
360/// `pointer.add(start)` must be valid. A nonempty selected range must contain
361/// `len` initialized bytes in one allocation retained for `'a`, without
362/// overlapping exclusive access. The nonnull selected pointer and extent must
363/// satisfy [`from_raw_parts`], including its `isize` bound and empty-range rules.
364pub(in crate::buffer) unsafe fn range<'a>(
365    pointer: *const u8,
366    start: usize,
367    len: usize,
368) -> &'a [u8] {
369    // SAFETY: the caller proved this exact initialized subrange of one allocation.
370    unsafe { from_raw_parts(pointer.add(start), len) }
371}
372
373/// Borrows the same initialized subrange exclusively.
374///
375/// # Safety
376/// As [`range`], with exclusive access to the selected range for `'a`.
377/// Other accesses during that loan must be disjoint; the selected pointer and
378/// extent must satisfy [`from_raw_parts_mut`], including its empty-range rules.
379pub(in crate::buffer) unsafe fn range_mut<'a>(
380    pointer: *mut u8,
381    start: usize,
382    len: usize,
383) -> &'a mut [u8] {
384    // SAFETY: the caller proved this exact initialized subrange and its exclusive retention.
385    unsafe { from_raw_parts_mut(pointer.add(start), len) }
386}
387
388impl<'data, const MAX: usize> Chunk<'data, MAX> {
389    /// Retains one exact initialized span from its original immutable borrow.
390    ///
391    /// # Safety
392    /// `bytes` is non-empty and `bytes.len() <= MAX`.
393    pub unsafe fn new(bytes: &'data [u8]) -> Self {
394        Self { bytes }
395    }
396
397    pub const fn bytes(&self) -> &'data [u8] {
398        self.bytes
399    }
400
401    pub const fn len(&self) -> num::bounded::NonZeroUsize<1, MAX> {
402        // SAFETY: construction proves the retained span is non-empty and bounded by MAX.
403        unsafe { num::bounded::raw::nonzero_usize(self.bytes.len()) }
404    }
405}
406
407const _: () = {
408    assert!(mem::size_of::<Chunk<'static>>() == mem::size_of::<&[u8]>());
409    assert!(mem::size_of::<Option<Chunk<'static>>>() == mem::size_of::<&[u8]>());
410};
411
412/// Copies slices consecutively without publishing a length.
413///
414/// # Safety
415/// The finite source sequence's total length must fit `isize` without overflow.
416/// `target` must be nonnull and retain exclusive writable storage for that range
417/// in one allocation; an aligned dangling pointer is allowed for a zero total.
418/// Sources must remain valid and disjoint from the entire destination throughout
419/// the call. Iterator callbacks must preserve these conditions and must not
420/// access the destination.
421pub unsafe fn copy_slices<'a>(sources: impl IntoIterator<Item = &'a [u8]>, target: *mut u8) {
422    let mut offset = 0;
423    for source in sources {
424        // SAFETY: the caller retains all sources and their complete disjoint target.
425        unsafe { source.copy_to(target.add(offset)) };
426        offset += source.len();
427    }
428}