o3 0.61.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
use std::{num::NonZero, ops, ptr};

pub(in crate::buffer) use prefix::Prefix;
pub(in crate::buffer) use tag::Header;
pub use tag::Tag;
pub(in crate::buffer) use value::{Complete, Empty, Init};

use crate::{
    buffer,
    buffer::{
        pool,
        pool::owners,
        resident,
        storage::{alloc, provided, regions},
    },
    mem::rc,
};

/// # Safety
/// The sources retain immutable bytes whose complete sum equals the capacity.
/// Their copy operation initializes that complete admitted destination exactly once.
#[inline(always)]
pub(in crate::buffer) unsafe fn try_init<P: crate::buffer::raw::Policy>(
    capacity: NonZero<u32>,
    sources: impl crate::buffer::raw::SliceExt,
    seed: P,
) -> Result<regions::Init<P>, alloc::Error<P::Failure>> {
    let mut heap = crate::buffer::raw::Heap::try_new(seed, capacity)?;
    // SAFETY: the retained sources exactly fill this fresh disjoint allocation.
    unsafe { sources.copy_to(heap.as_mut_ptr().cast()) };
    // SAFETY: copying every retained source initialized the complete allocation.
    Ok(unsafe { regions::Init::new(heap) })
}

mod prefix;
mod tag;
mod value;

pub(in crate::buffer) mod retained {
    use super::{Extent, ResidentBacking, Shared, resident};
    use crate::buffer::{self, raw, storage};

    #[derive(Debug)]
    enum Backing<'d> {
        Unique(raw::Heap<resident::Budget<'d>>),
        Shared(resident::State<'d>),
    }

    #[derive(Debug)]
    #[repr(transparent)]
    pub struct Owner<'d>(Backing<'d>);

    pub type Retained<'d> = Shared<Owner<'d>>;

    impl<'d> From<storage::Owned<resident::Budget<'d>>> for Retained<'d> {
        #[inline]
        fn from(value: storage::Owned<resident::Budget<'d>>) -> Self {
            let bytes = Extent::from_bytes(value.as_slice());
            let owner = match value.allocation {
                Some(heap) => Backing::Unique(heap),
                None => Backing::Shared(resident::State(resident::Kind::Slice)),
            };
            Self {
                owner: Owner(owner),
                bytes,
            }
        }
    }

    impl<'d> From<resident::Shared<'d>> for Retained<'d> {
        fn from(value: resident::Shared<'d>) -> Self {
            let Shared { owner, bytes } = value;
            Self {
                owner: Owner(Backing::Shared(owner)),
                bytes,
            }
        }
    }

    impl<'d, O: ResidentBacking<'d>> From<Shared<O>> for Retained<'d> {
        fn from(value: Shared<O>) -> Self {
            Self {
                owner: Owner::shared(value.owner.into_kind()),
                bytes: value.bytes,
            }
        }
    }

    impl<'d> Owner<'d> {
        pub(in crate::buffer) const fn shared(kind: resident::Kind<'d>) -> Self {
            Self(Backing::Shared(resident::State(kind)))
        }
    }

    impl<'d> Retained<'d> {
        pub const EMPTY: Self = Shared::empty(Owner::shared(resident::Kind::Slice));

        pub fn into_shared(self) -> resident::Shared<'d> {
            let Self { bytes, owner } = self;
            let owner = match owner.0 {
                Backing::Unique(heap) => {
                    resident::State(resident::Kind::Resident(heap.into_shared()))
                }
                Backing::Shared(owner) => owner,
            };
            Shared { owner, bytes }
        }
    }

    impl buffer::Residency for Owner<'_> {
        #[inline]
        fn resident(&self) -> usize {
            match &self.0 {
                Backing::Unique(heap) => heap.capacity().get() as usize,
                Backing::Shared(owner) => owner.resident(),
            }
        }
    }

    const _: () = {
        assert!(size_of::<Retained<'static>>() == size_of::<resident::Shared<'static>>());
        assert!(size_of::<Option<Retained<'static>>>() == size_of::<Retained<'static>>());
    };
}

/// Opaque byte coordinates, usable only under an exact backing-owner proof.
/// Public raw contracts may borrow this representation; it exposes no safe views.
#[derive(Debug)]
#[repr(transparent)]
pub struct Extent(ptr::NonNull<[u8]>);

/// Immutable initialized bytes inseparably paired with their retaining owner.
#[derive(Debug)]
#[repr(C)]
pub struct Shared<O = Option<regions::Tag>> {
    owner: O,
    bytes: Extent,
}

/// Completes consumption according to the actual backing's empty-owner policy.
pub trait End: Sized {
    const EMPTY: Option<Self>;
}

impl<O> Empty for Option<O> {
    const EMPTY: Self = None;
}

impl<O: Empty> End for O {
    const EMPTY: Option<Self> = Some(O::EMPTY);
}

impl regions::Extent {
    pub(in crate::buffer) const EMPTY: Self = Self(ptr::NonNull::slice_from_raw_parts(
        ptr::NonNull::dangling(),
        0,
    ));

