Debian Codegraph @

src/nouveau/compiler/nak/union_find.rs

raw
1 // Copyright © 2024 Mel Henning
2 // SPDX-License-Identifier: MIT
3
4 use std::collections::HashMap;
5 use std::hash::{BuildHasher, Hash};
6
7 #[derive(Copy, Clone)]
8 struct Root<X: Copy> {
9 size: usize,
10 representative: X,
11 }
12
13 #[derive(Copy, Clone)]
14 enum Node<X: Copy> {
15 Child { parent_idx: usize },
16 Root(Root<X>),
17 }
18
19 /// Union-find structure
20 ///
21 /// This implementation follows Tarjan and van Leeuwen - specifically the
22 /// "link by size" and "halving" variant.
23 ///
24 /// Robert E. Tarjan and Jan van Leeuwen. 1984. Worst-case Analysis of Set
25 /// Union Algorithms. J. ACM 31, 2 (April 1984), 245–281.
26 /// <https://doi.org/10.1145/62.2160>
27 pub struct UnionFind<X: Copy + Hash + Eq, H: BuildHasher + Default> {
28 idx_map: HashMap<X, usize, H>,
29 nodes: Vec<Node<X>>,
30 }
31
32 impl<X: Copy + Hash + Eq, H: BuildHasher + Default> UnionFind<X, H> {
33 /// Create a new union-find structure
34 ///
35 /// At initialization, each possible value is in its own set
36 pub fn new() -> Self {
37 UnionFind {
38 idx_map: Default::default(),
39 nodes: Vec::new(),
40 }
41 }
42
43 fn find_root(&mut self, mut idx: usize) -> (usize, Root<X>) {
44 loop {
45 match self.nodes[idx] {
46 Node::Child { parent_idx } => {
47 match self.nodes[parent_idx] {
48 Node::Child {
49 parent_idx: grandparent_idx,
50 } => {
51 // "Halving" in Tarjan and van Leeuwen
52 self.nodes[idx] = Node::Child {
53 parent_idx: grandparent_idx,
54 };
55 idx = grandparent_idx;
56 }
57 Node::Root(parent_root) => {
58 return (parent_idx, parent_root)
59 }
60 }
61 }
62 Node::Root(root) => return (idx, root),
63 }
64 }
65 }
66
67 /// Find the representative element for x
68 pub fn find(&mut self, x: X) -> X {
69 match self.idx_map.get(&x) {
70 Some(&idx) => {
71 let (_, Root { representative, .. }) = self.find_root(idx);
72 representative
73 }
74 None => x,
75 }
76 }
77
78 fn map_or_create(&mut self, x: X) -> usize {
79 *self.idx_map.entry(x).or_insert_with(|| {
80 self.nodes.push(Node::Root(Root {
81 size: 1,
82 representative: x,
83 }));
84 self.nodes.len() - 1
85 })
86 }
87
88 /// Union the sets containing a and b
89 ///
90 /// The representative for a will become the representative of
91 /// the combined set
92 pub fn union(&mut self, a: X, b: X) {
93 if a == b {
94 return;
95 }
96
97 let a_idx = self.map_or_create(a);
98 let b_idx = self.map_or_create(b);
99 let (a_root_idx, a_root) = self.find_root(a_idx);
100 let (b_root_idx, b_root) = self.find_root(b_idx);
101
102 if a_root_idx != b_root_idx {
103 // Keep the tree balanced
104 let (new_root_idx, new_child_idx) = if a_root.size >= b_root.size {
105 (a_root_idx, b_root_idx)
106 } else {
107 (b_root_idx, a_root_idx)
108 };
109
110 self.nodes[new_root_idx] = Node::Root(Root {
111 size: a_root.size + b_root.size,
112 representative: a_root.representative,
113 });
114 self.nodes[new_child_idx] = Node::Child {
115 parent_idx: new_root_idx,
116 };
117 }
118 }
119
120 /// Return true if find() is the identity mapping
121 pub fn is_empty(&self) -> bool {
122 self.nodes.is_empty()
123 }
124 }
125
126 #[cfg(test)]
127 mod tests {
128 use crate::union_find::Node;
129 use crate::union_find::UnionFind;
130 use std::cmp::max;
131 use std::hash::BuildHasher;
132 use std::hash::Hash;
133 use std::hash::RandomState;
134
135 fn ceil_log2(x: usize) -> u32 {
136 assert!(x > 0);
137 usize::BITS - (x - 1).leading_zeros()
138 }
139
140 struct HeightInfo {
141 height: u32,
142 size: usize,
143 }
144
145 pub struct HeightCalc<'a, X: Copy + Hash + Eq, H: BuildHasher + Default> {
146 uf: &'a UnionFind<X, H>,
147 downward_edges: Vec<Vec<usize>>,
148 }
149
150 impl<'a, X: Copy + Hash + Eq, H: BuildHasher + Default> HeightCalc<'a, X, H> {
151 fn new(uf: &'a UnionFind<X, H>) -> Self {
152 let mut downward_edges: Vec<Vec<usize>> =
153 uf.nodes.iter().map(|_| Vec::new()).collect();
154 for (i, node) in uf.nodes.iter().enumerate() {
155 if let Node::Child { parent_idx } = node {
156 downward_edges[*parent_idx].push(i);
157 }
158 }
159
160 HeightCalc { uf, downward_edges }
161 }
162
163 fn calc_info(&self, idx: usize) -> HeightInfo {
164 let mut result = HeightInfo { height: 0, size: 1 };
165 for child in &self.downward_edges[idx] {
166 let child_result = self.calc_info(*child);
167 result.height = max(result.height, child_result.height + 1);
168 result.size += child_result.size;
169 }
170 result
171 }
172
173 fn check_roots(&self) -> u32 {
174 let mut total_size = 0;
175 let mut max_height = 0;
176 for (i, node) in self.uf.nodes.iter().enumerate() {
177 if let Node::Root(root) = node {
178 let info = self.calc_info(i);
179 assert_eq!(root.size, info.size);
180
181 total_size += info.size;
182 max_height = max(max_height, info.height);
183
184 let max_expected_height = ceil_log2(root.size + 1) - 1;
185 if info.height > max_expected_height {
186 eprintln!(
187 "height {}\t max_expected_height {}\t size {}",
188 info.height, max_expected_height, info.size
189 );
190 }
191 assert!(info.height <= max_expected_height);
192 }
193 }
194 assert_eq!(total_size, self.uf.nodes.len());
195 assert_eq!(total_size, self.uf.idx_map.len());
196 max_height
197 }
198
199 pub fn check(uf: &'a UnionFind<X, H>) -> u32 {
200 HeightCalc::new(uf).check_roots()
201 }
202 }
203
204 #[test]
205 fn test_basic() {
206 let mut f = UnionFind::<u32, RandomState>::new();
207 assert_eq!(f.find(10), 10);
208 assert_eq!(f.find(12), 12);
209
210 f.union(10, 12);
211 f.union(11, 13);
212
213 HeightCalc::check(&f);
214
215 assert_eq!(f.find(13), 11);
216 assert_eq!(f.find(12), 10);
217 assert_eq!(f.find(11), 11);
218 assert_eq!(f.find(10), 10);
219
220 f.union(12, 13);
221
222 HeightCalc::check(&f);
223
224 assert_eq!(f.find(13), 10);
225 assert_eq!(f.find(12), 10);
226 assert_eq!(f.find(11), 10);
227 assert_eq!(f.find(10), 10);
228
229 assert_eq!(f.find(14), 14);
230
231 HeightCalc::check(&f);
232
233 // Union the set with itself
234 f.union(11, 10);
235
236 HeightCalc::check(&f);
237
238 assert_eq!(f.find(13), 10);
239 assert_eq!(f.find(12), 10);
240 assert_eq!(f.find(11), 10);
241 assert_eq!(f.find(10), 10);
242 }
243
244 #[test]
245 fn test_chain_a_height() {
246 let mut f = UnionFind::<u32, RandomState>::new();
247 for i in 0..1000 {
248 f.union(i, i + 1);
249 HeightCalc::check(&f);
250 }
251 assert_eq!(f.find(1000), 0);
252 }
253
254 #[test]
255 fn test_chain_b_height() {
256 let mut f = UnionFind::<u32, RandomState>::new();
257 for i in 0..1000 {
258 f.union(i + 1, i);
259 HeightCalc::check(&f);
260 }
261 assert_eq!(f.find(0), 1000);
262 }
263
264 #[test]
265 fn test_binary_tree_height() {
266 let height = 8;
267 let count = 1 << height;
268
269 let mut f = UnionFind::<usize, RandomState>::new();
270 for current_height in 0..height {
271 let stride = 1 << current_height;
272 for i in (0..count).step_by(2 * stride) {
273 f.union(i, i + stride);
274 }
275 let actual_height = HeightCalc::check(&f);
276
277 // actual_height can vary based on tiebreaker condition
278 assert!(
279 actual_height == current_height
280 || actual_height == current_height + 1
281 );
282 }
283
284 // Check path halving
285 let actual_height_before = HeightCalc::check(&f);
286 for i in 0..count {
287 assert_eq!(f.find(i), 0);
288 }
289 let actual_height_after = HeightCalc::check(&f);
290
291 assert!(actual_height_after <= actual_height_before.div_ceil(2));
292 }
293 }