1use std::cell::UnsafeCell;
4use std::fmt;
5use std::hash::{Hash, Hasher};
6use std::marker::PhantomData;
7use std::mem::{ManuallyDrop, MaybeUninit};
8
9use parking_lot::lock_api::RawMutex;
10
11use oxidd_core::util::{Borrowed, DropWith};
12use oxidd_core::{ApplyCache, Edge, Manager, ManagerEventSubscriber};
13
14#[cfg(feature = "hugealloc")]
15type Box<T> = allocator_api2::boxed::Box<T, hugealloc::HugeAlloc>;
16#[cfg(feature = "hugealloc")]
17type Vec<T> = allocator_api2::vec::Vec<T, hugealloc::HugeAlloc>;
18
19pub struct DMApplyCache<M: Manager, O, H, const ENTRY_CAP: usize = 3>(
21 Box<[Entry<M, O, ENTRY_CAP>]>,
22 PhantomData<H>,
23);
24
25impl<M: Manager, O, H, const ENTRY_CAP: usize> DropWith<M::Edge>
26 for DMApplyCache<M, O, H, ENTRY_CAP>
27where
28 O: Copy + Eq + Hash,
29{
30 fn drop_with(self, _drop_edge: impl Fn(M::Edge)) {
31 }
33}
34
35union Datum<E> {
36 edge: ManuallyDrop<E>,
37 numeric: u32,
38 uninit: (),
39}
40
41impl<E> Datum<E> {
42 const UNINIT: Self = Self { uninit: () };
43
44 unsafe fn assume_edge_ref(&self) -> &E {
46 unsafe { &self.edge }
48 }
49
50 unsafe fn assume_numeric(&self) -> u32 {
52 unsafe { self.numeric }
54 }
55
56 fn write_edge(&mut self, edge: Borrowed<E>) {
57 self.edge = unsafe { Borrowed::into_inner(edge) };
61 }
62
63 fn write_numeric(&mut self, num: u32) {
64 self.numeric = num;
65 }
66}
67
68const KIND_BITS: u32 = 4;
69const KIND_COUNT: usize = 1 << KIND_BITS;
70
71#[derive(Clone, Copy, PartialEq, Eq, Debug)]
72struct CountPair(u8);
73
74impl CountPair {
75 const NULL: Self = CountPair(0);
76
77 const fn new(edge: usize, numeric: usize) -> Self {
78 debug_assert!(edge < KIND_COUNT);
79 debug_assert!(numeric < KIND_COUNT);
80 Self((numeric << 4 | edge) as u8)
81 }
82
83 const fn edge(self) -> usize {
84 self.0 as usize & (KIND_COUNT - 1)
85 }
86
87 const fn numeric(self) -> usize {
88 (self.0 >> KIND_BITS) as usize
89 }
90}
91
92struct Entry<M: Manager, O, const ENTRY_CAP: usize> {
94 mutex: crate::util::RawMutex,
96 operands: UnsafeCell<CountPair>,
98 values: UnsafeCell<CountPair>,
100 operator: UnsafeCell<MaybeUninit<O>>,
102 data: UnsafeCell<[Datum<M::Edge>; ENTRY_CAP]>,
106}
107
108struct EntryGuard<'a, M: Manager, O, const ENTRY_CAP: usize>(&'a Entry<M, O, ENTRY_CAP>);
109
110unsafe impl<M: Manager, O: Send, const ENTRY_CAP: usize> Send for Entry<M, O, ENTRY_CAP> where
112 M::Edge: Send
113{
114}
115unsafe impl<M: Manager, O: Send, const ENTRY_CAP: usize> Sync for Entry<M, O, ENTRY_CAP> where
116 M::Edge: Send
117{
118}
119
120impl<M: Manager, O: Copy + Eq, const ENTRY_CAP: usize> Entry<M, O, ENTRY_CAP> {
121 #[allow(clippy::declare_interior_mutable_const)]
124 const INIT: Self = Self {
125 mutex: crate::util::RawMutex::INIT,
126 operands: UnsafeCell::new(CountPair::NULL),
127 values: UnsafeCell::new(CountPair::NULL),
128 operator: UnsafeCell::new(MaybeUninit::uninit()),
129 data: UnsafeCell::new([Datum::UNINIT; ENTRY_CAP]),
130 };
131
132 #[inline]
133 fn lock(&self) -> EntryGuard<'_, M, O, ENTRY_CAP> {
134 self.mutex.lock();
135 EntryGuard(self)
136 }
137
138 #[inline]
139 fn try_lock(&self) -> Option<EntryGuard<'_, M, O, ENTRY_CAP>> {
140 if self.mutex.try_lock() {
141 Some(EntryGuard(self))
142 } else {
143 None
144 }
145 }
146}
147
148impl<M: Manager, O, const ENTRY_CAP: usize> Drop for EntryGuard<'_, M, O, ENTRY_CAP> {
149 #[inline]
150 fn drop(&mut self) {
151 unsafe { self.0.mutex.unlock() }
153 }
154}
155
156impl<M: Manager, O, const ENTRY_CAP: usize> EntryGuard<'_, M, O, ENTRY_CAP>
157where
158 O: Copy + Eq,
159{
160 #[inline]
162 fn is_occupied(&self) -> bool {
163 unsafe { *self.0.operands.get() != CountPair::NULL }
165 }
166
167 #[inline]
175 fn get<const E: usize, const N: usize>(
176 &self,
177 manager: &M,
178 operator: O,
179 operands: (&[Borrowed<M::Edge>], &[u32]),
180 ) -> Option<([M::Edge; E], [u32; N])> {
181 debug_assert_ne!(operands.0.len() + operands.1.len(), 0);
184 debug_assert!(operands.0.len() <= KIND_COUNT);
185 debug_assert!(operands.1.len() <= KIND_COUNT);
186 debug_assert!(E <= KIND_COUNT);
187 debug_assert!(N <= KIND_COUNT);
188 debug_assert!(operands.0.len() + operands.1.len() + E + N <= ENTRY_CAP);
189
190 #[cfg(feature = "statistics")]
191 STAT_ACCESSES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
192
193 let num_operands = CountPair::new(operands.0.len(), operands.1.len());
194 if unsafe { *self.0.operands.get() } != num_operands {
196 return None;
197 }
198
199 let mut data = unsafe { &*self.0.data.get() }.iter();
201 for (o1, o2) in operands.0.iter().zip(data.by_ref()) {
202 if &**o1 != unsafe { o2.assume_edge_ref() } {
204 return None;
205 }
206 }
207 for (&o1, o2) in operands.1.iter().zip(data.by_ref()) {
208 if o1 != unsafe { o2.assume_numeric() } {
210 return None;
211 }
212 }
213
214 if unsafe { (*self.0.operator.get()).assume_init() } != operator
216 || unsafe { *self.0.values.get() } != const { CountPair::new(E, N) }
217 {
218 return None;
219 }
220
221 #[cfg(feature = "statistics")]
222 STAT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
223
224 let (edge_values, remaining) = data.as_slice().split_at(E);
225 let numeric_values = &remaining[..N];
226 Some((
227 std::array::from_fn(|i| unsafe {
229 manager.clone_edge(edge_values[i].assume_edge_ref())
230 }),
231 std::array::from_fn(|i| unsafe { numeric_values[i].assume_numeric() }),
233 ))
234 }
235
236 #[inline]
246 fn set(
247 &mut self,
248 operator: O,
249 operands: (&[Borrowed<M::Edge>], &[u32]),
250 values: (&[Borrowed<M::Edge>], &[u32]),
251 ) {
252 debug_assert_ne!(operands.0.len() + operands.1.len(), 0);
253 debug_assert!(operands.0.len() <= KIND_COUNT);
254 debug_assert!(operands.1.len() <= KIND_COUNT);
255 debug_assert!(values.0.len() <= KIND_COUNT);
256 debug_assert!(values.1.len() <= KIND_COUNT);
257 debug_assert!(
258 operands.0.len() + operands.1.len() + values.0.len() + values.1.len() <= ENTRY_CAP
259 );
260
261 self.clear();
262
263 #[cfg(feature = "statistics")]
264 STAT_INSERTIONS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
265
266 unsafe { &mut *self.0.operator.get() }.write(operator);
268 let mut data = unsafe { &mut *self.0.data.get() }.iter_mut();
269 for (src, dst) in operands.0.iter().zip(data.by_ref()) {
270 dst.write_edge(src.borrowed());
271 }
272 for (&src, dst) in operands.1.iter().zip(data.by_ref()) {
273 dst.write_numeric(src);
274 }
275 for (src, dst) in values.0.iter().zip(data.by_ref()) {
276 dst.write_edge(src.borrowed());
277 }
278 for (&src, dst) in values.1.iter().zip(data) {
279 dst.write_numeric(src);
280 }
281
282 unsafe { *self.0.values.get() = CountPair::new(values.0.len(), values.1.len()) };
285 unsafe { *self.0.operands.get() = CountPair::new(operands.0.len(), operands.1.len()) };
286 }
287
288 #[inline(always)]
290 fn clear(&mut self) {
291 unsafe { *self.0.operands.get() = CountPair::NULL };
293 }
295}
296
297impl<M, O, H, const ENTRY_CAP: usize> DMApplyCache<M, O, H, ENTRY_CAP>
298where
299 M: Manager,
300 O: Copy + Eq + Hash,
301 H: Hasher + Default,
302{
303 const CHECK_ENTRY_CAP: () = {
304 assert!(
305 0 < ENTRY_CAP && ENTRY_CAP <= KIND_COUNT * 4,
306 "ENTRY_CAP must be in range [1, 64]"
307 );
308 };
309
310 pub unsafe fn with_capacity(capacity: usize) -> Self {
319 let () = Self::CHECK_ENTRY_CAP;
320 let buckets = capacity
321 .checked_next_power_of_two()
322 .expect("capacity is too large");
323 #[cfg(not(feature = "hugealloc"))]
324 let mut vec = Vec::with_capacity(buckets);
325 #[cfg(feature = "hugealloc")]
326 let mut vec = Vec::with_capacity_in(buckets, hugealloc::HugeAlloc);
327
328 vec.resize_with(buckets, || Entry::INIT);
329 DMApplyCache(vec.into_boxed_slice(), PhantomData)
330 }
331
332 #[inline]
334 fn bucket(
335 &self,
336 operator: O,
337 operands: (&[Borrowed<M::Edge>], &[u32]),
338 ) -> &Entry<M, O, ENTRY_CAP> {
339 let mut hasher = H::default();
340 operator.hash(&mut hasher);
341 for o in operands.0 {
342 o.hash(&mut hasher);
343 }
344 for o in operands.1 {
345 o.hash(&mut hasher);
346 }
347 let mask = (self.0.len() - 1) as u64; let index = (hasher.finish() & mask) as usize;
349 debug_assert!(index < self.0.len());
350 unsafe { self.0.get_unchecked(index) }
352 }
353}
354
355#[cfg(feature = "statistics")]
356static STAT_ACCESSES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
357
358#[cfg(feature = "statistics")]
359static STAT_HITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
360
361#[cfg(feature = "statistics")]
362static STAT_INSERTIONS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
363
364impl<M, O, H, const ENTRY_CAP: usize> crate::StatisticsGenerator
365 for DMApplyCache<M, O, H, ENTRY_CAP>
366where
367 M: Manager,
368 O: Copy + Eq,
369{
370 #[cfg(not(feature = "statistics"))]
371 fn print_stats(&self) {}
372
373 #[cfg(feature = "statistics")]
374 fn print_stats(&self) {
375 let count = self.0.len();
376 debug_assert_ne!(count, 0);
377 let occupied = self.0.iter().filter(|e| e.lock().is_occupied()).count();
378
379 let accesses = STAT_ACCESSES.swap(0, std::sync::atomic::Ordering::Relaxed);
380 let hits = STAT_HITS.swap(0, std::sync::atomic::Ordering::Relaxed);
381 let insertions = STAT_INSERTIONS.swap(0, std::sync::atomic::Ordering::Relaxed);
382 println!(
383 "[DMApplyCache] fill level: {:.2} %, accesses: {accesses}, hits: {hits}, insertions: {insertions}, hit ratio ~{:.2} %",
384 100.0 * occupied as f32 / count as f32,
385 100.0 * hits as f32 / accesses as f32,
386 );
387 }
388}
389
390impl<M, O, H, const ENTRY_CAP: usize> ApplyCache<M, O> for DMApplyCache<M, O, H, ENTRY_CAP>
391where
392 M: Manager,
393 O: Copy + Hash + Ord,
394 H: Hasher + Default,
395{
396 #[inline(always)]
397 fn get_extended<const E: usize, const N: usize>(
398 &self,
399 manager: &M,
400 operator: O,
401 operands: (&[Borrowed<M::Edge>], &[u32]),
402 ) -> Option<([M::Edge; E], [u32; N])> {
403 let total_operands = operands.0.len() + operands.1.len();
404 if total_operands == 0
405 || total_operands + (N + E) > ENTRY_CAP
406 || operands.0.len() > KIND_COUNT
407 || operands.1.len() > KIND_COUNT
408 || N > KIND_COUNT
409 || E > KIND_COUNT
410 {
411 return None;
412 }
413 self.bucket(operator, operands)
414 .try_lock()?
415 .get(manager, operator, operands)
416 }
417
418 #[inline(always)]
419 fn add_extended(
420 &self,
421 _manager: &M,
422 operator: O,
423 operands: (&[Borrowed<M::Edge>], &[u32]),
424 values: (&[Borrowed<M::Edge>], &[u32]),
425 ) {
426 let total_operands = operands.0.len() + operands.1.len();
427 if total_operands == 0
428 || total_operands + (values.0.len() + values.1.len()) > ENTRY_CAP
429 || operands.0.len() > KIND_COUNT
430 || operands.1.len() > KIND_COUNT
431 || values.0.len() > KIND_COUNT
432 || values.1.len() > KIND_COUNT
433 {
434 return;
435 }
436 if let Some(mut entry) = self.bucket(operator, operands).try_lock() {
437 entry.set(operator, operands, values);
438 }
439 }
440
441 fn clear(&self, _manager: &M) {
442 for entry in &*self.0 {
443 entry.lock().clear();
444 }
445 }
446}
447
448impl<M, O, H, const ENTRY_CAP: usize> ManagerEventSubscriber<M> for DMApplyCache<M, O, H, ENTRY_CAP>
449where
450 M: Manager,
451 O: Copy + Hash + Ord,
452 H: Hasher + Default,
453{
454 fn pre_gc(&self, _manager: &M) {
455 for entry in &*self.0 {
458 let mut entry = entry.lock();
459 entry.clear();
460 std::mem::forget(entry);
462 }
463 }
464
465 unsafe fn post_gc(&self, _manager: &M) {
466 for entry in &*self.0 {
467 unsafe { entry.mutex.unlock() };
471 }
472 }
473}
474
475impl<M, O, H, const ENTRY_CAP: usize> fmt::Debug for DMApplyCache<M, O, H, ENTRY_CAP>
476where
477 M: Manager,
478 M::Edge: fmt::Debug,
479 O: Copy + Eq + fmt::Debug,
480{
481 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
482 f.debug_map()
483 .entries(
484 self.0
485 .iter()
486 .enumerate()
487 .map(|(i, e)| (i, e.lock()))
488 .filter(|(_, e)| e.is_occupied()),
489 )
490 .finish()
491 }
492}
493
494impl<M, O, const ENTRY_CAP: usize> fmt::Debug for EntryGuard<'_, M, O, ENTRY_CAP>
495where
496 M: Manager,
497 M::Edge: fmt::Debug,
498 O: Copy + Eq + fmt::Debug,
499{
500 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
501 let operands = unsafe { *self.0.operands.get() };
503 if operands == CountPair::NULL {
504 return f.write_str("None");
505 }
506
507 let operator = unsafe { (*self.0.operator.get()).assume_init() };
509 let values = unsafe { *self.0.operands.get() };
510 let mut data = unsafe { &*self.0.data.get() }.iter();
511
512 f.write_str("{{ ")?;
513 operator.fmt(f)?;
514
515 let mut tuple = f.debug_tuple("");
516 for operand in data.by_ref().take(operands.edge()) {
517 tuple.field(unsafe { operand.assume_edge_ref() });
518 }
519 for operand in data.by_ref().take(operands.numeric()) {
520 tuple.field(&unsafe { operand.assume_numeric() });
521 }
522 tuple.finish()?;
523
524 f.write_str(" = ")?;
525
526 let mut tuple = f.debug_tuple("");
527 for value in data.by_ref().take(values.edge()) {
528 tuple.field(unsafe { value.assume_edge_ref() });
529 }
530 for value in data.by_ref().take(values.numeric()) {
531 tuple.field(&unsafe { value.assume_numeric() });
532 }
533 tuple.finish()?;
534
535 f.write_str(" }}")
536 }
537}