    /// # Safety
    /// The inclusive address range from `ptr` through `ptr + len` must not wrap.
    /// The allocation need not remain live; coordinates alone expose no bytes.
    pub(in crate::buffer) const unsafe fn new(ptr: ptr::NonNull<u8>, len: usize) -> Self {
        Self(ptr::NonNull::slice_from_raw_parts(ptr, len))
    }

    pub(in crate::buffer) fn from_bytes(bytes: &[u8]) -> Self {
        Self(ptr::NonNull::from(bytes))
    }

    pub(in crate::buffer) const fn len(&self) -> usize {
        self.0.len()
    }

    /// # Safety
    /// The range must be ordered and contained in this exact initialized extent,
    /// proving its length cannot underflow.
    pub(in crate::buffer) unsafe fn restrict(&self, range: ops::Range<usize>) -> Self {
        let len = range.end - range.start;
        let pointer = self.0.cast::<u8>().as_ptr().wrapping_add(range.start);
        // SAFETY: the caller proves this subrange of the original nonwrapping extent.
        unsafe { Self::new(ptr::NonNull::new_unchecked(pointer), len) }
    }
}

const _: () = assert!(size_of::<regions::Extent>() == 2 * size_of::<usize>());

const _: () = {
    assert!(size_of::<regions::Shared<Option<regions::Tag>>>() == 3 * size_of::<usize>());
    assert!(size_of::<Option<regions::Shared<Option<regions::Tag>>>>() == 3 * size_of::<usize>());
    assert!(
        size_of::<regions::Shared<owners::Edge<owners::Plain, pool::Borrowed<'static>>>>()
            == 3 * size_of::<usize>()
    );
    assert!(
        size_of::<Result<regions::Shared<Option<regions::Tag>>, rc::Error>>()
            == size_of::<regions::Shared<Option<regions::Tag>>>()
    );
};

const _: () = assert!(usize::BITS >= 64);

impl<O> regions::Shared<O> {
    pub(in crate::buffer) const fn empty(owner: O) -> Self {
        Self {
            owner,
            bytes: regions::Extent::EMPTY,
        }
    }
    /// # Safety
    /// The extent must form one valid initialized immutable slice retained by
    /// the transferred owner for every region borrow, including after owner moves.
    pub(in crate::buffer) const unsafe fn from_extent(owner: O, extent: regions::Extent) -> Self {
        Self {
            owner,
            bytes: extent,
        }
    }
    pub(in crate::buffer) const fn owner(&self) -> &O {
        &self.owner
    }

    pub fn as_slice(&self) -> &[u8] {
        // SAFETY: this owner borrow retains the unchanged initialized extent.
        unsafe { self.bytes.0.as_ref() }
    }

    /// # Safety
    /// Every replacement must remain an initialized subrange of this exact
    /// owner's backing; the owner and its lifetime must remain unchanged.
    pub(in crate::buffer) unsafe fn extent_mut(&mut self) -> &mut regions::Extent {
        &mut self.bytes
    }
    /// # Safety
    /// The bounds must select a subrange of the unchanged current extent.
    pub(in crate::buffer) unsafe fn restrict(&mut self, bounds: ops::Range<usize>) {
        // SAFETY: the caller proves the range; the paired owner remains unchanged.
        self.bytes = unsafe { self.bytes.restrict(bounds) };
    }
}

impl<O: buffer::raw::Retain> regions::Shared<O> {
    pub fn try_clone(&self) -> Result<Self, rc::Error> {
        let extent = regions::Extent(self.bytes.0);
        Ok(Self {
            owner: self.owner.try_retain()?,
            bytes: extent,
        })
    }
    /// # Safety
    /// The slice must be an initialized subrange of this exact region, preserved
    /// by the source borrow until retaining its owner completes.
    pub(in crate::buffer) unsafe fn try_view(&self, bytes: &[u8]) -> Result<Self, rc::Error> {
        Ok(Self {
            owner: self.owner.try_retain()?,
            bytes: regions::Extent::from_bytes(bytes),
        })
    }
}

impl regions::Shared<Option<regions::Tag>> {
    pub fn try_get(&self, range: impl ops::RangeBounds<usize>) -> Result<Option<Self>, rc::Error> {
        let start = range.start_bound().cloned();
        if let ops::Bound::Excluded(usize::MAX) = start {
            return Ok(None);
        }
        let bytes = self.as_slice().get((start, range.end_bound().cloned()));
        drop(range);
        let Some(bytes) = bytes else {
            return Ok(None);
        };
        if bytes.is_empty() {
            return Ok(Some(Self::empty(None)));
        }
        // SAFETY: checked slicing keeps these bytes within this exact source.
        unsafe { self.try_view(bytes) }.map(Some)
    }
}

impl<O> ops::Deref for regions::Shared<O> {
    type Target = [u8];
    fn deref(&self) -> &Self::Target {
        self.as_slice()
    }
}

