Skip to main content

mid_tools/union_find/
linked_arc.rs

1use core::fmt;
2use std::{
3    cmp::Ordering,
4    mem,
5    sync::{Arc, Weak},
6};
7
8use spin::mutex::SpinMutex;
9
10use super::disjoint_set::{NoNode, RankedUnion};
11use crate::free::{Free, Succ};
12
13#[derive(Debug, Clone, Copy)]
14pub struct LinkedArc;
15
16const DROP_ERROR: &str = "Node dropped while still in use";
17
18struct DebugStr(&'static str);
19
20impl fmt::Debug for DebugStr {
21    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(self.0) }
22}
23
24struct RootInner<T: ?Sized, R, X> {
25    canon: Weak<T>,
26    rank: R,
27    next: Option<Arc<RootRef<T, R, X>>>,
28}
29
30pub struct RootRef<T: ?Sized, R, X> {
31    id: R,
32    inner: SpinMutex<RootInner<T, R, X>>,
33}
34
35impl<T: fmt::Debug, R: fmt::Debug, X> fmt::Debug for RootRef<T, R, X> {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        let Self { id, inner } = self;
38
39        if let Some(inner) = inner.try_lock() {
40            let RootInner { canon, rank, next } = &*inner;
41            let canon = canon.upgrade();
42            f.debug_struct("RootRef")
43                .field("id", &id)
44                .field(
45                    "canon",
46                    if let Some(canon) = canon.as_deref() {
47                        canon
48                    } else {
49                        &DebugStr("<dropped>")
50                    },
51                )
52                .field("rank", &rank)
53                .field("next", &next)
54                .finish()
55        } else {
56            f.debug_tuple("RootRef")
57                .field(&id)
58                .field(&DebugStr("<locked>"))
59                .finish()
60        }
61    }
62}
63
64impl<T: ?Sized, R, X> RootRef<T, R, X> {
65    fn find(self: &mut Arc<Self>) -> Option<&mut Arc<Self>> {
66        let mut inner = self.inner.lock();
67
68        if let Some(root) = inner.next.as_mut() {
69            root.find();
70
71            let root = Arc::clone(root);
72            drop(inner);
73
74            *self = root;
75            Some(self)
76        } else {
77            None
78        }
79    }
80
81    #[inline]
82    pub fn id(&self) -> &R { &self.id }
83
84    #[inline]
85    pub fn canon(&self) -> Option<Arc<T>> { self.inner.lock().canon.upgrade() }
86
87    #[inline]
88    pub fn is_root(&self) -> bool { self.inner.lock().next.is_none() }
89}
90
91impl<T: AsNode<Rank = R, Extra = X> + ?Sized, R: NodeRank, X: LinkedNodeExtra<T>> RootRef<T, R, X> {
92    pub fn merge_into(self: &Arc<Self>, root: &Arc<Self>) -> bool {
93        if Arc::ptr_eq(self, root) {
94            return false;
95        }
96
97        let root_rc = Arc::clone(root);
98        let mut root = root.inner.lock();
99        let mut merged = self.inner.lock();
100
101        assert!(root.next.is_none() && merged.next.is_none());
102
103        let root_canon = root.canon.upgrade().expect(DROP_ERROR);
104        let merged_canon = merged.canon.upgrade().expect(DROP_ERROR);
105
106        X::merge(&root_canon.as_node().extra, &merged_canon.as_node().extra);
107
108        root.rank = root.rank.join(merged.rank);
109        merged.next = Some(root_rc);
110
111        true
112    }
113}
114
115pub trait LinkedNodeExtra<T: ?Sized> {
116    fn new(node: &Weak<T>) -> Self;
117
118    fn merge(root: &Self, merged: &Self);
119}
120
121impl<T> LinkedNodeExtra<T> for () {
122    fn new(_: &Weak<T>) {}
123
124    fn merge((): &(), (): &()) {}
125}
126
127pub struct CircularList<T> {
128    next: SpinMutex<Weak<T>>,
129}
130
131impl<T> fmt::Debug for CircularList<T> {
132    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
133        f.write_str("CircularList")
134    }
135}
136
137impl<T> LinkedNodeExtra<T> for CircularList<T> {
138    fn new(node: &Weak<T>) -> Self {
139        Self {
140            next: Weak::clone(node).into(),
141        }
142    }
143
144    fn merge(root: &Self, merged: &Self) {
145        let mut root = root.next.lock();
146        let mut merged = merged.next.lock();
147        mem::swap(&mut *root, &mut *merged);
148    }
149}
150
151pub trait NodeRank: Copy {
152    const SINGLE: Self;
153
154    #[must_use]
155    fn join(self, other: Self) -> Self;
156}
157
158macro_rules! int_rank {
159    () => {};
160    ($ty:ty $(, $($tts:tt)*)?) => {
161        impl NodeRank for $ty {
162            const SINGLE: Self = 1;
163
164            #[inline]
165            fn join(self, other: Self) -> Self {
166                self.checked_add(other).unwrap_or_else(|| unreachable!())
167            }
168        }
169
170        $(int_rank!($($tts)*);)?
171    };
172}
173
174int_rank!(u8, u16, u32, u64, u128, usize);
175
176#[derive(Clone, Copy)]
177pub struct NoRank;
178
179impl fmt::Debug for NoRank {
180    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("∅") }
181}
182
183impl NodeRank for NoRank {
184    const SINGLE: Self = Self;
185
186    #[inline]
187    fn join(self, other: Self) -> Self {
188        let Self = self;
189        let Self = other;
190        Self
191    }
192}
193
194pub struct LinkedNodeBase<T: ?Sized, R, X> {
195    id: R,
196    root: SpinMutex<Arc<RootRef<T, R, X>>>,
197    extra: X,
198}
199
200pub type LinkedNode<T> = LinkedNodeBase<T, <T as AsNode>::Rank, <T as AsNode>::Extra>;
201
202impl<T: fmt::Debug, R: fmt::Debug, X: fmt::Debug> fmt::Debug for LinkedNodeBase<T, R, X> {
203    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
204        let Self { id, root, extra } = self;
205        let root = root.try_lock();
206
207        f.debug_tuple("LinkedNode")
208            .field(id)
209            .field(if let Some(root) = root.as_deref() {
210                root
211            } else {
212                &DebugStr("<locked>")
213            })
214            .field(extra)
215            .finish()
216    }
217}
218
219impl<T, R: NodeRank, X: LinkedNodeExtra<T>> LinkedNodeBase<T, R, X> {
220    #[must_use]
221    pub fn from_id<F: FnOnce(Self) -> T>(id: R, f: F) -> Arc<T> {
222        Arc::new_cyclic(|n| {
223            f(Self {
224                id,
225                root: Arc::new(RootRef {
226                    id,
227                    inner: RootInner {
228                        canon: Weak::clone(n),
229                        rank: R::SINGLE,
230                        next: None,
231                    }
232                    .into(),
233                })
234                .into(),
235                extra: X::new(n),
236            })
237        })
238    }
239}
240
241impl<T, X: LinkedNodeExtra<T>> LinkedNodeBase<T, NoRank, X> {
242    pub fn new_arc<F: FnOnce(Self) -> T>(f: F) -> Arc<T> { Self::from_id(NoRank, f) }
243}
244
245impl<T, R: NodeRank + Succ, X: LinkedNodeExtra<T>> LinkedNodeBase<T, R, X> {
246    #[must_use]
247    pub fn new_fresh<F: FnOnce(Self) -> T>(ids: &mut Free<R>, f: F) -> Arc<T> {
248        Self::from_id(ids.fresh(), f)
249    }
250}
251
252impl<T: ?Sized, R, X> LinkedNodeBase<T, R, X> {
253    pub fn id(&self) -> &R { &self.id }
254
255    pub fn root(&self) -> Arc<RootRef<T, R, X>> {
256        let mut root = self.root.lock();
257        root.find();
258        Arc::clone(&root)
259    }
260}
261
262pub trait AsNode {
263    type Extra;
264    type Rank;
265
266    fn as_node(&self) -> &LinkedNodeBase<Self, Self::Rank, Self::Extra>;
267}
268
269pub trait NodeRef {
270    type Value: AsNode<Extra = Self::Extra, Rank = Self::Rank>;
271    type Extra;
272    type Rank;
273
274    fn node_ref(&self) -> &LinkedNodeBase<Self::Value, Self::Rank, Self::Extra>;
275}
276
277impl<T: AsNode> NodeRef for T {
278    type Extra = T::Extra;
279    type Rank = T::Rank;
280    type Value = T;
281
282    #[inline]
283    fn node_ref(&self) -> &LinkedNodeBase<T, T::Rank, T::Extra> { self.as_node() }
284}
285
286impl<T: AsNode> NodeRef for Arc<T> {
287    type Extra = T::Extra;
288    type Rank = T::Rank;
289    type Value = T;
290
291    #[inline]
292    fn node_ref(&self) -> &LinkedNodeBase<Self::Value, Self::Rank, Self::Extra> { self.as_node() }
293}
294
295impl<'a, T: NodeRef<Rank: Ord + NodeRank, Extra: LinkedNodeExtra<T::Value>>> RankedUnion<&'a T>
296    for LinkedArc
297{
298    type Rank = T::Rank;
299    type Root = Arc<RootRef<T::Value, T::Rank, T::Extra>>;
300
301    #[inline]
302    fn find(&self, key: &'a T) -> Result<Self::Root, NoNode<&'a T>> { Ok(key.node_ref().root()) }
303
304    #[inline]
305    fn cmp_roots(&self, a: &Self::Root, b: &Self::Root) -> Ordering { a.id.cmp(&b.id) }
306
307    #[inline]
308    fn rank(&self, root: &Self::Root) -> Option<T::Rank> { Some(root.inner.lock().rank) }
309
310    #[inline]
311    fn merge(&mut self, root: &Self::Root, merged: &Self::Root) { merged.merge_into(root); }
312}
313
314#[cfg(test)]
315#[allow(dead_code)]
316fn assert_impls() {
317    use crate::union_find::disjoint_set;
318
319    #[derive(Debug)]
320    struct MyNode(LinkedNode<Self>);
321
322    impl AsNode for MyNode {
323        type Extra = ();
324        type Rank = u64;
325
326        #[inline]
327        fn as_node(&self) -> &LinkedNode<Self> { &self.0 }
328    }
329
330    #[allow(unreachable_code)]
331    fn node() -> Arc<MyNode> { LinkedNode::new_fresh(unreachable!(), MyNode) }
332
333    disjoint_set::ranked_union(&mut LinkedArc, &node(), &node()).unwrap();
334}