fastgraph 0.1.21

Graph abstraction providing a generic interface and powerful parallelized traversals.
Documentation
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
//=============================================================================
// CORE ABSTRACTIONS
//=============================================================================

//! # Graph Library Core
//!
//! This is the core part of the graph library. It contains a node and an
//! edge abstraction as well as traveral algorithms. Used to build
//! different graphs.
//!
use std::{
	fmt::{Debug, Display, Formatter},
    hash::Hash,
    sync::{
		atomic::{AtomicBool, Ordering},
        Arc, Weak,
    },
};
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use parking_lot::{RwLock, Mutex, RwLockReadGuard, RwLockWriteGuard};

//=============================================================================

/// The Traverse enum is used when exploring edges in a graph. It's
/// states signify if an edge should be included in the search, skipped
/// or if the search should stop because a terminating condition has
/// been met such as finding a sink node.
///
pub enum Traverse {
    Include,
    Skip,
    Finish,
}

/// Represents an empty parameter for either a node or an edge.
///
#[derive(Clone, Debug)]
pub struct Empty;

impl std::fmt::Display for Empty {
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(fmt, "_")
    }
}

pub type Frontier<K, N, E> = Vec<Weak<Edge<K, N, E>>>;

pub trait Explorer<K, N, E>
where
    K: Hash + Eq + Clone + Debug + Display + Sync + Send,
    N: Clone + Debug + Display + Sync + Send,
    E: Clone + Debug + Display + Sync + Send,
{
	fn next_frontier(&self) -> Option<Frontier<K, N, E>>;
	fn prev_frontier(&self) -> Option<Frontier<K, N, E>>;
}

const OPEN: bool = false;
const CLOSED: bool = true;

enum Continue<T> {
    Yes(T),
    No(T),
}

//=============================================================================
// EDGE IMPLEMENTATION
//=============================================================================

//=============================================================================

/// Edge representing a connection between two nodes. Relevant data can be
/// stored in the edge atomically. Edge's target and source node's are
/// weak references and can't outlive the nodes they represent.
///
#[derive(Debug)]
pub struct Edge<K, N, E>
where
    K: Hash + Eq + Clone + Debug + Display + Sync + Send,
    N: Clone + Debug + Display + Sync + Send,
    E: Clone + Debug + Display + Sync + Send,
{
    source: Weak<Node<K, N, E>>,
    target: Weak<Node<K, N, E>>,
    data: Mutex<E>,
	lock: AtomicBool,
}

//=============================================================================

impl<K, N, E> Edge<K, N, E>
where
    K: Hash + Eq + Clone + Debug + Display + Sync + Send,
    N: Clone + Debug + Display + Sync + Send,
    E: Clone + Debug + Display + Sync + Send,
{
    /// Creates a new edge.
    pub fn new(source: &Arc<Node<K, N, E>>, target: &Arc<Node<K, N, E>>, data: E) -> Edge<K, N, E> {
        Edge {
            source: Arc::downgrade(source),
            target: Arc::downgrade(target),
            data: Mutex::new(data),
			lock: AtomicBool::new(OPEN)
        }
    }

    /// Edge's source node.
    #[inline(always)]
    pub fn source(&self) -> Arc<Node<K, N, E>> {
        self.source.upgrade().unwrap()
    }

    /// Edge's target node.
    #[inline(always)]
    pub fn target(&self) -> Arc<Node<K, N, E>> {
        self.target.upgrade().unwrap()
    }

    /// Load data from the edge.
    #[inline(always)]
    pub fn load(&self) -> E {
        self.data.lock().clone()
    }

    /// Store data into the edge.
    #[inline(always)]
    pub fn store(&self, data: E) {
        let mut x = self.data.lock();
        *x = data;
    }

	#[inline(always)]
    fn try_lock(&self) -> bool {
        self.lock.load(Ordering::Relaxed)
    }

    #[inline(always)]
    fn close(&self) {
        self.lock.store(CLOSED, Ordering::Relaxed)
    }

    #[inline(always)]
    fn open(&self) {
        self.lock.store(OPEN, Ordering::Relaxed)
    }
}

//=============================================================================

unsafe impl<K, N, E> Sync for Edge<K, N, E>
where
    K: Hash + Eq + Clone + Debug + Display + Sync + Send,
    N: Clone + Debug + Display + Sync + Send,
    E: Clone + Debug + Display + Sync + Send,
{
}

