Skip to main content

o3/buffer/raw/
mod.rs

1use std::{
2    marker,
3    mem::MaybeUninit,
4    num::NonZero,
5    ops, ptr,
6    slice::{from_raw_parts, from_raw_parts_mut},
7};
8
9use crate::{
10    base::num::bounded,
11    buffer::{
12        self,
13        pool::owners,
14        resident::{self, staging},
15        segments::scatter::Take,
16        storage::{self, provided, range::Error},
17        write::consume::{self, scope},
18    },
19    mem::{self, Rejected, rc},
20};
21
22mod chunks;
23mod input;
24mod length;
25mod limit;
26mod output;
27mod policy;
28mod seal;
29mod slices;
30
31pub use chunks::Chunks;
32pub use input::Input;
33
34pub use length::Length;
35pub use limit::Limit;
36pub use output::Output;
37pub(in crate::buffer) use output::{Exclusive, Prefix};
38pub use policy::Policy;
39pub(in crate::buffer) use policy::{Header, Heap, Window};
40pub(in crate::buffer) use seal::Seal;
41pub use slices::Slices;
42pub(in crate::buffer) use slices::Transfer;
43
44/// # Safety
45/// The Source contract holds and `AsRef` exposes that exact initialized range.
46/// Consumption must advance exactly the proved prefix and preserve the remaining bytes.
47pub unsafe trait Consume: AsRef<[u8]> {
48    fn consume<const MAX: u32>(prefix: Input<&mut Self, scope::Prefix<MAX>>);
49}
50
51/// One owner edge that can retain the same backing independently.
52/// # Safety
53/// `try_retain` preserves backing identity, access, and branded lifetimes.
54pub unsafe trait Retain: Sized {
55    fn try_retain(&self) -> Result<Self, rc::Error>;
56}
57
58// SAFETY: cloning this counted edge preserves its target, access, and lifetime.
59unsafe impl<T: mem::raw::Target> Retain for mem::raw::Owner<T> {
60    fn try_retain(&self) -> Result<Self, rc::Error> {
61        self.try_clone()
62    }
63}
64
65// SAFETY: Some retains the same owner and lifetime; None retains no backing.
66unsafe impl<T: Retain> Retain for Option<T> {
67    fn try_retain(&self) -> Result<Self, rc::Error> {
68        self.as_ref().map(T::try_retain).transpose()
69    }
70}
71
72/// # Safety
73/// Shared access preserves its exact backing, range, and contents until exclusive mutation.
74/// Writes preserve the initialized prefix; successful writes append their complete input.
75pub unsafe trait Source: AsRef<[u8]> {
76    /// # Safety
77    /// The bounds lie within this unchanged source's initialized bytes.
78    unsafe fn view(&self, bounds: ops::Range<usize>) -> buffer::View<'_, Self> {
79        buffer::View {
80            source: self,
81            // SAFETY: the caller admits this range of the retained source.
82            proof: unsafe { self.as_ref().get_unchecked(bounds) },
83        }
84    }
85
86    /// # Safety
87    /// This source's complete unchanged visible range is valid UTF-8.
88    unsafe fn into_str(self) -> storage::Str<Self>
89    where
90        Self: Sized,
91    {
92        // SAFETY: the caller proved UTF-8 for this complete immutable source.
93        unsafe { storage::Str::new(self) }
94    }
95
96    /// # Safety
97    /// This source's unchanged initialized extent is nonempty.
98    unsafe fn nonempty(self) -> storage::NonEmpty<Self>
99    where
100        Self: Sized,
101    {
102        // SAFETY: the caller proved nonemptiness on this retained source.
103        unsafe { storage::raw::present(self) }
104    }
105}
106
107/// # Safety
108/// `AsMut::as_mut` returns the full Source range with its pre-call pointer and length, unchanged after the loan.
109/// The call changes no owner, descriptor, extent, or bytes; caller slice writes are allowed, and other exclusive operations retain their own contracts.
110pub unsafe trait Mutable: Source + AsMut<[u8]> {}
111
112/// # Safety
113/// Every `provided::Mutable::try_take` implementation returns the exact requested prefix
114/// and retains its disjoint suffix, contents, owner and lifetimes; failure changes nothing.
115pub unsafe trait Split: Mutable {}
116
117/// # Safety
118/// Freezing retains the exact backing, initialized range, contents, owner and lifetimes.
119/// It allocates, copies and clones nothing and introduces no sharing.
120pub unsafe trait Freeze: Source + Sized {
121    type Output: Source;
122
123    fn freeze(self) -> Self::Output;
124}
125
126/// # Safety
127/// The initialized range at `pointer.add(start)` stays retained for `'a`, without
128/// overlapping exclusive access, and satisfies every `from_raw_parts` requirement.
129pub(in crate::buffer) unsafe fn range<'a>(
130    pointer: *const u8,
131    start: usize,
132    len: usize,
133) -> &'a [u8] {
134    // SAFETY: the caller proved this exact initialized subrange of one allocation.
135    unsafe { from_raw_parts(pointer.add(start), len) }
136}
137
138/// # Safety
139/// As [`range`], with exclusive access for `'a` and every `from_raw_parts_mut` requirement.
140pub(in crate::buffer) unsafe fn range_mut<'a>(
141    pointer: *mut u8,
142    start: usize,
143    len: usize,
144) -> &'a mut [u8] {
145    // SAFETY: the caller proved this exact initialized subrange and its exclusive retention.
146    unsafe { from_raw_parts_mut(pointer.add(start), len) }
147}
148
149/// # Safety
150/// Shared access preserves the visible range, backing and contents until mutation.
151/// Projection applies the proved range and preserves the owner's empty-storage policy.
152pub unsafe trait Store: AsRef<[u8]> + Sized {
153    fn advance<const MAX: u32>(prefix: Input<&mut Self, scope::Prefix<MAX>>) {
154        let (source, consumed) = prefix.into_parts();
155        let end = source.as_ref().len();
156        // SAFETY: this admitted total prefix still retains the exact exclusive source.
157        Self::project(unsafe { Input::from_parts(source, consumed.count().get() as usize..end) });
158    }
159
160    /// Returns a canonical empty owner, or `None` to restrict the current owner
161    /// according to its own empty-storage policy.
162    /// A returned owner must expose no bytes and require no allocation.
163    fn empty() -> Option<Self> {
164        None
165    }
166
167    fn project(slice: Input<&mut Self, ops::Range<usize>>) {
168        if slice.proof.is_empty()
169            && let Some(empty) = Self::empty()
170        {
171            *slice.source = empty;
172            return;
173        }
174        Self::restrict(slice);
175    }
176
177    fn try_project(mut self, bounds: ops::Range<usize>) -> Result<Self, Rejected<Self, Error>> {
178        match Input::try_select(&mut self, bounds) {
179            Ok(slice) => {
180                Self::project(slice);
181                Ok(self)
182            }
183            Err(error) => Err(Rejected::new(self, error)),
184        }
185    }
186
187    /// Applies the selected extent. Nonempty selections must retain their original
188    /// backing; empty selections preserve this owner's empty-storage policy.
189    fn restrict(slice: Input<&mut Self, ops::Range<usize>>);
190}
191
192/// # Safety
193/// Release the same backing once after all access ends; static dimensions match its Header/Slot geometry.
194/// COUNTED is true whenever a live Span can share its slot before consuming publication.
195pub unsafe trait Backing {
196    const COUNTED: bool = false;
197    const SLOTS: Option<u32> = None;
198    const CAPACITY: Option<NonZero<u32>> = None;
199
200    /// # Safety
201    /// `core` must be the terminal allocation edge for this backing kind.
202    unsafe fn release<S>(core: owners::raw::Ptr<Self, S>)
203    where
204        Self: Sized,
205    {
206        // SAFETY: the caller transfers this backing's terminal allocation edge.
207        unsafe { core.deallocate() };
208    }
209}
210
211pub(in crate::buffer) fn staging_owner(
212    header: staging::Header<'_>,
213) -> Result<mem::raw::Owner<staging::Header<'_>>, resident::AllocError> {
214    let state = <Box<_> as crate::alloc::BoxExt<_>>::try_new(header)
215        .map_err(resident::AllocError::Exhausted)?;
216    // SAFETY: this freshly initialized Header transfers its initial counted edge and its box.
217    Ok(unsafe { mem::raw::Owner::from_raw(ptr::NonNull::from(Box::leak(state))) })
218}
219
220pub(in crate::buffer) fn select<const SUFFIX: bool, S: Store>(
221    input: Input<&mut S, (usize, usize)>,
222) -> usize {
223    let (start, rest) = input.proof;
224    let proof = if SUFFIX {
225        start..start + rest
226    } else {
227        0..start
228    };
229    S::project(Input {
230        source: input.source,
231        proof,
232    });
233    start
234}
235
236pub(in crate::buffer) fn select_max<const SUFFIX: bool, S: Store>(
237    source: &mut S,
238    max: usize,
239) -> usize {
240    let end = source.as_ref().len();
241    let start = max.min(end);
242    select::<SUFFIX, _>(Input {
243        source,
244        proof: (start, end - start),
245    })
246}
247
248pub(in crate::buffer) fn strict_prefix<S: Segment>(
249    source: &mut S,
250    end: usize,
251) -> Option<Input<&mut S, ops::RangeTo<usize>>> {
252    if end < source.as_ref().len() {
253        Some(Input {
254            source,
255            proof: ..end,
256        })
257    } else {
258        None
259    }
260}
261
262/// Retained bytes that narrow without copying their payload.
263/// # Safety
264/// Shared access preserves the range, and consuming advances its exact prefix.
265pub unsafe trait Segment:
266    Seal + Source + Store + consume::Consume + buffer::Residency
267{
268    /// # Safety
269    /// Preserve this owner's exact initialized extent and its original backing.
270    unsafe fn extent(&mut self) -> &mut storage::raw::Extent;
271
272    fn try_share(view: &storage::NonEmpty<buffer::View<'_, Self>>) -> Result<Self, rc::Error>;
273
274    fn try_clone(&self) -> Result<Self, rc::Error> {
275        buffer::View::new(self).try_retain()
276    }
277
278    fn try_get(&self, range: ops::Range<usize>) -> Result<Option<Self>, rc::Error> {
279        buffer::View::new(self)
280            .get(range)
281            .map(buffer::View::<Self>::try_retain)
282            .transpose()
283    }
284
285    /// Retains an in-bounds owner subrange without copying its payload.
286    /// # Safety
287    /// `range` must lie within the owner's visible bytes.
288    unsafe fn try_project(&self, range: ops::Range<usize>) -> Result<Self, rc::Error> {
289        // SAFETY: the caller admits this range of the unchanged owner.
290        unsafe { Source::view(self, range) }.try_retain()
291    }
292
293    /// Retains at most `limit` leading bytes without copying the payload.
294    fn prefix(mut self, limit: usize) -> Self {
295        select_max::<false, _>(&mut self, limit);
296        self
297    }
298
299    /// Splits off at most `limit` visible bytes without copying the payload.
300    fn try_split(mut self, limit: usize) -> Result<(Self, Option<Self>), (rc::Error, Self)> {
301        let Some(tail) = strict_prefix(&mut self, limit) else {
302            return Ok((self, None));
303        };
304        // SAFETY: strict_prefix admitted these bytes on the exclusively held source.
305        let prefix = match unsafe { Source::view(&*tail.source, 0..tail.proof.end) }.try_retain() {
306            Ok(result) => result,
307            Err(error) => return Err((error, self)),
308        };
309        tail.commit();
310        Ok((prefix, Some(self)))
311    }
312
313    /// Removes at most `amount` visible bytes without copying the payload.
314    fn suffix(mut self, amount: usize) -> Option<Self> {
315        strict_prefix(&mut self, amount)?.commit();
316        Some(self)
317    }
318}
319
320/// Projects fixed-residency items admitted by their original native context.
321pub trait Fixed<T> {
322    fn resident(&self) -> NonZero<u32>;
323
324    /// # Safety
325    /// Own this context's unique item; its full retained backing fits `resident()`.
326    /// Its prefix is initialized; `limit` is that ceiling and backing/layout live for `'a`.
327    unsafe fn project<'a, 'id>(&'a self, item: &'a mut T, limit: Limit<'id>)
328    -> Projection<'a, 'id>;
329
330    /// # Safety
331    /// Own its context's unique initialized item; full backing fits `resident()` and lives for `'d`.
332    /// Its layout and `resident()` match this arena's unchanged layout and resident ceiling.
333    unsafe fn insert<'d>(
334        vacant: provided::raw::Vacant<'d, T, (), &'d Self>,
335        item: T,
336    ) -> provided::raw::Slice<&'d mut [u8], provided::raw::Owner<'d, ()>>
337    where
338        Self: Sized,
339    {
340        // SAFETY: the caller admitted this unique item for the vacancy's fixed context.
341        unsafe { vacant.insert_fixed(item) }
342    }
343}
344
345/// A mutable projection proven to fit its resident byte ceiling.
346#[repr(transparent)]
347pub struct Projection<'a, 'id> {
348    bytes: &'a mut [u8],
349    operation: marker::PhantomData<fn(&'id mut ()) -> &'id mut ()>,
350}
351
352impl<'a> Projection<'a, '_> {
353    pub(in crate::buffer) const fn into_inner(self) -> &'a mut [u8] {
354        self.bytes
355    }
356}
357
358/// Copies a finite sequence into one admitted exclusive destination.
359pub trait IteratorExt<'a>: IntoIterator<Item = &'a [u8]> + Sized {
360    /// # Safety
361    /// The byte sum fits `isize`; target is nonnull and writable in one allocation (dangling for zero).
362    /// Sources stay valid and disjoint; iteration neither accesses nor invalidates the target.
363    unsafe fn copy_to(self, target: *mut u8) {
364        let mut offset = 0;
365        for source in self {
366            // SAFETY: the caller retains this source and its complete disjoint destination.
367            unsafe { Transfer::copy_to(source, target.add(offset)) };
368            offset += source.len();
369        }
370    }
371}
372
373impl<'a, I: IntoIterator<Item = &'a [u8]>> IteratorExt<'a> for I {}
374
375/// # Safety
376/// Retain source borrows and stable `len`; initialize the complete target once.
377/// Never read uninitialized output, retain its access, or invalidate source borrows.
378pub unsafe trait Initializer {
379    fn len(&self) -> usize;
380
381    fn is_empty(&self) -> bool {
382        self.len() == 0
383    }
384
385    /// # Safety
386    /// `target.len()` equals this unchanged source's previously admitted `len()`.
387    unsafe fn initialize(self, target: &mut [MaybeUninit<u8>]);
388}
389
390// SAFETY: the immutable array borrow keeps its N initialized bytes unchanged.
391unsafe impl<const N: usize> Initializer for &[u8; N] {
392    fn len(&self) -> usize {
393        N
394    }
395
396    unsafe fn initialize(self, target: &mut [MaybeUninit<u8>]) {
397        // SAFETY: the caller supplies this source's exact disjoint output extent.
398        unsafe { Transfer::copy_to(self.as_slice(), target.as_mut_ptr().cast()) };
399    }
400}
401
402/// One proven non-empty span borrowed from its source.
403#[repr(transparent)]
404pub struct Chunk<'data, const MAX: usize = { usize::MAX }> {
405    bytes: &'data [u8],
406}
407
408impl<'data, const MAX: usize> Chunk<'data, MAX> {
409    /// Retains one exact initialized span from its original immutable borrow.
410    ///
411    /// # Safety
412    /// `bytes` is non-empty and `bytes.len() <= MAX`.
413    pub unsafe fn new(bytes: &'data [u8]) -> Self {
414        Self { bytes }
415    }
416
417    pub const fn bytes(&self) -> &'data [u8] {
418        self.bytes
419    }
420
421    pub const fn len(&self) -> bounded::NonZeroUsize<1, MAX> {
422        // SAFETY: construction proves the retained span is non-empty and bounded by MAX.
423        unsafe { bounded::raw::nonzero_usize(self.bytes.len()) }
424    }
425}
426
427impl<'a, T: AsRef<[u8]>> From<&'a storage::NonEmpty<T>> for Chunk<'a> {
428    fn from(owner: &'a storage::NonEmpty<T>) -> Self {
429        Self {
430            bytes: owner.as_ref(),
431        }
432    }
433}
434
435const _: () = {
436    assert!(size_of::<Chunk<'static>>() == size_of::<&[u8]>());
437    assert!(size_of::<Option<Chunk<'static>>>() == size_of::<&[u8]>());
438};
439
440/// Exact-progress traversal over one immutable scattered source.
441///
442/// # Safety
443/// Progress, cap, remaining length, and `'data` must all be exact.
444pub unsafe trait Scatter<'data> {
445    fn remaining(&self) -> usize;
446
447    /// Advances to an admitted byte offset in this exact cursor.
448    fn seek(mut self, offset: usize) -> Option<Self>
449    where
450        Self: Sized,
451    {
452        if offset > self.remaining() {
453            return None;
454        }
455        Take::<_>::new(&mut self, offset).finish();
456        Some(self)
457    }
458
459    /// Borrows at most the requested number of remaining bytes.
460    fn take_bytes(&mut self, limit: usize) -> Take<'_, 'data, Self>
461    where
462        Self: Sized,
463    {
464        Take::<_>::new(self, limit)
465    }
466
467    /// Advances by a nonempty prefix of the admitted remaining bytes.
468    ///
469    /// # Safety
470    /// `cap <= self.remaining()` and `cap <= MAX`; output advances exactly `1..=cap` bytes.
471    unsafe fn advance<const MAX: usize>(&mut self, cap: NonZero<usize>) -> Chunk<'data, MAX>;
472}
473
474/// # Safety
475/// Capacity and backing stay stable through access; the initialized prefix fits and spare is exclusive.
476/// Truncation keeps min(len, current_len); completion extends by exactly amount after external access ends.
477pub unsafe trait Target: AsRef<[u8]> {
478    fn capacity(&self) -> usize;
479    fn truncate(&mut self, len: usize);
480
481    /// # Safety
482    /// Writes may initialize bytes, but must never deinitialize the backing.
483    unsafe fn spare(&mut self) -> &mut [MaybeUninit<u8>];
484
485    /// # Safety
486    /// Native access ended and initialized `amount` bytes of this unchanged suffix.
487    unsafe fn complete(&mut self, amount: usize);
488
489    /// # Safety
490    /// The initialized prefix fits capacity and all external access has ended.
491    unsafe fn set_len(&mut self, len: usize);
492}