bounded_graph 0.3.0

A thin newtype wrapper for `petgraph` to assist in the creation of graphs with restrictions on their edges
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
use petgraph::{csr::IndexType, graph::NodeIndex, Graph};

use crate::{
    BoundedDiGraph, BoundedGraph, BoundedGraphError, BoundedUnGraph, EdgeBounds, SimpleEdgeBounds,
    SymmetricFixedEdgeCount,
};

#[test]
fn test_deref_and_asref() {
    #[derive(Debug, Default)]
    pub struct TestNode {
        name: String,
        max_edges: usize,
    }

    impl TestNode {
        pub fn new(name: String, max_edges: usize) -> Self {
            Self { name, max_edges }
        }
    }

    impl<Ix: IndexType> EdgeBounds<Ix> for TestNode {
        fn max_incoming_edges(&self) -> Ix {
            Ix::new(self.max_edges)
        }

        fn max_outgoing_edges(&self) -> Ix {
            Ix::new(self.max_edges)
        }
    }

    impl SimpleEdgeBounds for TestNode {}

    let mut graph = BoundedGraph::<TestNode, &str>::new();
    let n1 = graph.add_node(TestNode::new("node1".to_string(), 2));
    let n2 = graph.add_node(TestNode::new("node2".to_string(), 2));
    let n3 = graph.add_node(TestNode::new("node3".to_string(), 2));

    graph.add_edge(n1, n2, "edge1").unwrap();
    graph.add_edge(n2, n3, "edge2").unwrap();

    // Test Deref allows calling Graph methods directly
    assert_eq!(graph.node_count(), 3);
    assert_eq!(graph.edge_count(), 2);
    assert!(graph.contains_edge(n1, n2));
    assert!(graph.contains_edge(n2, n3));
    assert!(!graph.contains_edge(n1, n3));
    assert_eq!(graph.node_weight(n1).unwrap().name, "node1");
    assert_eq!(graph.neighbors(n2).count(), 1);

    // Test AsRef works
    fn count_edges<N, E, Ty, Ix>(g: &impl AsRef<Graph<N, E, Ty, Ix>>) -> usize
    where
        Ty: petgraph::EdgeType,
        Ix: IndexType,
    {
        g.as_ref().edge_count()
    }

    assert_eq!(count_edges(&graph), 2);
}

#[test]
fn test_inner() {
    use crate::FixedEdgeCount;

    let mut graph = BoundedGraph::<FixedEdgeCount<3>, i32>::new();
    let n1 = graph.add_node(FixedEdgeCount::empty());
    let n2 = graph.add_node(FixedEdgeCount::empty());
    let e = graph.add_edge(n1, n2, 42).unwrap();

    // Test inner() provides access to underlying graph
    let inner = graph.inner();
    assert_eq!(inner.node_count(), 2);
    assert_eq!(inner.edge_count(), 1);
    assert_eq!(*inner.edge_weight(e).unwrap(), 42);

    // Test that we can use petgraph methods through inner()
    assert!(inner.contains_edge(n1, n2));
    assert!(!inner.contains_edge(n2, n1));

    // Test inner() with into_inner() for conversion
    let inner_graph = graph.into_inner();
    assert_eq!(inner_graph.node_count(), 2);
    assert_eq!(inner_graph.edge_count(), 1);
}

#[test]
fn test_type_aliases() {
    // Test BoundedDiGraph (directed) using SymmetricFixedEdgeCount
    let mut digraph = BoundedDiGraph::<SymmetricFixedEdgeCount<2>, ()>::new();
    let n1 = digraph.add_node(SymmetricFixedEdgeCount::empty());
    let n2 = digraph.add_node(SymmetricFixedEdgeCount::empty());
    digraph.add_edge(n1, n2, ()).unwrap();

    assert_eq!(digraph.node_count(), 2);
    assert_eq!(digraph.edge_count(), 1);
    assert!(digraph.is_directed());

    // Test BoundedUnGraph (undirected) using SymmetricFixedEdgeCount
    let mut ungraph = BoundedUnGraph::<SymmetricFixedEdgeCount<2>, ()>::new();
    let n1 = ungraph.add_node(SymmetricFixedEdgeCount::empty());
    let n2 = ungraph.add_node(SymmetricFixedEdgeCount::empty());
    ungraph.add_edge(n1, n2, ()).unwrap();

    assert_eq!(ungraph.node_count(), 2);
    assert_eq!(ungraph.edge_count(), 1);
    assert!(!ungraph.is_directed());
}