impl<K, N, E> Clone for Edge<K, N, E>
where
    K: Hash + Eq + Clone + Debug + Display + Sync + Send,
    N: Clone + Debug + Display + Sync + Send,
    E: Clone + Debug + Display + Sync + Send,
{
    fn clone(&self) -> Self {
        Edge {
            source: self.source.clone(),
            target: self.target.clone(),
            data: Mutex::new(self.data.lock().clone()),
			lock: AtomicBool::new(OPEN),
        }
    }
}

impl<K, N, E> Display for Edge<K, N, E>
where
    K: Hash + Eq + Clone + Debug + Display + Sync + Send,
    N: Clone + Debug + Display + Sync + Send,
    E: Clone + Debug + Display + Sync + Send,
{
    fn fmt(&self, fmt: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            fmt,
            "{} -> {}",
            self.source().key(),
            self.target().key()
        )
    }
}

//=============================================================================

/// Backtrack edges in an edge list starting from the last edge in the list.
/// Used for example to find the shortest path from the results of a breadth
/// first straversal.
///
pub fn backtrack_edges<K, N, E>(edges: &Vec<Weak<Edge<K, N, E>>>) -> Vec<Weak<Edge<K, N, E>>>
where
    K: Hash + Eq + Clone + Debug + Display + Sync + Send,
    N: Clone + Debug + Display + Sync + Send,
    E: Clone + Debug + Display + Sync + Send,
{
    let mut res = Vec::new();
    if edges.len() == 0 {
        return res;
    }
    let w = edges.get(edges.len() - 1).unwrap();
    res.push(w.clone());
    let mut i = 0;
    for edge in edges.iter().rev() {
        let source = res[i].upgrade().unwrap().source();
        if edge.upgrade().unwrap().target() == source {
            res.push(edge.clone());
            i += 1;
        }
    }
    res.reverse();
	res
}

// Opens all locks in
fn open_locks<K, N, E>(edges: &Vec<Weak<Edge<K, N, E>>>)
where
    K: Hash + Eq + Clone + Debug + Display + Sync + Send,
    N: Clone + Debug + Display + Sync + Send,
    E: Clone + Debug + Display + Sync + Send,
{
	if edges.len() < 1 {
		return ;
	}
	edges[0].upgrade().unwrap().source().open();
    for weak in edges.iter() {
        let edge = weak.upgrade().unwrap();
		edge.open();
        edge.target().open();
    }
}

//=============================================================================
// NODE IMPLEMENTATION
//=============================================================================

//=============================================================================
// TYPES

type Outbound<K, N, E> = RwLock<Vec<Arc<Edge<K, N, E>>>>;
type Inbound<K, N, E> = RwLock<Vec<Weak<Edge<K, N, E>>>>;

//=============================================================================
// STRUCT

/// Represents a node in the graph. Data can be stored in and loaded from the
/// node in a thread safe manner.
///
#[derive(Debug)]
pub struct Node<K, N, E>
where
    K: Hash + Eq + Clone + Debug + Display + Sync + Send,
    N: Clone + Debug + Display + Sync + Send,
    E: Clone + Debug + Display + Sync + Send,
{
    key: K,
    data: Mutex<N>,
    outbound: Outbound<K, N, E>,
    inbound: Inbound<K, N, E>,
    lock: AtomicBool,
}

//=============================================================================
// STRUCT IMPLEMENTATIONS

