Skip to main content

o3/mem/raw/
mod.rs

1use std::{
2    array, cell, convert::Infallible, fmt::Debug, hint, marker, mem::MaybeUninit, num::NonZero,
3    ops, ptr,
4};
5
6pub(crate) use account::Account;
7
8use crate::{
9    base::marker::ThreadBound,
10    mem::{credit::fair, lease, quota, rc},
11};
12mod account;
13mod occupied;
14mod owner;
15mod storage;
16mod vacant;
17pub use occupied::Occupied;
18pub use owner::Owner;
19pub use storage::Storage;
20pub use vacant::Vacant;
21
22/// # Safety
23/// `source` is `Some` and remains initialized for the returned loan.
24pub(crate) unsafe fn initialized<T>(source: &Option<T>) -> &T {
25    unsafe { source.as_slice().get_unchecked(0) }
26}
27
28/// # Safety
29/// `source` is `Some` and remains initialized for the returned loan.
30unsafe fn initialized_mut<T>(source: &mut Option<T>) -> &mut T {
31    unsafe { &mut *source.as_mut_slice().as_mut_ptr() }
32}
33
34/// # Safety
35/// Preserve the owner, visible range, resident capacity, and owner lifetimes.
36/// Allocate, copy, and clone nothing; do not introduce sharing.
37pub unsafe trait Convert<T, const BRANCH: u8 = 0> {
38    fn into(self) -> T;
39
40    /// # Safety
41    /// `source` owns one initialized, unpinned Self without loans; `place` is disjoint uninitialized storage.
42    /// Consume source once with `into`'s value and destruction effects; never access or drop source again.
43    unsafe fn take_into(source: *mut Self, place: &mut MaybeUninit<T>)
44    where
45        Self: Sized,
46    {
47        place.write(<Self as Convert<T, BRANCH>>::into(unsafe { source.read() }));
48    }
49}
50
51// SAFETY: identity retains the complete original value and its byte storage.
52unsafe impl<T> Convert<T> for T {
53    fn into(self) -> T {
54        self
55    }
56}
57
58// SAFETY: Infallible has no values, so conversion cannot move owners or bytes,
59// alter ranges or residency, or allocate, copy, clone or introduce sharing.
60unsafe impl Convert<()> for Infallible {
61    fn into(self) {
62        match self {}
63    }
64}
65
66// SAFETY: the selected variant owns this unchanged value and its complete storage.
67unsafe impl<L, R> Convert<crate::base::Either<L, R>, 1> for L {
68    fn into(self) -> crate::base::Either<L, R> {
69        crate::base::Either::Left(self)
70    }
71}
72
73// SAFETY: the selected variant owns this unchanged value and its complete storage.
74unsafe impl<L, R> Convert<crate::base::Either<L, R>, 2> for R {
75    fn into(self) -> crate::base::Either<L, R> {
76        crate::base::Either::Right(self)
77    }
78}
79
80/// Reborrows uninitialized storage for the same number of fitting values.
81/// This view does not reinterpret initialized values or own their destruction.
82pub(crate) fn cast_uninit<T, U, const N: usize>(
83    source: &mut [MaybeUninit<T>; N],
84) -> &mut [MaybeUninit<U>; N] {
85    const {
86        assert!(size_of::<U>() <= size_of::<T>(), "size");
87        assert!(align_of::<T>().is_multiple_of(align_of::<U>()), "align");
88    };
89    // SAFETY: the target array fits the source extent at compatible alignment.
90    // Its elements use U's stride; MaybeUninit permits the untouched contents.
91    // The exclusive view retains the original borrow and allocation owner.
92    unsafe { &mut *ptr::from_mut(source).cast::<[MaybeUninit<U>; N]>() }
93}
94
95/// Embedded thread-local count; only its nominal owner can transition it.
96#[derive(Debug)]
97#[repr(transparent)]
98pub struct Count<W: Counter = u32> {
99    value: cell::Cell<W>,
100    thread: ThreadBound,
101}
102
103impl<W: Counter> Count<W> {
104    pub const fn empty() -> Self {
105        Self {
106            value: cell::Cell::new(W::ZERO),
107            thread: ThreadBound::NEW,
108        }
109    }
110
111    pub const fn one() -> Self {
112        Self {
113            value: cell::Cell::new(W::ONE),
114            thread: ThreadBound::NEW,
115        }
116    }
117}
118
119const _: () = assert!(size_of::<Count>() == size_of::<u32>());
120
121/// One nominal owner domain projected onto its embedded local count.
122/// # Safety
123/// The returned count must remain the exact count for every edge operation.
124pub unsafe trait Edge<W: Counter = u32> {
125    fn count(&self) -> &crate::mem::raw::Count<W>;
126
127    #[inline]
128    fn is_empty(&self) -> bool {
129        self.count().value.get() == W::ZERO
130    }
131
132    #[inline]
133    fn is_unique(&self) -> bool {
134        self.count().value.get() == W::ONE
135    }
136
137    /// Starts the first live owner with one store.
138    /// # Safety
139    /// The caller exclusively owns this empty domain until publication.
140    #[inline]
141    unsafe fn activate(&self) {
142        self.count().value.set(W::ONE);
143    }
144
145    /// Publishes exactly two live edges.
146    /// # Safety
147    /// Consume exclusive ownership of the empty domain or its only live edge.
148    unsafe fn start_pair(&self) {
149        self.count().value.set(W::TWO);
150    }
151
152    /// Transfers the sole counted edge into exclusive uncounted ownership.
153    /// # Safety
154    /// The caller consumes the unique live edge before exposing its replacement.
155    unsafe fn retire(&self) {
156        self.count().value.set(W::ZERO);
157    }
158
159    /// # Safety
160    /// Retain this initialized nonzero domain without releasing edges during the call.
161    /// Success transfers one new edge; exhaustion leaves the count unchanged.
162    #[inline]
163    unsafe fn try_retain(&self) -> Result<(), rc::Error> {
164        let count = self.count();
165        // SAFETY: the caller retains this exact live domain.
166        let current: W = Into::into(unsafe { count.value.get().nonzero() });
167        count
168            .value
169            .set(current.checked_add(W::ONE).ok_or(rc::Error::Exhausted)?);
170        Ok(())
171    }
172
173    /// Consumes exactly one live owner edge and stores the resulting count.
174    /// # Safety
175    /// The caller owns one edge and retires `Last` before reuse.
176    #[inline]
177    unsafe fn release(&self) -> rc::Release {
178        let count = self.count();
179        // SAFETY: the caller transfers one live edge from this exact domain.
180        let current: W = Into::into(unsafe { count.value.get().nonzero() });
181        let next = current - W::ONE;
182        let release = if next == W::ZERO {
183            rc::Release::Last
184        } else {
185            rc::Release::Shared
186        };
187        count.value.set(next);
188        release
189    }
190}
191
192/// # Safety
193/// Safe target access preserves its exact count and allocation until all edges end.
194/// Finalization consumes ownership once; empty domains cannot be reused during it.
195pub unsafe trait Target<W: Counter = u32>: crate::mem::raw::Edge<W> + Sized {
196    /// # Safety
197    /// `pointer` owns the exact initialized allocation after its last counted
198    /// edge ended. Its count is zero and no outstanding borrow can access it.
199    unsafe fn destroy(pointer: ptr::NonNull<Self>);
200}
201
202/// # Safety
203/// `get` returns the immutable component vector; AXES is within 0..N and omitted axes are zero.
204/// Every operation preserves exact admission, all-or-nothing commit and conserved refunds.
205pub unsafe trait Amount<const N: usize, W: crate::mem::raw::Word>: Copy + Eq {
206    const AXES: ops::Range<usize> = 0..N;
207
208    fn get(self) -> [W; N];
209
210    fn try_acquire<const COMMIT: bool>(
211        self,
212        held: &cell::Cell<[W; N]>,
213        shared: &cell::Cell<[W; N]>,
214        reserve: &[W; N],
215    ) -> Result<(), fair::Cause<W, N>> {
216        let amount = self.get();
217        let held = held.as_array_of_cells();
218        let shared = shared.as_array_of_cells();
219        let mut next = [const { MaybeUninit::<(W, W)>::uninit() }; N];
220        for index in Self::AXES {
221            let current = held[index].get();
222            let request = amount[index];
223            let Some(total) = current.checked_add(request) else {
224                hint::cold_path();
225                return Err(fair::Cause::Overflow {
226                    axis: fair::Axis::<N>::ALL[index],
227                    held: current,
228                    requested: request,
229                });
230            };
231            let required = required(current, reserve[index], request);
232            let spare = shared[index].get();
233            if required > spare {
234                return Err(fair::Cause::Exhausted {
235                    axis: fair::Axis::<N>::ALL[index],
236                    required,
237                    available: spare,
238                });
239            }
240            if COMMIT {
241                next[index].write((total, spare - required));
242            }
243        }
244        if COMMIT {
245            for index in Self::AXES {
246                // SAFETY: the completed first loop initialized every active-axis pair.
247                let (owned, spare) = unsafe { next[index].assume_init() };
248                held[index].set(owned);
249                shared[index].set(spare);
250            }
251        }
252        Ok(())
253    }
254
255    /// # Safety
256    /// Exact held-plus-amount sums fit W and all shared demand remains available.
257    unsafe fn acquire(
258        self,
259        held: &cell::Cell<[W; N]>,
260        shared: &cell::Cell<[W; N]>,
261        reserve: &[W; N],
262    ) {
263        let amount = self.get();
264        let held = held.as_array_of_cells();
265        let shared = shared.as_array_of_cells();
266        for axis in Self::AXES {
267            let current = held[axis].get();
268            let required = required(current, reserve[axis], amount[axis]);
269            held[axis].set(current + amount[axis]);
270            shared[axis].set(shared[axis].get() - required);
271        }
272    }
273
274    fn demand(self, held: &cell::Cell<[W; N]>, reserve: &[W; N]) -> [W; N] {
275        let amount = self.get();
276        let held = held.as_array_of_cells();
277        array::from_fn(|axis| required(held[axis].get(), reserve[axis], amount[axis]))
278    }
279
280    /// # Safety
281    /// These exact accounts hold this acquisition; conserved capacity bounds its refund.
282    unsafe fn release(
283        self,
284        held: &cell::Cell<[W; N]>,
285        shared: &cell::Cell<[W; N]>,
286        reserve: &[W; N],
287    ) {
288        let amount = self.get();
289        let held = held.as_array_of_cells();
290        let shared = shared.as_array_of_cells();
291        for axis in Self::AXES {
292            let current = held[axis].get();
293            let returned = current.sub_or_zero(reserve[axis]).min(amount[axis]);
294            held[axis].set(current - amount[axis]);
295            shared[axis].set(shared[axis].get() + returned);
296        }
297    }
298}
299
300fn required<W: Word>(held: W, reserve: W, amount: W) -> W {
301    amount.sub_or_zero(reserve.sub_or_zero(held))
302}
303
304// SAFETY: the array is its own immutable component vector.
305unsafe impl<const N: usize, W: crate::mem::raw::Word> Amount<N, W> for [W; N] {
306    fn get(self) -> [W; N] {
307        self
308    }
309}
310
311// SAFETY: admission proves every component sum fits W.
312unsafe impl<const N: usize, W: Word> Sum<N, W> for [W; N] {
313    unsafe fn add_raw(self, other: Self) -> Self {
314        array::from_fn(|axis| self[axis] + other[axis])
315    }
316}
317
318/// Caller-proved sum for compact fair credit.
319/// # Safety
320/// `add_raw` returns the exact componentwise sum when every component fits.
321pub unsafe trait Sum<const N: usize, W: Word>: Amount<N, W> {
322    /// Adds two values after the caller proves that every component fits.
323    /// # Safety
324    /// The componentwise sum must be representable by `W`.
325    unsafe fn add_raw(self, other: Self) -> Self;
326}
327
328/// # Safety
329/// Representable arithmetic is exact.
330/// `checked_add` rejects overflow; `sub_or_zero` clamps negative differences to zero.
331pub unsafe trait Word:
332    Copy + Eq + Ord + ops::Add<Output = Self> + ops::Sub<Output = Self> + owner::Sealed
333{
334    const ZERO: Self;
335
336    fn checked_add(self, other: Self) -> Option<Self>;
337
338    fn sub_or_zero(self, other: Self) -> Self;
339}
340
341// SAFETY: u32 is sealed; checked addition rejects overflow and subtraction saturates.
342unsafe impl Word for u32 {
343    const ZERO: Self = 0;
344
345    fn checked_add(self, other: Self) -> Option<Self> {
346        self.checked_add(other)
347    }
348
349    fn sub_or_zero(self, other: Self) -> Self {
350        self.saturating_sub(other)
351    }
352}
353
354// SAFETY: usize is sealed; checked addition rejects overflow and subtraction saturates.
355unsafe impl Word for usize {
356    const ZERO: Self = 0;
357
358    fn checked_add(self, other: Self) -> Option<Self> {
359        self.checked_add(other)
360    }
361
362    fn sub_or_zero(self, other: Self) -> Self {
363        self.saturating_sub(other)
364    }
365}
366
367/// Supported local reference-count integers and their nonzero representations.
368pub trait Counter: Word {
369    type NonZero: Copy + Debug + Into<Self>;
370
371    const ONE: Self;
372    const TWO: Self;
373
374    /// # Safety
375    /// The value is nonzero.
376    unsafe fn nonzero(self) -> Self::NonZero;
377}
378
379impl Counter for u32 {
380    type NonZero = NonZero<Self>;
381
382    const ONE: Self = 1;
383    const TWO: Self = 2;
384
385    unsafe fn nonzero(self) -> Self::NonZero {
386        // SAFETY: the caller proves the count is nonzero.
387        unsafe { NonZero::new_unchecked(self) }
388    }
389}
390
391impl Counter for usize {
392    type NonZero = NonZero<Self>;
393
394    const ONE: Self = 1;
395    const TWO: Self = 2;
396
397    unsafe fn nonzero(self) -> Self::NonZero {
398        // SAFETY: the caller proves the count is nonzero.
399        unsafe { NonZero::new_unchecked(self) }
400    }
401}
402
403/// A reservation which can split exclusive child leases through shared access.
404#[must_use = "unused quota is returned when the shared reservation is dropped"]
405#[repr(C)]
406pub struct Shared<'source, Tag = (), M = lease::Sealed> {
407    source: &'source Account,
408    remaining: quota::Ledger<Tag>,
409    mode: marker::PhantomData<M>,
410}
411
412impl<'source, Tag, M> Shared<'source, Tag, M> {
413    pub fn reserve_up<SourceTag>(source: &'source quota::Ledger<SourceTag>, limit: usize) -> Self {
414        Self {
415            source: &source.remaining,
416            remaining: quota::Ledger::new(source.remaining.reserve_up(limit)),
417            mode: marker::PhantomData,
418        }
419    }
420
421    pub fn reserve_all<SourceTag>(source: &'source quota::Ledger<SourceTag>) -> Self {
422        Self::reserve_up(source, usize::MAX)
423    }
424
425    pub fn lease_up_to<ChildTag>(&self, limit: usize) -> quota::Lease<'_, ChildTag> {
426        quota::Lease::reserve_up(&self.remaining, limit)
427    }
428
429    pub fn remaining(&self) -> usize {
430        self.remaining.remaining()
431    }
432}
433
434impl<'source, Tag> Shared<'source, Tag, lease::Open> {
435    /// Reserves `limit - 1` refundable units; `debit` charges one more unit.
436    pub fn reserve<SourceTag>(
437        source: &'source quota::Ledger<SourceTag>,
438        limit: NonZero<usize>,
439        debit: bool,
440    ) -> Option<Self> {
441        let unused = limit.get() - 1;
442        let source = &source.remaining;
443        source.reserve(unused + usize::from(debit)).ok()?;
444        Some(Self {
445            source,
446            remaining: quota::Ledger::new(unused),
447            mode: marker::PhantomData,
448        })
449    }
450
451    /// # Safety
452    /// `unused` is this reservation's exact unused quota, excluding outstanding debits.
453    pub unsafe fn settle(&mut self, unused: usize) {
454        self.remaining.reset(unused);
455    }
456}
457
458impl<Tag, M> Drop for Shared<'_, Tag, M> {
459    fn drop(&mut self) {
460        self.source.refund_spare(self.remaining.remaining());
461    }
462}