#[test]
fn test_update_edge_error_handling() {
    // Test that update_edge properly returns errors instead of panicking
    // Uses SymmetricFixedEdgeCount for simplicity
    let mut graph = BoundedGraph::<SymmetricFixedEdgeCount<1>, &str>::new();

    // Create nodes with very limited capacity
    let n1 = graph.add_node(SymmetricFixedEdgeCount::empty());
    let n2 = graph.add_node(SymmetricFixedEdgeCount::empty());
    let n3 = graph.add_node(SymmetricFixedEdgeCount::empty());

    // First edge should succeed
    assert!(graph.add_edge(n1, n2, "edge1").is_ok());

    // update_edge on existing edge should succeed (just updates weight)
    assert!(graph.update_edge(n1, n2, "updated").is_ok());
    assert_eq!(graph.edge_count(), 1);

    // update_edge to create new edge when source is full should fail
    let result = graph.update_edge(n1, n3, "edge2");
    assert!(result.is_err());
    assert!(matches!(
        result.unwrap_err(),
        BoundedGraphError::EdgeRejected {
            source_rejected: true,
            target_rejected: false,
            ..
        }
    ));

    // Verify no edge was added on failure
    assert_eq!(graph.edge_count(), 1);
    assert!(!graph.contains_edge(n1, n3));

    // add_edge should also properly return error
    let result = graph.add_edge(n1, n3, "edge3");
    assert!(result.is_err());
    assert_eq!(graph.edge_count(), 1);
}

#[test]
fn test_no_panic_on_capacity_errors() {
    // Verify that capacity errors never panic - they always return Results
    // Uses SymmetricFixedEdgeCount with 0 capacity
    let mut graph = BoundedGraph::<SymmetricFixedEdgeCount<0>, ()>::new();
    let n1 = graph.add_node(SymmetricFixedEdgeCount::empty());
    let n2 = graph.add_node(SymmetricFixedEdgeCount::empty());

    // Attempting to add edges to nodes with 0 capacity should fail gracefully
    // Both nodes have 0 capacity, so we expect RejectedByBothNodes
    let result = graph.add_edge(n1, n2, ());
    assert!(result.is_err());
    assert!(matches!(
        result.unwrap_err(),
        BoundedGraphError::EdgeRejected {
            source_rejected: true,
            target_rejected: true,
            ..
        }
    ));

    let result = graph.update_edge(n1, n2, ());
    assert!(result.is_err());

    // Graph should remain empty
    assert_eq!(graph.edge_count(), 0);
    assert_eq!(graph.node_count(), 2);
}

#[test]
fn test_can_add_edge_invalid_nodes() {
    // Verify that can_add_edge correctly handles invalid node indices
    // Uses SymmetricFixedEdgeCount for simplicity
    let mut graph = BoundedGraph::<SymmetricFixedEdgeCount<2>, ()>::new();
    let n1 = graph.add_node(SymmetricFixedEdgeCount::empty());
    let n2 = graph.add_node(SymmetricFixedEdgeCount::empty());

    // Valid nodes should work
    assert!(graph.can_add_edge(n1, n2));

    // Invalid node indices should return false
    let invalid = NodeIndex::new(999);
    assert!(!graph.can_add_edge(invalid, n2));
    assert!(!graph.can_add_edge(n1, invalid));
    assert!(!graph.can_add_edge(invalid, invalid));

    // After adding an edge, check still works
    graph.add_edge(n1, n2, ()).unwrap();
    assert!(graph.can_add_edge(n1, n2)); // Can still add more (max is 2)
}

#[test]
fn test_try_extend_with_edges_success() {
    // Test complete success - all edges should be added
    // Uses SymmetricFixedEdgeCount for simplicity
    let mut graph = BoundedGraph::<SymmetricFixedEdgeCount<3>, i32>::new();
    let _ = graph.add_node(SymmetricFixedEdgeCount::empty());
    let _ = graph.add_node(SymmetricFixedEdgeCount::empty());
    let _ = graph.add_node(SymmetricFixedEdgeCount::empty());

    let edges = vec![(0u32, 1u32, 10), (1u32, 2u32, 20), (2u32, 0u32, 30)];
    let result = graph.try_extend_with_edges(&edges);

    assert!(result.is_ok());
    let added = result.unwrap();
    assert_eq!(added.len(), 3);
    assert_eq!(graph.edge_count(), 3);

    // Verify edge weights were set correctly
    assert_eq!(*graph.edge_weight(added[0]).unwrap(), 10);
    assert_eq!(*graph.edge_weight(added[1]).unwrap(), 20);
    assert_eq!(*graph.edge_weight(added[2]).unwrap(), 30);
}

#[test]
fn test_try_extend_with_edges_partial_success() {
    // Test partial success - some edges added before failure
    #[derive(Debug, Default)]
    pub struct TestNode {
        max_edges: usize,
    }

    impl<Ix: IndexType> EdgeBounds<Ix> for TestNode {
        fn max_incoming_edges(&self) -> Ix {
            Ix::new(self.max_edges)
        }

        fn max_outgoing_edges(&self) -> Ix {
            Ix::new(self.max_edges)
        }
    }

    impl SimpleEdgeBounds for TestNode {}

    let mut graph = BoundedGraph::<TestNode, i32>::new();
    let _ = graph.add_node(TestNode { max_edges: 2 }); // Limited capacity
    let _ = graph.add_node(TestNode { max_edges: 5 });
    let _ = graph.add_node(TestNode { max_edges: 5 });

    // Try to add 3 edges from node 0, but it can only handle 2
    let edges = vec![(0u32, 1u32, 10), (0u32, 2u32, 20), (0u32, 1u32, 30)];
    let result = graph.try_extend_with_edges(&edges);

    assert!(result.is_err());
    let (added, err) = result.unwrap_err();

    // First 2 edges should have been added successfully
    assert_eq!(added.len(), 2);
    assert_eq!(graph.edge_count(), 2);

    // Verify the error is about node 0 being full
    assert!(matches!(
        err,
        BoundedGraphError::EdgeRejected {
            source_rejected: true,
            target_rejected: false,
            ..
        }
    ));

    // Verify the edges that were added
    assert_eq!(*graph.edge_weight(added[0]).unwrap(), 10);
    assert_eq!(*graph.edge_weight(added[1]).unwrap(), 20);
}

