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
use std::{
    array, cell, convert::Infallible, fmt::Debug, hint, marker, mem::MaybeUninit, num::NonZero,
    ops, ptr,
};

pub(crate) use account::Account;

use crate::{
    base::marker::ThreadBound,
    mem::{credit::fair, lease, quota, rc},
};
mod account;
mod occupied;
mod owner;
mod storage;
mod vacant;
pub use occupied::Occupied;
pub use owner::Owner;
pub use storage::Storage;
pub use vacant::Vacant;

/// # Safety
/// `source` is `Some` and remains initialized for the returned loan.
pub(crate) unsafe fn initialized<T>(source: &Option<T>) -> &T {
    unsafe { source.as_slice().get_unchecked(0) }
}

/// # Safety
/// `source` is `Some` and remains initialized for the returned loan.
unsafe fn initialized_mut<T>(source: &mut Option<T>) -> &mut T {
    unsafe { &mut *source.as_mut_slice().as_mut_ptr() }
}

/// # Safety
/// Preserve the owner, visible range, resident capacity, and owner lifetimes.
/// Allocate, copy, and clone nothing; do not introduce sharing.
pub unsafe trait Convert<T, const BRANCH: u8 = 0> {
    fn into(self) -> T;

    /// # Safety
    /// `source` owns one initialized, unpinned Self without loans; `place` is disjoint uninitialized storage.
    /// Consume source once with `into`'s value and destruction effects; never access or drop source again.
    unsafe fn take_into(source: *mut Self, place: &mut MaybeUninit<T>)
    where
        Self: Sized,
    {
        place.write(<Self as Convert<T, BRANCH>>::into(unsafe { source.read() }));
    }
}

// SAFETY: identity retains the complete original value and its byte storage.
unsafe impl<T> Convert<T> for T {
    fn into(self) -> T {
        self
    }
}

// SAFETY: Infallible has no values, so conversion cannot move owners or bytes,
// alter ranges or residency, or allocate, copy, clone or introduce sharing.
unsafe impl Convert<()> for Infallible {
    fn into(self) {
        match self {}
    }
}

// SAFETY: the selected variant owns this unchanged value and its complete storage.
unsafe impl<L, R> Convert<crate::base::Either<L, R>, 1> for L {
    fn into(self) -> crate::base::Either<L, R> {
        crate::base::Either::Left(self)
    }
}

// SAFETY: the selected variant owns this unchanged value and its complete storage.
unsafe impl<L, R> Convert<crate::base::Either<L, R>, 2> for R {
    fn into(self) -> crate::base::Either<L, R> {
        crate::base::Either::Right(self)
    }
}

/// Reborrows uninitialized storage for the same number of fitting values.
/// This view does not reinterpret initialized values or own their destruction.
pub(crate) fn cast_uninit<T, U, const N: usize>(
    source: &mut [MaybeUninit<T>; N],
) -> &mut [MaybeUninit<U>; N] {
    const {
        assert!(size_of::<U>() <= size_of::<T>(), "size");
        assert!(align_of::<T>().is_multiple_of(align_of::<U>()), "align");
    };
    // SAFETY: the target array fits the source extent at compatible alignment.
    // Its elements use U's stride; MaybeUninit permits the untouched contents.
    // The exclusive view retains the original borrow and allocation owner.
    unsafe { &mut *ptr::from_mut(source).cast::<[MaybeUninit<U>; N]>() }
}

/// Embedded thread-local count; only its nominal owner can transition it.
#[derive(Debug)]
#[repr(transparent)]
pub struct Count<W: Counter = u32> {
    value: cell::Cell<W>,
    thread: ThreadBound,
}

impl<W: Counter> Count<W> {
    pub const fn empty() -> Self {
        Self {
            value: cell::Cell::new(W::ZERO),
            thread: ThreadBound::NEW,
        }
    }

    pub const fn one() -> Self {
        Self {
            value: cell::Cell::new(W::ONE),
            thread: ThreadBound::NEW,
        }
    }
}

const _: () = assert!(size_of::<Count>() == size_of::<u32>());

/// One nominal owner domain projected onto its embedded local count.
/// # Safety
/// The returned count must remain the exact count for every edge operation.
pub unsafe trait Edge<W: Counter = u32> {
    fn count(&self) -> &crate::mem::raw::Count<W>;

    #[inline]
    fn is_empty(&self) -> bool {
        self.count().value.get() == W::ZERO
    }

    #[inline]
    fn is_unique(&self) -> bool {
        self.count().value.get() == W::ONE
    }

    /// Starts the first live owner with one store.
    /// # Safety
    /// The caller exclusively owns this empty domain until publication.
    #[inline]
    unsafe fn activate(&self) {
        self.count().value.set(W::ONE);
    }

    /// Publishes exactly two live edges.
    /// # Safety
    /// Consume exclusive ownership of the empty domain or its only live edge.
    unsafe fn start_pair(&self) {
        self.count().value.set(W::TWO);
    }

    /// Transfers the sole counted edge into exclusive uncounted ownership.
    /// # Safety
    /// The caller consumes the unique live edge before exposing its replacement.
    unsafe fn retire(&self) {
        self.count().value.set(W::ZERO);
    }

