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
#![allow(dead_code)] use std::{
cmp::Ordering,
fmt,
hash::{self, Hash},
iter::{Cloned, DoubleEndedIterator, FromIterator},
marker::PhantomData,
ops::Deref,
slice::Iter,
};
use indexmap::{
map::{Iter as IndexMapIter, IterMut as IndexMapIterMut, Keys},
IndexMap,
};
use petgraph::{
graph::{node_index, Graph},
visit::{
GraphBase, IntoNeighbors, IntoNeighborsDirected, IntoNodeIdentifiers, NodeCount,
NodeIndexable, Visitable,
},
Directed, Direction, EdgeType, Incoming, IntoWeightedEdge, Outgoing, Undirected,
};
use swc_common::collections::AHashSet;
pub type FastDiGraphMap<N, E> = FastGraphMap<N, E, Directed>;
#[derive(Clone)]
pub struct FastGraphMap<N, E, Ty> {
nodes: IndexMap<N, Vec<(N, CompactDirection)>, ahash::RandomState>,
edges: IndexMap<(N, N), E, ahash::RandomState>,
ty: PhantomData<Ty>,
}
impl<N: Eq + Hash + fmt::Debug, E: fmt::Debug, Ty: EdgeType> fmt::Debug for FastGraphMap<N, E, Ty> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.nodes.fmt(f)
}
}
pub trait NodeTrait: Copy + Ord + Hash {}
impl<N> NodeTrait for N where N: Copy + Ord + Hash {}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum CompactDirection {
Outgoing,
Incoming,
}
impl From<Direction> for CompactDirection {
fn from(d: Direction) -> Self {
match d {
Outgoing => CompactDirection::Outgoing,
Incoming => CompactDirection::Incoming,
}
}
}
impl PartialEq<Direction> for CompactDirection {
fn eq(&self, rhs: &Direction) -> bool {
(*self as usize) == (*rhs as usize)
}
}
impl<N, E, Ty> FastGraphMap<N, E, Ty>
where
N: NodeTrait,
Ty: EdgeType,
{
pub fn new() -> Self {
Self::default()
}
pub fn with_capacity(nodes: usize, edges: usize) -> Self {
FastGraphMap {
nodes: IndexMap::with_capacity_and_hasher(nodes, Default::default()),
edges: IndexMap::with_capacity_and_hasher(edges, Default::default()),
ty: PhantomData,
}
}
pub fn capacity(&self) -> (usize, usize) {
(self.nodes.capacity(), self.edges.capacity())
}
#[inline]
fn edge_key(a: N, b: N) -> (N, N) {
if Ty::is_directed() || a <= b {
(a, b)
} else {
(b, a)
}
}
pub fn is_directed(&self) -> bool {
Ty::is_directed()
}
pub fn from_edges<I>(iterable: I) -> Self
where
I: IntoIterator,
I::Item: IntoWeightedEdge<E, NodeId = N>,
{
Self::from_iter(iterable)
}
pub fn node_count(&self) -> usize {
self.nodes.len()
}
pub fn edge_count(&self) -> usize {
self.edges.len()
}
pub fn clear(&mut self) {
self.nodes.clear();
self.edges.clear();
}
pub fn add_node(&mut self, n: N) -> N {
self.nodes.entry(n).or_default();
n
}
pub fn remove_node(&mut self, n: N) -> bool {
let links = match self.nodes.swap_remove(&n) {
None => return false,
Some(sus) => sus,
};
for (succ, _) in links {
self.remove_single_edge(&succ, &n, Incoming);
self.edges.swap_remove(&Self::edge_key(n, succ));
}
true
}
pub fn contains_node(&self, n: N) -> bool {
self.nodes.contains_key(&n)
}
pub fn add_edge(&mut self, a: N, b: N, weight: E) -> Option<E> {
if let old @ Some(_) = self.edges.insert(Self::edge_key(a, b), weight) {
old
} else {
self.nodes
.entry(a)
.or_insert_with(|| Vec::with_capacity(1))
.push((b, CompactDirection::Outgoing));
if a != b {
self.nodes
.entry(b)
.or_insert_with(|| Vec::with_capacity(1))
.push((a, CompactDirection::Incoming));
}
None
}
}
fn remove_single_edge(&mut self, a: &N, b: &N, dir: Direction) -> bool {
match self.nodes.get_mut(a) {
None => false,
Some(sus) => {
if Ty::is_directed() {
match sus
.iter()
.position(|elt| elt == &(*b, CompactDirection::from(dir)))
{
Some(index) => {
sus.swap_remove(index);
true
}
None => false,
}
} else {
match sus.iter().position(|elt| &elt.0 == b) {
Some(index) => {
sus.swap_remove(index);
true
}
None => false,
}
}
}
}
}
pub fn remove_edge(&mut self, a: N, b: N) -> Option<E> {
let exist1 = self.remove_single_edge(&a, &b, Outgoing);
let exist2 = if a != b {
self.remove_single_edge(&b, &a, Incoming)
} else {
exist1
};
let weight = self.edges.remove(&Self::edge_key(a, b));
debug_assert!(exist1 == exist2 && exist1 == weight.is_some());
weight
}
pub fn contains_edge(&self, a: N, b: N) -> bool {
self.edges.contains_key(&Self::edge_key(a, b))
}
pub fn nodes(&self) -> Nodes<N> {
Nodes {
iter: self.nodes.keys().cloned(),
}
}
pub fn neighbors(&self, a: N) -> Neighbors<N, Ty> {
Neighbors {
iter: match self.nodes.get(&a) {
Some(neigh) => neigh.iter(),
None => [].iter(),
},
ty: self.ty,
}
}
pub fn neighbors_directed(&self, a: N, dir: Direction) -> NeighborsDirected<N, Ty> {
NeighborsDirected {
iter: match self.nodes.get(&a) {
Some(neigh) => neigh.iter(),
None => [].iter(),
},
start_node: a,
dir,
ty: self.ty,
}
}
pub fn edges(&self, from: N) -> Edges<N, E, Ty> {
Edges {
from,
iter: self.neighbors(from),
edges: &self.edges,
}
}
pub fn edge_weight(&self, a: N, b: N) -> Option<&E> {
self.edges.get(&Self::edge_key(a, b))
}
pub fn edge_weight_mut(&mut self, a: N, b: N) -> Option<&mut E> {
self.edges.get_mut(&Self::edge_key(a, b))
}
pub fn all_edges(&self) -> AllEdges<N, E, Ty> {
AllEdges {
inner: self.edges.iter(),
ty: self.ty,
}
}
pub fn all_edges_mut(&mut self) -> AllEdgesMut<N, E, Ty> {
AllEdgesMut {
inner: self.edges.iter_mut(),
ty: self.ty,
}
}
pub fn into_graph<Ix>(self) -> Graph<N, E, Ty, Ix>
where
Ix: petgraph::graph::IndexType,
{
let mut gr = Graph::with_capacity(self.node_count(), self.edge_count());
for (&node, _) in &self.nodes {
gr.add_node(node);
}
for ((a, b), edge_weight) in self.edges {
let (ai, _, _) = self.nodes.get_full(&a).unwrap();
let (bi, _, _) = self.nodes.get_full(&b).unwrap();
gr.add_edge(node_index(ai), node_index(bi), edge_weight);
}
gr
}
}
impl<N, E, Ty, Item> FromIterator<Item> for FastGraphMap<N, E, Ty>
where
Item: IntoWeightedEdge<E, NodeId = N>,
N: NodeTrait,
Ty: EdgeType,
{
fn from_iter<I>(iterable: I) -> Self
where
I: IntoIterator<Item = Item>,
{
let iter = iterable.into_iter();
let (low, _) = iter.size_hint();
let mut g = Self::with_capacity(0, low);
g.extend(iter);
g
}
}
impl<N, E, Ty, Item> Extend<Item> for FastGraphMap<N, E, Ty>
where
Item: IntoWeightedEdge<E, NodeId = N>,
N: NodeTrait,
Ty: EdgeType,
{
fn extend<I>(&mut self, iterable: I)
where
I: IntoIterator<Item = Item>,
{
let iter = iterable.into_iter();
let (low, _) = iter.size_hint();
self.edges.reserve(low);
for elt in iter {
let (source, target, weight) = elt.into_weighted_edge();
self.add_edge(source, target, weight);
}
}
}
macro_rules! iterator_wrap {
($name: ident <$($typarm:tt),*> where { $($bounds: tt)* }
item: $item: ty,
iter: $iter: ty,
) => (
pub struct $name <$($typarm),*> where $($bounds)* {
iter: $iter,
}
impl<$($typarm),*> Iterator for $name <$($typarm),*>
where $($bounds)*
{
type Item = $item;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
self.iter.next()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
);
}
iterator_wrap! {
Nodes <'a, N> where { N: 'a + NodeTrait }
item: N,
iter: Cloned<Keys<'a, N, Vec<(N, CompactDirection)>>>,
}
pub struct Neighbors<'a, N, Ty = Undirected>
where
N: 'a,
Ty: EdgeType,
{
iter: Iter<'a, (N, CompactDirection)>,
ty: PhantomData<Ty>,
}
impl<'a, N, Ty> Iterator for Neighbors<'a, N, Ty>
where
N: NodeTrait,
Ty: EdgeType,
{
type Item = N;
fn next(&mut self) -> Option<N> {
if Ty::is_directed() {
(&mut self.iter)
.filter_map(|&(n, dir)| if dir == Outgoing { Some(n) } else { None })
.next()
} else {
self.iter.next().map(|&(n, _)| n)
}
}
}
pub struct NeighborsDirected<'a, N, Ty>
where
N: 'a,
Ty: EdgeType,
{
iter: Iter<'a, (N, CompactDirection)>,
start_node: N,
dir: Direction,
ty: PhantomData<Ty>,
}
impl<'a, N, Ty> Iterator for NeighborsDirected<'a, N, Ty>
where
N: NodeTrait,
Ty: EdgeType,
{
type Item = N;
fn next(&mut self) -> Option<N> {
if Ty::is_directed() {
let self_dir = self.dir;
let start_node = self.start_node;
(&mut self.iter)
.filter_map(move |&(n, dir)| {
if dir == self_dir || n == start_node {
Some(n)
} else {
None
}
})
.next()
} else {
self.iter.next().map(|&(n, _)| n)
}
}
}
pub struct Edges<'a, N, E: 'a, Ty>
where
N: 'a + NodeTrait,
Ty: EdgeType,
{
from: N,
edges: &'a IndexMap<(N, N), E, ahash::RandomState>,
iter: Neighbors<'a, N, Ty>,
}
impl<'a, N, E, Ty> Iterator for Edges<'a, N, E, Ty>
where
N: 'a + NodeTrait,
E: 'a,
Ty: EdgeType,
{
type Item = (N, N, &'a E);
fn next(&mut self) -> Option<Self::Item> {
match self.iter.next() {
None => None,
Some(b) => {
let a = self.from;
match self.edges.get(&FastGraphMap::<N, E, Ty>::edge_key(a, b)) {
None => unreachable!(),
Some(edge) => Some((a, b, edge)),
}
}
}
}
}
pub struct AllEdges<'a, N, E: 'a, Ty>
where
N: 'a + NodeTrait,
{
inner: IndexMapIter<'a, (N, N), E>,
ty: PhantomData<Ty>,
}
impl<'a, N, E, Ty> Iterator for AllEdges<'a, N, E, Ty>
where
N: 'a + NodeTrait,
E: 'a,
Ty: EdgeType,
{
type Item = (N, N, &'a E);
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(|(&(a, b), v)| (a, b, v))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
fn count(self) -> usize {
self.inner.count()
}
fn nth(&mut self, n: usize) -> Option<Self::Item> {
self.inner
.nth(n)
.map(|(&(n1, n2), weight)| (n1, n2, weight))
}
fn last(self) -> Option<Self::Item> {
self.inner
.last()
.map(|(&(n1, n2), weight)| (n1, n2, weight))
}
}
impl<'a, N, E, Ty> DoubleEndedIterator for AllEdges<'a, N, E, Ty>
where
N: 'a + NodeTrait,
E: 'a,
Ty: EdgeType,
{
fn next_back(&mut self) -> Option<Self::Item> {
self.inner
.next_back()
.map(|(&(n1, n2), weight)| (n1, n2, weight))
}
}
pub struct AllEdgesMut<'a, N, E: 'a, Ty>
where
N: 'a + NodeTrait,
{
inner: IndexMapIterMut<'a, (N, N), E>,
ty: PhantomData<Ty>,
}
impl<'a, N, E, Ty> Iterator for AllEdgesMut<'a, N, E, Ty>
where
N: 'a + NodeTrait,
E: 'a,
Ty: EdgeType,
{
type Item = (N, N, &'a mut E);
fn next(&mut self) -> Option<Self::Item> {
self.inner
.next()
.map(|(&(n1, n2), weight)| (n1, n2, weight))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
fn count(self) -> usize {
self.inner.count()
}
fn nth(&mut self, n: usize) -> Option<Self::Item> {
self.inner
.nth(n)
.map(|(&(n1, n2), weight)| (n1, n2, weight))
}
fn last(self) -> Option<Self::Item> {
self.inner
.last()
.map(|(&(n1, n2), weight)| (n1, n2, weight))
}
}
impl<'a, N, E, Ty> DoubleEndedIterator for AllEdgesMut<'a, N, E, Ty>
where
N: 'a + NodeTrait,
E: 'a,
Ty: EdgeType,
{
fn next_back(&mut self) -> Option<Self::Item> {
self.inner
.next_back()
.map(|(&(n1, n2), weight)| (n1, n2, weight))
}
}
impl<N, E, Ty> Default for FastGraphMap<N, E, Ty>
where
N: NodeTrait,
Ty: EdgeType,
{
fn default() -> Self {
FastGraphMap::with_capacity(0, 0)
}
}
pub struct Ptr<'b, T: 'b>(pub &'b T);
impl<'b, T> Copy for Ptr<'b, T> {}
impl<'b, T> Clone for Ptr<'b, T> {
fn clone(&self) -> Self {
*self
}
}
fn ptr_eq<T>(a: *const T, b: *const T) -> bool {
a == b
}
impl<'b, T> PartialEq for Ptr<'b, T> {
fn eq(&self, other: &Ptr<'b, T>) -> bool {
ptr_eq(self.0, other.0)
}
}
impl<'b, T> PartialOrd for Ptr<'b, T> {
fn partial_cmp(&self, other: &Ptr<'b, T>) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<'b, T> Ord for Ptr<'b, T> {
fn cmp(&self, other: &Ptr<'b, T>) -> Ordering {
let a: *const T = self.0;
let b: *const T = other.0;
a.cmp(&b)
}
}
impl<'b, T> Deref for Ptr<'b, T> {
type Target = T;
fn deref(&self) -> &T {
self.0
}
}
impl<'b, T> Eq for Ptr<'b, T> {}
impl<'b, T> Hash for Ptr<'b, T> {
fn hash<H: hash::Hasher>(&self, st: &mut H) {
let ptr = (self.0) as *const T;
ptr.hash(st)
}
}
impl<'b, T: fmt::Debug> fmt::Debug for Ptr<'b, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
pub struct NodeIdentifiers<'a, N, E: 'a, Ty>
where
N: 'a + NodeTrait,
{
iter: IndexMapIter<'a, N, Vec<(N, CompactDirection)>>,
ty: PhantomData<Ty>,
edge_ty: PhantomData<E>,
}
impl<'a, N, E, Ty> Iterator for NodeIdentifiers<'a, N, E, Ty>
where
N: 'a + NodeTrait,
E: 'a,
Ty: EdgeType,
{
type Item = N;
fn next(&mut self) -> Option<Self::Item> {
self.iter.next().map(|(&n, _)| n)
}
}
pub struct NodeReferences<'a, N, E: 'a, Ty>
where
N: 'a + NodeTrait,
{
iter: IndexMapIter<'a, N, Vec<(N, CompactDirection)>>,
ty: PhantomData<Ty>,
edge_ty: PhantomData<E>,
}
impl<'a, N, E, Ty> Iterator for NodeReferences<'a, N, E, Ty>
where
N: 'a + NodeTrait,
E: 'a,
Ty: EdgeType,
{
type Item = (N, &'a N);
fn next(&mut self) -> Option<Self::Item> {
self.iter.next().map(|(n, _)| (*n, n))
}
}
impl<N, E, Ty> NodeCount for FastGraphMap<N, E, Ty>
where
N: Copy + PartialEq,
{
fn node_count(&self) -> usize {
self.nodes.len()
}
}
impl<N, E, Ty> GraphBase for FastGraphMap<N, E, Ty>
where
N: Copy + PartialEq,
{
type EdgeId = (N, N);
type NodeId = N;
}
impl<N, E, Ty> Visitable for FastGraphMap<N, E, Ty>
where
N: Copy + Ord + Hash,
Ty: EdgeType,
{
type Map = AHashSet<N>;
fn visit_map(&self) -> AHashSet<N> {
AHashSet::with_capacity_and_hasher(self.node_count(), Default::default())
}
fn reset_map(&self, map: &mut Self::Map) {
map.clear();
}
}
impl<'a, N: 'a, E, Ty> IntoNeighbors for &'a FastGraphMap<N, E, Ty>
where
N: Copy + Ord + Hash,
Ty: EdgeType,
{
type Neighbors = Neighbors<'a, N, Ty>;
fn neighbors(self, n: Self::NodeId) -> Self::Neighbors {
self.neighbors(n)
}
}
impl<'a, N: 'a, E, Ty> IntoNeighborsDirected for &'a FastGraphMap<N, E, Ty>
where
N: Copy + Ord + Hash,
Ty: EdgeType,
{
type NeighborsDirected = NeighborsDirected<'a, N, Ty>;
fn neighbors_directed(self, n: N, dir: Direction) -> Self::NeighborsDirected {
self.neighbors_directed(n, dir)
}
}
impl<'a, N, E: 'a, Ty> IntoNodeIdentifiers for &'a FastGraphMap<N, E, Ty>
where
N: NodeTrait,
Ty: EdgeType,
{
type NodeIdentifiers = NodeIdentifiers<'a, N, E, Ty>;
fn node_identifiers(self) -> Self::NodeIdentifiers {
NodeIdentifiers {
iter: self.nodes.iter(),
ty: self.ty,
edge_ty: PhantomData,
}
}
}
impl<N, E, Ty> NodeIndexable for FastGraphMap<N, E, Ty>
where
N: NodeTrait,
Ty: EdgeType,
{
fn node_bound(&self) -> usize {
self.node_count()
}
fn to_index(&self, ix: Self::NodeId) -> usize {
let (i, _, _) = self.nodes.get_full(&ix).unwrap();
i
}
fn from_index(&self, ix: usize) -> Self::NodeId {
assert!(
ix < self.nodes.len(),
"The requested index {} is out-of-bounds.",
ix
);
let (&key, _) = self.nodes.get_index(ix).unwrap();
key
}
}