oxidd_core/lib.rs
1//! Collection of fundamental traits and types to represent decision diagrams
2//!
3//! # Overview
4//!
5//! One of the most central traits is [`Manager`]. The manager is responsible
6//! for storing the nodes of a decision diagram ([`InnerNode`]s and terminal
7//! nodes) and provides [`Edge`]s to identify them.
8//!
9//! From the user's perspective, [`Function`][function::Function] is very
10//! important. A function is some kind of external reference to a node and is
11//! the basis for assigning semantics to nodes and providing operations such as
12//! applying connectives of boolean logic.
13
14#![warn(missing_docs)]
15#![deny(unsafe_op_in_unsafe_fn)]
16#![allow(clippy::double_must_use)]
17// Explicitly writing out `'id` lifetimes possibly makes some code easier to
18// read.
19#![allow(clippy::needless_lifetimes)]
20// `match` syntax may be easier to read
21#![allow(clippy::manual_map)]
22
23use std::borrow::Borrow;
24use std::hash::Hash;
25use std::ops::Range;
26
27pub mod error;
28pub mod function;
29pub mod util;
30
31use error::DuplicateVarName;
32use util::{AllocResult, DropWith, NodeSet, Own, Ref};
33
34/// Manager reference
35///
36/// The methods of this trait synchronize accesses to the manager: In a
37/// concurrent setting, a manager has some kind of read/write lock, and
38/// [`Self::with_manager_shared()`] / [`Self::with_manager_exclusive()`] acquire
39/// this lock accordingly. In a sequential implementation, a
40/// [`RefCell`][std::cell::RefCell] or the like may be used instead of lock.
41pub trait ManagerRef: Clone + Eq + Hash + for<'a, 'id> From<&'a Self::Manager<'id>> {
42 /// Type of the associated manager
43 ///
44 /// For more details on why this type is generic over `'id`, see the
45 /// documentation of [`Function::Manager`][function::Function::Manager].
46 type Manager<'id>: Manager;
47
48 /// Obtain a shared manager reference
49 ///
50 /// Locking behavior: acquires the manager's lock for shared access.
51 fn with_manager_shared<F, T>(&self, f: F) -> T
52 where
53 F: for<'id> FnOnce(&Self::Manager<'id>) -> T;
54
55 /// Obtain an exclusive manager reference
56 ///
57 /// Locking behavior: acquires the manager's lock for exclusive access.
58 fn with_manager_exclusive<F, T>(&self, f: F) -> T
59 where
60 F: for<'id> FnOnce(&mut Self::Manager<'id>) -> T;
61}
62
63/// Reduction rules for decision diagrams
64///
65/// This trait is intended to be implemented on a zero-sized type. Refer to
66/// [`DiagramRules::reduce()`] for an example implementation.
67pub trait DiagramRules<E: Edge, N: InnerNode<E>, T> {
68 /// Iterator created by [`DiagramRules::cofactors()`]
69 type Cofactors<'a>: Iterator<Item = Ref<'a, E>>
70 where
71 E: 'a,
72 N: 'a;
73
74 /// Apply the reduction rule(s)
75 ///
76 /// Besides uniqueness of nodes (there are no two nodes with the same
77 /// children at the same level), decision diagrams typically impose some
78 /// other reduction rules. The former is provided by the [`Manager`] /
79 /// [`LevelView`]s, the latter is implemented here.
80 ///
81 /// The implementation is responsible for consuming the entire `children`
82 /// iterator and dropping unused edges.
83 ///
84 /// # Example implementation
85 ///
86 /// In binary decision diagrams (BDDs), there are no nodes with equal
87 /// children. An implementation might look like this:
88 ///
89 /// ```
90 /// # use oxidd_core::{*, util::EdgeRefIter, util::Own};
91 /// struct BDDRules;
92 /// impl<E: Edge, N: InnerNode<E>, T> DiagramRules<E, N, T> for BDDRules {
93 /// type Cofactors<'a> = N::ChildrenIter<'a> where N: 'a, E: 'a;
94 ///
95 /// fn reduce<M: Manager<Edge = E, InnerNode = N, Terminal = T>>(
96 /// manager: &M,
97 /// level: LevelNo,
98 /// children: impl IntoIterator<Item = Own<E>>,
99 /// ) -> ReducedOrNew<E, N> {
100 /// let mut it = children.into_iter();
101 /// let f0 = it.next().unwrap();
102 /// let f1 = it.next().unwrap();
103 /// debug_assert!(it.next().is_none());
104 ///
105 /// if f0 == f1 {
106 /// manager.drop_edge(f1);
107 /// ReducedOrNew::Reduced(f0)
108 /// } else {
109 /// ReducedOrNew::New(InnerNode::new(level, [f0, f1]), Default::default())
110 /// }
111 /// }
112 ///
113 /// fn cofactors(_tag: E::Tag, node: &N) -> Self::Cofactors<'_> {
114 /// node.children()
115 /// }
116 /// }
117 /// ```
118 ///
119 /// Note that we assume no complemented edges, hence the cofactor iterator
120 /// is just `node.children()`.
121 ///
122 /// The implementation assumes that there are no panics, otherwise it would
123 /// leak some edges. It might be a bit better to use
124 /// [`EdgeDropGuard`][util::EdgeDropGuard]s, but this would make the code
125 /// more clumsy, and our assumption is usually fair enough.
126 fn reduce<M: Manager<Edge = E, InnerNode = N, Terminal = T>>(
127 manager: &M,
128 level: LevelNo,
129 children: impl IntoIterator<Item = Own<E>>,
130 ) -> ReducedOrNew<E, N>;
131
132 /// Get the cofactors of `node` assuming an incoming edge with `tag`
133 ///
134 /// In some diagram types, this is the same as [`InnerNode::children()`].
135 /// However, in a binary decision diagram with complement edges, we need to
136 /// respect the tag of the incoming edge: If the incoming edge is
137 /// complemented, then we need to complement the outgoing edges as well.
138 fn cofactors(tag: E::Tag, node: &N) -> Self::Cofactors<'_>;
139
140 /// Get the `n`-th cofactor of `node` assuming an incoming edge with `tag`
141 ///
142 /// This is equivalent to `Self::cofactors(tag, node).nth(n).unwrap()`.
143 #[inline]
144 fn cofactor(tag: E::Tag, node: &N, n: usize) -> Ref<'_, E> {
145 Self::cofactors(tag, node).nth(n).expect("out of range")
146 }
147}
148
149/// Result of the attempt to create a new node
150///
151/// Before actually creating a new node, reduction rules should be applied
152/// (see [`DiagramRules::reduce()`]). If a reduction was applied, then
153/// [`DiagramRules::reduce()`] returns the `Reduced` variant, otherwise the
154/// `New` variant.
155pub enum ReducedOrNew<E: Edge, N: InnerNode<E>> {
156 /// A reduction rule was applied
157 Reduced(Own<E>),
158 /// The node is new. After inserting it into the manager, the edge should be
159 /// tagged with the given tag.
160 New(N, E::Tag),
161}
162
163impl<E: Edge, N: InnerNode<E>> ReducedOrNew<E, N> {
164 /// Insert `self` into `manager` and `unique_table` at the given `level` if
165 /// it is `New`, otherwise return the `Reduced` edge.
166 ///
167 /// `level` must agree with the level used for creating the node, and must
168 /// be strictly above (i.e. less than) the children's levels.
169 #[must_use]
170 #[inline(always)]
171 pub fn then_insert<M>(self, manager: &M, level: LevelNo) -> AllocResult<Own<E>>
172 where
173 M: Manager<InnerNode = N, Edge = E>,
174 {
175 match self {
176 ReducedOrNew::Reduced(e) => Ok(e),
177 ReducedOrNew::New(node, tag) => {
178 debug_assert_ne!(level, LevelNo::MAX);
179 debug_assert!(node.check_level(|l| l == level));
180 debug_assert!(node.children().all(|c| {
181 if let Node::Inner(node) = manager.get_node(c) {
182 node.check_level(|l| level < l)
183 } else {
184 true
185 }
186 }));
187
188 let edge = manager.level(level).get_or_insert(node)?;
189 Ok(edge.with_tag(tag))
190 }
191 }
192 }
193}
194
195/// Node in a decision diagram
196///
197/// [`Eq`] and [`Hash`] should consider the children only, in particular no
198/// level information. This means that if `Self` implements [`HasLevel`],
199/// [`HasLevel::set_level()`] may be called while the node is present in a
200/// [`LevelView`]. This is not the case for [`InnerNode::set_child()`]: The user
201/// must remove the node from the [`LevelView`] before setting the children (and
202/// re-insert it afterwards).
203#[must_use]
204pub trait InnerNode<E: Edge>: Sized + Eq + Hash + DropWith<E> {
205 /// The node's arity (upper bound)
206 const ARITY: usize;
207
208 /// Iterator over children of an inner node
209 type ChildrenIter<'a>: ExactSizeIterator<Item = Ref<'a, E>>
210 where
211 Self: 'a,
212 E: 'a;
213
214 /// Create a new node
215 ///
216 /// Note that this does not apply any reduction rules. A node type that does
217 /// not store levels internally (does not implement [`HasLevel`]) may simply
218 /// ignore the `level` parameter.
219 ///
220 /// Panics if `children`'s length does not match the node's requirements
221 /// (typically, the length should be [`Self::ARITY`], but some node types
222 /// may deviate from that).
223 #[must_use]
224 fn new(level: LevelNo, children: impl IntoIterator<Item = Own<E>>) -> Self;
225
226 /// Returns the result of `check` applied to the node's level in case this
227 /// node type stores levels, otherwise returns `true`.
228 ///
229 /// Use [`HasLevel::level()`] if you require your nodes to store the level
230 /// number and want to get the level number.
231 fn check_level(&self, check: impl FnOnce(LevelNo) -> bool) -> bool;
232
233 /// Panics if the node types stores a level and the node's level is not
234 /// `level`
235 fn assert_level_matches(&self, level: LevelNo);
236
237 /// Get the children of this node as an iterator
238 #[must_use]
239 fn children(&self) -> Self::ChildrenIter<'_>;
240
241 /// Get the `n`-th child of this node
242 fn child(&self, n: usize) -> Ref<'_, E>;
243
244 /// Set the `n`-th child of this node
245 ///
246 /// Returns the previous `n`-th child.
247 ///
248 /// Note that this function may also change the node's hash value etc., so
249 /// in case the node is stored in a hash table ([`LevelView`]), it needs to
250 /// be removed before calling this method.
251 ///
252 /// Panics if the node does not have an `n`-th child.
253 ///
254 /// # Safety
255 ///
256 /// The caller must have exclusive access to the node. In the first place,
257 /// this is granted by acquiring an exclusive manager lock
258 /// ([`Function::with_manager_exclusive()`][function::Function::with_manager_exclusive] or
259 /// [`ManagerRef::with_manager_exclusive()`]). However, exclusive access to
260 /// some nodes may be delegated to other threads (which is the reason why we
261 /// only require a shared and not a mutable manager reference). Furthermore,
262 /// there must not be a borrowed child (obtained via
263 /// [`InnerNode::children()`]).
264 #[must_use = "call `Manager::drop_edge()` if you don't need the previous edge"]
265 unsafe fn set_child(&self, n: usize, child: Own<E>) -> Own<E>;
266
267 /// Get the node's reference count
268 ///
269 /// This ignores all internal references used by the manager
270 /// implementation.
271 #[must_use]
272 fn ref_count(&self) -> usize;
273}
274
275/// Level number type
276///
277/// Levels with lower numbers are located at the top of the diagram, higher
278/// numbers at the bottom. [`LevelNo::MAX`] is reserved for terminal nodes.
279/// Adjacent levels have adjacent level numbers.
280pub type LevelNo = u32;
281
282/// Atomic version of [`LevelNo`]
283pub type AtomicLevelNo = std::sync::atomic::AtomicU32;
284
285/// Variable number type
286pub type VarNo = LevelNo;
287
288/// Atomic version of [`VarNo`]
289pub type AtomicVarNo = AtomicLevelNo;
290
291/// Trait for nodes that have a level
292///
293/// Quasi-reduced BDDs, for instance, do not need the level information stored
294/// in their nodes, so there is no need to implement this trait.
295///
296/// Implementors should also implement [`InnerNode`]. If `Self` is [`Sync`],
297/// then the level number should be implemented using [`AtomicLevelNo`]. In
298/// particular, concurrent calls to [`Self::level()`] and [`Self::set_level()`]
299/// must not lead to data races.
300///
301/// # Safety
302///
303/// 1. A node in a [`LevelView`] with level number L has level number L (i.e.
304/// `self.level()` returns L).
305/// 2. [`InnerNode::check_level()`] with a check `c` must return
306/// `c(self.level())`. Similarly, [`InnerNode::assert_level_matches()`] must
307/// panic if the level does not match.
308///
309/// These conditions are crucial to enable concurrent level swaps as part of
310/// reordering (see the `oxidd-reorder` crate): The algorithm iterates over the
311/// nodes at the upper level and needs to know whether a node is part of the
312/// level directly below it. The procedure only has access to nodes at these two
313/// levels, hence it must rely on the level information for SAFETY.
314///
315/// Note that invariant 1 may be broken by [`HasLevel::set_level()`] and
316/// [`LevelView::swap()`]; the caller of these functions is responsible to
317/// re-establish the invariant.
318pub unsafe trait HasLevel {
319 /// Get the node's level
320 #[must_use]
321 fn level(&self) -> LevelNo;
322
323 /// Set the node's level
324 ///
325 /// # Safety
326 ///
327 /// This method may break SAFETY invariant 1 of the [`HasLevel`] trait: A
328 /// node in a [`LevelView`] with level number L has level number L (i.e.
329 /// `self.level()` returns L). The caller is responsible to re-establish the
330 /// invariant. (Make sure that the calling code is exception-safe!)
331 unsafe fn set_level(&self, level: LevelNo);
332}
333
334/// Node identifier returned by [`Edge::node_id()`]
335///
336/// The most significant bit is reserved, i.e. `NodeID`s must (normally) be less
337/// than `1 << (NodeID::BITS - 1)`
338pub type NodeID = usize;
339
340/// Edge in a decision diagram
341///
342/// Generally speaking, an edge is the directed connection between two nodes,
343/// with some kind of annotation. In a binary decision diagram with complement
344/// edges, there are the "true" edges as well as the normal and the complemented
345/// "false" edges. When considering a single edge, it usually is not so
346/// important whether this edge is a "true" or "false" edge; we can simply have
347/// distinguishable "slots" in the source node. In contrast, whether an edge is
348/// complemented or not has a much greater influence on the meaning of an edge.
349///
350/// In a decision diagram, obtaining the source of an edge is usually not so
351/// important, hence this trait does not provide such functionality. This means
352/// that an edge can (more or less) be implemented as a (tagged) pointer to the
353/// target node.
354///
355/// This trait requires implementors to also implement [`Ord`]. Edges should be
356/// considered equal if and only if they point to the same node with the same
357/// tag. Besides that, there are no further restrictions. The order implemented
358/// for [`Ord`] can be an arbitrary, fixed order (e.g. using addresses of the
359/// nodes). The main idea of this is to give the set `{f, g}` of two edges `f`
360/// and `g` a unique tuple/array representation.
361pub trait Edge: Copy + Sized + Ord + Hash {
362 /// Edge tag
363 ///
364 /// For instance, an edge tag can be used to mark an edge as complemented.
365 ///
366 /// If the decision diagram does not need any special edge tags, this can
367 /// simply be `()`.
368 type Tag: Tag;
369
370 /// Get a version of this [`Edge`] with the given tag
371 fn with_tag(self, tag: Self::Tag) -> Self;
372
373 /// Get the [`Tag`] of this [`Edge`]
374 fn tag(self) -> Self::Tag;
375
376 /// Returns some unique identifier for the referenced node, e.g., for I/O
377 /// purposes
378 fn node_id(self) -> NodeID;
379}
380
381/// Trait for tags that can be attached to pointers (e.g. edges, see
382/// [`Edge::Tag`])
383///
384/// This trait is automatically implemented for types that implement [`Eq`],
385/// [`Default`], and [`Countable`].
386pub trait Tag: Sized + Copy + Eq + Default + Countable {}
387impl<T: Eq + Default + Countable> Tag for T {}
388
389/// Types whose values can be counted, i.e. there is a bijection between the
390/// values of the type and the range `0..=MAX_VALUE`.
391///
392/// This is mainly intended to be implemented on `enum`s. In most cases, you can
393/// simply derive it.
394///
395/// # Safety
396///
397/// [`Countable::as_usize()`] and [`Countable::from_usize()`] must form a
398/// bijection between the values of type `Self` and `0..=MAX_VALUE`, more
399/// formally: For all `t: Self` it must hold that
400/// `Self::from_usize(t.as_usize()) == t`.
401/// For all `u: usize` such that `t.as_usize() == u` for some `t: Self`,
402/// `Self::from_usize(u).as_usize() == u` must be true. Furthermore,
403/// `t.as_usize() <= Self::MAX_VALUE` must hold.
404///
405/// This trait is marked unsafe because violating any invariant of the above may
406/// e.g. result in out-of-bounds accesses.
407pub unsafe trait Countable: Sized + Copy {
408 /// Maximum value returned by `self.as_usize()`.
409 const MAX_VALUE: usize;
410
411 /// Convert `self` into a `usize`.
412 #[must_use]
413 fn as_usize(self) -> usize;
414 /// Convert the given `value` into an instance of `Self`.
415 ///
416 /// May panic if an invalid value is passed, or return some default value.
417 #[must_use]
418 fn from_usize(value: usize) -> Self;
419}
420
421// SAFETY: There is a bijection for all values of type `()` and `0..=MAX_VALUE`.
422unsafe impl Countable for () {
423 const MAX_VALUE: usize = 0;
424
425 #[inline]
426 fn as_usize(self) -> usize {
427 0
428 }
429
430 #[inline]
431 fn from_usize(_value: usize) -> Self {}
432}
433
434// SAFETY: There is a bijection for all values of type `bool` and `0..=1`.
435unsafe impl Countable for bool {
436 const MAX_VALUE: usize = 1;
437
438 #[inline]
439 fn as_usize(self) -> usize {
440 self as usize
441 }
442
443 #[inline]
444 fn from_usize(value: usize) -> Self {
445 value != 0
446 }
447}
448
449/// Either an inner or a terminal node
450pub enum Node<'a, M: Manager + 'a> {
451 #[allow(missing_docs)]
452 Inner(&'a M::InnerNode),
453 #[allow(missing_docs)]
454 Terminal(M::TerminalRef<'a>),
455}
456
457impl<'a, M: Manager + 'a> Clone for Node<'a, M> {
458 fn clone(&self) -> Self {
459 *self
460 }
461}
462impl<'a, M: Manager + 'a> Copy for Node<'a, M> {}
463
464impl<'a, M: Manager> Node<'a, M> {
465 /// Get the reference count of the underlying node
466 #[must_use]
467 #[inline]
468 pub fn ref_count(self) -> usize {
469 match self {
470 Node::Inner(node) => node.ref_count(),
471 Node::Terminal(_) => usize::MAX, /* TODO: should we support concrete reference counts
472 * for terminals? */
473 }
474 }
475}
476
477impl<'a, M: Manager> Node<'a, M>
478where
479 M::InnerNode: HasLevel,
480{
481 /// Get the level of the underlying node (`LevelNo::MAX` for terminals)
482 #[must_use]
483 #[inline]
484 pub fn level(self) -> LevelNo {
485 match self {
486 Node::Inner(node) => node.level(),
487 Node::Terminal(_) => LevelNo::MAX,
488 }
489 }
490}
491
492impl<'a, M: Manager> Node<'a, M> {
493 /// Unwrap the inner node
494 ///
495 /// Panics if `self` is a terminal.
496 #[must_use]
497 #[track_caller]
498 #[inline]
499 pub fn unwrap_inner(self) -> &'a M::InnerNode {
500 match self {
501 Node::Inner(node) => node,
502 Node::Terminal(_) => panic!("expected an inner node, but this is a terminal"),
503 }
504 }
505
506 /// Unwrap the inner node
507 ///
508 /// Panics with `msg` if `self` is a terminal.
509 #[must_use]
510 #[track_caller]
511 #[inline]
512 pub fn expect_inner(self, msg: &str) -> &'a M::InnerNode {
513 match self {
514 Node::Inner(node) => node,
515 Node::Terminal(_) => panic!("{}", msg),
516 }
517 }
518
519 /// Returns `true` if this is an inner node
520 #[inline]
521 pub fn is_inner(self) -> bool {
522 match self {
523 Node::Inner(_) => true,
524 Node::Terminal(_) => false,
525 }
526 }
527
528 /// Unwrap the terminal
529 ///
530 /// Panics if `self` is an inner node
531 #[must_use]
532 #[track_caller]
533 #[inline]
534 pub fn unwrap_terminal(&self) -> &M::Terminal {
535 match self {
536 Node::Inner(_) => panic!("expected a terminal node, but this is an inner node"),
537 Node::Terminal(t) => t.borrow(),
538 }
539 }
540
541 /// Unwrap the terminal
542 ///
543 /// Panics with `msg` if `self` is an inner node
544 #[must_use]
545 #[track_caller]
546 #[inline]
547 pub fn expect_terminal(&self, msg: &str) -> &M::Terminal {
548 match self {
549 Node::Inner(_) => panic!("{}", msg),
550 Node::Terminal(t) => t.borrow(),
551 }
552 }
553
554 /// Returns `true` if this is any terminal node
555 #[inline]
556 pub fn is_any_terminal(self) -> bool {
557 match self {
558 Node::Inner(_) => false,
559 Node::Terminal(_) => true,
560 }
561 }
562
563 /// Returns `true` if this is the given `terminal`
564 #[inline]
565 pub fn is_terminal(self, terminal: &M::Terminal) -> bool {
566 match self {
567 Node::Inner(_) => false,
568 Node::Terminal(t) => t.borrow() == terminal,
569 }
570 }
571}
572
573/// Manager for nodes in a decision diagram
574///
575/// In the basic formulation, a decision diagram is a directed acyclic graph
576/// where all inner nodes are associated with a level, and each level in turn is
577/// associated with a variable. A decision diagram can represent functions
578/// Dⁿ → T, where n is the number of variables. Every inner node has |D|
579/// outgoing edges, pointing to child nodes. The semantics of an inner node
580/// depends on the value of its associated variable. If the variable has
581/// value d ∈ D, then the node's semantics is the semantics of the child
582/// referenced by the edge corresponding to d. Every terminal node is associated
583/// with a value t ∈ T, and the node's semantics is just that value t. Some
584/// kinds of decision diagrams deviate from this formulation in one way or the
585/// other, but still fit into the framework.
586///
587/// The manager's responsibility is to store nodes and provide edges to identify
588/// them. Internally, it has a unique table to ensure uniqueness of nodes
589/// (typically, there should be no two nodes with the same children at the same
590/// level). The manager supports some kind of garbage collection: If there are
591/// no more edges pointing to a node, the node does not necessarily have to be
592/// deleted immediately. It may well be that the node revives. But from time to
593/// time it may make sense to remove all currently dead nodes. The manager also
594/// supports a levelized view on the diagram (via [`LevelView`]s).
595///
596/// Note that we are way more concerned about levels than about variables here.
597/// This is because variables can easily be handled externally. For many kinds
598/// of diagrams, we can just use the function representation of a variable and
599/// get the mapping between variables and levels "for free". This is especially
600/// nice as there are reordering operations which change the mapping between
601/// levels and variables but implicitly update the function representations
602/// accordingly.
603///
604/// # Safety
605///
606/// The implementation must ensure that every inner node only refers to nodes
607/// stored in this manager.
608///
609/// Every level view is associated with a manager and a level number.
610/// [`Manager::level()`] must always return the level view associated to this
611/// manager with the given level number.
612pub unsafe trait Manager: Sized {
613 /// Type of edge
614 type Edge: Edge<Tag = Self::EdgeTag>;
615 /// Type of edge tags
616 type EdgeTag: Tag;
617 /// Type of inner nodes
618 type InnerNode: InnerNode<Self::Edge>;
619 /// Type of terminals
620 type Terminal: Eq + Hash;
621 /// References to [`Self::Terminal`]s
622 ///
623 /// Should either be a `&'a Self::Terminal` or just `Self::Terminal`. The
624 /// latter is useful for "static terminal managers" which don't actually
625 /// store terminal nodes but can map between edges and terminal nodes on the
626 /// fly. In this case, it would be hard to hand out node references.
627 type TerminalRef<'a>: Borrow<Self::Terminal> + Copy
628 where
629 Self: 'a;
630 /// Diagram rules, see [`DiagramRules`] for more details
631 type Rules: DiagramRules<Self::Edge, Self::InnerNode, Self::Terminal>;
632
633 /// Iterator over all terminals
634 ///
635 /// The actual items are edges pointing to terminals since this allows us to
636 /// get a [`NodeID`].
637 type TerminalIterator<'a>: Iterator<Item = Own<Self::Edge>>
638 where
639 Self: 'a;
640
641 /// Node set type, possibly more efficient than a `HashSet<NodeID>`
642 type NodeSet: NodeSet<Self::Edge>;
643
644 /// A view on a single level of the unique table.
645 type LevelView<'a>: LevelView<Self::Edge, Self::InnerNode>
646 where
647 Self: 'a;
648
649 /// Iterator over levels
650 type LevelIterator<'a>: DoubleEndedIterator<Item = Self::LevelView<'a>> + ExactSizeIterator
651 where
652 Self: 'a;
653
654 /// Get a reference to the node to which `edge` points
655 #[must_use]
656 fn get_node<'a>(&'a self, edge: Ref<'a, Self::Edge>) -> Node<'a, Self>;
657
658 /// Clone `edge`
659 #[must_use]
660 fn clone_edge(&self, edge: Ref<'_, Self::Edge>) -> Own<Self::Edge>;
661
662 /// Drop `edge`
663 fn drop_edge(&self, edge: Own<Self::Edge>);
664 /// Drop `edge` and try to remove the node it points to
665 ///
666 /// `level` is the node's level. This is required because nodes do not
667 /// necessarily store their level, but the lookup in a unique table split by
668 /// levels needs the level.
669 ///
670 /// Returns whether the node has been removed. There are multiple reasons
671 /// why removing the node can fail. Obviously, it could still be referenced
672 /// by other edges. It might also be that removing nodes is currently not
673 /// possible, e.g., because the manager is not prepared for it. Also, if
674 /// `level` does not match the node's actual level, the node referenced by
675 /// `edge` may not be removed. In this case, the method might even remove
676 /// another node with the same children which is only referenced from the
677 /// unique table.
678 ///
679 /// Passing the wrong `level` is considered to be a programming mistake. To
680 /// aid debugging, the implementation is allowed (but not required) to panic
681 /// if it can diagnose such a mistake.
682 fn try_remove_node(&self, edge: Own<Self::Edge>, level: LevelNo) -> bool;
683
684 /// Get the count of inner nodes
685 #[must_use]
686 fn num_inner_nodes(&self) -> usize;
687
688 /// Get an approximate count of inner nodes
689 ///
690 /// For concurrent implementations, it may be much less costly to determine
691 /// an approximation of the inner node count than an accurate count
692 /// ([`Self::num_inner_nodes()`]).
693 #[must_use]
694 fn approx_num_inner_nodes(&self) -> usize {
695 self.num_inner_nodes()
696 }
697
698 /// Get the number of variables
699 ///
700 /// Same as [`Self::num_levels()`]
701 #[must_use]
702 #[inline(always)]
703 fn num_vars(&self) -> VarNo {
704 self.num_levels()
705 }
706
707 /// Get the number of levels
708 ///
709 /// Same as [`Self::num_vars()`]
710 #[must_use]
711 fn num_levels(&self) -> LevelNo;
712
713 /// Get the number of named variables
714 #[must_use]
715 fn num_named_vars(&self) -> VarNo;
716
717 /// Add `additional` unnamed variables to the decision diagram
718 ///
719 /// The new variables are added at the bottom of the variable order. More
720 /// precisely, the level number equals the variable number for each new
721 /// variable.
722 ///
723 /// Note that some algorithms may assume that the domain of a function
724 /// represented by a decision diagram is just the set of all variables. In
725 /// this regard, adding variables can change the semantics of decision
726 /// diagram nodes.
727 ///
728 /// Returns the range of new variable numbers.
729 ///
730 /// Panics if [`self.num_vars()`][Self::num_vars()] plus `additional` is
731 /// greater than to [`VarNo::MAX`].
732 fn add_vars(&mut self, additional: VarNo) -> Range<VarNo>;
733
734 /// Add named variables to the decision diagram
735 ///
736 /// This is a shorthand for [`Self::add_vars()`] and respective
737 /// [`Self::set_var_name()`] calls. More details can be found there.
738 ///
739 /// Returns the range of new variable numbers on success. In case a name
740 /// is not unique (and not `""`), only the first variables with unique names
741 /// are added, and a [`DuplicateVarName`] error provides more details.
742 ///
743 /// Panics if there would be more than [`VarNo::MAX`] variables after adding
744 /// the ones from `names`.
745 fn add_named_vars<S: Into<String>>(
746 &mut self,
747 names: impl IntoIterator<Item = S>,
748 ) -> Result<Range<VarNo>, DuplicateVarName>;
749
750 /// Add named variables to the decision diagram
751 ///
752 /// This is a possibly specialized version of [`Self::add_named_vars()`].
753 ///
754 /// Panics if there would be more than [`VarNo::MAX`] variables after adding
755 /// the ones from `names`.
756 fn add_named_vars_from_map(
757 &mut self,
758 map: crate::util::VarNameMap,
759 ) -> Result<Range<VarNo>, DuplicateVarName> {
760 self.add_named_vars(map.into_names_iter())
761 }
762
763 /// Get `var`'s name
764 ///
765 /// For unnamed variables, this will return the empty string.
766 ///
767 /// Panics if `var` is greater or equal to the number of variables in this
768 /// manager.
769 fn var_name(&self, var: VarNo) -> &str;
770
771 /// Label `var` as `name`
772 ///
773 /// An empty name means that the variable will become unnamed, and cannot be
774 /// retrieved via [`Self::name_to_var()`] anymore.
775 ///
776 /// Returns a [`DuplicateVarName`] error if `name` is not unique (and not
777 /// `""`).
778 ///
779 /// Panics if `var` is greater or equal to the number of variables in this
780 /// manager.
781 fn set_var_name(&mut self, var: VarNo, name: impl Into<String>)
782 -> Result<(), DuplicateVarName>;
783
784 /// Get the variable number for the given variable name, if present
785 ///
786 /// Note that you cannot retrieve unnamed variables.
787 /// `manager.name_to_var("")` always returns `None`.
788 fn name_to_var(&self, name: impl AsRef<str>) -> Option<VarNo>;
789
790 /// Get the level for the given variable
791 ///
792 /// Panics if `level >= self.num_vars()`.
793 fn var_to_level(&self, var: VarNo) -> LevelNo;
794
795 /// Get the variable for the given level
796 ///
797 /// Panics if `level >= self.num_levels()`.
798 fn level_to_var(&self, level: LevelNo) -> VarNo;
799
800 /// Get the level given by `no`
801 ///
802 /// Implementations may or may not acquire a lock here.
803 ///
804 /// Panics if `no >= self.num_levels()`.
805 #[must_use]
806 fn level(&self, no: LevelNo) -> Self::LevelView<'_>;
807
808 /// Get the level given by `no`. Unsafe version of [`Self::level()`]
809 ///
810 /// Implementations may or may not acquire a lock here.
811 ///
812 /// # Safety
813 ///
814 /// `no < self.num_levels()` must hold.
815 #[must_use]
816 unsafe fn level_unchecked(&self, no: LevelNo) -> Self::LevelView<'_>;
817
818 /// Iterate over the levels from top to bottom
819 #[must_use]
820 fn levels(&self) -> Self::LevelIterator<'_>;
821
822 /// Get an edge for the given terminal
823 ///
824 /// Locking behavior: May acquire a lock for the internal terminal unique
825 /// table. In particular, this means that calling this function while
826 /// holding a terminal iterator ([`Manager::terminals()`]) may cause a
827 /// deadlock.
828 #[must_use]
829 fn get_terminal(&self, terminal: Self::Terminal) -> AllocResult<Own<Self::Edge>>;
830
831 /// Get the number of terminals
832 ///
833 /// Should agree with the length of the iterator returned by
834 /// [`Manager::terminals()`].
835 ///
836 /// Locking behavior: May acquire a lock for the internal terminal unique
837 /// table. In particular, this means that calling this function while
838 /// holding a terminal iterator ([`Manager::terminals()`]) may cause a
839 /// deadlock.
840 #[must_use]
841 fn num_terminals(&self) -> usize;
842
843 /// Iterator over all terminals
844 ///
845 /// Locking behavior: May acquire a lock for the internal terminal unique
846 /// table.
847 #[must_use]
848 fn terminals(&self) -> Self::TerminalIterator<'_>;
849
850 /// Perform garbage collection
851 ///
852 /// This method looks for nodes that are neither referenced by a
853 /// [`Function`][function::Function] nor another node and removes them. The
854 /// method works from top to bottom, so if a node is only referenced by
855 /// nodes that can be removed, this node will be removed as well.
856 ///
857 /// Returns the number of nodes removed.
858 ///
859 /// The implementation should emit the [`ManagerEventSubscriber::pre_gc()`]
860 /// and [`ManagerEventSubscriber::post_gc()`] events unless called from the
861 /// closure passed to [`Self::reorder()`].
862 fn gc(&self) -> usize;
863
864 /// Prepare and postprocess a reordering operation. The reordering itself is
865 /// performed in `f`.
866 ///
867 /// Returns the value returned by `f`.
868 ///
869 /// In case of a recursive call (i.e., the closure passed to this method
870 /// calls this method again), the implementation should just call `f` and
871 /// return.
872 ///
873 /// Otherwise, the implementation should emit
874 /// [events][ManagerEventSubscriber] in the following order:
875 ///
876 /// 1. [`pre_gc`][ManagerEventSubscriber::pre_gc()]. This enables node
877 /// removal during the `pre_reorder` events.
878 /// 2. [`pre_reorder`][ManagerEventSubscriber::pre_reorder()] and
879 /// [`pre_reorder_mut`][ManagerEventSubscriber::pre_reorder_mut()]
880 /// 3. Call `f`
881 /// 4. [`post_reorder`][ManagerEventSubscriber::post_reorder()] and
882 /// [`post_reorder_mut`][ManagerEventSubscriber::post_reorder_mut()]
883 /// 5. [`post_gc`][ManagerEventSubscriber::post_gc()]
884 fn reorder<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T;
885
886 /// Get the count of garbage collections
887 ///
888 /// This counter should monotonically increase to ensure that caches are
889 /// invalidated accordingly.
890 fn gc_count(&self) -> u64;
891
892 /// Get the count of reordering operations
893 ///
894 /// This counter should monotonically increase to ensure that caches are
895 /// invalidated accordingly.
896 fn reorder_count(&self) -> u64;
897}
898
899/// Event subscriber for [`Manager`]-related events
900///
901/// This is intended to be implemented by data structures that can be plugged
902/// into the [`Manager`], e.g., an [`ApplyCache`] implementation.
903///
904/// # Use Cases
905///
906/// When using reference counting to implement garbage collection of dead nodes,
907/// cloning and dropping edges when inserting entries into the apply cache may
908/// cause many CPU cache misses. To circumvent this performance issue, the apply
909/// cache may store raw [`Edge`]s. Now, the apply cache implementation has to
910/// guarantee that every edge returned by the [`get()`][ApplyCache::get]
911/// method still points to a valid node. To that end, the cache may, e.g., clear
912/// itself when [`Self::pre_gc()`] is called and reject any insertion of new
913/// entries until [`Self::post_gc()`].
914///
915/// # Safety
916///
917/// A use-case such as the one described above requires the `pre_*` methods to
918/// actually be called before any garbage collection / reordering for SAFETY.
919/// This means the struct implementing `ManagerEventSubscriber` must only be
920/// plugged into [`Manager`] implementations or other wrapper structures that
921/// uphold this contract, i.e., creation of the `ManagerEventSubscriber`
922/// implementation must be `unsafe`.
923///
924/// Additionally, we require each [`post_gc`][Self::post_gc] call to be paired
925/// with a distinct preceding [`pre_gc`][Self::pre_gc] call, see below.
926pub trait ManagerEventSubscriber<M: Manager> {
927 /// Initialization
928 ///
929 /// This method is called once at the very end of initializing a new
930 /// manager.
931 #[inline(always)]
932 #[allow(unused_variables)]
933 fn init(&self, manager: &M) {}
934
935 /// Initialization
936 ///
937 /// This is an alternative to [`Self::post_reorder()`] with a mutable
938 /// reference to the manager as an argument. Since `self` may be a
939 /// substructure of `manager`, the method cannot provide mutable references
940 /// to both `self` and `manager`.
941 #[inline(always)]
942 #[allow(unused_variables)]
943 fn init_mut(manager: &mut M) {}
944
945 /// Prepare a garbage collection
946 ///
947 /// The [`Manager`] implementation should only remove nodes (as part of a
948 /// garbage collection or reordering) after calling this method. Between a
949 /// `pre_gc` and the subsequent [`post_gc`][Self::post_gc] call, there
950 /// should not be another `pre_gc` call.
951 ///
952 /// This method may lock (parts of) `self`. Unlocking is then done in
953 /// [`Self::post_gc()`].
954 ///
955 /// Note that this method and [`Self::pre_reorder`] may both be called in
956 /// case of reordering, but can also be
957 #[inline(always)]
958 #[allow(unused_variables)]
959 fn pre_gc(&self, manager: &M) {}
960
961 /// Post-process a garbage collection
962 ///
963 /// # Safety
964 ///
965 /// Each call to this method must be paired with a distinct preceding
966 /// [`Self::pre_gc()`] call. All operations potentially removing nodes must
967 /// happen between such a pair of method calls.
968 #[inline(always)]
969 #[allow(unused_variables)]
970 unsafe fn post_gc(&self, manager: &M) {}
971
972 /// Prepare a reordering operation (including any addition of levels)
973 ///
974 /// The [`Manager`] implementation should only add or reorder levels after
975 /// calling this method and [`pre_reorder_mut`][Self::pre_reorder_mut].
976 /// Between a `pre_reorder` and the subsequent
977 /// [`post_reorder`][Self::post_reorder] call, there should not be
978 /// another `pre_reorder` call.
979 #[inline(always)]
980 #[allow(unused_variables)]
981 fn pre_reorder(&self, manager: &M) {}
982
983 /// Prepare a reordering operation (including any addition of levels)
984 ///
985 /// This is an alternative to [`Self::pre_reorder()`] with a mutable
986 /// reference to the manager as an argument. Since `self` may be a
987 /// substructure of `manager`, the method cannot provide mutable references
988 /// to both `self` and `manager`.
989 #[inline(always)]
990 #[allow(unused_variables)]
991 fn pre_reorder_mut(manager: &mut M) {}
992
993 /// Post-process a reordering operation
994 ///
995 /// Each call to this method should be paired with a distinct preceding
996 /// [`Self::pre_reorder()`] call. All operations reordering (or adding)
997 /// levels of the decision diagram should happen between such a pair of
998 /// method calls.
999 #[inline(always)]
1000 #[allow(unused_variables)]
1001 fn post_reorder(&self, manager: &M) {}
1002
1003 /// Post-process a reordering operation
1004 ///
1005 /// This is an alternative to [`Self::post_reorder()`] with a mutable
1006 /// reference to the manager as an argument. Since `self` may be a
1007 /// substructure of `manager`, the method cannot provide mutable references
1008 /// to both `self` and `manager`.
1009 #[inline(always)]
1010 #[allow(unused_variables)]
1011 fn post_reorder_mut(manager: &mut M) {}
1012}
1013
1014/// View of a single level in the manager
1015///
1016/// # Safety
1017///
1018/// Each level view is associated with a [`Manager`] M and a [`LevelNo`] L. The
1019/// level view must ensure that all contained nodes and their descendants are
1020/// stored in M. The edges returned by [`LevelView::get()`] and
1021/// [`LevelView::get_or_insert()`] must reference nodes at this level.
1022/// [`LevelView::iter()`] must yield all edges to nodes at this level (it must
1023/// not hide some away).
1024///
1025/// [`LevelView::swap()`] conceptually removes all nodes from this level and
1026/// inserts them at the other level and vice versa.
1027pub unsafe trait LevelView<E: Edge, N: InnerNode<E>> {
1028 /// Iterator over [`Edge`]s pointing to nodes at this level
1029 type Iterator<'a>: Iterator<Item = Ref<'a, E>>
1030 where
1031 Self: 'a,
1032 E: 'a;
1033
1034 /// Taken level view, see [`LevelView::take()`]
1035 type Taken: LevelView<E, N>;
1036
1037 /// Get the number of nodes on this level
1038 #[must_use]
1039 fn len(&self) -> usize;
1040
1041 /// Returns `true` iff this level contains nodes
1042 #[must_use]
1043 fn is_empty(&self) -> bool {
1044 self.len() == 0
1045 }
1046
1047 /// Get the level number of this level
1048 #[must_use]
1049 fn level_no(&self) -> LevelNo;
1050
1051 /// Reserve space for `additional` nodes on this level
1052 fn reserve(&mut self, additional: usize);
1053
1054 /// Get the edge corresponding to the given node (if present)
1055 #[must_use]
1056 fn get(&self, node: &N) -> Option<Ref<'_, E>>;
1057
1058 /// Insert the given edge into the unique table at this level, assuming that
1059 /// the referenced node is already stored in the associated manager.
1060 ///
1061 /// Returns `true` if the edge was inserted, `false` if it was already
1062 /// present.
1063 ///
1064 /// Panics if `edge`
1065 /// - points to a terminal node,
1066 /// - references a node from a different manager, or
1067 /// - `N` implements [`HasLevel`] and `edge` references a node for which
1068 /// [`HasLevel::level()`] returns a different level.
1069 ///
1070 /// Furthermore, this function ideally panics if `edge` is tagged, but the
1071 /// caller must not rely on that. An implementation may simply remove the
1072 /// tag for optimization purposes.
1073 fn insert(&mut self, edge: Own<E>) -> bool;
1074
1075 /// Insert the given edge into the unique table at this level, assuming that
1076 /// the referenced node is already stored in the associated manager. Unsafe
1077 /// version of [`Self::insert()`].
1078 ///
1079 /// Returns `true` if the edge was inserted, `false` if it was already
1080 /// present.
1081 ///
1082 /// Panics if `edge` references a node from a different manager.
1083 /// Furthermore, this function ideally panics if `edge` is tagged, but the
1084 /// caller must not rely on that. An implementation may simply remove the
1085 /// tag for optimization purposes.
1086 ///
1087 /// # Safety
1088 ///
1089 /// The caller must ensure that edge points to an inner node. Additionally,
1090 /// if `N` implements [`HasLevel`], [`HasLevel::level()`] must return the
1091 /// level number of this level for the referenced node. During reordering,
1092 /// the second requirement does not need to be fulfilled immediately,
1093 /// but must hold at the end of the reordering process.
1094 unsafe fn insert_unchecked(&mut self, edge: Own<E>) -> bool;
1095
1096 /// Get the edge corresponding to `level` and `node` if present, or insert
1097 /// it.
1098 ///
1099 /// Panics if
1100 /// - the children of `node` are stored in a different manager, or
1101 /// - `N` implements [`HasLevel`] and
1102 /// [`HasLevel::level(node)`][HasLevel::level()] returns a different
1103 /// level.
1104 #[must_use]
1105 fn get_or_insert(&mut self, node: N) -> AllocResult<Own<E>>;
1106
1107 /// Get the edge corresponding to `level` and `node` if present, or insert
1108 /// it. Unsafe version of [`Self::get_or_insert()`]
1109 ///
1110 /// Panics if the children of `node` are stored in a different manager.
1111 ///
1112 /// # Safety
1113 ///
1114 /// If `N` implements [`HasLevel`], the caller must ensure that
1115 /// [`HasLevel::level(node)`][HasLevel::level()] returns the level number of
1116 /// this level. During reordering, this requirement does not need to be
1117 /// fulfilled immediately, but must hold at the end of the reordering
1118 /// process.
1119 #[must_use]
1120 unsafe fn get_or_insert_unchecked(&mut self, node: N) -> AllocResult<Own<E>>;
1121
1122 /// Perform garbage collection on this level
1123 ///
1124 /// This method may be a no-op unless a garbage collection has been
1125 /// prepared. For instance, this is what [`Manager::reorder()`] does.
1126 fn gc(&mut self);
1127
1128 /// Try to remove the node referred to by `edge` from (this level of) the
1129 /// manager
1130 ///
1131 /// Returns whether the node was present at this level and has been removed.
1132 ///
1133 /// This method may be a no-op unless a garbage collection has been
1134 /// prepared. For instance, this is what [`Manager::reorder()`] does. In the
1135 /// no-op case, the return value is always false.
1136 fn try_remove(&mut self, edge: Own<E>) -> bool;
1137
1138 /// Move all nodes from this level to the other level and vice versa.
1139 ///
1140 /// # Safety
1141 ///
1142 /// This method does not necessarily change the level returned by
1143 /// [`HasLevel::level()`] for the nodes at this or the `other` level. The
1144 /// caller must ensure a consistent state using calls to
1145 /// [`HasLevel::set_level()`]. (Be aware of exception safety!)
1146 unsafe fn swap(&mut self, other: &mut Self);
1147
1148 /// Iterate over all the edges at this level
1149 #[must_use]
1150 fn iter(&self) -> Self::Iterator<'_>;
1151
1152 /// If a reordering operation is in progress: Clear this level, returning a
1153 /// level view containing all the previous edges. Otherwise, this method
1154 /// returns `None` and leaves `self` unchanged.
1155 #[must_use]
1156 fn take(&mut self) -> Option<Self::Taken>;
1157}
1158
1159/// Cache for the result of apply operations
1160///
1161/// This trait provides methods to add computation results to the apply cache
1162/// and to query the cache for these results. Just as every cache, the
1163/// implementation may decide to evict results from the cache.
1164pub trait ApplyCache<M: Manager, O: Copy>: DropWith<M::Edge> {
1165 /// Get the result for the key consisting of `operand` and `operator`, if
1166 /// cached
1167 ///
1168 /// This is the extended version of [`Self::get()`], allowing for numeric
1169 /// operands and multiple, possibly numeric values. The constants `E` and
1170 /// `N` indicate the number of expected edge values and numeric values,
1171 /// respectively.
1172 #[must_use]
1173 #[allow(clippy::type_complexity)]
1174 fn get_extended<const E: usize, const N: usize>(
1175 &self,
1176 manager: &M,
1177 operator: O,
1178 operands: (&[Ref<'_, M::Edge>], &[u32]),
1179 ) -> Option<([Own<M::Edge>; E], [u32; N])>;
1180
1181 /// Add the result of `operation` to this cache
1182 ///
1183 /// An implementation is free to not cache any result. (This is why we use
1184 /// [`Ref<M::Edge>`], which in this case elides a few clone and drop
1185 /// operations.) If the cache already contains the key consisting of
1186 /// `operator` and `operands`, there is no need to update its value. (Again,
1187 /// an implementation could elide clone and drop operations.)
1188 #[allow(clippy::type_complexity)]
1189 fn add_extended(
1190 &self,
1191 manager: &M,
1192 operator: O,
1193 operands: (&[Ref<'_, M::Edge>], &[u32]),
1194 values: (&[Ref<'_, M::Edge>], &[u32]),
1195 );
1196
1197 /// Shorthand for [`Self::get_extended()`] without numeric operands and just
1198 /// a single edge value
1199 #[inline(always)]
1200 #[must_use]
1201 fn get(&self, manager: &M, operator: O, operands: &[Ref<'_, M::Edge>]) -> Option<Own<M::Edge>> {
1202 let ([e], []) = self.get_extended::<1, 0>(manager, operator, (operands, &[]))?;
1203 Some(e)
1204 }
1205
1206 /// Shorthand for [`Self::add_extended()`] without numeric operands and just
1207 /// a single edge value
1208 #[inline(always)]
1209 fn add(
1210 &self,
1211 manager: &M,
1212 operator: O,
1213 operands: &[Ref<'_, M::Edge>],
1214 value: Ref<'_, M::Edge>,
1215 ) {
1216 self.add_extended(manager, operator, (operands, &[]), (&[value], &[]))
1217 }
1218
1219 /// Remove all entries from the cache
1220 fn clear(&self, manager: &M);
1221}
1222
1223/// Apply cache container
1224///
1225/// Intended to be implemented by [`Manager`]s such that generic implementations
1226/// of the recursive apply algorithm can simply require
1227/// `M: Manager + HasApplyCache<M, O>`, where `O` is the operator type.
1228pub trait HasApplyCache<M: Manager, O: Copy> {
1229 /// The concrete apply cache type
1230 type ApplyCache: ApplyCache<M, O>;
1231
1232 /// Get a shared reference to the contained apply cache
1233 #[must_use]
1234 fn apply_cache(&self) -> &Self::ApplyCache;
1235
1236 /// Get a mutable reference to the contained apply cache
1237 #[must_use]
1238 fn apply_cache_mut(&mut self) -> &mut Self::ApplyCache;
1239}
1240
1241/// Worker thread pool associated with a [`Manager`]
1242///
1243/// A manager having its own thread pool has the advantage that it may use
1244/// thread-local storage for its workers to pre-allocate some resources (e.g.,
1245/// slots for nodes) and thereby reduce lock contention.
1246pub trait WorkerPool: Sync {
1247 /// Get the current number of threads
1248 fn current_num_threads(&self) -> usize;
1249
1250 /// Get the recursion depth up to which operations are split
1251 fn split_depth(&self) -> u32;
1252
1253 /// Set the recursion depth up to which operations are split
1254 ///
1255 /// `None` means that the implementation should automatically choose the
1256 /// depth. `Some(0)` means that no operations are split.
1257 fn set_split_depth(&self, depth: Option<u32>);
1258
1259 /// Execute `op` within the thread pool
1260 ///
1261 /// If this method is called from another thread pool, it may cooperatively
1262 /// yield execution to that pool until `op` has finished.
1263 fn install<R: Send>(&self, op: impl FnOnce() -> R + Send) -> R;
1264
1265 /// Execute `op_a` and `op_b` in parallel within the thread pool
1266 ///
1267 /// Note that the split depth has no influence on this method. Checking
1268 /// whether to split an operation must be done externally.
1269 fn join<RA: Send, RB: Send>(
1270 &self,
1271 op_a: impl FnOnce() -> RA + Send,
1272 op_b: impl FnOnce() -> RB + Send,
1273 ) -> (RA, RB);
1274
1275 /// Execute `op` on every worker in the thread pool
1276 fn broadcast<R: Send>(&self, op: impl Fn(BroadcastContext) -> R + Sync) -> Vec<R>;
1277
1278 /// Execute `op` concurrently for every element of `slice`
1279 fn slice_for_each<T: Sync>(&self, slice: &[T], op: impl Fn(&T) + Sync) {
1280 match slice {
1281 [] => {}
1282 [x] => op(x),
1283 _ => {
1284 let done = std::sync::atomic::AtomicU64::new(0);
1285 self.broadcast(|_| {
1286 loop {
1287 let i = done.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1288 if i >= slice.len() as u64 {
1289 return;
1290 }
1291 op(&slice[i as usize])
1292 }
1293 });
1294 }
1295 }
1296 }
1297}
1298
1299/// Context provided to workers by [`WorkerPool::broadcast()`]
1300#[derive(Clone, Copy, Debug)]
1301pub struct BroadcastContext {
1302 /// Index of this worker (in range `0..num_threads`)
1303 pub index: u32,
1304
1305 /// Number of threads receiving the broadcast
1306 pub num_threads: u32,
1307}
1308
1309/// Helper trait to be implemented by [`Manager`] and [`ManagerRef`] if they
1310/// feature a [`WorkerPool`].
1311pub trait HasWorkers: Sync {
1312 /// Type of the worker pool
1313 type WorkerPool: WorkerPool;
1314
1315 /// Get the worker pool
1316 fn workers(&self) -> &Self::WorkerPool;
1317}