impl<K, N, E> Node<K, N, E>
where
    K: Hash + Eq + Clone + Debug + Display + Sync + Send,
    N: Clone + Debug + Display + Sync + Send,
    E: Clone + Debug + Display + Sync + Send,
{
	//=============================================================================
	// PUBLIC

    /// Create a new node.
    ///
    #[inline(always)]
    pub fn new(key: K, data: N) -> Node<K, N, E> {
        Self {
            key,
            data: Mutex::new(data),
            outbound: Outbound::new(Vec::new()),
            inbound: Inbound::new(Vec::new()),
            lock: AtomicBool::new(OPEN),
        }
    }

    /// Load data from the node.
    ///
    #[inline(always)]
    pub fn load(&self) -> N {
        self.data.lock().clone()
    }

    /// Store data to the node.
    ///
    #[inline(always)]
    pub fn store(&self, data: N) {
        *self.data.lock() = data;
    }

    /// Get node key.
    ///
    #[inline(always)]
    pub fn key(&self) -> &K {
        &self.key
    }

    /// Get node degree ie. amount of outbound edges.
    ///
    #[inline(always)]
    pub fn degree(&self) -> usize {
        self.outbound().len()
    }

    /// Check if node is a leaf node ie. has no outbound edges.
    ///
    #[inline(always)]
    pub fn is_leaf(&self) -> bool {
        self.outbound().len() == 0
    }

    /// Find an outbound node and return the corresponding edge if found.
    ///
    #[inline(always)]
    pub fn find_outbound(&self, target: &Arc<Node<K, N, E>>) -> Option<Arc<Edge<K, N, E>>> {
        for edge in self.outbound().iter() {
            if edge.target() == *target {
                return Some(edge.clone());
            }
        }
        None
    }

    /// Find an inbound node and return the corresponding edge if found.
    ///
    #[inline(always)]
    pub fn find_inbound(&self, source: &Arc<Node<K, N, E>>) -> Option<Weak<Edge<K, N, E>>> {
        for edge in self.inbound().iter() {
            if edge.upgrade().unwrap().source() == *source {
                return Some(edge.clone());
            }
        }
        None
    }

    /// Get read access to outbound edges of the node.
    ///
    #[inline(always)]
    pub fn outbound(&self) -> RwLockReadGuard<Vec<Arc<Edge<K, N, E>>>> {
        self.outbound.read()
    }

    /// Get read and write access to the outbound edges of the node. Will block other threads.
    ///
    #[inline(always)]
    pub fn outbound_mut(&self) -> RwLockWriteGuard<Vec<Arc<Edge<K, N, E>>>> {
        self.outbound.write()
    }

    /// Get read access to inbound edges of the node.
    ///
    #[inline(always)]
    pub fn inbound(&self) -> RwLockReadGuard<Vec<Weak<Edge<K, N, E>>>> {
        self.inbound.read()
    }

    /// Get read and write access to the outbound edges of the node. Will block other threads.
    ///
    #[inline(always)]
    pub fn inbound_mut(&self) -> RwLockWriteGuard<Vec<Weak<Edge<K, N, E>>>> {
        self.inbound.write()
    }

	//=============================================================================
	// PRIVATE

    #[inline(always)]
    fn try_lock(&self) -> bool {
        self.lock.load(Ordering::Relaxed)
    }

    #[inline(always)]
    fn close(&self) {
        self.lock.store(CLOSED, Ordering::Relaxed)
    }

    #[inline(always)]
    fn open(&self) {
        self.lock.store(OPEN, Ordering::Relaxed)
    }

    #[inline(always)]
    fn map_adjacent_dir<F>(
        &self,
        user_closure: &F,
    ) -> Continue<Vec<Weak<Edge<K, N, E>>>>
    where
        K: Hash + Eq + Clone + Debug + Display + Sync + Send,
        N: Clone + Debug + Display + Sync + Send,
        E: Clone + Debug + Display + Sync + Send,
		F: Fn(&Arc<Edge<K, N, E>>) -> Traverse + Sync + Send + Copy,
    {
        let mut segment: Vec<Weak<Edge<K, N, E>>> = Vec::new();
        for edge in self.outbound().iter() {
            if edge.target().try_lock() == OPEN {
                edge.target().close();
                let traversal_state = user_closure(edge);
                match traversal_state {
                    Traverse::Include => {
                        segment.push(Arc::downgrade(edge));
                    }
                    Traverse::Finish => {
                        segment.push(Arc::downgrade(edge));
                        return Continue::No(segment);
                    }
                    Traverse::Skip => {
                        edge.target().open();
                    }
                }
            }
        }
        Continue::Yes(segment)
    }

	#[inline(always)]
    fn map_adjacent_undir<F>(
        &self,
        user_closure: &F,
    ) -> Continue<Vec<Weak<Edge<K, N, E>>>>
    where
        K: Hash + Eq + Clone + Debug + Display + Sync + Send,
        N: Clone + Debug + Display + Sync + Send,
        E: Clone + Debug + Display + Sync + Send,
		F: Fn(&Arc<Edge<K, N, E>>) -> Traverse + Sync + Send + Copy,
    {
        let mut segment: Vec<Weak<Edge<K, N, E>>> = Vec::new();
        for edge in self.outbound().iter() {
            if edge.try_lock() == OPEN
			&& edge.target().try_lock() == OPEN {
				edge.close();
                edge.target().close();
                let traversal_state = user_closure(edge);
                match traversal_state {
                    Traverse::Include => {
                        segment.push(Arc::downgrade(edge));
                    }
                    Traverse::Finish => {
                        segment.push(Arc::downgrade(edge));
                        return Continue::No(segment);
                    }
                    Traverse::Skip => {
                        edge.target().open();
                    }
                }
            }
        }
		for edge in self.inbound().iter() {
			let upgrade = edge.upgrade().unwrap();
            if upgrade.try_lock() == OPEN
			&& upgrade.target().try_lock() == OPEN {
				upgrade.close();
                upgrade.target().close();
                let traversal_state = user_closure(&upgrade);
                match traversal_state {
                    Traverse::Include => {
                        segment.push(edge.clone());
                    }
                    Traverse::Finish => {
                        segment.push(edge.clone());
                        return Continue::No(segment);
                    }
                    Traverse::Skip => {
						upgrade.target().open();
						upgrade.open();
                    }
                }
            }
        }
        Continue::Yes(segment)
    }
}

