use std::{array, cell::Cell, hint, mem::MaybeUninit};
use crate::mem::{
credit::fair,
raw::{Amount, Word},
};
pub fn try_acquire<
const COMMIT: bool,
const N: usize,
W: Word,
A: Amount<N, W>,
E: From<fair::Cause<W, N>>,
>(
held: &Cell<[W; N]>,
shared: &Cell<[W; N]>,
reserve: &[W; N],
amount: A,
) -> Result<(), E> {
let amount = amount.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 A::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,
}
.into());
};
let required = required(current, reserve[index], request);
let available = shared[index].get();
if required > available {
return Err(fair::Cause::Exhausted {
axis: fair::Axis::<N>::ALL[index],
required,
available,
}
.into());
}
if COMMIT {
next[index].write((total, available - required));
}
}
if COMMIT {
for index in A::AXES {
let (next_held, next_shared) = unsafe { next[index].assume_init() };
held[index].set(next_held);
shared[index].set(next_shared);
}
}
Ok(())
}
pub unsafe fn acquire_raw<const N: usize, W: Word, A: Amount<N, W>>(
held: &Cell<[W; N]>,
shared: &Cell<[W; N]>,
reserve: &[W; N],
amount: A,
) {
let amount = amount.get();
let held = held.as_array_of_cells();
let shared = shared.as_array_of_cells();
for axis in A::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);
}
}
pub fn demand<const N: usize, W: Word, A: Amount<N, W>>(
held: &Cell<[W; N]>,
reserve: &[W; N],
amount: A,
) -> [W; N] {
let amount = amount.get();
let held = held.as_array_of_cells();
array::from_fn(|axis| required(held[axis].get(), reserve[axis], amount[axis]))
}
pub unsafe fn release_raw<const N: usize, W: Word, A: Amount<N, W>>(
held: &Cell<[W; N]>,
shared: &Cell<[W; N]>,
reserve: &[W; N],
amount: A,
) {
let amount = amount.get();
let held = held.as_array_of_cells();
let shared = shared.as_array_of_cells();
for axis in A::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))
}