egglog_union_find/lib.rs
1//! This crate contains two basic union-find implementations:
2//!
3//! * [`UnionFind`], a basic single-threaded union-find data-structure.
4//! * [`concurrent::UnionFind`], a concurrent union-find data-structure.
5//!
6//! Both structures are fairly rudimentary and are customized to be used in an
7//! egraph-related setting. In particular, they do "union by min id", which is a
8//! strategy that _does not_ guarantee the same asymptotic complexity as the
9//! main techniques in the literature (e.g. union by rank). Union by min is a
10//! heuristic introduced to reduce the number of ids perturbed during congruence
11//! closure. There's likely more to do in this area but for now it seems to work
12//! well enough. It doesn't hurt that it's also simpler to implement.
13use egglog_numeric_id as numeric_id;
14use numeric_id::{AtomicNumericId, NumericId};
15use std::{cmp, marker::PhantomData, mem, slice};
16
17pub mod concurrent;
18
19#[cfg(test)]
20mod tests;
21
22/// A basic implementation of a union-find datastructure.
23#[derive(Clone)]
24pub struct UnionFind<Value> {
25 parents: Vec<Value>,
26}
27
28/// A concurrent, fixed-capacity view borrowed from a serial [`UnionFind`].
29///
30/// Creating this view requires exclusive access to the serial union-find. The
31/// view may be shared with scoped worker threads, and the serial representation
32/// becomes accessible again only after all of those borrows have ended.
33///
34/// Operations on this fixed view use relaxed atomics. Parent entries are the
35/// only shared state: a successful union changes a root from itself to a
36/// strictly smaller ID, and path splitting changes a parent to a strictly
37/// smaller ancestor. Consequently links never increase, cannot exhibit ABA,
38/// and cannot form a cycle. A stale load is still a same-component ancestor,
39/// while every mutation uses compare-exchange to verify the observed link.
40/// The scope join before this view is dropped provides the happens-before edge
41/// needed before ordinary reads resume; parent links do not publish any other
42/// payload.
43pub struct AtomicUnionFindAccess<'a, Value: AtomicNumericId> {
44 parents: &'a [Value::Atomic],
45 marker: PhantomData<Value>,
46}
47
48impl<Value: AtomicNumericId> AtomicUnionFindAccess<'_, Value>
49where
50 Value::Atomic: concurrent::atomic_int::AtomicInt<Underlying = Value::Rep>,
51{
52 /// Merge two equivalence classes.
53 ///
54 /// Panics if either ID exceeds the fixed capacity selected when this view
55 /// was created.
56 #[inline]
57 pub fn union(&self, l: Value, r: Value) -> (Value, Value) {
58 let (parent, child) = concurrent::uf::merge_scoped_impl(self.parents, l.rep(), r.rep());
59 (Value::new(parent), Value::new(child))
60 }
61}
62
63impl<V> Default for UnionFind<V> {
64 fn default() -> Self {
65 Self {
66 parents: Vec::new(),
67 }
68 }
69}
70
71impl<Value: NumericId> UnionFind<Value> {
72 /// Reset the union-find data-structure to the point where all Ids are their
73 /// own parents.
74 pub fn reset(&mut self) {
75 for (i, v) in self.parents.iter_mut().enumerate() {
76 *v = Value::from_usize(i);
77 }
78 }
79
80 /// Reserve sufficient space for the given value `v`.
81 pub fn reserve(&mut self, v: Value) {
82 if v.index() >= self.parents.len() {
83 for i in self.parents.len()..=v.index() {
84 self.parents.push(Value::from_usize(i));
85 }
86 }
87 }
88
89 /// Merge two equivalence classes.
90 pub fn union(&mut self, a: Value, b: Value) -> (Value /* parent */, Value /* child */) {
91 self.reserve(a);
92 self.reserve(b);
93 let a = self.find(a);
94 let b = self.find(b);
95 if a != b {
96 let parent = cmp::min(a, b);
97 let child = cmp::max(a, b);
98 self.parents[child.index()] = parent;
99 (parent, child)
100 } else {
101 (a, a)
102 }
103 }
104
105 /// Find the representative of an equivalence class.
106 pub fn find(&mut self, id: Value) -> Value {
107 self.reserve(id);
108 let mut cur = id;
109 loop {
110 let parent = self.parents[cur.index()];
111 if cur == parent {
112 break;
113 }
114 let grand = self.parents[parent.index()];
115 self.parents[cur.index()] = grand;
116 cur = grand;
117 }
118 cur
119 }
120
121 /// Find the representative of an equivalence class without using path compression.
122 ///
123 /// The primary advantage of this method is that it allows the ability to answer `find` queries
124 /// without holding a mutable reference to the union-find.
125 pub fn find_naive(&self, id: Value) -> Value {
126 if self.parents.len() <= id.index() {
127 return id;
128 }
129 let mut cur = id;
130 loop {
131 let parent = self.parents[cur.index()];
132 if cur == parent {
133 break;
134 }
135 cur = parent;
136 }
137 cur
138 }
139}
140
141impl<Value: AtomicNumericId> UnionFind<Value>
142where
143 Value::Atomic: concurrent::atomic_int::AtomicInt<Underlying = Value::Rep>,
144{
145 /// Temporarily borrow this union-find as a fixed-capacity atomic view.
146 ///
147 /// The backing vector is grown before the atomic view is created and
148 /// cannot resize while `f` runs. Atomic and ordinary accesses never
149 /// overlap: the mutable receiver excludes ordinary readers until `f` and
150 /// every scoped worker borrowing its view have completed. No allocation,
151 /// resize, or per-operation access guard occurs while the view is active.
152 /// `max_id` is inclusive, and `f` must not request a union containing a
153 /// larger ID.
154 ///
155 /// # Panics
156 ///
157 /// Panics if the ID and its atomic integer do not have identical size and
158 /// alignment on the target platform.
159 pub fn with_atomic_access<R>(
160 &mut self,
161 max_id: Value,
162 f: impl FnOnce(&AtomicUnionFindAccess<'_, Value>) -> R,
163 ) -> R {
164 self.reserve(max_id);
165 assert_eq!(
166 mem::size_of::<Value>(),
167 mem::size_of::<Value::Atomic>(),
168 "numeric id and atomic representation must have equal size"
169 );
170 assert_eq!(
171 mem::align_of::<Value>(),
172 mem::align_of::<Value::Atomic>(),
173 "numeric id and atomic representation must have equal alignment"
174 );
175
176 // SAFETY:
177 // - `AtomicNumericId` guarantees a transparent integer
178 // representation compatible with the corresponding atomic; the
179 // assertions above defensively verify its size and alignment.
180 // - Integer bit patterns are valid atomic integer bit patterns.
181 // - `&mut self` excludes every ordinary access to `parents` for the
182 // lifetime of this slice.
183 // - `f` cannot let the borrowed view escape, so every atomic access
184 // ends before ordinary access resumes.
185 let parents = unsafe {
186 slice::from_raw_parts(
187 self.parents.as_mut_ptr().cast::<Value::Atomic>(),
188 self.parents.len(),
189 )
190 };
191 f(&AtomicUnionFindAccess {
192 parents,
193 marker: PhantomData,
194 })
195 }
196}