//=============================================================================
// TRAIT IMPLEMENTATIONS

unsafe impl<K, N, E> Sync for Node<K, N, E>
where
    K: Hash + Eq + Clone + Debug + Display + Sync + Send,
    N: Clone + Debug + Display + Sync + Send,
    E: Clone + Debug + Display + Sync + Send,
{}

impl<K, N, E> Clone for Node<K, N, E>
where
    K: Hash + Eq + Clone + Debug + Display + Sync + Send,
    N: Clone + Debug + Display + Sync + Send,
    E: Clone + Debug + Display + Sync + Send,
{
    fn clone(&self) -> Self {
        Node {
            key: self.key.clone(),
            data: Mutex::new(self.data.lock().clone()),
            outbound: Outbound::new(Vec::new()),
            inbound: Inbound::new(Vec::new()),
            lock: AtomicBool::new(OPEN),
        }
    }
}

impl<K, N, E> PartialEq for Node<K, N, E>
where
    K: Hash + Eq + Clone + Debug + Display + Sync + Send,
    N: Clone + Debug + Display + Sync + Send,
    E: Clone + Debug + Display + Sync + Send,
{
    fn eq(&self, other: &Self) -> bool {
        if self.key == other.key {
            return true;
        }
        false
    }
}

impl<K, N, E> Display for Node<K, N, E>
where
    K: Hash + Eq + Clone + Debug + Display + Sync + Send,
    N: Clone + Debug + Display + Sync + Send,
    E: Clone + Debug + Display + Sync + Send,
{
    fn fmt(&self, fmt: &mut Formatter<'_>) -> std::fmt::Result {
		let header = format!(
            "{} [label = \"{} : {}\"]",
            self.key,
			self.key,
            self.data.lock()
        );
        write!(fmt, "{}", header)
    }
}

//=============================================================================
// FUNCTION IMPLEMENTATIONS

#[inline]
fn overlaps<K, N, E>(source: &Arc<Node<K, N, E>>, target: &Arc<Node<K, N, E>>) -> bool
where
    K: Hash + Eq + Clone + Debug + Display + Sync + Send,
    N: Clone + Debug + Display + Sync + Send,
    E: Clone + Debug + Display + Sync + Send,
{
    for edge in source.outbound().iter() {
        if edge.target() == *target {
            return true;
        }
    }
    false
}

/// Connect two nodes if no previous connection exists.
pub fn connect<K, N, E>(source: &Arc<Node<K, N, E>>, target: &Arc<Node<K, N, E>>, data: E) -> bool
where
    K: Hash + Eq + Clone + Debug + Display + Sync + Send,
    N: Clone + Debug + Display + Sync + Send,
    E: Clone + Debug + Display + Sync + Send,
{
    if !overlaps(source, target) {
        let new_edge = Arc::new(Edge::new(source, target, data));
        source.outbound_mut().push(new_edge.clone());
        target.inbound_mut().push(Arc::downgrade(&new_edge));
        return true;
    }
    false
}