#[test]
fn test_try_extend_with_edges_immediate_failure() {
    // Test immediate failure - first edge fails
    #[derive(Debug, Default)]
    pub struct TestNode {
        max_edges: usize,
    }

    impl<Ix: IndexType> EdgeBounds<Ix> for TestNode {
        fn max_incoming_edges(&self) -> Ix {
            Ix::new(self.max_edges)
        }

        fn max_outgoing_edges(&self) -> Ix {
            Ix::new(self.max_edges)
        }
    }

    impl SimpleEdgeBounds for TestNode {}

    let mut graph = BoundedGraph::<TestNode, i32>::new();
    let _ = graph.add_node(TestNode { max_edges: 0 }); // Cannot accept any edges
    let _ = graph.add_node(TestNode { max_edges: 5 });

    let edges = vec![(0u32, 1u32, 10), (1u32, 0u32, 20)];
    let result = graph.try_extend_with_edges(&edges);

    assert!(result.is_err());
    let (added, err) = result.unwrap_err();

    // No edges should have been added
    assert_eq!(added.len(), 0);
    assert_eq!(graph.edge_count(), 0);

    // Verify the error
    assert!(matches!(
        err,
        BoundedGraphError::EdgeRejected {
            source_rejected: true,
            target_rejected: false,
            ..
        }
    ));
}

#[test]
fn test_try_extend_with_edges_creates_nodes() {
    // Test that default nodes are created as needed
    #[derive(Debug)]
    pub struct TestNode {
        max_edges: usize,
    }

    impl Default for TestNode {
        fn default() -> Self {
            Self { max_edges: 10 } // Default nodes have capacity
        }
    }

    impl<Ix: IndexType> EdgeBounds<Ix> for TestNode {
        fn max_incoming_edges(&self) -> Ix {
            Ix::new(self.max_edges)
        }

        fn max_outgoing_edges(&self) -> Ix {
            Ix::new(self.max_edges)
        }
    }

    impl SimpleEdgeBounds for TestNode {}

    let mut graph = BoundedGraph::<TestNode, i32>::new();
    assert_eq!(graph.node_count(), 0);

    // Try to add edges with node indices that don't exist yet
    let edges = vec![(0u32, 1u32, 10), (1u32, 2u32, 20)];
    let result = graph.try_extend_with_edges(&edges);

    // Should succeed and create default nodes
    assert!(result.is_ok());
    assert_eq!(graph.node_count(), 3); // Created nodes 0, 1, 2
    assert_eq!(graph.edge_count(), 2);
}

#[test]
fn test_try_extend_with_edges_empty() {
    // Test with empty iterator
    #[derive(Debug, Default)]
    pub struct TestNode {
        max_edges: usize,
    }

    impl<Ix: IndexType> EdgeBounds<Ix> for TestNode {
        fn max_incoming_edges(&self) -> Ix {
            Ix::new(self.max_edges)
        }

        fn max_outgoing_edges(&self) -> Ix {
            Ix::new(self.max_edges)
        }
    }

    impl SimpleEdgeBounds for TestNode {}

    let mut graph = BoundedGraph::<TestNode, i32>::new();
    let edges: Vec<(u32, u32, i32)> = vec![];
    let result = graph.try_extend_with_edges(&edges);

    assert!(result.is_ok());
    let added = result.unwrap();
    assert_eq!(added.len(), 0);
    assert_eq!(graph.edge_count(), 0);
}

