use alloc::vec::Vec;
use core::marker::PhantomData;
use super::sync::{AtomicU64, Ordering};
use super::{Entry, Table, TableKey};
use crate::{Bound, TotalF32};
pub trait Packed: Sized {
const BITS: u32;
fn pack(&self) -> u64;
fn unpack(bits: u64) -> Self;
}
macro_rules! packed_int {
($($int:ty => $bits:ty),* $(,)?) => {
$(
impl Packed for $int {
const BITS: u32 = <$int>::BITS;
fn pack(&self) -> u64 {
u64::from(<$bits>::from_ne_bytes(self.to_ne_bytes()))
}
fn unpack(bits: u64) -> Self {
let bits = <$bits>::try_from(bits & low_bits(Self::BITS))
.expect("the masked bits fit the type");
<$int>::from_ne_bytes(bits.to_ne_bytes())
}
}
)*
};
}
packed_int!(i8 => u8, i16 => u16, i32 => u32, u8 => u8, u16 => u16, u32 => u32);
impl Packed for TotalF32 {
const BITS: u32 = 32;
fn pack(&self) -> u64 {
u64::from(self.get().to_bits())
}
fn unpack(bits: u64) -> Self {
let bits = u32::try_from(bits & low_bits(32)).expect("the masked bits fit in 32");
Self::new(f32::from_bits(bits)).expect("a packed score is not NaN")
}
}
const fn low_bits(bits: u32) -> u64 {
(1 << bits) - 1
}
const META_BITS: u32 = 16;
const BOUND_SHIFT: u32 = 0;
const PROVEN_SHIFT: u32 = 2;
const DEPTH_SHIFT: u32 = 3;
const REACH_SHIFT: u32 = 9;
const HAS_MOVE_SHIFT: u32 = 15;
const DEPTH_BITS: u32 = 6;
pub(crate) const MAX_DEPTH: u32 = 62;
const EMPTY_DEPTH: u64 = 63;
const EMPTY: u64 = EMPTY_DEPTH << DEPTH_SHIFT;
#[derive(Debug)]
struct Slot {
check: AtomicU64,
data: AtomicU64,
}
impl Slot {
fn empty() -> Self {
Self {
check: AtomicU64::new(EMPTY),
data: AtomicU64::new(EMPTY),
}
}
}
type Holds<K, M, S> = fn() -> (K, M, S);
#[derive(Debug)]
pub struct PackedTable<K, M, S> {
slots: Vec<Slot>,
types: PhantomData<Holds<K, M, S>>,
}
impl<K: TableKey, M: Packed, S: Packed> PackedTable<K, M, S> {
#[must_use]
pub fn new(capacity: usize) -> Self {
const {
assert!(
M::BITS + S::BITS <= 64 - META_BITS,
"a packed move and score must fit 48 bits together"
);
}
let slots = capacity
.max(1)
.checked_next_power_of_two()
.expect("the capacity fits in usize when rounded up");
Self {
slots: (0..slots).map(|_| Slot::empty()).collect(),
types: PhantomData,
}
}
#[must_use]
pub fn capacity(&self) -> usize {
self.slots.len()
}
pub fn clear(&self) {
for slot in &self.slots {
slot.check.store(EMPTY, Ordering::Relaxed);
slot.data.store(EMPTY, Ordering::Relaxed);
}
}
fn slot(&self, key: &K) -> &Slot {
let mask = u64::try_from(self.slots.len() - 1).expect("a slot count fits in u64");
let index = usize::try_from(key.slot() & mask).expect("a masked slot is below the count");
&self.slots[index]
}
}
impl<K: TableKey, M: Packed, S: Packed> Table<K, M, S> for &PackedTable<K, M, S> {
fn probe(&mut self, key: &K) -> Option<Entry<M, S>> {
let slot = self.slot(key);
let check = slot.check.load(Ordering::Relaxed);
let data = slot.data.load(Ordering::Relaxed);
(check ^ data == key.slot()).then(|| unpack(data)).flatten()
}
fn store(&mut self, key: K, entry: Entry<M, S>) {
let Some(data) = pack(&entry) else {
return;
};
let slot = self.slot(&key);
slot.check.store(key.slot() ^ data, Ordering::Relaxed);
slot.data.store(data, Ordering::Relaxed);
}
}
pub(crate) fn pack<M: Packed, S: Packed>(entry: &Entry<M, S>) -> Option<u64> {
let reach = if entry.proven { entry.reach } else { 0 };
if entry.depth > MAX_DEPTH || reach > MAX_DEPTH {
return None;
}
let bound: u64 = match entry.bound {
Bound::Exact => 0,
Bound::Lower => 1,
Bound::Upper => 2,
Bound::Approximate => 3,
};
let best = entry.best.as_ref().map_or(0, |mv| (mv.pack() << 1) | 1);
let meta = (bound << BOUND_SHIFT)
| (u64::from(entry.proven) << PROVEN_SHIFT)
| (u64::from(entry.depth) << DEPTH_SHIFT)
| (u64::from(reach) << REACH_SHIFT);
Some(meta | (best << HAS_MOVE_SHIFT) | (entry.score.pack() << (META_BITS + M::BITS)))
}
pub(crate) fn unpack<M: Packed, S: Packed>(data: u64) -> Option<Entry<M, S>> {
let field = |shift: u32, bits: u32| (data >> shift) & low_bits(bits);
let depth = field(DEPTH_SHIFT, DEPTH_BITS);
if depth == EMPTY_DEPTH {
return None;
}
let bound = match field(BOUND_SHIFT, 2) {
0 => Bound::Exact,
1 => Bound::Lower,
2 => Bound::Upper,
_ => Bound::Approximate,
};
let best = (field(HAS_MOVE_SHIFT, 1) == 1).then(|| M::unpack(field(META_BITS, M::BITS)));
let small = |bits: u64| u32::try_from(bits).expect("six bits fit in u32");
Some(Entry {
depth: small(depth),
score: S::unpack(data >> (META_BITS + M::BITS)),
bound,
best,
proven: field(PROVEN_SHIFT, 1) == 1,
reach: small(field(REACH_SHIFT, DEPTH_BITS)),
})
}
#[cfg(all(test, loom))]
mod races;
#[cfg(all(test, not(loom)))]
mod tests {
use super::{EMPTY, MAX_DEPTH, PackedTable, Slot, pack, unpack};
use crate::table::{Entry, Table};
use crate::{Bound, TotalF32};
fn entry<M, S>(score: S, best: Option<M>, bound: Bound, depth: u32) -> Entry<M, S> {
Entry {
depth,
score,
bound,
best,
proven: false,
reach: 0,
}
}
#[test]
fn entries_round_trip() {
for bound in [Bound::Exact, Bound::Lower, Bound::Upper, Bound::Approximate] {
for (score, best) in [(i32::MIN, Some(u16::MAX)), (i32::MAX, None), (-1, Some(0))] {
for depth in [0, MAX_DEPTH] {
let mut original = entry(score, best, bound, depth);
original.proven = depth > 0;
original.reach = if original.proven { MAX_DEPTH } else { 0 };
let packed = pack(&original).expect("within the limits");
assert_eq!(unpack::<u16, i32>(packed), Some(original));
}
}
}
let float = entry(
TotalF32::new(-0.5).expect("not NaN"),
Some(7u8),
Bound::Lower,
3,
);
assert_eq!(unpack(pack(&float).expect("shallow")), Some(float));
}
proptest::proptest! {
#[test]
fn any_entry_round_trips(
score in proptest::prelude::any::<i32>(),
best in proptest::option::of(proptest::prelude::any::<u16>()),
bound in 0..4usize,
depth in 0..=MAX_DEPTH,
proven in proptest::prelude::any::<bool>(),
reach in 0..=MAX_DEPTH,
) {
let bound = [Bound::Exact, Bound::Lower, Bound::Upper, Bound::Approximate][bound];
let mut original = entry(score, best, bound, depth);
original.proven = proven;
original.reach = if proven { reach } else { 0 };
let packed = pack(&original).expect("within the limits");
proptest::prop_assert_eq!(unpack::<u16, i32>(packed), Some(original));
}
}
#[test]
fn deep_entries_are_dropped() {
let deep = entry(0i8, None::<u8>, Bound::Exact, MAX_DEPTH + 1);
assert_eq!(pack(&deep), None);
let mut unproven = entry(0i8, None::<u8>, Bound::Exact, 4);
unproven.reach = 99;
let back = unpack::<u8, i8>(pack(&unproven).expect("reach ignored")).expect("stored");
assert_eq!(back.reach, 0);
unproven.proven = true;
assert_eq!(pack(&unproven), None);
}
#[test]
fn keys_check_their_slot() {
let table = PackedTable::<u64, u8, i16>::new(4);
let mut handle = &table;
assert_eq!(handle.probe(&0), None);
let stored = entry(-3i16, Some(2u8), Bound::Upper, 5);
handle.store(5, stored.clone());
assert_eq!(handle.probe(&5), Some(stored.clone()));
assert_eq!(handle.probe(&1), None, "same slot, other key");
handle.store(5, entry(0i16, None, Bound::Exact, MAX_DEPTH + 1));
assert_eq!(handle.probe(&5), Some(stored));
table.clear();
assert_eq!(handle.probe(&5), None);
assert_eq!(table.capacity(), 4);
}
#[test]
fn torn_entries_are_ignored() {
let table = PackedTable::<u64, u8, i16>::new(1);
let mut handle = &table;
let (first, second) = (
entry(1i16, None, Bound::Exact, 1),
entry(2i16, None, Bound::Exact, 2),
);
handle.store(7, first);
let first_check = table.slots[0]
.check
.load(core::sync::atomic::Ordering::Relaxed);
handle.store(7, second);
table.slots[0]
.check
.store(first_check, core::sync::atomic::Ordering::Relaxed);
assert_eq!(handle.probe(&7), None);
let empty = Slot::empty();
assert_eq!(empty.data.into_inner(), EMPTY);
}
}