use std::{mem, num::NonZero};
use crate::depot::arena::{self, linked};
#[must_use]
pub struct Batch<'a, N: arena::raw::LinkedNode, const C: usize> {
pub(super) owner: &'a mut linked::raw::Fixed<N>,
pub(super) indices: [mem::MaybeUninit<NonZero<u16>>; C],
pub(super) len: u16,
pub(super) next: u16,
}
impl<N: arena::raw::LinkedNode, const C: usize> Batch<'_, N, C> {
pub fn take(&mut self) -> Option<(NonZero<u16>, &mut N)> {
if self.next == self.len {
return None;
}
let index = unsafe {
self.indices
.get_unchecked(usize::from(self.next))
.assume_init_read()
};
self.next += 1;
let node = unsafe {
self.owner
.parts()
.1
.get_unchecked_mut(usize::from(index.get() - 1))
};
Some((index, node))
}
pub fn get_mut(&mut self, index: NonZero<u16>) -> Option<&mut N> {
self.owner.get_mut(index)
}
}
impl<N: arena::raw::LinkedNode, const C: usize> Drop for Batch<'_, N, C> {
fn drop(&mut self) {
if self.next == self.len {
return;
}
let (state, nodes) = self.owner.parts();
let pending = unsafe {
self.indices
.get_unchecked(usize::from(self.next)..usize::from(self.len))
.assume_init_ref()
};
for &index in pending {
unsafe { state.recycle(index, nodes.get_unchecked_mut(usize::from(index.get() - 1))) };
}
state.available = state.available.wrapping_add(self.len - self.next);
}
}