#[test]
fn test_add_edge_error_variants() {
    // Test that add_edge returns the correct error variant for each scenario
    #[derive(Debug, Default)]
    pub struct TestNode {
        max_in: usize,
        max_out: usize,
    }

    impl<Ix: IndexType> EdgeBounds<Ix> for TestNode {
        fn max_incoming_edges(&self) -> Ix {
            Ix::new(self.max_in)
        }

        fn max_outgoing_edges(&self) -> Ix {
            Ix::new(self.max_out)
        }
    }

    impl SimpleEdgeBounds for TestNode {}

    let mut graph = BoundedGraph::<TestNode, ()>::new();

    // Create nodes with different capacities
    let n1 = graph.add_node(TestNode {
        max_in: 2,
        max_out: 1,
    });
    let n2 = graph.add_node(TestNode {
        max_in: 1,
        max_out: 2,
    });
    let n3 = graph.add_node(TestNode {
        max_in: 0,
        max_out: 0,
    });
    let n4 = graph.add_node(TestNode {
        max_in: 2,
        max_out: 2,
    });

    // Test EdgeRejected with source_rejected: n1 can only have 1 outgoing edge
    assert!(graph.add_edge(n1, n2, ()).is_ok());
    let result = graph.add_edge(n1, n4, ());
    assert!(result.is_err());
    assert!(matches!(
        result.unwrap_err(),
        BoundedGraphError::EdgeRejected {
            source_rejected: true,
            target_rejected: false,
            ..
        }
    ));

    // Test EdgeRejected with target_rejected: n2 can only have 1 incoming edge
    let result = graph.add_edge(n4, n2, ());
    assert!(result.is_err());
    assert!(matches!(
        result.unwrap_err(),
        BoundedGraphError::EdgeRejected {
            source_rejected: false,
            target_rejected: true,
            ..
        }
    ));

    // Test EdgeRejected with both rejected: n3 has 0 capacity for both in and out
    let result = graph.add_edge(n3, n3, ());
    assert!(result.is_err());
    assert!(matches!(
        result.unwrap_err(),
        BoundedGraphError::EdgeRejected {
            source_rejected: true,
            target_rejected: true,
            ..
        }
    ));

    // Test NodeNotFound: invalid node index
    let invalid = NodeIndex::new(999);
    let result = graph.add_edge(n1, invalid, ());
    assert!(result.is_err());
    assert!(matches!(
        result.unwrap_err(),
        BoundedGraphError::NodeNotFound {
            source: Some(_),
            target: None
        }
    ));

    let result = graph.add_edge(invalid, n1, ());
    assert!(result.is_err());
    assert!(matches!(
        result.unwrap_err(),
        BoundedGraphError::NodeNotFound {
            source: None,
            target: Some(_)
        }
    ));
}

#[test]
fn test_from_edges() {
    // Test creating graph from edges iterator
    let edges = vec![(0, 1), (1, 2), (2, 0), (0, 2)];
    let graph = BoundedGraph::<SymmetricFixedEdgeCount<5>, ()>::from_edges(&edges);

    assert_eq!(graph.node_count(), 3);
    assert_eq!(graph.edge_count(), 4);
    assert!(graph.contains_edge(NodeIndex::new(0), NodeIndex::new(1)));
    assert!(graph.contains_edge(NodeIndex::new(1), NodeIndex::new(2)));
    assert!(graph.contains_edge(NodeIndex::new(2), NodeIndex::new(0)));
    assert!(graph.contains_edge(NodeIndex::new(0), NodeIndex::new(2)));
}

#[test]
fn test_from_edges_with_bounds_violation() {
    // Test that from_edges skips edges that violate bounds
    let edges = vec![(0, 1), (0, 2), (0, 3)]; // 3 edges from node 0
    let graph = BoundedGraph::<SymmetricFixedEdgeCount<2>, ()>::from_edges(&edges);

    assert_eq!(graph.node_count(), 4);
    assert_eq!(graph.edge_count(), 2); // Only 2 edges added, third was skipped
}

#[test]
fn test_with_capacity() {
    // Test pre-allocation constructor for Graph (default)
    let mut graph = BoundedGraph::<SymmetricFixedEdgeCount<3>, i32>::with_capacity(10, 20);

    // Should be empty but with capacity
    assert_eq!(graph.node_count(), 0);
    assert_eq!(graph.edge_count(), 0);

    // Should be able to add nodes and edges
    let n1 = graph.add_node(SymmetricFixedEdgeCount::empty());
    let n2 = graph.add_node(SymmetricFixedEdgeCount::empty());
    assert!(graph.add_edge(n1, n2, 42).is_ok());

    assert_eq!(graph.node_count(), 2);
    assert_eq!(graph.edge_count(), 1);

    // Test with_capacity for both Graph and StableGraph type aliases
    use crate::{BoundedDiGraph, BoundedStableDiGraph};

    let graph_based = BoundedDiGraph::<SymmetricFixedEdgeCount<2>, ()>::with_capacity(5, 10);
    assert_eq!(graph_based.node_count(), 0);

    let stable_based = BoundedStableDiGraph::<SymmetricFixedEdgeCount<2>, ()>::with_capacity(5, 10);
    assert_eq!(stable_based.node_count(), 0);
}

#[test]
fn test_map() {
    // Test mapping node and edge weights
    let mut graph = BoundedGraph::<SymmetricFixedEdgeCount<2, i32>, &str>::new();
    let n1 = graph.add_node(SymmetricFixedEdgeCount::new(10));
    let n2 = graph.add_node(SymmetricFixedEdgeCount::new(20));
    let e1 = graph.add_edge(n1, n2, "edge").unwrap();

    // Map to different types
    let mapped = graph.map(
        |_idx, node| SymmetricFixedEdgeCount::<2, i32>::new(node.data * 2),
        |_idx, edge| edge.len(),
    );

    assert_eq!(mapped.node_count(), 2);
    assert_eq!(mapped.edge_count(), 1);
    assert_eq!(mapped[n1].data, 20);
    assert_eq!(mapped[n2].data, 40);
    assert_eq!(mapped[e1], 4); // "edge" has length 4
}

