use std::cell::UnsafeCell;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;
use std::mem::MaybeUninit;
use parking_lot::lock_api::RawMutex;
use oxidd_core::util::{DropWith, Own, Ref};
use oxidd_core::{ApplyCache, Manager, ManagerEventSubscriber};
#[cfg(feature = "hugealloc")]
type Box<T> = allocator_api2::boxed::Box<T, hugealloc::HugeAlloc>;
#[cfg(feature = "hugealloc")]
type Vec<T> = allocator_api2::vec::Vec<T, hugealloc::HugeAlloc>;
pub struct DMApplyCache<M: Manager, O, H, const ENTRY_CAP: usize = 3>(
Box<[Entry<M, O, ENTRY_CAP>]>,
PhantomData<H>,
);
impl<M: Manager, O, H, const ENTRY_CAP: usize> DropWith<M::Edge>
for DMApplyCache<M, O, H, ENTRY_CAP>
where
O: Copy + Eq + Hash,
{
fn drop_with(self, _drop_edge: impl Fn(Own<M::Edge>)) {
}
}
union Datum<E: Copy> {
edge: E,
numeric: u32,
uninit: (),
}
impl<E: Copy> Datum<E> {
const UNINIT: Self = Self { uninit: () };
}
const KIND_BITS: u32 = 4;
const KIND_COUNT: usize = 1 << KIND_BITS;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct CountPair(u8);
impl CountPair {
const NULL: Self = CountPair(0);
#[inline]
const fn new(edge: usize, numeric: usize) -> Self {
debug_assert!(edge < KIND_COUNT);
debug_assert!(numeric < KIND_COUNT);
Self((numeric << 4 | edge) as u8)
}
#[inline]
const fn edge(self) -> usize {
self.0 as usize & (KIND_COUNT - 1)
}
#[inline]
const fn numeric(self) -> usize {
(self.0 >> KIND_BITS) as usize
}
}
struct Entry<M: Manager, O, const ENTRY_CAP: usize> {
mutex: crate::util::RawMutex,
operands: UnsafeCell<CountPair>,
values: UnsafeCell<CountPair>,
operator: UnsafeCell<MaybeUninit<O>>,
data: UnsafeCell<[Datum<M::Edge>; ENTRY_CAP]>,
}
struct EntryGuard<'a, M: Manager, O, const ENTRY_CAP: usize>(&'a Entry<M, O, ENTRY_CAP>);
unsafe impl<M: Manager, O: Send, const ENTRY_CAP: usize> Send for Entry<M, O, ENTRY_CAP> where
M::Edge: Send
{
}
unsafe impl<M: Manager, O: Send, const ENTRY_CAP: usize> Sync for Entry<M, O, ENTRY_CAP> where
M::Edge: Send
{
}
impl<M: Manager, O: Copy + Eq, const ENTRY_CAP: usize> Entry<M, O, ENTRY_CAP> {
#[allow(clippy::declare_interior_mutable_const)]
const INIT: Self = Self {
mutex: crate::util::RawMutex::INIT,
operands: UnsafeCell::new(CountPair::NULL),
values: UnsafeCell::new(CountPair::NULL),
operator: UnsafeCell::new(MaybeUninit::uninit()),
data: UnsafeCell::new([Datum::UNINIT; ENTRY_CAP]),
};
#[inline]
fn lock(&self) -> EntryGuard<'_, M, O, ENTRY_CAP> {
self.mutex.lock();
EntryGuard(self)
}
#[inline]
fn try_lock(&self) -> Option<EntryGuard<'_, M, O, ENTRY_CAP>> {
if self.mutex.try_lock() {
Some(EntryGuard(self))
} else {
None
}
}
}
impl<M: Manager, O, const ENTRY_CAP: usize> Drop for EntryGuard<'_, M, O, ENTRY_CAP> {
#[inline]
fn drop(&mut self) {
unsafe { self.0.mutex.unlock() }
}
}
impl<M: Manager, O, const ENTRY_CAP: usize> EntryGuard<'_, M, O, ENTRY_CAP>
where
O: Copy + Eq,
{
#[inline]
fn is_occupied(&self) -> bool {
unsafe { *self.0.operands.get() != CountPair::NULL }
}
#[inline(always)]
#[allow(clippy::type_complexity)]
fn get<const E: usize, const N: usize>(
&self,
manager: &M,
operator: O,
operands: (&[Ref<'_, M::Edge>], &[u32]),
) -> Option<([Own<M::Edge>; E], [u32; N])> {
debug_assert_ne!(operands.0.len() + operands.1.len(), 0);
debug_assert!(operands.0.len() <= KIND_COUNT);
debug_assert!(operands.1.len() <= KIND_COUNT);
debug_assert!(E <= KIND_COUNT);
debug_assert!(N <= KIND_COUNT);
debug_assert!(operands.0.len() + operands.1.len() + E + N <= ENTRY_CAP);
#[cfg(feature = "statistics")]
STAT_ACCESSES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let num_operands = CountPair::new(operands.0.len(), operands.1.len());
if unsafe { *self.0.operands.get() } != num_operands {
return None;
}
let mut data = unsafe { &*self.0.data.get() }.iter();
for (o1, o2) in operands.0.iter().zip(data.by_ref()) {
if o1.raw() != unsafe { o2.edge } {
return None;
}
}
for (&o1, o2) in operands.1.iter().zip(data.by_ref()) {
if o1 != unsafe { o2.numeric } {
return None;
}
}
if unsafe { (*self.0.operator.get()).assume_init() } != operator
|| unsafe { *self.0.values.get() } != const { CountPair::new(E, N) }
{
return None;
}
#[cfg(feature = "statistics")]
STAT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let (edge_values, remaining) = data.as_slice().split_at(E);
let numeric_values = &remaining[..N];
let mut edges = MaybeUninit::uninit();
let edges_mut = unsafe { &mut *(&raw mut edges as *mut [MaybeUninit<Own<M::Edge>>; E]) };
for (dst, src) in edges_mut.iter_mut().zip(edge_values) {
dst.write(manager.clone_edge(unsafe { Ref::from_raw(src.edge) }));
}
Some((
unsafe { edges.assume_init() },
std::array::from_fn(|i| unsafe { numeric_values[i].numeric }),
))
}
#[inline(always)]
fn set(
&mut self,
operator: O,
operands: (&[Ref<'_, M::Edge>], &[u32]),
values: (&[Ref<'_, M::Edge>], &[u32]),
) {
debug_assert_ne!(operands.0.len() + operands.1.len(), 0);
debug_assert!(operands.0.len() <= KIND_COUNT);
debug_assert!(operands.1.len() <= KIND_COUNT);
debug_assert!(values.0.len() <= KIND_COUNT);
debug_assert!(values.1.len() <= KIND_COUNT);
debug_assert!(
operands.0.len() + operands.1.len() + values.0.len() + values.1.len() <= ENTRY_CAP
);
self.clear();
#[cfg(feature = "statistics")]
STAT_INSERTIONS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
unsafe { &mut *self.0.operator.get() }.write(operator);
let mut data = unsafe { &mut *self.0.data.get() }.iter_mut();
for (src, dst) in operands.0.iter().zip(data.by_ref()) {
dst.edge = src.raw();
}
for (&src, dst) in operands.1.iter().zip(data.by_ref()) {
dst.numeric = src;
}
for (src, dst) in values.0.iter().zip(data.by_ref()) {
dst.edge = src.raw();
}
for (&src, dst) in values.1.iter().zip(data) {
dst.numeric = src;
}
unsafe { *self.0.values.get() = CountPair::new(values.0.len(), values.1.len()) };
unsafe { *self.0.operands.get() = CountPair::new(operands.0.len(), operands.1.len()) };
}
#[inline(always)]
fn clear(&mut self) {
unsafe { *self.0.operands.get() = CountPair::NULL };
}
}
impl<M, O, H, const ENTRY_CAP: usize> DMApplyCache<M, O, H, ENTRY_CAP>
where
M: Manager,
O: Copy + Eq + Hash,
H: Hasher + Default,
{
const CHECK_ENTRY_CAP: () = {
assert!(
0 < ENTRY_CAP && ENTRY_CAP <= KIND_COUNT * 4,
"ENTRY_CAP must be in range [1, 64]"
);
};
pub unsafe fn with_capacity(capacity: usize) -> Self {
let () = Self::CHECK_ENTRY_CAP;
let buckets = capacity
.checked_next_power_of_two()
.expect("capacity is too large");
#[cfg(not(feature = "hugealloc"))]
let mut vec = Vec::with_capacity(buckets);
#[cfg(feature = "hugealloc")]
let mut vec = Vec::with_capacity_in(buckets, hugealloc::HugeAlloc);
vec.resize_with(buckets, || Entry::INIT);
DMApplyCache(vec.into_boxed_slice(), PhantomData)
}
#[inline(always)]
fn bucket(
&self,
operator: O,
operands: (&[Ref<'_, M::Edge>], &[u32]),
) -> &Entry<M, O, ENTRY_CAP> {
let mut hasher = H::default();
operator.hash(&mut hasher);
for o in operands.0 {
o.hash(&mut hasher);
}
for o in operands.1 {
o.hash(&mut hasher);
}
let mask = (self.0.len() - 1) as u64; let index = (hasher.finish() & mask) as usize;
debug_assert!(index < self.0.len());
unsafe { self.0.get_unchecked(index) }
}
}
#[cfg(feature = "statistics")]
static STAT_ACCESSES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
#[cfg(feature = "statistics")]
static STAT_HITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
#[cfg(feature = "statistics")]
static STAT_INSERTIONS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
impl<M, O, H, const ENTRY_CAP: usize> crate::StatisticsGenerator
for DMApplyCache<M, O, H, ENTRY_CAP>
where
M: Manager,
O: Copy + Eq,
{
#[cfg(not(feature = "statistics"))]
fn print_stats(&self) {}
#[cfg(feature = "statistics")]
fn print_stats(&self) {
let count = self.0.len();
debug_assert_ne!(count, 0);
let occupied = self.0.iter().filter(|e| e.lock().is_occupied()).count();
let accesses = STAT_ACCESSES.swap(0, std::sync::atomic::Ordering::Relaxed);
let hits = STAT_HITS.swap(0, std::sync::atomic::Ordering::Relaxed);
let insertions = STAT_INSERTIONS.swap(0, std::sync::atomic::Ordering::Relaxed);
println!(
"[DMApplyCache] fill level: {:.2} %, accesses: {accesses}, hits: {hits}, insertions: {insertions}, hit ratio ~{:.2} %",
100.0 * occupied as f32 / count as f32,
100.0 * hits as f32 / accesses as f32,
);
}
}
impl<M, O, H, const ENTRY_CAP: usize> ApplyCache<M, O> for DMApplyCache<M, O, H, ENTRY_CAP>
where
M: Manager,
O: Copy + Hash + Ord,
H: Hasher + Default,
{
#[inline(always)]
fn get_extended<const E: usize, const N: usize>(
&self,
manager: &M,
operator: O,
operands: (&[Ref<'_, M::Edge>], &[u32]),
) -> Option<([Own<M::Edge>; E], [u32; N])> {
let total_operands = operands.0.len() + operands.1.len();
if total_operands == 0
|| total_operands + (N + E) > ENTRY_CAP
|| operands.0.len() > KIND_COUNT
|| operands.1.len() > KIND_COUNT
|| const { N > KIND_COUNT || E > KIND_COUNT }
{
return None;
}
self.bucket(operator, operands)
.try_lock()?
.get(manager, operator, operands)
}
#[inline(always)]
fn add_extended(
&self,
_manager: &M,
operator: O,
operands: (&[Ref<'_, M::Edge>], &[u32]),
values: (&[Ref<'_, M::Edge>], &[u32]),
) {
let total_operands = operands.0.len() + operands.1.len();
if total_operands == 0
|| total_operands + (values.0.len() + values.1.len()) > ENTRY_CAP
|| operands.0.len() > KIND_COUNT
|| operands.1.len() > KIND_COUNT
|| values.0.len() > KIND_COUNT
|| values.1.len() > KIND_COUNT
{
return;
}
if let Some(mut entry) = self.bucket(operator, operands).try_lock() {
entry.set(operator, operands, values);
}
}
fn clear(&self, _manager: &M) {
for entry in &*self.0 {
entry.lock().clear();
}
}
}
impl<M, O, H, const ENTRY_CAP: usize> ManagerEventSubscriber<M> for DMApplyCache<M, O, H, ENTRY_CAP>
where
M: Manager,
O: Copy + Hash + Ord,
H: Hasher + Default,
{
fn pre_gc(&self, _manager: &M) {
for entry in &*self.0 {
let mut entry = entry.lock();
entry.clear();
std::mem::forget(entry);
}
}
unsafe fn post_gc(&self, _manager: &M) {
for entry in &*self.0 {
unsafe { entry.mutex.unlock() };
}
}
}
impl<M, O, H, const ENTRY_CAP: usize> fmt::Debug for DMApplyCache<M, O, H, ENTRY_CAP>
where
M: Manager,
M::Edge: fmt::Debug,
O: Copy + Eq + fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_map()
.entries(
self.0
.iter()
.enumerate()
.map(|(i, e)| (i, e.lock()))
.filter(|(_, e)| e.is_occupied()),
)
.finish()
}
}
impl<M, O, const ENTRY_CAP: usize> fmt::Debug for EntryGuard<'_, M, O, ENTRY_CAP>
where
M: Manager,
M::Edge: fmt::Debug,
O: Copy + Eq + fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let operands = unsafe { *self.0.operands.get() };
if operands == CountPair::NULL {
return f.write_str("None");
}
let operator = unsafe { (*self.0.operator.get()).assume_init() };
let values = unsafe { *self.0.operands.get() };
let mut data = unsafe { &*self.0.data.get() }.iter();
f.write_str("{{ ")?;
operator.fmt(f)?;
let mut tuple = f.debug_tuple("");
for operand in data.by_ref().take(operands.edge()) {
tuple.field(&unsafe { operand.edge });
}
for operand in data.by_ref().take(operands.numeric()) {
tuple.field(&unsafe { operand.numeric });
}
tuple.finish()?;
f.write_str(" = ")?;
let mut tuple = f.debug_tuple("");
for value in data.by_ref().take(values.edge()) {
tuple.field(&unsafe { value.edge });
}
for value in data.by_ref().take(values.numeric()) {
tuple.field(&unsafe { value.numeric });
}
tuple.finish()?;
f.write_str(" }}")
}
}