    /// # Safety
    /// Retain this initialized nonzero domain without releasing edges during the call.
    /// Success transfers one new edge; exhaustion leaves the count unchanged.
    #[inline]
    unsafe fn try_retain(&self) -> Result<(), rc::Error> {
        let count = self.count();
        // SAFETY: the caller retains this exact live domain.
        let current: W = Into::into(unsafe { count.value.get().nonzero() });
        count
            .value
            .set(current.checked_add(W::ONE).ok_or(rc::Error::Exhausted)?);
        Ok(())
    }

    /// Consumes exactly one live owner edge and stores the resulting count.
    /// # Safety
    /// The caller owns one edge and retires `Last` before reuse.
    #[inline]
    unsafe fn release(&self) -> rc::Release {
        let count = self.count();
        // SAFETY: the caller transfers one live edge from this exact domain.
        let current: W = Into::into(unsafe { count.value.get().nonzero() });
        let next = current - W::ONE;
        let release = if next == W::ZERO {
            rc::Release::Last
        } else {
            rc::Release::Shared
        };
        count.value.set(next);
        release
    }
}

/// # Safety
/// Safe target access preserves its exact count and allocation until all edges end.
/// Finalization consumes ownership once; empty domains cannot be reused during it.
pub unsafe trait Target<W: Counter = u32>: crate::mem::raw::Edge<W> + Sized {
    /// # Safety
    /// `pointer` owns the exact initialized allocation after its last counted
    /// edge ended. Its count is zero and no outstanding borrow can access it.
    unsafe fn destroy(pointer: ptr::NonNull<Self>);
}

/// # Safety
/// `get` returns the immutable component vector; AXES is within 0..N and omitted axes are zero.
/// Every operation preserves exact admission, all-or-nothing commit and conserved refunds.
pub unsafe trait Amount<const N: usize, W: crate::mem::raw::Word>: Copy + Eq {
    const AXES: ops::Range<usize> = 0..N;

    fn get(self) -> [W; N];

    fn try_acquire<const COMMIT: bool>(
        self,
        held: &cell::Cell<[W; N]>,
        shared: &cell::Cell<[W; N]>,
        reserve: &[W; N],
    ) -> Result<(), fair::Cause<W, N>> {
        let amount = self.get();
        let held = held.as_array_of_cells();
        let shared = shared.as_array_of_cells();
        let mut next = [const { MaybeUninit::<(W, W)>::uninit() }; N];
        for index in Self::AXES {
            let current = held[index].get();
            let request = amount[index];
            let Some(total) = current.checked_add(request) else {
                hint::cold_path();
                return Err(fair::Cause::Overflow {
                    axis: fair::Axis::<N>::ALL[index],
                    held: current,
                    requested: request,
                });
            };
            let required = required(current, reserve[index], request);
            let spare = shared[index].get();
            if required > spare {
                return Err(fair::Cause::Exhausted {
                    axis: fair::Axis::<N>::ALL[index],
                    required,
                    available: spare,
                });
            }
            if COMMIT {
                next[index].write((total, spare - required));
            }
        }
        if COMMIT {
            for index in Self::AXES {
                // SAFETY: the completed first loop initialized every active-axis pair.
                let (owned, spare) = unsafe { next[index].assume_init() };
                held[index].set(owned);
                shared[index].set(spare);
            }
        }
        Ok(())
    }

    /// # Safety
    /// Exact held-plus-amount sums fit W and all shared demand remains available.
    unsafe fn acquire(
        self,
        held: &cell::Cell<[W; N]>,
        shared: &cell::Cell<[W; N]>,
        reserve: &[W; N],
    ) {
        let amount = self.get();
        let held = held.as_array_of_cells();
        let shared = shared.as_array_of_cells();
        for axis in Self::AXES {
            let current = held[axis].get();
            let required = required(current, reserve[axis], amount[axis]);
            held[axis].set(current + amount[axis]);
            shared[axis].set(shared[axis].get() - required);
        }
    }

    fn demand(self, held: &cell::Cell<[W; N]>, reserve: &[W; N]) -> [W; N] {
        let amount = self.get();
        let held = held.as_array_of_cells();
        array::from_fn(|axis| required(held[axis].get(), reserve[axis], amount[axis]))
    }

    /// # Safety
    /// These exact accounts hold this acquisition; conserved capacity bounds its refund.
    unsafe fn release(
        self,
        held: &cell::Cell<[W; N]>,
        shared: &cell::Cell<[W; N]>,
        reserve: &[W; N],
    ) {
        let amount = self.get();
        let held = held.as_array_of_cells();
        let shared = shared.as_array_of_cells();
        for axis in Self::AXES {
            let current = held[axis].get();
            let returned = current.sub_or_zero(reserve[axis]).min(amount[axis]);
            held[axis].set(current - amount[axis]);
            shared[axis].set(shared[axis].get() + returned);
        }
    }
}

fn required<W: Word>(held: W, reserve: W, amount: W) -> W {
    amount.sub_or_zero(reserve.sub_or_zero(held))
}