#[test]
fn test_filter_map() {
    // Test conditional mapping
    let mut graph = BoundedGraph::<SymmetricFixedEdgeCount<3, i32>, i32>::new();
    let n1 = graph.add_node(SymmetricFixedEdgeCount::new(10));
    let n2 = graph.add_node(SymmetricFixedEdgeCount::new(20));
    let n3 = graph.add_node(SymmetricFixedEdgeCount::new(5));
    graph.add_edge(n1, n2, 100).unwrap();
    graph.add_edge(n2, n3, 50).unwrap();
    graph.add_edge(n1, n3, 25).unwrap();

    // Filter: keep nodes with value >= 10, edges with weight >= 50
    let filtered = graph.filter_map(
        |_idx, node| {
            if node.data >= 10 {
                Some(SymmetricFixedEdgeCount::<3, i32>::new(node.data))
            } else {
                None
            }
        },
        |_idx, edge| {
            if *edge >= 50 {
                Some(*edge)
            } else {
                None
            }
        },
    );

    assert_eq!(filtered.node_count(), 2); // Only n1 and n2
                                          // Only 1 edge: n1->n2 with weight 100
                                          // n2->n3 is filtered because n3 is removed
                                          // n1->n3 is filtered both because n3 is removed AND weight < 50
    assert_eq!(filtered.edge_count(), 1);
}

#[test]
fn test_into_edge_type() {
    use petgraph::Undirected;

    // Create a directed graph
    let mut digraph = BoundedGraph::<SymmetricFixedEdgeCount<3>, i32>::new();
    let n1 = digraph.add_node(SymmetricFixedEdgeCount::empty());
    let n2 = digraph.add_node(SymmetricFixedEdgeCount::empty());
    digraph.add_edge(n1, n2, 42).unwrap();

    assert!(digraph.is_directed());
    assert_eq!(digraph.edge_count(), 1);

    // Convert to undirected by accessing the underlying graph
    let inner_graph = digraph.into_inner().into_edge_type::<Undirected>();
    let ungraph = BoundedGraph {
        graph: inner_graph,
        _phantom: std::marker::PhantomData,
    };
    assert!(!ungraph.is_directed());
    assert_eq!(ungraph.edge_count(), 1);
    assert_eq!(ungraph.node_count(), 2);
}

#[test]
fn test_self_loops() {
    // Test that self-loops (node connected to itself) work correctly
    let mut graph = BoundedGraph::<SymmetricFixedEdgeCount<2>, ()>::new();
    let n1 = graph.add_node(SymmetricFixedEdgeCount::empty());

    // Self-loop should count as both incoming and outgoing
    assert!(graph.can_add_edge(n1, n1));
    assert!(graph.add_edge(n1, n1, ()).is_ok());
    assert_eq!(graph.edge_count(), 1);

    // After one self-loop, should still have capacity for another
    assert!(graph.can_add_edge(n1, n1));
    assert!(graph.add_edge(n1, n1, ()).is_ok());
    assert_eq!(graph.edge_count(), 2);

    // Now node should be full
    assert!(!graph.can_add_edge(n1, n1));
    let result = graph.add_edge(n1, n1, ());
    assert!(result.is_err());
}

#[test]
fn test_undirected_graph_constraints() {
    // Test that undirected graphs properly check edge constraints
    let mut graph = BoundedUnGraph::<SymmetricFixedEdgeCount<2>, ()>::new();
    let n1 = graph.add_node(SymmetricFixedEdgeCount::empty());
    let n2 = graph.add_node(SymmetricFixedEdgeCount::empty());
    let n3 = graph.add_node(SymmetricFixedEdgeCount::empty());

    // In undirected graph, edge n1-n2 counts for both nodes
    assert!(graph.add_edge(n1, n2, ()).is_ok());
    assert!(graph.add_edge(n1, n3, ()).is_ok());

    // n1 now has 2 edges, should be full
    let n4 = graph.add_node(SymmetricFixedEdgeCount::empty());
    let result = graph.add_edge(n1, n4, ());
    assert!(result.is_err());

    // But n2 and n3 each only have 1 edge, so they can connect
    assert!(graph.add_edge(n2, n3, ()).is_ok());
}

#[test]
fn test_default_constructor() {
    // Test that Default trait works correctly
    let graph = BoundedDiGraph::<SymmetricFixedEdgeCount<5>, i32>::default();
    assert_eq!(graph.node_count(), 0);
    assert_eq!(graph.edge_count(), 0);
}

#[test]
fn test_node_weight_mutation() {
    // Test that we can mutate node weights through the graph
    let mut graph = BoundedGraph::<SymmetricFixedEdgeCount<2, i32>, ()>::new();
    let n1 = graph.add_node(SymmetricFixedEdgeCount::new(100));

    assert_eq!(graph[n1].data, 100);

    // Mutate through node_weight_mut (direct call on inner graph)
    if let Some(weight) = graph.graph.node_weight_mut(n1) {
        weight.data = 200;
    }

    assert_eq!(graph[n1].data, 200);

    // Also test via IndexMut
    graph[n1].data += 50;
    assert_eq!(graph[n1].data, 250);
}

