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
22pub(crate) unsafe fn initialized<T>(source: &Option<T>) -> &T {
25 unsafe { source.as_slice().get_unchecked(0) }
26}
27
28unsafe fn initialized_mut<T>(source: &mut Option<T>) -> &mut T {
31 unsafe { &mut *source.as_mut_slice().as_mut_ptr() }
32}
33
34pub unsafe trait Convert<T, const BRANCH: u8 = 0> {
38 fn into(self) -> T;
39
40 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
51unsafe impl<T> Convert<T> for T {
53 fn into(self) -> T {
54 self
55 }
56}
57
58unsafe impl Convert<()> for Infallible {
61 fn into(self) {
62 match self {}
63 }
64}
65
66unsafe 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
73unsafe 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
80pub(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 unsafe { &mut *ptr::from_mut(source).cast::<[MaybeUninit<U>; N]>() }
93}
94
95#[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
121pub 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 #[inline]
141 unsafe fn activate(&self) {
142 self.count().value.set(W::ONE);
143 }
144
145 unsafe fn start_pair(&self) {
149 self.count().value.set(W::TWO);
150 }
151
152 unsafe fn retire(&self) {
156 self.count().value.set(W::ZERO);
157 }
158
159 #[inline]
163 unsafe fn try_retain(&self) -> Result<(), rc::Error> {
164 let count = self.count();
165 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 #[inline]
177 unsafe fn release(&self) -> rc::Release {
178 let count = self.count();
179 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
192pub unsafe trait Target<W: Counter = u32>: crate::mem::raw::Edge<W> + Sized {
196 unsafe fn destroy(pointer: ptr::NonNull<Self>);
200}
201
202pub 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 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 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 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
304unsafe 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
311unsafe 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
318pub unsafe trait Sum<const N: usize, W: Word>: Amount<N, W> {
322 unsafe fn add_raw(self, other: Self) -> Self;
326}
327
328pub 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
341unsafe 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
354unsafe 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
367pub trait Counter: Word {
369 type NonZero: Copy + Debug + Into<Self>;
370
371 const ONE: Self;
372 const TWO: Self;
373
374 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 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 unsafe { NonZero::new_unchecked(self) }
400 }
401}
402
403#[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 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 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}