/// Disconnect two nodes from each other if they share an edge.
pub fn disconnect<K, N, E>(source: &Arc<Node<K, N, E>>, target: &Arc<Node<K, N, E>>) -> bool
where
    K: Hash + Eq + Clone + Debug + Display + Sync + Send,
    N: Clone + Debug + Display + Sync + Send,
    E: Clone + Debug + Display + Sync + Send,
{
    let mut idx: (usize, usize) = (0, 0);
    let mut flag = false;
    for (i, edge) in source.outbound().iter().enumerate() {
        if edge.target() == *target {
            idx.0 = i;
            flag = true;
        }
    }
    for (i, edge) in target.inbound().iter().enumerate() {
        if edge.upgrade().unwrap().source() == *source {
            idx.1 = i;
        }
    }
    if flag == true {
        source.outbound_mut().remove(idx.0);
        source.inbound_mut().remove(idx.1);
    }
    flag
}

//=============================================================================
// TRAVERSAL ALGORITHMS
//=============================================================================

/// # Breadth Traversal
///
/// Conduct a breadth first traversal starting from the source node.
/// User provides an `explorer` closure which determines how nodes and edges
/// are to be interpreted. The closure will return a Traverse enum which has
/// 3 states Include, Skip and Finish. These states determine if we are to
/// "go through" the edge and thus include it in our search. Include will
/// include the edge and continue the search, Skip will indicate that the edge
/// is not to be traversed and Finish will include the edge and finish the
/// algorithm.
///
/// Function will return an `Option<Vec<Weak<Edge<K, N, E>>>>` where a Some value
/// indicates that the traversal was successful ie. a Finish condition was
/// reached. And WeakEdges is a collection of all the traversed edges.
/// The last edge will contain the result that triggered the Finish condition.
/// To get the shortest path for example, we'd backtrack the WeakEdges starting
/// from the last edge which would contain our sink node.
///
/// # Examples
///
/// ```
/// use fastgraph::core::*;
/// use std::sync::Arc;
///
/// let n1 = Arc::new(Node::<u32, Empty, Empty>::new(1, Empty));
/// let n2 = Arc::new(Node::<u32, Empty, Empty>::new(2, Empty));
/// let n3 = Arc::new(Node::<u32, Empty, Empty>::new(3, Empty));
///
/// connect(&n1, &n2, Empty);
/// connect(&n2, &n3, Empty);
/// connect(&n1, &n3, Empty);
///
/// let edges = directed_breadth_traversal(&n1,
/// 	| edge | {
/// 		if n3 == edge.target() {
///				Traverse::Finish
///			} else {
///				Traverse::Include
///			}
/// 	})
/// 	.unwrap();
///
/// let shortest_path = backtrack_edges(&edges);
///
/// assert!(shortest_path.len() == 1);
/// ```
///

pub fn directed_breadth_traversal<K, N, E, F>(
    source: &Arc<Node<K, N, E>>,
    explorer: F,
) -> Option<Vec<Weak<Edge<K, N, E>>>>
where
    K: Hash + Eq + Clone + Debug + Display + Sync + Send,
    N: Clone + Debug + Display + Sync + Send,
    E: Clone + Debug + Display + Sync + Send,
    F: Fn(&Arc<Edge<K, N, E>>) -> Traverse + Sync + Send + Copy,
{
    let mut frontiers: Vec<Weak<Edge<K, N, E>>>;
    let mut bounds: (usize, usize) = (0, 0);
    source.close();
    let initial = source.map_adjacent_dir(&explorer);
    match initial {
        Continue::No(segment) => {
            open_locks(&segment);
            return Some(segment);
        }
        Continue::Yes(segment) => {
            frontiers = segment;
        }
    }
    loop {
        bounds.1 = frontiers.len();
        if bounds.0 == bounds.1 {
            break;
        }
        let current_frontier = &frontiers[bounds.0..bounds.1];
        bounds.0 = bounds.1;
        let mut new_segments = Vec::new();
        for edge in current_frontier.into_iter() {
            let node = edge.upgrade().unwrap().target();
            let haystack = node.map_adjacent_dir(&explorer);
            match haystack {
                Continue::No(mut segment) => {
                    new_segments.append(&mut segment);
                    frontiers.append(&mut new_segments);
                    open_locks(&frontiers);
                    return Some(frontiers);
                }
                Continue::Yes(mut segment) => {
                    new_segments.append(&mut segment);
                }
            }
        }
        frontiers.append(&mut new_segments);
    }
    open_locks(&frontiers);
    None
}