#[test]
fn test_edge_weight_mutation() {
    // Test that we can mutate edge weights
    let mut graph = BoundedGraph::<SymmetricFixedEdgeCount<2>, i32>::new();
    let n1 = graph.add_node(SymmetricFixedEdgeCount::empty());
    let n2 = graph.add_node(SymmetricFixedEdgeCount::empty());
    let e1 = graph.add_edge(n1, n2, 42).unwrap();

    assert_eq!(graph[e1], 42);

    // Mutate through edge_weight_mut (direct call on inner graph)
    if let Some(weight) = graph.graph.edge_weight_mut(e1) {
        *weight = 100;
    }

    assert_eq!(graph[e1], 100);

    // Also test via IndexMut
    graph[e1] += 50;
    assert_eq!(graph[e1], 150);
}

#[test]
fn test_stable_graph_compatibility() {
    use crate::{BoundedStableDiGraph, BoundedStableUnGraph};

    // Test BoundedStableDiGraph (directed with stable indices)
    let mut stable_digraph = BoundedStableDiGraph::<SymmetricFixedEdgeCount<3>, i32>::new();
    let n1 = stable_digraph.add_node(SymmetricFixedEdgeCount::empty());
    let n2 = stable_digraph.add_node(SymmetricFixedEdgeCount::empty());
    let n3 = stable_digraph.add_node(SymmetricFixedEdgeCount::empty());

    // Add edges
    stable_digraph.add_edge(n1, n2, 10).unwrap();
    stable_digraph.add_edge(n2, n3, 20).unwrap();
    stable_digraph.add_edge(n1, n3, 30).unwrap();

    assert_eq!(stable_digraph.node_count(), 3);
    assert_eq!(stable_digraph.edge_count(), 3);
    assert!(stable_digraph.is_directed());

    // Test edge capacity enforcement
    stable_digraph.add_edge(n1, n2, 40).unwrap(); // 2nd edge n1->n2
    let result = stable_digraph.add_edge(n1, n2, 50);
    assert!(
        result.is_err(),
        "Should fail - n1 already has 3 outgoing edges"
    );

    // Test BoundedStableUnGraph (undirected with stable indices)
    let mut stable_ungraph = BoundedStableUnGraph::<SymmetricFixedEdgeCount<2>, &str>::new();
    let u1 = stable_ungraph.add_node(SymmetricFixedEdgeCount::empty());
    let u2 = stable_ungraph.add_node(SymmetricFixedEdgeCount::empty());
    let u3 = stable_ungraph.add_node(SymmetricFixedEdgeCount::empty());

    stable_ungraph.add_edge(u1, u2, "edge1").unwrap();
    stable_ungraph.add_edge(u2, u3, "edge2").unwrap();

    assert_eq!(stable_ungraph.node_count(), 3);
    assert_eq!(stable_ungraph.edge_count(), 2);
    assert!(!stable_ungraph.is_directed());

    // Verify capacity constraints work with undirected stable graph
    stable_ungraph.add_edge(u1, u3, "edge3").unwrap();
    let result = stable_ungraph.add_edge(u1, u2, "edge4");
    assert!(
        result.is_err(),
        "Should fail - u1 already has 2 edges in undirected graph"
    );
}

#[test]
fn test_stable_graph_node_removal() {
    use crate::BoundedStableDiGraph;

    // StableGraph maintains stable indices after node removal
    let mut graph = BoundedStableDiGraph::<SymmetricFixedEdgeCount<5>, i32>::new();

    let n0 = graph.add_node(SymmetricFixedEdgeCount::empty());
    let n1 = graph.add_node(SymmetricFixedEdgeCount::empty());
    let n2 = graph.add_node(SymmetricFixedEdgeCount::empty());
    let n3 = graph.add_node(SymmetricFixedEdgeCount::empty());

    graph.add_edge(n0, n1, 1).unwrap();
    graph.add_edge(n1, n2, 2).unwrap();
    graph.add_edge(n2, n3, 3).unwrap();

    // Remove middle node
    graph.graph.remove_node(n1);

    // Indices should remain stable - n0, n2, n3 should still be valid
    assert_eq!(graph.node_count(), 3);
    assert!(graph.graph.node_weight(n0).is_some());
    assert!(graph.graph.node_weight(n1).is_none()); // Removed
    assert!(graph.graph.node_weight(n2).is_some());
    assert!(graph.graph.node_weight(n3).is_some());

    // Can still add edges using stable indices
    let result = graph.add_edge(n0, n2, 4);
    assert!(result.is_ok());
}

#[test]
fn test_stable_graph_with_capacity() {
    use crate::BoundedStableDiGraph;

    // Test with_capacity for StableGraph
    let graph = BoundedStableDiGraph::<SymmetricFixedEdgeCount<3>, ()>::with_capacity(10, 20);

    assert_eq!(graph.node_count(), 0);
    assert_eq!(graph.edge_count(), 0);

    // Capacity is a hint, so we just verify the graph was created successfully
    // and can be used normally
    let mut graph = graph;
    let n1 = graph.add_node(SymmetricFixedEdgeCount::empty());
    let n2 = graph.add_node(SymmetricFixedEdgeCount::empty());

    assert!(graph.add_edge(n1, n2, ()).is_ok());
}