impl From<regions::Shared<crate::buffer::raw::Rc>> for regions::Shared<Option<regions::Tag>> {
    fn from(region: regions::Shared<crate::buffer::raw::Rc>) -> Self {
        Self {
            owner: Some(regions::Tag::allocation(region.owner)),
            bytes: region.bytes,
        }
    }
}

impl<L, M> From<regions::Shared<owners::Edge<owners::Plain<L>, M>>>
    for regions::Shared<Option<regions::Tag>>
where
    owners::Plain<L>: crate::buffer::raw::Backing,
{
    fn from(region: regions::Shared<owners::Edge<owners::Plain<L>, M>>) -> Self {
        Self {
            owner: regions::Tag::pool(region.owner),
            bytes: region.bytes,
        }
    }
}

impl<'a: 'd, 'd> From<&'a [u8]> for resident::Shared<'d> {
    fn from(bytes: &'a [u8]) -> Self {
        Self {
            owner: resident::State(resident::Kind::Slice),
            bytes: regions::Extent::from_bytes(bytes),
        }
    }
}

// Each implementation moves the owner of the same initialized extent.
pub(in crate::buffer) trait ResidentBacking<'d> {
    fn into_kind(self) -> resident::Kind<'d>;

    fn payer(&self) -> Option<resident::Budget<'d>> {
        None
    }

    fn additional(&self, budget: resident::Budget<'d>, bytes: usize) -> usize {
        match self.payer() {
            Some(payer) if ptr::eq(payer.core(), budget.core()) => 0,
            _ => bytes,
        }
    }
}

impl<'d, O: ResidentBacking<'d>> From<Shared<O>> for resident::Shared<'d> {
    #[inline]
    fn from(region: Shared<O>) -> Self {
        Self {
            owner: resident::State(region.owner.into_kind()),
            bytes: region.bytes,
        }
    }
}

// SAFETY: the existing conversion moves the same owner and initialized extent.
unsafe impl<'d> buffer::raw::Convert<resident::Shared<'d>> for Shared<Option<regions::Tag>> {
    fn into(self) -> resident::Shared<'d> {
        From::from(self)
    }
}

impl<'d> ResidentBacking<'d> for Option<regions::Tag> {
    fn into_kind(self) -> resident::Kind<'d> {
        self.map_or(resident::Kind::Static, resident::Kind::Owned)
    }
}

impl<'d> ResidentBacking<'d> for crate::buffer::raw::Rc<resident::Budget<'d>> {
    fn into_kind(self) -> resident::Kind<'d> {
        resident::Kind::Resident(self)
    }

    fn payer(&self) -> Option<resident::Budget<'d>> {
        Some(self.seed())
    }
}

impl<'d, L> ResidentBacking<'d> for owners::Edge<owners::Plain<L>, pool::Borrowed<'_>>
where
    owners::Plain<L>: crate::buffer::raw::Backing,
{
    fn into_kind(self) -> resident::Kind<'d> {
        regions::Tag::pool(self).into_kind()
    }
}

impl<'d, L: provided::Layout> ResidentBacking<'d> for Option<provided::Account<'d, L>>
where
    resident::Kind<'d>: From<provided::Account<'d, L>>,
{
    fn into_kind(self) -> resident::Kind<'d> {
        match self {
            Some(owner) => owner.into(),
            None => resident::Kind::Slice,
        }
    }

    fn payer(&self) -> Option<resident::Budget<'d>> {
        self.as_ref().map(|owner| owner.payer())
    }
}

impl<'d> resident::Shared<'d> {
    /// Transfers independent backing or a uniquely owned resident allocation.
    /// Resident transfers refund their domain charge without changing the range.
    /// A backing that cannot become independent is returned unchanged.
    pub fn try_owned(mut self) -> Result<regions::Shared<Option<regions::Tag>>, Self> {
        self.prepare_owner();
        self.try_detach()
    }

    /// Makes unique resident backing independent without moving its extent.
    pub fn prepare_owned(&mut self) -> Option<&Self> {
        self.prepare_owner();
        self.scope()
    }

    fn prepare_owner(&mut self) {
        if let resident::Kind::Resident(owner) = &mut self.owner.0 {
            // SAFETY: this exclusive match transfers the actual Rc. try_own has
            // no external execution, and both outcomes republish its owner here.
            let owner = unsafe { ptr::read(owner) };
            let owner = match owner.try_own() {
                Ok(owner) => resident::Kind::Owned(regions::Tag::allocation(owner)),
                Err(owner) => resident::Kind::Resident(owner),
            };
            // SAFETY: the previous Rc was consumed; this writes its sole resulting owner.
            unsafe { ptr::write(&mut self.owner.0, owner) };
        }
    }

    pub fn try_detach(self) -> Result<regions::Shared<Option<regions::Tag>>, Self> {
        let Self { owner, bytes } = self;
        let owner = match owner.0 {
            resident::Kind::Owned(owner) => Some(owner),
            resident::Kind::Static => None,
            resident::Kind::Slice if bytes.len() == 0 => None,
            kind => {
                return Err(Self {
                    owner: resident::State(kind),
                    bytes,
                });
            }
        };
        Ok(regions::Shared { owner, bytes })
    }
}