1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
//! Generic tree visitation functions that can be used with tree-like structures
//!
//! In order to use these algorithms, the data structure has to implement the [`TreeNode`] and for
//! mutable access the [`TreeNodeMut`] trait. These traits only require to give access to a slice
//! of child nodes of a node.
//!
//! This module provides algorithms for breadth-first and depth-first visitation.
//! Overview of the traits:
//!  - [`VisitableTree`] provides non-mutable sequential iteration.
//!  - [`MutVisitableTree`] provides sequential visitation using a visitor function with mutable access to the current node.
//!  - [`ParVisitableTree`] provides parallel visitation using a visitor function, parallelized using rayon.
//!  - [`ParMutVisitableTree`] provides parallel visitation using a visitor function with mutable access to the current node, parallelized using rayon.
//!
//! Note that the mutation of nodes during visitation is safe as the mutation is only possible either
//! before the children are enqueued or after the children were already processed.
//!

use parking_lot::RwLock;
use rayon::{Scope, ScopeFifo};
use std::collections::VecDeque;
use std::iter::FusedIterator;
use std::ops::{Deref, DerefMut};
use std::sync::Arc;

// TODO: Tests for the algorithms

/// Trait that has to be implemented by tree-like structures to make them visitable
pub trait TreeNode {
    /// Returns a slice of all child nodes
    fn children(&self) -> &[Box<Self>];
}

/// Trait that has to be implemented by tree-like structures to visit and mutate them
pub trait TreeNodeMut: TreeNode {
    /// Returns a mutable slice of all child nodes
    fn children_mut(&mut self) -> &mut [Box<Self>];
}

/// Trait for non-mutable sequential tree iteration algorithms. Automatically implemented for types that implement [`TreeNode`].
pub trait VisitableTree: TreeNode {
    /// An iterator over all nodes and its children in depth-first order.
    fn dfs_iter<'a>(&'a self) -> DfsIter<'a, Self> {
        DfsIter::new(self)
    }

    /// An iterator over all nodes and its children in breadth-first order.
    fn bfs_iter<'a>(&'a self) -> BfsIter<'a, Self> {
        BfsIter::new(self)
    }
}

/// Trait for sequential tree visitation algorithms that support mutation during visitation. Automatically implemented for types that implement [`TreeNodeMut`].
pub trait MutVisitableTree: TreeNodeMut {
    /// Visits a node and its children in depth-first order. The visitor is applied before enqueuing each node's children.
    fn visit_mut_dfs<F: FnMut(&mut Self)>(&mut self, mut visitor: F) {
        let mut stack = Vec::new();
        stack.push(self);

        while let Some(current_node) = stack.pop() {
            visitor(current_node);
            stack.extend(
                current_node
                    .children_mut()
                    .iter_mut()
                    .rev()
                    .map(DerefMut::deref_mut),
            );
        }
    }

    /// Visits a node and its children in breadth-first order. The visitor is applied before enqueuing each node's children.
    fn visit_mut_bfs<F: FnMut(&mut Self)>(&mut self, mut visitor: F) {
        let mut queue_down = VecDeque::new();
        queue_down.push_back(self);

        while let Some(current_node) = queue_down.pop_front() {
            visitor(current_node);
            queue_down.extend(
                current_node
                    .children_mut()
                    .iter_mut()
                    .map(DerefMut::deref_mut),
            );
        }
    }
}

/// Depth-first search iterator returned by the [`VisitableTree::dfs_iter`] function
pub struct DfsIter<'a, T: ?Sized> {
    stack: Vec<&'a T>,
}

impl<'a, T: ?Sized> DfsIter<'a, T> {
    fn new(start: &'a T) -> Self {
        Self { stack: vec![start] }
    }
}

impl<'a, T: TreeNode + ?Sized> Iterator for DfsIter<'a, T> {
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(current_node) = self.stack.pop() {
            self.stack
                .extend(current_node.children().iter().rev().map(Deref::deref));
            Some(current_node)
        } else {
            None
        }
    }
}

impl<'a, T: TreeNode + ?Sized> FusedIterator for DfsIter<'a, T> {}

/// Breadth-first search iterator returned by the [`VisitableTree::bfs_iter`] function
pub struct BfsIter<'a, T: ?Sized> {
    queue: VecDeque<&'a T>,
}