pub fn undirected_breadth_traversal<K, N, E, F>(
    source: &Arc<Node<K, N, E>>,
    explorer: F,
) -> Option<Vec<Weak<Edge<K, N, E>>>>
where
    K: Hash + Eq + Clone + Debug + Display + Sync + Send,
    N: Clone + Debug + Display + Sync + Send,
    E: Clone + Debug + Display + Sync + Send,
    F: Fn(&Arc<Edge<K, N, E>>) -> Traverse + Sync + Send + Copy,
{
    let mut frontiers: Vec<Weak<Edge<K, N, E>>>;
    let mut bounds: (usize, usize) = (0, 0);
    source.close();
    let initial = source.map_adjacent_undir(&explorer);
    match initial {
        Continue::No(segment) => {
            open_locks(&segment);
            return Some(segment);
        }
        Continue::Yes(segment) => {
            frontiers = segment;
        }
    }
    loop {
        bounds.1 = frontiers.len();
        if bounds.0 == bounds.1 {
            break;
        }
        let current_frontier = &frontiers[bounds.0..bounds.1];
        bounds.0 = bounds.1;
        let mut new_segments = Vec::new();
        for edge in current_frontier.into_iter() {
            let node = edge.upgrade().unwrap().target();
            let haystack = node.map_adjacent_undir(&explorer);
            match haystack {
                Continue::No(mut segment) => {
                    new_segments.append(&mut segment);
                    frontiers.append(&mut new_segments);
                    open_locks(&frontiers);
                    return Some(frontiers);
                }
                Continue::Yes(mut segment) => {
                    new_segments.append(&mut segment);
                }
            }
        }
        frontiers.append(&mut new_segments);
    }
    open_locks(&frontiers);
    None
}

//=============================================================================

/// # Parallel Breadth Traversal
///
/// Conduct a parallel breadth first traversal starting from the source node.
/// User provides an `explorer` closure which determines how nodes and edges
/// are to be interpreted. The closure will return a Traverse enum which has
/// 3 states Include, Skip and Finish. These states determine if we are to
/// "go through" the edge and thus include it in our search. Include will
/// include the edge and continue the search, Skip will indicate that the edge
/// is not to be traversed and Finish will include the edge and finish the
/// algorithm.
///
/// Function will return an `Option<Vec<Weak<Edge<K, N, E>>>>` where a Some value
/// indicates that the traversal was successful ie. a Finish condition was
/// reached. And WeakEdges is a collection of all the traversed edges.
/// The last edge will contain the result that triggered the Finish condition.
/// To get the shortest path for example, we'd backtrack the WeakEdges starting
/// from the last edge which would contain our sink node.
///
/// # Examples
///
/// ```
/// use fastgraph::core::*;
/// use std::sync::Arc;
///
/// let n1 = Arc::new(Node::<u32, Empty, Empty>::new(1, Empty));
/// let n2 = Arc::new(Node::<u32, Empty, Empty>::new(2, Empty));
/// let n3 = Arc::new(Node::<u32, Empty, Empty>::new(3, Empty));
///
/// connect(&n1, &n2, Empty);
/// connect(&n2, &n3, Empty);
/// connect(&n1, &n3, Empty);
///
/// let edges = parallel_directed_breadth_traversal(&n1,
/// 	| edge | {
/// 		if n3 == edge.target() {
///				Traverse::Finish
///			} else {
///				Traverse::Include
///			}
/// 	})
/// 	.unwrap();
///
/// let shortest_path = backtrack_edges(&edges);
///
/// assert!(shortest_path.len() == 1);
/// ```
///

pub fn parallel_directed_breadth_traversal<K, N, E, F>(
    source: &Arc<Node<K, N, E>>,
    explorer: F,
) -> Option<Vec<Weak<Edge<K, N, E>>>>
where
    K: Hash + Eq + Clone + Debug + Display + Sync + Send,
    N: Clone + Debug + Display + Sync + Send,
    E: Clone + Debug + Display + Sync + Send,
    F: Fn(&Arc<Edge<K, N, E>>) -> Traverse + Sync + Send + Copy,
{
    let mut frontiers: Vec<Weak<Edge<K, N, E>>>;
    let mut bounds: (usize, usize) = (0, 0);
    let terminate: Arc<AtomicBool> = Arc::new(AtomicBool::new(false));
    source.close();
    match source.map_adjacent_dir(&explorer) {
        Continue::No(segment) => {
            open_locks(&segment);
            return Some(segment);
        }
        Continue::Yes(segment) => {
            frontiers = segment;
        }
    }
    loop {
        bounds.1 = frontiers.len();
        if bounds.0 == bounds.1 {
            break;
        }
        let current_frontier = &frontiers[bounds.0..bounds.1];
        bounds.0 = bounds.1;
        let frontier_segments: Vec<_> = current_frontier
            .into_par_iter()
            .map(|edge| {
				match terminate.load(Ordering::Relaxed) {
					true => { None }
					false => {
						let node = edge.upgrade().unwrap().target();
                    	match node.map_adjacent_dir(&explorer) {
                    	    Continue::No(segment) => {
                    	        terminate.store(true, Ordering::Relaxed);
                    	        Some(segment)
                    	    }
                    	    Continue::Yes(segment) => Some(segment),
                    	}
					}
				}
            })
            .while_some()
            .collect();
        for mut segment in frontier_segments {
            frontiers.append(&mut segment);
        }
        if terminate.load(Ordering::Relaxed) == true {
            break;
        }
    }
    open_locks(&frontiers);
    if terminate.load(Ordering::Relaxed) == true {
        Some(frontiers)
    } else {
        None
    }
}

