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
use crate::{graph::NodeContainer, AdjList};

use {
    crate::{GenericGraph, AdjContainer},
    super::dual_graph_iterators::*,
    crate::iter::{NContainedIterMut, NContainedIter},
    std::ops::{Deref, DerefMut}
};

#[cfg(feature = "serde_support")]
use serde::{Serialize, Deserialize};

pub type MultiDualGraph<T1, A1, T2, A2> = DualGraph<Adj, T1, A1, T2, A2>;
pub type SingleDualGraph<T1, A1, T2, A2> = DualGraph<AdjSingle, T1, A1, T2, A2>;
pub type DefaultSDG<T1, T2> = SingleDualGraph<T1, NodeContainer<T1>, T2, NodeContainer<T2>>;


#[derive(Clone)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct DualGraph<ADJ, T1, A1, T2, A2>
{
    pub(crate) graph_1: GenericGraph<T1, A1>,
    pub(crate) graph_2: GenericGraph<T2, A2>,
    pub(crate) adj_1: Vec<ADJ>,
    pub(crate) adj_2: Vec<ADJ>
}

impl<ADJ, T1, A1, T2, A2> DualGraph<ADJ, T1, A1, T2, A2>
where ADJ: AdjTrait{
    pub fn new(
        graph_1: GenericGraph<T1, A1>, 
        graph_2: GenericGraph<T2, A2>
    ) -> Self
    {
        let adj_1 = (0..graph_1.vertices.len())
            .map(|_| ADJ::new())
            .collect();

        let adj_2 = (0..graph_2.vertices.len())
            .map(|_| ADJ::new())
            .collect();

        Self{
            graph_1,
            graph_2,
            adj_1,
            adj_2
        }
    }

    pub fn graph_1(&self) -> &GenericGraph<T1, A1>
    {
        &self.graph_1
    }

    pub fn graph_2(&self) -> &GenericGraph<T2, A2>
    {
        &self.graph_2
    }

    pub fn graph_1_mut(&mut self) -> &mut GenericGraph<T1, A1>
    {
        &mut self.graph_1
    }

    pub fn graph_2_mut(&mut self) -> &mut GenericGraph<T2, A2>
    {
        &mut self.graph_2
    }

    pub fn adj_1(&self) -> &[ADJ]
    {
        &self.adj_1
    }

    pub fn adj_2(&self) -> &[ADJ]
    {
        &self.adj_2
    }

    pub fn size(&self) -> (usize, usize)
    {
        (
            self.graph_1.vertices.len(),
            self.graph_2.vertices.len()
        )
    }

    pub fn add_edge(
        &mut self, 
        index_graph_1: usize, 
        index_graph_2: usize
    ) -> Result<(), AddEdgeError>
    {
        if self.adj_1.len() <= index_graph_1 || self.adj_2.len() <= index_graph_2 {
            return Err(AddEdgeError::IndexOutOfBounds);
        }
        unsafe {
            if !self.adj_1
                .get_unchecked_mut(index_graph_1)
                .add_edge(index_graph_2)
            {
                return Err(AddEdgeError::EdgeExists)   
            }
            
            if !self.adj_2
                .get_unchecked_mut(index_graph_2)
                .add_edge(index_graph_1)
            {
                unreachable!()
            } else {
                Ok(())
            }
        }

    }

    pub fn total_vertices(&self) -> usize
    {
        self.graph_1.vertices.len() + self.graph_2.vertices.len()
    }

}

impl<ADJ, T1, A1, T2, A2> DualGraph<ADJ, T1, A1, T2, A2>
where A1: AdjContainer<T1>,
    ADJ: AdjTrait
{
    pub fn degree_1(&self, index: usize) -> usize
    {
        self.graph_1.container(index)
            .degree() + self.adj_1[index].slice().len()
    }
}

impl<ADJ, T1, A1, T2, A2> DualGraph<ADJ, T1, A1, T2, A2>
where A2: AdjContainer<T2>,
    ADJ: AdjTrait
{
    pub fn degree_2(&self, index: usize) -> usize
    {
        self.graph_2.container(index)
            .degree() + self.adj_2[index].slice().len()
    }
}