impl<'a, T: ?Sized> BfsIter<'a, T> {
    fn new(start: &'a T) -> Self {
        Self {
            queue: vec![start].into(),
        }
    }
}

impl<'a, T: TreeNode + ?Sized> Iterator for BfsIter<'a, T> {
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(current_node) = self.queue.pop_front() {
            self.queue
                .extend(current_node.children().iter().rev().map(Deref::deref));
            Some(current_node)
        } else {
            None
        }
    }
}

impl<'a, T: TreeNode + ?Sized> FusedIterator for BfsIter<'a, T> {}

/// Trait for non-mutable parallel tree visitation algorithms. Automatically implemented for types that implement [`TreeNode`] and [`ThreadSafe`](crate::ThreadSafe).
pub trait ParVisitableTree: TreeNode {
    /// Visits a node and its children in breadth-first order. The visitor is applied in parallel to processing the children.
    fn par_visit_bfs<F>(&self, visitor: F)
    where
        Self: Sync,
        F: Fn(&Self) + Sync,
    {
        // Parallel implementation of recursive breadth-first visitation
        fn par_visit_bfs_impl<'scope, T, F>(
            node: &'scope T,
            s: &ScopeFifo<'scope>,
            visitor: &'scope F,
        ) where
            T: TreeNode + Sync + ?Sized,
            F: Fn(&T) + Sync,
        {
            // Spawn task for visitor
            s.spawn_fifo(move |_| visitor(node));

            // Spawn tasks for all children
            for child in node.children().iter().map(Deref::deref) {
                s.spawn_fifo(move |s| par_visit_bfs_impl(child, s, visitor));
            }
        }

        let v = &visitor;
        rayon::scope_fifo(move |s| par_visit_bfs_impl(self, s, v));
    }

    /// Visits a node and its children in breadth-first order, stops visitation on first error and returns it. The visitor is applied in parallel to processing the children.
    fn try_par_visit_bfs<E, F>(&self, visitor: F) -> Result<(), E>
    where
        Self: Sync,
        E: Send + Sync,
        F: Fn(&Self) -> Result<(), E> + Sync,
    {
        let error = Arc::new(RwLock::new(Ok(())));

        // Parallel implementation of recursive breadth-first visitation
        fn try_par_visit_bfs_impl<'scope, T, E, F>(
            node: &'scope T,
            s: &ScopeFifo<'scope>,
            error: Arc<RwLock<Result<(), E>>>,
            visitor: &'scope F,
        ) where
            T: TreeNode + Sync + ?Sized,
            E: Send + Sync + 'scope,
            F: Fn(&T) -> Result<(), E> + Sync,
        {
            // Stop recursion if there is already an error
            if error.read().is_err() {
                return;
            }

            // Spawn task for visitor
            {
                let error = error.clone();
                s.spawn_fifo(move |_| {
                    // Only run visitor if there was no error in the meantime
                    if error.read().is_ok() {
                        // Run visitor and check returned result
                        let res = visitor(node);
                        if res.is_err() {
                            let mut error_guard = error.write();
                            // Don't overwrite error if there is already one
                            if !error_guard.is_err() {
                                *error_guard = res;
                            }
                        }
                    }
                });
            }

            // Spawn tasks for all children
            for child in node.children().iter().map(Deref::deref) {
                let error = error.clone();
                s.spawn_fifo(move |s| try_par_visit_bfs_impl(child, s, error, visitor));
            }
        }

        // Start the visitation
        {
            let v = &visitor;
            let e = error.clone();
            rayon::scope_fifo(move |s| try_par_visit_bfs_impl(self, s, e, v));
        }

        // Return any potential error collected during visitation
        if !error.read().is_ok() {
            match Arc::try_unwrap(error) {
                Ok(e) => e.into_inner(),
                Err(_) => panic!("Unable to unwrap Arc that stores error of tree visitation"),
            }
        } else {
            Ok(())
        }
    }
}

