1use std::cell::UnsafeCell;
4use std::fmt;
5use std::hash::{Hash, Hasher};
6use std::marker::PhantomData;
7use std::mem::MaybeUninit;
8
9use parking_lot::lock_api::RawMutex;
10
11use oxidd_core::util::{DropWith, Own, Ref};
12use oxidd_core::{ApplyCache, 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(Own<M::Edge>)) {
31 }
33}
34
35union Datum<E: Copy> {
36 edge: E,
37 numeric: u32,
38 uninit: (),
39}
40
41impl<E: Copy> Datum<E> {
42 const UNINIT: Self = Self { uninit: () };
43}
44
45const KIND_BITS: u32 = 4;
46const KIND_COUNT: usize = 1 << KIND_BITS;
47
48#[derive(Clone, Copy, PartialEq, Eq, Debug)]
49struct CountPair(u8);
50
51impl CountPair {
52 const NULL: Self = CountPair(0);
53
54 #[inline]
55 const fn new(edge: usize, numeric: usize) -> Self {
56 debug_assert!(edge < KIND_COUNT);
57 debug_assert!(numeric < KIND_COUNT);
58 Self((numeric << 4 | edge) as u8)
59 }
60
61 #[inline]
62 const fn edge(self) -> usize {
63 self.0 as usize & (KIND_COUNT - 1)
64 }
65
66 #[inline]
67 const fn numeric(self) -> usize {
68 (self.0 >> KIND_BITS) as usize
69 }
70}
71
72struct Entry<M: Manager, O, const ENTRY_CAP: usize> {
74 mutex: crate::util::RawMutex,
76 operands: UnsafeCell<CountPair>,
78 values: UnsafeCell<CountPair>,
80 operator: UnsafeCell<MaybeUninit<O>>,
82 data: UnsafeCell<[Datum<M::Edge>; ENTRY_CAP]>,
86}
87
88struct EntryGuard<'a, M: Manager, O, const ENTRY_CAP: usize>(&'a Entry<M, O, ENTRY_CAP>);
89
90unsafe impl<M: Manager, O: Send, const ENTRY_CAP: usize> Send for Entry<M, O, ENTRY_CAP> where
92 M::Edge: Send
93{
94}
95unsafe impl<M: Manager, O: Send, const ENTRY_CAP: usize> Sync for Entry<M, O, ENTRY_CAP> where
96 M::Edge: Send
97{
98}
99
100impl<M: Manager, O: Copy + Eq, const ENTRY_CAP: usize> Entry<M, O, ENTRY_CAP> {
101 #[allow(clippy::declare_interior_mutable_const)]
104 const INIT: Self = Self {
105 mutex: crate::util::RawMutex::INIT,
106 operands: UnsafeCell::new(CountPair::NULL),
107 values: UnsafeCell::new(CountPair::NULL),
108 operator: UnsafeCell::new(MaybeUninit::uninit()),
109 data: UnsafeCell::new([Datum::UNINIT; ENTRY_CAP]),
110 };
111
112 #[inline]
113 fn lock(&self) -> EntryGuard<'_, M, O, ENTRY_CAP> {
114 self.mutex.lock();
115 EntryGuard(self)
116 }
117
118 #[inline]
119 fn try_lock(&self) -> Option<EntryGuard<'_, M, O, ENTRY_CAP>> {
120 if self.mutex.try_lock() {
121 Some(EntryGuard(self))
122 } else {
123 None
124 }
125 }
126}
127
128impl<M: Manager, O, const ENTRY_CAP: usize> Drop for EntryGuard<'_, M, O, ENTRY_CAP> {
129 #[inline]
130 fn drop(&mut self) {
131 unsafe { self.0.mutex.unlock() }
133 }
134}
135
136impl<M: Manager, O, const ENTRY_CAP: usize> EntryGuard<'_, M, O, ENTRY_CAP>
137where
138 O: Copy + Eq,
139{
140 #[inline]
142 fn is_occupied(&self) -> bool {
143 unsafe { *self.0.operands.get() != CountPair::NULL }
145 }
146
147 #[inline(always)]
155 #[allow(clippy::type_complexity)]
156 fn get<const E: usize, const N: usize>(
157 &self,
158 manager: &M,
159 operator: O,
160 operands: (&[Ref<'_, M::Edge>], &[u32]),
161 ) -> Option<([Own<M::Edge>; E], [u32; N])> {
162 debug_assert_ne!(operands.0.len() + operands.1.len(), 0);
165 debug_assert!(operands.0.len() <= KIND_COUNT);
166 debug_assert!(operands.1.len() <= KIND_COUNT);
167 debug_assert!(E <= KIND_COUNT);
168 debug_assert!(N <= KIND_COUNT);
169 debug_assert!(operands.0.len() + operands.1.len() + E + N <= ENTRY_CAP);
170
171 #[cfg(feature = "statistics")]
172 STAT_ACCESSES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
173
174 let num_operands = CountPair::new(operands.0.len(), operands.1.len());
175 if unsafe { *self.0.operands.get() } != num_operands {
177 return None;
178 }
179
180 let mut data = unsafe { &*self.0.data.get() }.iter();
182 for (o1, o2) in operands.0.iter().zip(data.by_ref()) {
183 if o1.raw() != unsafe { o2.edge } {
185 return None;
186 }
187 }
188 for (&o1, o2) in operands.1.iter().zip(data.by_ref()) {
189 if o1 != unsafe { o2.numeric } {
191 return None;
192 }
193 }
194
195 if unsafe { (*self.0.operator.get()).assume_init() } != operator
197 || unsafe { *self.0.values.get() } != const { CountPair::new(E, N) }
198 {
199 return None;
200 }
201
202 #[cfg(feature = "statistics")]
203 STAT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
204
205 let (edge_values, remaining) = data.as_slice().split_at(E);
206 let numeric_values = &remaining[..N];
207
208 let mut edges = MaybeUninit::uninit();
211 let edges_mut = unsafe { &mut *(&raw mut edges as *mut [MaybeUninit<Own<M::Edge>>; E]) };
213 for (dst, src) in edges_mut.iter_mut().zip(edge_values) {
214 dst.write(manager.clone_edge(unsafe { Ref::from_raw(src.edge) }));
217 }
218
219 Some((
220 unsafe { edges.assume_init() },
222 std::array::from_fn(|i| unsafe { numeric_values[i].numeric }),
224 ))
225 }
226
227 #[inline(always)]
237 fn set(
238 &mut self,
239 operator: O,
240 operands: (&[Ref<'_, M::Edge>], &[u32]),
241 values: (&[Ref<'_, M::Edge>], &[u32]),
242 ) {
243 debug_assert_ne!(operands.0.len() + operands.1.len(), 0);
244 debug_assert!(operands.0.len() <= KIND_COUNT);
245 debug_assert!(operands.1.len() <= KIND_COUNT);
246 debug_assert!(values.0.len() <= KIND_COUNT);
247 debug_assert!(values.1.len() <= KIND_COUNT);
248 debug_assert!(
249 operands.0.len() + operands.1.len() + values.0.len() + values.1.len() <= ENTRY_CAP
250 );
251
252 self.clear();
253
254 #[cfg(feature = "statistics")]
255 STAT_INSERTIONS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
256
257 unsafe { &mut *self.0.operator.get() }.write(operator);
259 let mut data = unsafe { &mut *self.0.data.get() }.iter_mut();
260 for (src, dst) in operands.0.iter().zip(data.by_ref()) {
261 dst.edge = src.raw();
262 }
263 for (&src, dst) in operands.1.iter().zip(data.by_ref()) {
264 dst.numeric = src;
265 }
266 for (src, dst) in values.0.iter().zip(data.by_ref()) {
267 dst.edge = src.raw();
268 }
269 for (&src, dst) in values.1.iter().zip(data) {
270 dst.numeric = src;
271 }
272
273 unsafe { *self.0.values.get() = CountPair::new(values.0.len(), values.1.len()) };
276 unsafe { *self.0.operands.get() = CountPair::new(operands.0.len(), operands.1.len()) };
277 }
278
279 #[inline(always)]
281 fn clear(&mut self) {
282 unsafe { *self.0.operands.get() = CountPair::NULL };
284 }
286}
287
288impl<M, O, H, const ENTRY_CAP: usize> DMApplyCache<M, O, H, ENTRY_CAP>
289where
290 M: Manager,
291 O: Copy + Eq + Hash,
292 H: Hasher + Default,
293{
294 const CHECK_ENTRY_CAP: () = {
295 assert!(
296 0 < ENTRY_CAP && ENTRY_CAP <= KIND_COUNT * 4,
297 "ENTRY_CAP must be in range [1, 64]"
298 );
299 };
300
301 pub unsafe fn with_capacity(capacity: usize) -> Self {
310 let () = Self::CHECK_ENTRY_CAP;
311 let buckets = capacity
312 .checked_next_power_of_two()
313 .expect("capacity is too large");
314 #[cfg(not(feature = "hugealloc"))]
315 let mut vec = Vec::with_capacity(buckets);
316 #[cfg(feature = "hugealloc")]
317 let mut vec = Vec::with_capacity_in(buckets, hugealloc::HugeAlloc);
318
319 vec.resize_with(buckets, || Entry::INIT);
320 DMApplyCache(vec.into_boxed_slice(), PhantomData)
321 }
322
323 #[inline(always)]
325 fn bucket(
326 &self,
327 operator: O,
328 operands: (&[Ref<'_, M::Edge>], &[u32]),
329 ) -> &Entry<M, O, ENTRY_CAP> {
330 let mut hasher = H::default();
331 operator.hash(&mut hasher);
332 for o in operands.0 {
333 o.hash(&mut hasher);
334 }
335 for o in operands.1 {
336 o.hash(&mut hasher);
337 }
338 let mask = (self.0.len() - 1) as u64; let index = (hasher.finish() & mask) as usize;
340 debug_assert!(index < self.0.len());
341 unsafe { self.0.get_unchecked(index) }
343 }
344}
345
346#[cfg(feature = "statistics")]
347static STAT_ACCESSES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
348
349#[cfg(feature = "statistics")]
350static STAT_HITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
351
352#[cfg(feature = "statistics")]
353static STAT_INSERTIONS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
354
355impl<M, O, H, const ENTRY_CAP: usize> crate::StatisticsGenerator
356 for DMApplyCache<M, O, H, ENTRY_CAP>
357where
358 M: Manager,
359 O: Copy + Eq,
360{
361 #[cfg(not(feature = "statistics"))]
362 fn print_stats(&self) {}
363
364 #[cfg(feature = "statistics")]
365 fn print_stats(&self) {
366 let count = self.0.len();
367 debug_assert_ne!(count, 0);
368 let occupied = self.0.iter().filter(|e| e.lock().is_occupied()).count();
369
370 let accesses = STAT_ACCESSES.swap(0, std::sync::atomic::Ordering::Relaxed);
371 let hits = STAT_HITS.swap(0, std::sync::atomic::Ordering::Relaxed);
372 let insertions = STAT_INSERTIONS.swap(0, std::sync::atomic::Ordering::Relaxed);
373 println!(
374 "[DMApplyCache] fill level: {:.2} %, accesses: {accesses}, hits: {hits}, insertions: {insertions}, hit ratio ~{:.2} %",
375 100.0 * occupied as f32 / count as f32,
376 100.0 * hits as f32 / accesses as f32,
377 );
378 }
379}
380
381impl<M, O, H, const ENTRY_CAP: usize> ApplyCache<M, O> for DMApplyCache<M, O, H, ENTRY_CAP>
382where
383 M: Manager,
384 O: Copy + Hash + Ord,
385 H: Hasher + Default,
386{
387 #[inline(always)]
388 fn get_extended<const E: usize, const N: usize>(
389 &self,
390 manager: &M,
391 operator: O,
392 operands: (&[Ref<'_, M::Edge>], &[u32]),
393 ) -> Option<([Own<M::Edge>; E], [u32; N])> {
394 let total_operands = operands.0.len() + operands.1.len();
395 if total_operands == 0
396 || total_operands + (N + E) > ENTRY_CAP
397 || operands.0.len() > KIND_COUNT
398 || operands.1.len() > KIND_COUNT
399 || const { N > KIND_COUNT || E > KIND_COUNT }
400 {
401 return None;
402 }
403 self.bucket(operator, operands)
404 .try_lock()?
405 .get(manager, operator, operands)
406 }
407
408 #[inline(always)]
409 fn add_extended(
410 &self,
411 _manager: &M,
412 operator: O,
413 operands: (&[Ref<'_, M::Edge>], &[u32]),
414 values: (&[Ref<'_, M::Edge>], &[u32]),
415 ) {
416 let total_operands = operands.0.len() + operands.1.len();
417 if total_operands == 0
418 || total_operands + (values.0.len() + values.1.len()) > ENTRY_CAP
419 || operands.0.len() > KIND_COUNT
420 || operands.1.len() > KIND_COUNT
421 || values.0.len() > KIND_COUNT
422 || values.1.len() > KIND_COUNT
423 {
424 return;
425 }
426 if let Some(mut entry) = self.bucket(operator, operands).try_lock() {
427 entry.set(operator, operands, values);
428 }
429 }
430
431 fn clear(&self, _manager: &M) {
432 for entry in &*self.0 {
433 entry.lock().clear();
434 }
435 }
436}
437
438impl<M, O, H, const ENTRY_CAP: usize> ManagerEventSubscriber<M> for DMApplyCache<M, O, H, ENTRY_CAP>
439where
440 M: Manager,
441 O: Copy + Hash + Ord,
442 H: Hasher + Default,
443{
444 fn pre_gc(&self, _manager: &M) {
445 for entry in &*self.0 {
448 let mut entry = entry.lock();
449 entry.clear();
450 std::mem::forget(entry);
452 }
453 }
454
455 unsafe fn post_gc(&self, _manager: &M) {
456 for entry in &*self.0 {
457 unsafe { entry.mutex.unlock() };
461 }
462 }
463}
464
465impl<M, O, H, const ENTRY_CAP: usize> fmt::Debug for DMApplyCache<M, O, H, ENTRY_CAP>
466where
467 M: Manager,
468 M::Edge: fmt::Debug,
469 O: Copy + Eq + fmt::Debug,
470{
471 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
472 f.debug_map()
473 .entries(
474 self.0
475 .iter()
476 .enumerate()
477 .map(|(i, e)| (i, e.lock()))
478 .filter(|(_, e)| e.is_occupied()),
479 )
480 .finish()
481 }
482}
483
484impl<M, O, const ENTRY_CAP: usize> fmt::Debug for EntryGuard<'_, M, O, ENTRY_CAP>
485where
486 M: Manager,
487 M::Edge: fmt::Debug,
488 O: Copy + Eq + fmt::Debug,
489{
490 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
491 let operands = unsafe { *self.0.operands.get() };
493 if operands == CountPair::NULL {
494 return f.write_str("None");
495 }
496
497 let operator = unsafe { (*self.0.operator.get()).assume_init() };
499 let values = unsafe { *self.0.operands.get() };
500 let mut data = unsafe { &*self.0.data.get() }.iter();
501
502 f.write_str("{{ ")?;
503 operator.fmt(f)?;
504
505 let mut tuple = f.debug_tuple("");
506 for operand in data.by_ref().take(operands.edge()) {
507 tuple.field(&unsafe { operand.edge });
508 }
509 for operand in data.by_ref().take(operands.numeric()) {
510 tuple.field(&unsafe { operand.numeric });
511 }
512 tuple.finish()?;
513
514 f.write_str(" = ")?;
515
516 let mut tuple = f.debug_tuple("");
517 for value in data.by_ref().take(values.edge()) {
518 tuple.field(&unsafe { value.edge });
519 }
520 for value in data.by_ref().take(values.numeric()) {
521 tuple.field(&unsafe { value.numeric });
522 }
523 tuple.finish()?;
524
525 f.write_str(" }}")
526 }
527}