#[test]
fn test_edge_count_trait() {
    use petgraph::visit::EdgeCount;

    // Test EdgeCount trait for DiGraph
    let mut graph = BoundedDiGraph::<SymmetricFixedEdgeCount<5>, ()>::new();
    let n1 = graph.add_node(SymmetricFixedEdgeCount::empty());
    let n2 = graph.add_node(SymmetricFixedEdgeCount::empty());
    let n3 = graph.add_node(SymmetricFixedEdgeCount::empty());

    // Initially no edges
    assert_eq!(EdgeCount::edge_count(&graph), 0);

    // Add some edges
    graph.add_edge(n1, n2, ()).unwrap();
    assert_eq!(EdgeCount::edge_count(&graph), 1);

    graph.add_edge(n2, n3, ()).unwrap();
    assert_eq!(EdgeCount::edge_count(&graph), 2);

    graph.add_edge(n1, n3, ()).unwrap();
    assert_eq!(EdgeCount::edge_count(&graph), 3);

    // Test EdgeCount trait for UnGraph
    let mut ungraph = BoundedUnGraph::<SymmetricFixedEdgeCount<3>, ()>::new();
    let u1 = ungraph.add_node(SymmetricFixedEdgeCount::empty());
    let u2 = ungraph.add_node(SymmetricFixedEdgeCount::empty());
    let u3 = ungraph.add_node(SymmetricFixedEdgeCount::empty());

    assert_eq!(EdgeCount::edge_count(&ungraph), 0);

    ungraph.add_edge(u1, u2, ()).unwrap();
    ungraph.add_edge(u2, u3, ()).unwrap();
    assert_eq!(EdgeCount::edge_count(&ungraph), 2);
}

#[test]
fn test_node_count_trait() {
    use petgraph::visit::NodeCount;

    // Test NodeCount trait for DiGraph
    let mut graph = BoundedDiGraph::<SymmetricFixedEdgeCount<5>, ()>::new();

    // Initially no nodes
    assert_eq!(NodeCount::node_count(&graph), 0);

    // Add some nodes
    let n1 = graph.add_node(SymmetricFixedEdgeCount::empty());
    assert_eq!(NodeCount::node_count(&graph), 1);

    let n2 = graph.add_node(SymmetricFixedEdgeCount::empty());
    assert_eq!(NodeCount::node_count(&graph), 2);

    let n3 = graph.add_node(SymmetricFixedEdgeCount::empty());
    assert_eq!(NodeCount::node_count(&graph), 3);

    // Add edges (shouldn't affect node count)
    graph.add_edge(n1, n2, ()).unwrap();
    graph.add_edge(n2, n3, ()).unwrap();
    assert_eq!(NodeCount::node_count(&graph), 3);

    // Test NodeCount trait for UnGraph
    let mut ungraph = BoundedUnGraph::<SymmetricFixedEdgeCount<3>, ()>::new();
    assert_eq!(NodeCount::node_count(&ungraph), 0);

    let u1 = ungraph.add_node(SymmetricFixedEdgeCount::empty());
    let u2 = ungraph.add_node(SymmetricFixedEdgeCount::empty());
    let u3 = ungraph.add_node(SymmetricFixedEdgeCount::empty());
    let _u4 = ungraph.add_node(SymmetricFixedEdgeCount::empty());

    assert_eq!(NodeCount::node_count(&ungraph), 4);

    ungraph.add_edge(u1, u2, ()).unwrap();
    ungraph.add_edge(u2, u3, ()).unwrap();
    assert_eq!(NodeCount::node_count(&ungraph), 4);
}

#[test]
fn test_try_from_graph_success() {
    use crate::FixedEdgeCount;
    use std::convert::TryFrom;

    // Create a regular petgraph with nodes that have capacity
    let mut pg = Graph::new();
    let n1 = pg.add_node(FixedEdgeCount::<3, 3>::empty());
    let n2 = pg.add_node(FixedEdgeCount::<3, 3>::empty());
    let n3 = pg.add_node(FixedEdgeCount::<3, 3>::empty());

    // Add edges within capacity
    pg.add_edge(n1, n2, ());
    pg.add_edge(n2, n3, ());

    // Convert to BoundedGraph - should succeed
    let bounded = BoundedGraph::try_from(pg).unwrap();

    assert_eq!(bounded.node_count(), 3);
    assert_eq!(bounded.edge_count(), 2);
    assert!(bounded.contains_edge(n1, n2));
    assert!(bounded.contains_edge(n2, n3));
}

#[test]
fn test_try_from_graph_violates_outgoing_capacity() {
    use crate::FixedEdgeCount;
    use std::convert::TryFrom;

    // Create a graph where a node exceeds its outgoing capacity
    let mut pg = Graph::new();
    let n1 = pg.add_node(FixedEdgeCount::<2, 2>::empty()); // Max 2 outgoing
    let n2 = pg.add_node(FixedEdgeCount::<2, 2>::empty());
    let n3 = pg.add_node(FixedEdgeCount::<2, 2>::empty());
    let n4 = pg.add_node(FixedEdgeCount::<2, 2>::empty());

    // Add 3 outgoing edges from n1 (exceeds capacity)
    pg.add_edge(n1, n2, ());
    pg.add_edge(n1, n3, ());
    pg.add_edge(n1, n4, ());

    // Conversion should fail
    let result = BoundedGraph::try_from(pg);
    assert!(result.is_err());
    assert!(matches!(
        result.unwrap_err(),
        BoundedGraphError::EdgeRejected {
            source_rejected: true,
            ..
        }
    ));
}