pub fn parallel_undirected_breadth_traversal<K, N, E, F>(
    source: &Arc<Node<K, N, E>>,
    explorer: F,
) -> Option<Vec<Weak<Edge<K, N, E>>>>
where
    K: Hash + Eq + Clone + Debug + Display + Sync + Send,
    N: Clone + Debug + Display + Sync + Send,
    E: Clone + Debug + Display + Sync + Send,
    F: Fn(&Arc<Edge<K, N, E>>) -> Traverse + Sync + Send + Copy,
{
    let mut frontiers: Vec<Weak<Edge<K, N, E>>>;
    let mut bounds: (usize, usize) = (0, 0);
    let terminate: Arc<AtomicBool> = Arc::new(AtomicBool::new(false));
    source.close();
    match source.map_adjacent_undir(&explorer) {
        Continue::No(segment) => {
            open_locks(&segment);
            return Some(segment);
        }
        Continue::Yes(segment) => {
            frontiers = segment;
        }
    }
    loop {
        bounds.1 = frontiers.len();
        if bounds.0 == bounds.1 {
            break;
        }
        let current_frontier = &frontiers[bounds.0..bounds.1];
        bounds.0 = bounds.1;
        let frontier_segments: Vec<_> = current_frontier
            .into_par_iter()
            .map(|edge| {
				match terminate.load(Ordering::Relaxed) {
					true => { None }
					false => {
						let node = edge.upgrade().unwrap().target();
                    	match node.map_adjacent_undir(&explorer) {
                    	    Continue::No(segment) => {
                    	        terminate.store(true, Ordering::Relaxed);
                    	        Some(segment)
                    	    }
                    	    Continue::Yes(segment) => Some(segment),
                    	}
					}
				}
            })
            .while_some()
            .collect();
        for mut segment in frontier_segments {
            frontiers.append(&mut segment);
        }
        if terminate.load(Ordering::Relaxed) == true {
            break;
        }
    }
    open_locks(&frontiers);
    if terminate.load(Ordering::Relaxed) == true {
        Some(frontiers)
    } else {
        None
    }
}

//=============================================================================

/// # Depth First Traversal
///
/// Conduct a depth first traversal starting from the source node.
/// User provides an `explorer` closure which determines how nodes and edges
/// are to be interpreted. The closure will return a Traverse enum which has
/// 3 states Include, Skip and Finish. These states determine if we are to
/// "go through" the edge and thus include it in our search. Include will
/// include the edge and continue the search, Skip will indicate that the edge
/// is not to be traversed and Finish will include the edge and finish the
/// algorithm.
///
/// Function will return an `Option<Vec<Weak<Edge<K, N, E>>>>` where a Some value
/// indicates that the traversal was successful ie. a Finish condition was
/// reached. And WeakEdges is a collection of all the traversed edges.
/// The last edge will contain the result that triggered the Finish condition.
/// To get the shortest path for example, we'd backtrack the WeakEdges starting
/// from the last edge which would contain our sink node.
///
/// # Examples
///
/// ```
/// use fastgraph::core::*;
/// use std::sync::Arc;
///
/// let n1 = Arc::new(Node::<u32, Empty, Empty>::new(1, Empty));
/// let n2 = Arc::new(Node::<u32, Empty, Empty>::new(2, Empty));
/// let n3 = Arc::new(Node::<u32, Empty, Empty>::new(3, Empty));
///
/// connect(&n1, &n2, Empty);
/// connect(&n2, &n3, Empty);
/// connect(&n1, &n3, Empty);
///
/// let edges = directed_depth_traversal(&n1,
/// 	| edge | {
/// 		if n3 == edge.target() {
///				Traverse::Finish
///			} else {
///				Traverse::Include
///			}
/// 	})
/// 	.unwrap();
///
/// let shortest_path = backtrack_edges(&edges);
///
/// assert!(shortest_path.len() == 2);
/// ```
///