// SAFETY: the array is its own immutable component vector.
unsafe impl<const N: usize, W: crate::mem::raw::Word> Amount<N, W> for [W; N] {
    fn get(self) -> [W; N] {
        self
    }
}

// SAFETY: admission proves every component sum fits W.
unsafe impl<const N: usize, W: Word> Sum<N, W> for [W; N] {
    unsafe fn add_raw(self, other: Self) -> Self {
        array::from_fn(|axis| self[axis] + other[axis])
    }
}

/// Caller-proved sum for compact fair credit.
/// # Safety
/// `add_raw` returns the exact componentwise sum when every component fits.
pub unsafe trait Sum<const N: usize, W: Word>: Amount<N, W> {
    /// Adds two values after the caller proves that every component fits.
    /// # Safety
    /// The componentwise sum must be representable by `W`.
    unsafe fn add_raw(self, other: Self) -> Self;
}

/// # Safety
/// Representable arithmetic is exact.
/// `checked_add` rejects overflow; `sub_or_zero` clamps negative differences to zero.
pub unsafe trait Word:
    Copy + Eq + Ord + ops::Add<Output = Self> + ops::Sub<Output = Self> + owner::Sealed
{
    const ZERO: Self;

    fn checked_add(self, other: Self) -> Option<Self>;

    fn sub_or_zero(self, other: Self) -> Self;
}

// SAFETY: u32 is sealed; checked addition rejects overflow and subtraction saturates.
unsafe impl Word for u32 {
    const ZERO: Self = 0;

    fn checked_add(self, other: Self) -> Option<Self> {
        self.checked_add(other)
    }

    fn sub_or_zero(self, other: Self) -> Self {
        self.saturating_sub(other)
    }
}

// SAFETY: usize is sealed; checked addition rejects overflow and subtraction saturates.
unsafe impl Word for usize {
    const ZERO: Self = 0;

    fn checked_add(self, other: Self) -> Option<Self> {
        self.checked_add(other)
    }

    fn sub_or_zero(self, other: Self) -> Self {
        self.saturating_sub(other)
    }
}

/// Supported local reference-count integers and their nonzero representations.
pub trait Counter: Word {
    type NonZero: Copy + Debug + Into<Self>;

    const ONE: Self;
    const TWO: Self;

    /// # Safety
    /// The value is nonzero.
    unsafe fn nonzero(self) -> Self::NonZero;
}

impl Counter for u32 {
    type NonZero = NonZero<Self>;

    const ONE: Self = 1;
    const TWO: Self = 2;

    unsafe fn nonzero(self) -> Self::NonZero {
        // SAFETY: the caller proves the count is nonzero.
        unsafe { NonZero::new_unchecked(self) }
    }
}

impl Counter for usize {
    type NonZero = NonZero<Self>;

    const ONE: Self = 1;
    const TWO: Self = 2;

    unsafe fn nonzero(self) -> Self::NonZero {
        // SAFETY: the caller proves the count is nonzero.
        unsafe { NonZero::new_unchecked(self) }
    }
}

/// A reservation which can split exclusive child leases through shared access.
#[must_use = "unused quota is returned when the shared reservation is dropped"]
#[repr(C)]
pub struct Shared<'source, Tag = (), M = lease::Sealed> {
    source: &'source Account,
    remaining: quota::Ledger<Tag>,
    mode: marker::PhantomData<M>,
}

impl<'source, Tag, M> Shared<'source, Tag, M> {
    pub fn reserve_up<SourceTag>(source: &'source quota::Ledger<SourceTag>, limit: usize) -> Self {
        Self {
            source: &source.remaining,
            remaining: quota::Ledger::new(source.remaining.reserve_up(limit)),
            mode: marker::PhantomData,
        }
    }

    pub fn reserve_all<SourceTag>(source: &'source quota::Ledger<SourceTag>) -> Self {
        Self::reserve_up(source, usize::MAX)
    }

    pub fn lease_up_to<ChildTag>(&self, limit: usize) -> quota::Lease<'_, ChildTag> {
        quota::Lease::reserve_up(&self.remaining, limit)
    }

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

impl<'source, Tag> Shared<'source, Tag, lease::Open> {
    /// Reserves `limit - 1` refundable units; `debit` charges one more unit.
    pub fn reserve<SourceTag>(
        source: &'source quota::Ledger<SourceTag>,
        limit: NonZero<usize>,
        debit: bool,
    ) -> Option<Self> {
        let unused = limit.get() - 1;
        let source = &source.remaining;
        source.reserve(unused + usize::from(debit)).ok()?;
        Some(Self {
            source,
            remaining: quota::Ledger::new(unused),
            mode: marker::PhantomData,
        })
    }

    /// # Safety
    /// `unused` is this reservation's exact unused quota, excluding outstanding debits.
    pub unsafe fn settle(&mut self, unused: usize) {
        self.remaining.reset(unused);
    }
}

impl<Tag, M> Drop for Shared<'_, Tag, M> {
    fn drop(&mut self) {
        self.source.refund_spare(self.remaining.remaining());
    }
}