#[test]
fn test_try_from_graph_violates_incoming_capacity() {
    use crate::FixedEdgeCount;
    use std::convert::TryFrom;

    // Create a graph where a node exceeds its incoming capacity
    let mut pg = Graph::new();
    let n1 = pg.add_node(FixedEdgeCount::<2, 2>::empty());
    let n2 = pg.add_node(FixedEdgeCount::<2, 2>::empty());
    let n3 = pg.add_node(FixedEdgeCount::<2, 2>::empty());
    let n4 = pg.add_node(FixedEdgeCount::<2, 2>::empty()); // Max 2 incoming

    // Add 3 incoming edges to n4 (exceeds capacity)
    pg.add_edge(n1, n4, ());
    pg.add_edge(n2, n4, ());
    pg.add_edge(n3, n4, ());

    // Conversion should fail
    let result = BoundedGraph::try_from(pg);
    assert!(result.is_err());
    assert!(matches!(
        result.unwrap_err(),
        BoundedGraphError::EdgeRejected {
            target_rejected: true,
            ..
        }
    ));
}

#[test]
fn test_try_from_graph_empty() {
    use crate::FixedEdgeCount;
    use std::convert::TryFrom;

    // Empty graph should always succeed
    let pg = Graph::<FixedEdgeCount<2, 2>, ()>::new();
    let bounded = BoundedGraph::try_from(pg).unwrap();

    assert_eq!(bounded.node_count(), 0);
    assert_eq!(bounded.edge_count(), 0);
}

#[test]
fn test_try_from_graph_asymmetric_limits() {
    use crate::FixedEdgeCount;
    use std::convert::TryFrom;

    // Test with asymmetric limits - all nodes must have same type
    let mut pg = Graph::new();
    let n1 = pg.add_node(FixedEdgeCount::<3, 5>::empty()); // 3 in, 5 out
    let n2 = pg.add_node(FixedEdgeCount::<3, 5>::empty());
    let n3 = pg.add_node(FixedEdgeCount::<3, 5>::empty());

    // n1 can send to multiple nodes (has capacity for 5 outgoing)
    pg.add_edge(n1, n2, ());
    pg.add_edge(n1, n3, ());

    // This should succeed
    let bounded = BoundedGraph::try_from(pg).unwrap();
    assert_eq!(bounded.edge_count(), 2);
}

#[test]
fn test_try_from_stable_graph_success() {
    use crate::FixedEdgeCount;
    use petgraph::stable_graph::StableGraph;
    use std::convert::TryFrom;

    // Create a StableGraph
    let mut pg = StableGraph::new();
    let n1 = pg.add_node(FixedEdgeCount::<3, 3>::empty());
    let n2 = pg.add_node(FixedEdgeCount::<3, 3>::empty());

    pg.add_edge(n1, n2, ());

    // Convert to BoundedGraph
    let bounded = BoundedGraph::try_from(pg).unwrap();

    assert_eq!(bounded.node_count(), 2);
    assert_eq!(bounded.edge_count(), 1);
}

#[test]
fn test_try_from_stable_graph_violates_capacity() {
    use crate::FixedEdgeCount;
    use petgraph::stable_graph::StableGraph;
    use std::convert::TryFrom;

    // Create a StableGraph that violates capacity - all nodes same type
    let mut pg = StableGraph::new();
    let n1 = pg.add_node(FixedEdgeCount::<1, 1>::empty()); // Max 1 outgoing
    let n2 = pg.add_node(FixedEdgeCount::<1, 1>::empty());
    let n3 = pg.add_node(FixedEdgeCount::<1, 1>::empty());

    pg.add_edge(n1, n2, ());
    pg.add_edge(n1, n3, ()); // Exceeds n1's capacity

    // Conversion should fail
    let result = BoundedGraph::try_from(pg);
    assert!(result.is_err());
}

#[test]
fn test_try_from_with_self_loops() {
    use crate::FixedEdgeCount;
    use std::convert::TryFrom;

    // Test with self-loops
    let mut pg = Graph::new();
    let n1 = pg.add_node(FixedEdgeCount::<2, 2>::empty());

    // Self-loop counts as both incoming and outgoing
    pg.add_edge(n1, n1, ());

    // Should succeed if capacity allows
    let bounded = BoundedGraph::try_from(pg).unwrap();
    assert_eq!(bounded.edge_count(), 1);
}

#[test]
fn test_try_from_preserves_node_data() {
    use crate::FixedEdgeCount;
    use std::convert::TryFrom;

    // Verify that node data is preserved during conversion
    let mut pg = Graph::new();
    let n1 = pg.add_node(FixedEdgeCount::<2, 2, String>::new("Node1".to_string()));
    let n2 = pg.add_node(FixedEdgeCount::<2, 2, String>::new("Node2".to_string()));

    pg.add_edge(n1, n2, "Edge");

    let bounded = BoundedGraph::try_from(pg).unwrap();

    assert_eq!(bounded[n1].data, "Node1");
    assert_eq!(bounded[n2].data, "Node2");
    assert_eq!(bounded[bounded.find_edge(n1, n2).unwrap()], "Edge");
}