impl<T1, T2, A1, A2, ADJ> DualGraph<ADJ, T1, A1, T2, A2>
where A1: AdjContainer<T1>,
    A2: AdjContainer<T2>,
    ADJ: AdjTrait
{
    /// Depth first search iterator starting at the node corresponding to `index`
    /// 
    /// Note that, this iterator will return indices from both graphs, the corresponding
    /// graph is given by the variant of DualIndex
    pub fn dfs_index(&self, index: DualIndex) -> impl '_ + Iterator<Item=DualIndex>
    {
        DfsDualIndex::new(self, index)
    }

    /// Depth first search iterator starting at the node in graph_1 corresponding to `index`
    /// 
    /// Note that, this iterator will return indices from both graphs, the corresponding
    /// graph is given by the variant of DualIndex
    pub fn dfs_1_index(&self, index: usize) -> impl '_ + Iterator<Item=DualIndex>
    {
        self.dfs_index(DualIndex::Graph1(index))
    }

    /// Depth first search iterator starting at the node in graph_2 corresponding to `index`
    /// 
    /// Note that, this iterator will return indices from both graphs, the corresponding
    /// graph is given by the variant of DualIndex
    pub fn dfs_2_index(&self, index: usize) -> impl '_ + Iterator<Item=DualIndex>
    {
        self.dfs_index(DualIndex::Graph2(index))
    }

    pub fn bfs_index(&self, index: DualIndex) -> impl '_ + Iterator<Item=(DualIndex, usize)>
    {
        BfsDualIndex::new(self, index)
    }

    pub fn is_connected(&self) -> bool
    {
        let v1 = self.graph_1.vertex_count() == 0;
        let v2 = self.graph_2.vertex_count() == 0;
        if v1 && v2 {
            true
        } else if  v1 && !v2 {
            match self.graph_2.is_connected()
            {
                Some(r) => r,
                None => unsafe {std::hint::unreachable_unchecked()}
            }
        } else if !v1 && v2 {
            match self.graph_1.is_connected()
            {
                Some(r) => r,
                None => unsafe {std::hint::unreachable_unchecked()}
            }
        } else {
            self.dfs_1_index(0).count() == self.total_vertices()
        }
    }

    /// * returns `None` **if** graph not connected **or** does not contain any vertices
    /// * uses repeated breadth first search
    pub fn diameter(&self) -> Option<usize>
    {
        if self.total_vertices() == 0 || !self.is_connected(){
            // This could be further optimized by using the first consumtion of the 
            // bfs Iterator to also check if the network is connected,
            // however I did not bother to
            None
        } else {
            let mut max_depth = 0;
            // only one of the vertex counts can be 0, otherwise the total vertex count would be zero
            // also, we have a connected graph
            // Though, which one i choose here does not matter, as I reuse the Iterator before its first use anyway 
            let mut bfs = BfsDualIndex::new(self, DualIndex::Graph1(0));


            for i in 0..self.graph_1.vertex_count() {
                bfs.reuse(DualIndex::Graph1(i));
                let consumable = &mut bfs;
                let depth = match consumable.last(){
                    Some((.., depth)) => depth,
                    None => {
                        // safety: The Iterator will return at least one element as it was "reused"
                        // with a valid index. Therefore "last" cannot return None
                        #[cfg(debug_assertions)]
                        {
                            unreachable!()
                        }
                        #[cfg(not(debug_assertions))]
                        unsafe{
                            std::hint::unreachable_unchecked()
                        }
                    }
                };
                max_depth = max_depth.max(depth);
            }
            // I can ignore one node here, as the last iteration would be redundant
            for i in 1..self.graph_2.vertex_count() {
                bfs.reuse(DualIndex::Graph2(i));
                let consumable = &mut bfs;
                let depth = match consumable.last() {
                    Some((.., depth)) => depth,
                    None => {
                        // safety: The Iterator will return at least one element as it was "reused"
                        // with a valid index. Therefore "last" cannot return None
                        #[cfg(debug_assertions)]
                        {
                            unreachable!()
                        }
                        #[cfg(not(debug_assertions))]
                        unsafe{
                            std::hint::unreachable_unchecked()
                        }
                    }
                };
                max_depth = max_depth.max(depth);
            }
            Some(max_depth)
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
/// Stores information T and the graph the information corresponds to
pub enum WhichGraph<T>{
    /// information is related to graph 1
    Graph1(T),
    /// information is related to graph 2
    Graph2(T)
}

impl<T> Deref for WhichGraph<T>
{
    type Target = T;
    #[inline(always)]
    fn deref(&self) -> &Self::Target {
        match self{
            WhichGraph::Graph1(inner) => inner,
            WhichGraph::Graph2(inner) => inner,
        }
    }
}

impl<T> DerefMut for WhichGraph<T>
{
    #[inline(always)]
    fn deref_mut(&mut self) -> &mut Self::Target
    {
        match self{
            WhichGraph::Graph1(inner) => inner,
            WhichGraph::Graph2(inner) => inner
        }
    }
}

impl<T> WhichGraph<T>
{
    #[inline(always)]
    pub fn into_inner(self) -> T
    {
        match self{
            WhichGraph::Graph1(inner) => inner,
            WhichGraph::Graph2(inner) => inner
        }
    }
}

impl<T, A1, A2> SingleDualGraph<T, A1, T, A2>
where A1: AdjContainer<T> + AdjList<usize>,
    A2: AdjContainer<T> + AdjList<usize>,
{
    #[inline]
    pub fn graph_1_contained_iter_neighbors_in_other_graph_mut(&mut self, index: usize) -> impl Iterator<Item=&mut T>
    {
        NContainedIterMut::new(
            &mut self.graph_2.vertices,
            self.adj_1[index].slice().iter()
        )
    }

    #[inline]
    pub fn graph_2_contained_iter_neighbors_in_other_graph_mut(&mut self, index: usize) -> impl Iterator<Item=&mut T>
    {
        NContainedIterMut::new(
            &mut self.graph_1.vertices,
            self.adj_2[index].slice().iter()
        )
    }

    #[inline]
    /// Note: This will first iterate over all neighbors from this graph and then over 
    /// all neighbors from the other graph
    pub fn graph_1_contained_iter_mut(&mut self, index: usize) -> impl Iterator<Item=&mut T>
    {
        debug_assert!(
            index < self.graph_1().vertices.len(),
            "graph_1_contained_iter_mut_which_graph - index out of bounds"
        );

        let ptr = self.graph_1.vertices.as_mut_ptr();
        let iter_helper: &mut A1 = unsafe { &mut *ptr.add(index) };
        let iter = iter_helper.edges();

        let iter = NContainedIterMut::new(
            &mut self.graph_1.vertices,
            iter.iter()
        );

        let o = {
            let slice = self.adj_1[index].slice();
            if slice.is_empty(){
                None
            } else {
                let index = slice[0];
                Some(self.graph_2.at_mut(index))
            }
        };

        iter
            .chain(o.into_iter())
    }

    #[inline]
    /// Note: This will first iterate over all neighbors from this graph and then over 
    /// all neighbors from the other graph
    pub fn graph_1_contained_iter(&self, index: usize) -> impl Iterator<Item=&T>
    {
        debug_assert!(
            index < self.graph_1().vertices.len(),
            "graph_1_contained_iter_mut_which_graph - index out of bounds"
        );

        let ptr = self.graph_1.vertices.as_ptr();
        let iter_helper: &A1 = unsafe { & *ptr.add(index) };
        let iter = iter_helper.edges();

        let iter = NContainedIter::new(
            &self.graph_1.vertices,
            iter.iter()
        );

        let o = {
            let slice = self.adj_1[index].slice();
            if slice.is_empty(){
                None
            } else {
                let index = slice[0];
                Some(self.graph_2.at(index))
            }
        };

        iter
            .chain(o.into_iter())
    }

    #[inline]
    /// Note: This will first iterate over all neighbors from this graph and then over 
    /// all neighbors from the other graph
    pub fn graph_2_contained_iter(&self, index: usize) -> impl Iterator<Item=&T>
    {
        debug_assert!(
            index < self.graph_2().vertices.len(),
            "graph_1_contained_iter_mut_which_graph - index out of bounds"
        );

        let ptr = self.graph_2.vertices.as_ptr();
        let iter_helper: &A2 = unsafe { & *ptr.add(index) };
        let iter = iter_helper.edges();

        let iter = NContainedIter::new(
            &self.graph_2.vertices,
            iter.iter()
        );

        let o = {
            let slice = self.adj_2[index].slice();
            if slice.is_empty(){
                None
            } else {
                let index = slice[0];
                Some(self.graph_1.at(index))
            }
        };

        iter
            .chain(o.into_iter())
    }

    #[inline]
    pub fn graph_1_contained_iter_mut_which_graph_with_index(&mut self, index: usize) -> impl Iterator<Item=WhichGraph<(usize, &mut T)>>
    {
        assert!(
            index < self.graph_1().vertices.len(),
            "graph_1_contained_iter_mut_which_graph - index out of bounds"
        );

        let ptr = self.graph_1.vertices.as_mut_ptr();
        let iter_helper: &mut A1 = unsafe { &mut *ptr.add(index) };
        let iter = iter_helper.edges();

        let iter = NContainedIterMut::new(
            &mut self.graph_1.vertices,
            iter.iter()
        );

        let o = {
            let slice = self.adj_1[index].slice();
            if slice.is_empty(){
                None
            } else {
                let index = slice[0];
                Some(WhichGraph::Graph2((index, self.graph_2.at_mut(index))))
            }
        };

        iter_helper.edges().iter().copied()
            .zip(iter)
            .map(WhichGraph::Graph1)
            .chain(o.into_iter())
    }

    #[inline]
    pub fn graph_1_contained_iter_mut_which_graph(&mut self, index: usize) -> impl Iterator<Item=WhichGraph<&mut T>>
    {
        assert!(
            index < self.graph_1().vertices.len(),
            "graph_1_contained_iter_mut_which_graph - index out of bounds"
        );

        let ptr = self.graph_1.vertices.as_mut_ptr();
        let iter_helper: &mut A1 = unsafe { &mut *ptr.add(index) };
        let iter = iter_helper.edges();

        let iter = NContainedIterMut::new(
            &mut self.graph_1.vertices,
            iter.iter()
        );

        let o = {
            let slice = self.adj_1[index].slice();
            if slice.is_empty(){
                None
            } else {
                Some(WhichGraph::Graph2(self.graph_2.at_mut(slice[0])))
            }
        };

        iter
            .map(WhichGraph::Graph1)
            .chain(o.into_iter())
    }


    #[inline]
    pub fn graph_2_contained_iter_mut_which_graph(&mut self, index: usize) -> impl Iterator<Item=WhichGraph<&mut T>>
    {
        assert!(
            index < self.graph_2().vertices.len(),
            "graph_2_contained_iter_mut_which_graph - index out of bounds"
        );

        let ptr = self.graph_2.vertices.as_mut_ptr();
        let iter_helper: &mut A2 = unsafe { &mut *ptr.add(index) };
        let iter = iter_helper.edges();

        let iter = NContainedIterMut::new(
            &mut self.graph_2.vertices,
            iter.iter()
        );

        let o = {
            let slice = self.adj_2[index].slice();
            if slice.is_empty(){
                None
            } else {
                Some(WhichGraph::Graph1(self.graph_1.at_mut(slice[0])))
            }
        };

        iter
            .map(WhichGraph::Graph2)
            .chain(o.into_iter())
    }

    #[inline]
    pub fn graph_2_contained_iter_mut_which_graph_with_index(&mut self, index: usize)-> impl Iterator<Item=WhichGraph<(usize, &mut T)>>
    {
        assert!(
            index < self.graph_2().vertices.len(),
            "graph_2_contained_iter_mut_which_graph - index out of bounds"
        );

        let ptr = self.graph_2.vertices.as_mut_ptr();
        let iter_helper: &mut A2 = unsafe { &mut *ptr.add(index) };
        let iter = iter_helper.edges();

        let iter = NContainedIterMut::new(
            &mut self.graph_2.vertices,
            iter.iter()
        );

        let o = {
            let slice = self.adj_2[index].slice();
            if slice.is_empty(){
                None
            } else {
                let index = slice[0];
                Some(WhichGraph::Graph1((index, self.graph_1.at_mut(index))))
            }
        };


        iter_helper.edges()
            .iter()
            .copied()
            .zip(iter)
            .map(WhichGraph::Graph2)
            .chain(o.into_iter())

    }

}

//#[inline(always)]
//fn map_chain<'a, T, A, I, F>(
//    ncontained: NContainedIterMut<'a, T, A, I>, 
//    option: Option<WhichGraph<&'a mut T>>,
//    graph_fun: F
//) -> impl Iterator<Item=WhichGraph<&mut T>>
//where I: Iterator<Item=&'a usize>,
//    A: AdjContainer<T>,
//    F: Fn(&'a mut T) -> WhichGraph<&'a mut T>
//{
//    ncontained
//            .map(graph_fun)
//            .chain(option.into_iter())
//}

impl<T, A1, A2, ADJ> DualGraph<ADJ, T, A1, T, A2>
where A1: AdjContainer<T>,
    A2: AdjContainer<T>,
    ADJ: AdjTrait,
{
    /// Iterate over all neighbors of the node corresponding to
    /// index from graph_1. 
    /// Note, that this also includes possible neighbors in the second 
    /// graph
    pub fn contained_iter_neighbors_1(&self, index: usize) -> impl Iterator<Item=&T>
    {
        self.graph_1
            .contained_iter_neighbors(index)
            .chain(
                NContainedIter2::new(
                    self.graph_2.vertices.as_slice(), 
                    self.adj_1[index].slice()
                )
            )
    }

    /// Iterate over all neighbors of the node corresponding to
    /// index from graph_1. 
    /// Note, that this also includes possible neighbors in the second 
    /// graph
    pub fn contained_iter_neighbors_2(&self, index: usize) -> impl Iterator<Item=&T>
    {
        self.graph_2
            .contained_iter_neighbors(index)
            .chain(
                NContainedIter2::new(
                    self.graph_1.vertices.as_slice(), 
                    self.adj_2[index].slice()
                )
            )
    }

    pub fn dfs_contained(&self, index: DualIndex) -> DfsDualContained<T, A1, A2, ADJ>
    {
        DfsDualContained::new(self, index)
    }

    pub fn dfs_1_contained(&self, index_graph_1: usize) -> DfsDualContained<T, A1, A2, ADJ>
    {
        DfsDualContained::new(self, DualIndex::Graph1(index_graph_1))
    }

    pub fn dfs_2_contained(&self, index_graph_2: usize) -> DfsDualContained<T, A1, A2, ADJ>
    {
        DfsDualContained::new(self, DualIndex::Graph2(index_graph_2))
    }
}

#[derive(Clone)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct Adj{
    pub(crate) adj: Vec<usize>
}

impl AdjTrait for Adj
{
    fn new() -> Self
    {
        Self{
            adj: Vec::new()
        }
    }

    fn is_adjacent(&self, other_index: &usize) -> bool
    {
        self.adj.contains(other_index)
    }

    fn add_edge(&mut self, other_index: usize) -> bool
    {
        if self.is_adjacent(&other_index){
            return false;
        }
        self.adj.push(other_index);
        true
    }

    fn slice(&self) -> &[usize]
    {
        self.adj.as_slice()
    }
}

pub trait AdjTrait{
    fn new() -> Self;

    fn is_adjacent(&self, other_index: &usize) -> bool;

    fn add_edge(&mut self, other_index: usize) -> bool;

    fn slice(&self) -> &[usize];
}

#[derive(Clone, Copy)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub enum AdjSingle
{
    Nothing([usize;0]),
    Something([usize;1])
}

impl AdjSingle
{
    #[inline]
    pub fn is_nothing(&self) -> bool
    {
        matches!(self, Self::Nothing(..))
    }

    #[inline]
    pub fn is_something(&self) -> bool{
        matches!(self, Self::Something(..))
    }
}

impl AdjTrait for AdjSingle
{
    #[inline(always)]
    fn new() -> Self
    {
        Self::Nothing([])
    }

    #[inline(always)]
    fn is_adjacent(&self, other_index: &usize) -> bool
    {
        if let Self::Something(s) = self
        {
            s[0] == *other_index
        } else {
            false
        }
    }

    #[inline(always)]
    fn add_edge(&mut self, other_index: usize) -> bool
    {
        if self.is_nothing(){
            *self = Self::Something([other_index]);
            true
        } else {
            false
        }
    }

    #[inline(always)]
    fn slice(&self) -> &[usize]
    {
        match self
        {
            Self::Nothing(nothing) => nothing,
            Self::Something(something) => something
        }
    }
}


/// Index which also stores for which graph the index is
pub type DualIndex = WhichGraph<usize>;

#[derive(Debug, Copy, Clone)]
pub enum AddEdgeError{
    IndexOutOfBounds,
    EdgeExists
}


#[cfg(test)]
mod testing {
    use super::*;
    use crate::{Graph, EmptyNode, SwGraph, CountingNode};
    use std::num::*;

    #[test]
    fn dual_graph_basic_test()
    {
        let mut graph_1 = Graph::<EmptyNode>::new(5);
        graph_1.add_edge(0, 1).unwrap();
        graph_1.add_edge(1, 2).unwrap();
        graph_1.add_edge(3, 4).unwrap();

        assert_eq!(graph_1.is_connected(), Some(false));

        let mut graph_2 = SwGraph::<CountingNode>::new(5);

        graph_2.init_ring_2();
        assert_eq!(graph_2.is_connected(), Some(true));

        let mut dual = SingleDualGraph::new(graph_1, graph_2);

        assert!(!dual.is_connected());

        dual.add_edge(1, 0).unwrap();
        assert!(!dual.is_connected());
        dual.add_edge(3, 4).unwrap();
        assert!(dual.is_connected());
    }

    #[test]
    fn dual_graph_dfs_test()
    {
        let mut graph_1 = Graph::<CountingNode>::new(5);
        graph_1.init_ring(NonZeroUsize::new(2).unwrap()).unwrap();
        let sum_1: usize = graph_1.dfs(0).map(CountingNode::number).sum();
        assert_eq!(sum_1, 10);
        
        let mut graph_2 = Graph::<CountingNode>::new(11);
        graph_2.init_ring(NonZeroUsize::new(1).unwrap()).unwrap();

        let sum_2: usize = graph_2.dfs(0).map(CountingNode::number).sum();

        assert_eq!(sum_2, 55);

        let mut dual = MultiDualGraph::new(
            graph_1,
            graph_2
        );

        let sum_dual_1: usize = dual.dfs_1_contained(0).map(CountingNode::number).sum();
        assert_eq!(sum_1, sum_dual_1);

        let sum_dual_2: usize = dual.dfs_2_contained(0).map(CountingNode::number).sum();
        assert_eq!(sum_2, sum_dual_2);

        dual.add_edge(0, 0).unwrap();

        let sum_of_sum: usize = dual
            .dfs_contained(DualIndex::Graph1(0))
            .map(CountingNode::number)
            .sum();
        
        assert_eq!(sum_1 + sum_2, sum_of_sum);
    }

    #[test]
    fn dual_graph_bfs_test()
    {
        let is_connected = |dual_graph: &MultiDualGraph<_, _, _, _>| {
            dual_graph.bfs_index(DualIndex::Graph1(0)).count() == dual_graph.total_vertices()
        };

        
        let mut graph_1 = Graph::<EmptyNode>::new(5);
        graph_1.add_edge(0, 1).unwrap();
        graph_1.add_edge(1, 2).unwrap();
        graph_1.add_edge(3, 4).unwrap();

        assert_eq!(graph_1.is_connected(), Some(false));

        let mut graph_2 = SwGraph::<CountingNode>::new(5);

        graph_2.init_ring_2();
        assert_eq!(graph_2.is_connected(), Some(true));

        let mut dual = DualGraph::new(graph_1, graph_2);
        
        assert!(!is_connected(&dual));
        is_connected(&dual);

        dual.add_edge(1, 0).unwrap();
        assert!(!is_connected(&dual));

        dual.add_edge(3, 4).unwrap();
        // now it should be connected
        assert!(is_connected(&dual));

    }

    #[test]
    fn dual_graph_bfs_depth_test()
    {
        let mut graph_1 = Graph::<EmptyNode>::new(6);
        graph_1.init_ring(NonZeroUsize::new(1).unwrap()).unwrap();
        let graph_2 = graph_1.clone();

        let mut dual = MultiDualGraph::new(graph_1, graph_2);

        // connect them
        dual.add_edge(0, 0).unwrap();

        let depth = dual.bfs_index(DualIndex::Graph1(3)).last().unwrap().1;
        assert!(dual.is_connected());
        assert_eq!(depth, 7);

        assert_eq!(dual.diameter(), Some(7));

    }
}