fn directed_depth_traversal_recursion<K, N, E, F>(
    source: &Arc<Node<K, N, E>>,
    results: &mut Vec<Weak<Edge<K, N, E>>>,
    explorer: F,
) -> bool
where
    K: Hash + Eq + Clone + Debug + Display + Sync + Send,
    N: Clone + Debug + Display + Sync + Send,
    E: Clone + Debug + Display + Sync + Send,
    F: Fn(&Arc<Edge<K, N, E>>) -> Traverse,
{
    source.close();
    for edge in source.outbound().iter() {
        if edge.target().try_lock() == OPEN {
            edge.target().close();
            let traverse = explorer(edge);
            match traverse {
                Traverse::Include => {
                    results.push(Arc::downgrade(edge));
                }
                Traverse::Finish => {
                    results.push(Arc::downgrade(edge));
                    return true;
                }
                Traverse::Skip => {
                    edge.target().open();
                }
            }
            return directed_depth_traversal_recursion(&edge.target(), results, explorer);
        }
    }
    false
}

pub fn directed_depth_traversal<K, N, E, F>(
    source: &Arc<Node<K, N, E>>,
    explorer: F,
) -> Option<Vec<Weak<Edge<K, N, E>>>>
where
    K: Hash + Eq + Clone + Debug + Display + Sync + Send,
    N: Clone + Debug + Display + Sync + Send,
    E: Clone + Debug + Display + Sync + Send,
    F: Fn(&Arc<Edge<K, N, E>>) -> Traverse,
{
    let mut result = Vec::new();
    let res = directed_depth_traversal_recursion(source, &mut result, explorer);
    open_locks(&result);
    match res {
        true => Some(result),
        false => None,
    }
}

fn undirected_depth_traversal_recursion<K, N, E, F>(
    source: &Arc<Node<K, N, E>>,
    results: &mut Vec<Weak<Edge<K, N, E>>>,
    explorer: F,
) -> bool
where
    K: Hash + Eq + Clone + Debug + Display + Sync + Send,
    N: Clone + Debug + Display + Sync + Send,
    E: Clone + Debug + Display + Sync + Send,
    F: Fn(&Arc<Edge<K, N, E>>) -> Traverse,
{
    source.close();
    for edge in source.outbound().iter() {
        if edge.target().try_lock() == OPEN {
            edge.target().close();
            let traverse = explorer(edge);
            match traverse {
                Traverse::Include => {
                    results.push(Arc::downgrade(edge));
                }
                Traverse::Finish => {
                    results.push(Arc::downgrade(edge));
                    return true;
                }
                Traverse::Skip => {
                    edge.target().open();
                }
            }
            return undirected_depth_traversal_recursion(&edge.target(), results, explorer);
        }
    }
	for edge in source.inbound().iter() {
		let upgrade = edge.upgrade().unwrap();
		if upgrade.target().try_lock() == OPEN {
			upgrade.target().close();
			let traversal_state = explorer(&upgrade);
			match traversal_state {
				Traverse::Include => {
					results.push(edge.clone());
				}
				Traverse::Finish => {
					results.push(edge.clone());
					return true;
				}
				Traverse::Skip => {
					upgrade.target().open();
				}
			}
		}
	}
    false
}

pub fn undirected_depth_traversal<K, N, E, F>(
    source: &Arc<Node<K, N, E>>,
    explorer: F,
) -> Option<Vec<Weak<Edge<K, N, E>>>>
where
    K: Hash + Eq + Clone + Debug + Display + Sync + Send,
    N: Clone + Debug + Display + Sync + Send,
    E: Clone + Debug + Display + Sync + Send,
    F: Fn(&Arc<Edge<K, N, E>>) -> Traverse,
{
    let mut result = Vec::new();
    let res = undirected_depth_traversal_recursion(source, &mut result, explorer);
    open_locks(&result);
    match res {
        true => Some(result),
        false => None,
    }
}

//=============================================================================