/// Trait for mutable parallel tree visitation algorithms. Automatically implemented for types that implement [`TreeNodeMut`] and [`ThreadSafe`](crate::ThreadSafe).
pub trait ParMutVisitableTree: TreeNodeMut {
    /// Visits a node and its children in breadth-first order. The visitor is applied before enqueuing each node's children. Parallel version.
    fn par_visit_mut_bfs<F>(&mut self, visitor: F)
    where
        Self: Send + Sync,
        F: Fn(&mut Self) + Sync,
    {
        // Parallel implementation of recursive breadth-first visitation
        fn par_visit_mut_bfs_impl<'scope, T, F>(
            node: &'scope mut T,
            s: &ScopeFifo<'scope>,
            visitor: &'scope F,
        ) where
            T: TreeNodeMut + Send + Sync + ?Sized,
            F: Fn(&mut T) + Sync,
        {
            // Apply visitor before enqueuing children
            visitor(node);

            // Spawn tasks for all children
            for child in node.children_mut().iter_mut().map(DerefMut::deref_mut) {
                s.spawn_fifo(move |s| par_visit_mut_bfs_impl(child, s, visitor));
            }
        }

        let v = &visitor;
        rayon::scope_fifo(move |s| par_visit_mut_bfs_impl(self, s, v));
    }

    /// Visits a node and its children in depth-first post-order. The visitor is applied after processing each node's children. Parallel version.
    fn par_visit_mut_dfs_post<F>(&mut self, visitor: F)
    where
        Self: Send + Sync,
        F: Fn(&mut Self) + Sync,
    {
        fn par_visit_mut_dfs_post_impl<'scope, T, F>(
            node: &'scope mut T,
            _s: &Scope<'scope>,
            visitor: &'scope F,
        ) where
            T: TreeNodeMut + Send + Sync + ?Sized,
            F: Fn(&mut T) + Sync,
        {
            // Create a new scope to ensure that tasks are completed before the visitor runs
            rayon::scope(|s| {
                for child in node.children_mut().iter_mut().map(DerefMut::deref_mut) {
                    s.spawn(move |s| par_visit_mut_dfs_post_impl(child, s, visitor));
                }
            });

            visitor(node);
        }

        let v = &visitor;
        rayon::scope(move |s| par_visit_mut_dfs_post_impl(self, s, v));
    }

    /// Visits a node and its children in depth-first post-order, stops visitation on first error and returns it. The visitor is applied after processing each node's children. Parallel version.
    fn try_par_visit_mut_dfs_post<E, F>(&mut self, visitor: F) -> Result<(), E>
    where
        Self: Send + Sync,
        E: Send + Sync,
        F: Fn(&mut Self) -> Result<(), E> + Sync,
    {
        let error = Arc::new(RwLock::new(Ok(())));

        fn try_par_visit_mut_dfs_post_impl<'scope, T, E, F>(
            node: &'scope mut T,
            _s: &Scope<'scope>,
            error: Arc<RwLock<Result<(), E>>>,
            visitor: &'scope F,
        ) where
            T: TreeNodeMut + Send + Sync + ?Sized,
            E: Send + Sync,
            F: Fn(&mut T) -> Result<(), E> + Sync,
        {
            // Stop recursion if there is already an error
            if error.read().is_err() {
                return;
            }

            // Create a new scope to ensure that tasks are completed before the visitor runs
            rayon::scope(|s| {
                for child in node.children_mut().iter_mut().map(DerefMut::deref_mut) {
                    let error = error.clone();
                    s.spawn(move |s| try_par_visit_mut_dfs_post_impl(child, s, error, visitor));
                }
            });

            // Only run visitor if none of the child nodes returned an error
            if error.read().is_ok() {
                // Run visitor and check returned result
                let res = visitor(node);
                if res.is_err() {
                    let mut error_guard = error.write();
                    // Don't overwrite error if there is already one
                    if !error_guard.is_err() {
                        *error_guard = res;
                    }
                }
            }
        }

        // Start the visitation
        {
            let v = &visitor;
            let e = error.clone();
            rayon::scope(move |s| try_par_visit_mut_dfs_post_impl(self, s, e, v));
        }

        // Return any potential error collected during visitation
        if !error.read().is_ok() {
            match Arc::try_unwrap(error) {
                Ok(e) => e.into_inner(),
                Err(_) => panic!("Unable to unwrap Arc that stores error of tree visitation"),
            }
        } else {
            Ok(())
        }
    }
}

impl<T: TreeNode> VisitableTree for T {}
impl<T: TreeNodeMut> MutVisitableTree for T {}
impl<T: TreeNode + Send + Sync> ParVisitableTree for T {}
impl<T: TreeNodeMut + Send + Sync> ParMutVisitableTree for T {}