Skip to main content

oxidd_core/util/
mod.rs

1//! Various utilities
2
3use std::collections::{BTreeSet, HashMap, HashSet};
4use std::fmt;
5use std::hash::BuildHasher;
6use std::iter::FusedIterator;
7use std::marker::PhantomData;
8use std::mem::ManuallyDrop;
9
10use crate::{Edge, LevelNo, Manager, NodeID};
11
12mod on_drop;
13mod substitution;
14
15pub mod edge_hash_map;
16pub use edge_hash_map::EdgeHashMap;
17pub mod num;
18pub use on_drop::*;
19pub use substitution::*;
20pub mod var_name_map;
21pub use var_name_map::VarNameMap;
22
23pub use nanorand::WyRand as Rng;
24
25/// Owned version of some handle
26///
27/// This is the owned version, [`Ref<'a, H>`] is the borrowed, and `H` itself is
28/// the raw variant. See [`Ref<'a, H>`] for more details.
29///
30/// An owned handle cannot simply be dropped on its own but must be moved to
31/// functions that handle resource deallocation properly.
32///
33/// `Own<H>` always has the same representation as `H` and `Ref<'a, H>`.
34#[repr(transparent)]
35#[must_use = "Own<H> cannot be dropped on its own"]
36#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
37pub struct Own<H: Copy>(H);
38
39impl<H: Copy> Own<H> {
40    /// Create a new borrowed handle
41    ///
42    /// # Safety
43    ///
44    /// The caller must ensure that the handle provides access to the referenced
45    /// resource as long as the returned value lives.
46    #[inline(always)]
47    pub unsafe fn from_raw(raw: H) -> Self {
48        Self(raw)
49    }
50
51    /// Get the underlying raw handle
52    #[inline(always)]
53    pub fn raw(&self) -> H {
54        self.0
55    }
56    /// Convert an owned handle into the underlying raw handle
57    #[inline]
58    pub fn into_raw(self) -> H {
59        let this = ManuallyDrop::new(self);
60        this.0
61    }
62
63    /// Borrow this handle
64    #[inline(always)]
65    pub fn borrowed(&self) -> Ref<'_, H> {
66        Ref(self.0, PhantomData)
67    }
68}
69
70impl<H: Copy> Drop for Own<H> {
71    #[cold]
72    #[inline(never)]
73    fn drop(&mut self) {
74        eprintln!(
75            "{} must not be dropped. Backtrace:\n{}",
76            std::any::type_name::<Self>(),
77            std::backtrace::Backtrace::capture()
78        );
79
80        #[cfg(feature = "static_leak_check")]
81        {
82            extern "C" {
83                #[link_name = "\n\n`Own<H>`s must not be dropped.`.\n"]
84                fn trigger() -> !;
85            }
86            unsafe { trigger() }
87        }
88    }
89}
90
91impl<H: Copy + fmt::Debug> fmt::Debug for Own<H> {
92    #[inline]
93    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94        self.0.fmt(f)
95    }
96}
97
98/// Borrowed version of some handle
99///
100/// This is the borrowed version, [`Own<H>`] is the owned, and `H` itself is the
101/// raw variant. The raw variant is typically just a pointer or an integer,
102/// freely copyable, and does not provide permission to access the referenced
103/// value on its own. In this sense `H` is like a `*const T`, `Own<H>` like a
104/// `Box<T>`, and `Ref<'a, H>` like a `&'a T`. However, a handle may be tagged,
105/// which cannot really be represented in a `&T`, especially when the tag should
106/// be updated on such a borrowed handle.
107///
108/// `Ref<'a, H>` always has the same representation as `H` and `Own<H>`.
109#[repr(transparent)]
110#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
111pub struct Ref<'a, H: Copy>(H, PhantomData<&'a H>);
112
113impl<'a, H: Copy> Ref<'a, H> {
114    /// Create a new borrowed handle
115    ///
116    /// # Safety
117    ///
118    /// The caller must ensure that the handle provides access to the referenced
119    /// resource for lifetime `'a`.
120    #[must_use]
121    #[inline]
122    pub unsafe fn from_raw(raw: H) -> Self {
123        Self(raw, PhantomData)
124    }
125
126    /// Convert a borrowed handle into the underlying raw handle
127    #[inline]
128    pub fn raw(self) -> H {
129        self.0
130    }
131}
132
133impl<'a, H: Copy> std::borrow::Borrow<Own<H>> for Ref<'a, H> {
134    fn borrow(&self) -> &Own<H> {
135        let ptr = self as *const Self as *const Own<H>;
136        // SAFETY: `Ref<'_, H>` and `Own<H>` have the same representation as
137        // `H`, we are just casting the reference. `Ref<'_, H>` provides the
138        // same permissions as `&Own<H>`.
139        unsafe { &*ptr }
140    }
141}
142
143impl<'a, H: Copy + fmt::Debug> fmt::Debug for Ref<'a, H> {
144    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145        self.0.fmt(f)
146    }
147}
148
149impl<E: Edge> Own<E> {
150    /// Get a version of this [`Edge`] with the given tag
151    #[inline]
152    pub fn with_tag(self, tag: E::Tag) -> Self {
153        let this = ManuallyDrop::new(self);
154        Self(this.0.with_tag(tag))
155    }
156
157    /// Get the [`Tag`][crate::Tag] of this [`Edge`]
158    #[inline]
159    pub fn tag(&self) -> E::Tag {
160        self.0.tag()
161    }
162
163    /// Returns some unique identifier for the referenced node, e.g., for I/O
164    /// purposes
165    #[inline]
166    pub fn node_id(&self) -> usize {
167        self.0.node_id()
168    }
169}
170
171impl<'a, E: Edge> Ref<'a, E> {
172    /// Get a version of this [`Edge`] with the given tag
173    #[inline]
174    pub fn with_tag(self, tag: E::Tag) -> Self {
175        Self(self.0.with_tag(tag), PhantomData)
176    }
177
178    /// Get the [`Tag`][crate::Tag] of this [`Edge`]
179    #[inline]
180    pub fn tag(self) -> E::Tag {
181        self.0.tag()
182    }
183
184    /// Returns some unique identifier for the referenced node, e.g., for I/O
185    /// purposes
186    #[inline]
187    pub fn node_id(self) -> usize {
188        self.0.node_id()
189    }
190}
191
192/// Drop functionality for containers of [`Edge`]s
193///
194/// An edge on its own cannot be dropped: It may well be just an integer index
195/// for an array. In this case we are lacking the base pointer, or more
196/// abstractly the [`Manager`]. Most edge containers cannot store a manager
197/// reference, be it for memory consumption or lifetime restrictions. This trait
198/// provides methods to drop such a container with an externally supplied
199/// function to drop edges.
200pub trait DropWith<E: Edge>: Sized {
201    /// Drop `self`
202    ///
203    /// Among dropping other parts, this calls `drop_edge` for all children.
204    ///
205    /// Having [`Self::drop_with_manager()`] only is not enough: To drop a
206    /// [`Function`][crate::function::Function], we should not require a manager
207    /// lock, otherwise we might end up in a dead-lock (if we are in a
208    /// [`.with_manager_exclusive()`][crate::function::Function::with_manager_exclusive]
209    /// block). So we cannot provide a `&Manager` reference. Furthermore, when
210    /// all [`Function`][crate::function::Function]s and
211    /// [`ManagerRef`][crate::ManagerRef]s referencing a manager are gone and
212    /// the manager needs to drop e.g. the apply cache, it may also provide a
213    /// function that only forgets edges rather than actually dropping them,
214    /// saving the (in this case) unnecessary work of changing reference
215    /// counters etc.
216    fn drop_with(self, drop_edge: impl Fn(Own<E>));
217
218    /// Drop `self`
219    ///
220    /// This is equivalent to `self.drop_with(|e| manager.drop_edge(e))`.
221    ///
222    /// Among dropping other parts, this calls
223    /// [`manager.drop_edge()`][Manager::drop_edge] for all children.
224    #[inline]
225    fn drop_with_manager<M: Manager<Edge = E>>(self, manager: &M) {
226        self.drop_with(|e| manager.drop_edge(e));
227    }
228}
229
230/// Iterator that yields borrowed edges ([`Ref<'a, E>`][Ref]) provided that `I`
231/// is an iterator that yields [`&'a Own<E>`][Own].
232pub struct EdgeRefIter<'a, E: Edge + 'a, I>(I, PhantomData<Ref<'a, E>>);
233
234impl<'a, E: Edge, I: Iterator<Item = &'a Own<E>>> From<I> for EdgeRefIter<'a, E, I> {
235    fn from(it: I) -> Self {
236        Self(it, PhantomData)
237    }
238}
239
240impl<'a, E: Edge, I: Iterator<Item = &'a Own<E>>> Iterator for EdgeRefIter<'a, E, I> {
241    type Item = Ref<'a, E>;
242
243    #[inline]
244    fn next(&mut self) -> Option<Self::Item> {
245        Some(self.0.next()?.borrowed())
246    }
247
248    #[inline]
249    fn size_hint(&self) -> (usize, Option<usize>) {
250        self.0.size_hint()
251    }
252}
253
254impl<'a, E: Edge, I: FusedIterator<Item = &'a Own<E>>> FusedIterator for EdgeRefIter<'a, E, I> {}
255
256impl<'a, E: Edge, I: ExactSizeIterator<Item = &'a Own<E>>> ExactSizeIterator
257    for EdgeRefIter<'a, E, I>
258{
259    #[inline]
260    fn len(&self) -> usize {
261        self.0.len()
262    }
263}
264
265/// Set of nodes
266pub trait NodeSet<E: Copy>: Clone + Default + Eq {
267    /// Get the number of nodes in the set
268    #[must_use]
269    fn len(&self) -> usize;
270
271    /// Returns `true` iff there are no nodes in the set
272    #[must_use]
273    fn is_empty(&self) -> bool {
274        self.len() == 0
275    }
276
277    /// Add a node (the node to which edge points) to the set
278    ///
279    /// Returns `true` if the element was added (i.e. not previously present).
280    fn insert(&mut self, edge: Ref<'_, E>) -> bool;
281
282    /// Return `true` if the set contains the given node
283    #[must_use]
284    fn contains(&self, edge: Ref<'_, E>) -> bool;
285
286    /// Remove a node from the set
287    ///
288    /// Returns `true` if the node was present in the set.
289    fn remove(&mut self, edge: Ref<'_, E>) -> bool;
290}
291impl<E: Edge, S: Clone + Default + BuildHasher> NodeSet<E> for HashSet<NodeID, S> {
292    #[inline]
293    fn len(&self) -> usize {
294        HashSet::len(self)
295    }
296    #[inline]
297    fn insert(&mut self, edge: Ref<'_, E>) -> bool {
298        self.insert(edge.node_id())
299    }
300    #[inline]
301    fn contains(&self, edge: Ref<'_, E>) -> bool {
302        self.contains(&edge.node_id())
303    }
304    #[inline]
305    fn remove(&mut self, edge: Ref<'_, E>) -> bool {
306        self.remove(&edge.node_id())
307    }
308}
309impl<E: Edge> NodeSet<E> for BTreeSet<NodeID> {
310    #[inline]
311    fn len(&self) -> usize {
312        BTreeSet::len(self)
313    }
314    #[inline]
315    fn insert(&mut self, edge: Ref<'_, E>) -> bool {
316        self.insert(edge.node_id())
317    }
318    #[inline]
319    fn contains(&self, edge: Ref<'_, E>) -> bool {
320        self.contains(&edge.node_id())
321    }
322    #[inline]
323    fn remove(&mut self, edge: Ref<'_, E>) -> bool {
324        self.remove(&edge.node_id())
325    }
326}
327
328/// Optional Boolean with `repr(i8)`
329#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
330#[repr(i8)]
331pub enum OptBool {
332    /// Don't care
333    None = -1,
334    #[allow(missing_docs)]
335    False = 0,
336    #[allow(missing_docs)]
337    True = 1,
338}
339
340impl From<bool> for OptBool {
341    fn from(value: bool) -> Self {
342        if value { Self::True } else { Self::False }
343    }
344}
345
346/// Result type with [`OutOfMemory`][crate::error::OutOfMemory] error
347pub type AllocResult<T> = Result<T, crate::error::OutOfMemory>;
348
349/// Is the underlying type a floating point number?
350pub trait IsFloatingPoint {
351    /// `true` iff the underlying type is a floating point number
352    const FLOATING_POINT: bool;
353
354    /// One greater than the minimum possible normal power of 2 exponent, see
355    /// [`f64::MIN_EXP`] for instance. `0` for integers
356    const MIN_EXP: i32;
357}
358
359// dirty hack until we have specialization
360/// cbindgen:ignore
361impl<T: std::ops::ShlAssign<i32>> IsFloatingPoint for T {
362    const FLOATING_POINT: bool = false;
363    const MIN_EXP: i32 = 0;
364}
365
366/// A number type suitable for counting satisfying assignments
367pub trait SatCountNumber:
368    Clone
369    + From<u32>
370    + std::ops::Add<Self, Output = Self>
371    + std::ops::Shl<u32, Output = Self>
372    + std::ops::Shr<u32, Output = Self>
373    + IsFloatingPoint
374{
375}
376
377impl<T> SatCountNumber for T where
378    T: Clone
379        + From<u32>
380        + std::ops::Add<Self, Output = Self>
381        + std::ops::Shl<u32, Output = Self>
382        + std::ops::Shr<u32, Output = Self>
383        + IsFloatingPoint
384{
385}
386
387/// Cache for counting satisfying assignments
388pub struct SatCountCache<N: SatCountNumber, S: BuildHasher> {
389    /// Main map from [`NodeID`]s to their model count
390    pub map: HashMap<NodeID, N, S>,
391
392    /// Number of variables in the domain
393    vars: LevelNo,
394
395    /// Epoch to indicate if the cache is still valid.
396    ///
397    /// If we cached the number of satisfying assignments of a function that has
398    /// been dropped and garbage collected in the meantime, the [`NodeID`]s may
399    /// have been re-used for semantically different functions. The `map` should
400    /// only be considered valid if `epoch` is [`Manager::gc_count()`].
401    epoch: u64,
402
403    /// Whether to cache the SAT counts even for all nodes, including those that
404    /// have only a single incoming edge.
405    pub cache_all: bool,
406}
407
408impl<N: SatCountNumber, S: BuildHasher + Default> Default for SatCountCache<N, S> {
409    fn default() -> Self {
410        Self {
411            map: HashMap::default(),
412            vars: 0,
413            epoch: 0,
414            cache_all: false,
415        }
416    }
417}
418
419impl<N: SatCountNumber, S: BuildHasher> SatCountCache<N, S> {
420    /// Create a new satisfiability counting cache
421    pub fn with_hasher(hash_builder: S) -> Self {
422        Self {
423            map: HashMap::with_hasher(hash_builder),
424            vars: 0,
425            epoch: 0,
426            cache_all: false,
427        }
428    }
429
430    /// Clear the cache if it has become invalid due to garbage collections or a
431    /// change in the number of variables
432    pub fn clear_if_invalid<M: Manager>(&mut self, manager: &M, vars: LevelNo) {
433        let epoch = manager.gc_count();
434        if epoch != self.epoch || vars != self.vars {
435            self.epoch = epoch;
436            self.vars = vars;
437            self.map.clear();
438        }
439    }
440}