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
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
extern crate fixedbitset;
extern crate rand;

mod cycle_detector;

use cycle_detector::CycleDetector;
use fixedbitset::FixedBitSet;
use rand::Rng;
use std::fmt::Debug;

pub trait NodeType: Clone + Debug + Send + Sized + PartialEq + Eq {
    /// Whether or not the node allows incoming connections
    fn accept_incoming_links(&self) -> bool;

    /// Whether or not the node allows outgoing connections
    fn accept_outgoing_links(&self) -> bool;
}

/// Every node or link contains an external id. This id is
/// never modified by this library.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct ExternalId(pub usize);

/// Newtype wrapping a node index. The node index is
/// used as an internal index into the node array.
/// It can become unstable in case of removal of nodes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct NodeIndex(usize);

/// Newtype wrapping a link index.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct LinkIndex(usize);

impl NodeIndex {
    #[inline(always)]
    pub fn index(&self) -> usize {
        self.0
    }

    pub fn new(index: usize) -> Self {
        NodeIndex(index)
    }
}

impl LinkIndex {
    #[inline(always)]
    pub fn index(&self) -> usize {
        self.0
    }
}

// Wraps a Link for use in a double linked list
#[derive(Clone, Debug)]
struct LinkItem<L, EXTID>
where
    L: Copy + Debug + Send + Sized,
    EXTID: Copy + Debug + Send + Sized + Ord,
{
    prev: Option<LinkIndex>,
    next: Option<LinkIndex>,
    link: Link<L, EXTID>,
}

pub struct LinkIter<'a, L, EXTID>
where
    L: Copy + Debug + Send + Sized + 'a,
    EXTID: Copy + Debug + Send + Sized + Ord + 'a,
{
    next_link_idx: Option<LinkIndex>,
    link_array: &'a [LinkItem<L, EXTID>],
}

impl<'a, L, EXTID> LinkIter<'a, L, EXTID>
where
    L: Copy + Debug + Send + Sized + 'a,
    EXTID: Copy + Debug + Send + Sized + Ord + 'a,
{
    fn new(link_idx_opt: Option<LinkIndex>, link_array: &'a [LinkItem<L, EXTID>]) -> Self {
        LinkIter {
            next_link_idx: link_idx_opt,
            link_array: link_array,
        }
    }
}

impl<'a, L, EXTID> Iterator for LinkIter<'a, L, EXTID>
where
    L: Copy + Debug + Send + Sized + 'a,
    EXTID: Copy + Debug + Send + Sized + Ord + 'a,
{
    type Item = (LinkIndex, &'a Link<L, EXTID>);

    fn next(&mut self) -> Option<Self::Item> {
        match self.next_link_idx {
            Some(idx) => {
                let item = &self.link_array[idx.index()];
                self.next_link_idx = item.next;
                return Some((idx, &item.link));
            }
            None => {
                return None;
            }
        }
    }
}

pub struct LinkRefIter<'a, N, L, EXTID>
where
    N: NodeType + 'a,
    L: Copy + Debug + Send + Sized + 'a,
    EXTID: Copy + Debug + Send + Sized + Ord + 'a,
{
    next_link_idx: Option<LinkIndex>,
    network: &'a Network<N, L, EXTID>,
}

/// A LinkRefItem includes a pointer to the network,
/// as such, it is read only.
pub struct LinkRefItem<'a, N, L, EXTID>
where
    N: NodeType + 'a,
    L: Copy + Debug + Send + Sized + 'a,
    EXTID: Copy + Debug + Send + Sized + Ord + 'a,
{
    link: &'a Link<L, EXTID>,
    network: &'a Network<N, L, EXTID>,
}

impl<'a, N, L, EXTID> LinkRefItem<'a, N, L, EXTID>
where
    N: NodeType + 'a,
    L: Copy + Debug + Send + Sized + 'a,
    EXTID: Copy + Debug + Send + Sized + Ord + 'a,
{
    pub fn link(&self) -> &Link<L, EXTID> {
        self.link
    }

    pub fn network(&self) -> &Network<N, L, EXTID> {
        self.network
    }

    pub fn external_link_id(&self) -> EXTID {
        self.link.external_link_id()
    }

    pub fn source_node(&self) -> &Node<N, EXTID> {
        self.network.node(self.link.source_node_idx)
    }

    pub fn target_node(&self) -> &Node<N, EXTID> {
        self.network.node(self.link.target_node_idx)
    }

    pub fn external_source_node_id(&self) -> EXTID {
        self.source_node().external_node_id()
    }

    pub fn external_target_node_id(&self) -> EXTID {
        self.target_node().external_node_id()
    }
}

impl<'a, N, L, EXTID> LinkRefIter<'a, N, L, EXTID>
where
    N: NodeType + 'a,
    L: Copy + Debug + Send + Sized + 'a,
    EXTID: Copy + Debug + Send + Sized + Ord + 'a,
{
    fn new(link_idx_opt: Option<LinkIndex>, network: &'a Network<N, L, EXTID>) -> Self {
        LinkRefIter {
            next_link_idx: link_idx_opt,
            network: network,
        }
    }
}

impl<'a, N, L, EXTID> Iterator for LinkRefIter<'a, N, L, EXTID>
where
    N: NodeType + 'a,
    L: Copy + Debug + Send + Sized + 'a,
    EXTID: Copy + Debug + Send + Sized + Ord + 'a,
{
    type Item = (LinkRefItem<'a, N, L, EXTID>);

    fn next(&mut self) -> Option<Self::Item> {
        match self.next_link_idx {
            Some(idx) => {
                let item = &self.network.links[idx.index()];
                self.next_link_idx = item.next;
                return Some(LinkRefItem {
                    link: &item.link,
                    network: &self.network,
                });
            }
            None => {
                return None;
            }
        }
    }
}

#[derive(Clone, Debug)]
pub struct Link<L, EXTID>
where
    L: Copy + Debug + Send + Sized,
    EXTID: Copy + Debug + Send + Sized + Ord,
{
    source_node_idx: NodeIndex,
    target_node_idx: NodeIndex,
    weight: L,
    external_link_id: EXTID,

    // the activeness of a link has no influence on the
    // cycle detection.
    active: bool,
}

impl<L, EXTID> Link<L, EXTID>
where
    L: Copy + Debug + Send + Sized,
    EXTID: Copy + Debug + Send + Sized + Ord,
{
    #[inline(always)]
    pub fn external_link_id(&self) -> EXTID {
        self.external_link_id
    }

    #[inline(always)]
    pub fn source_node_index(&self) -> NodeIndex {
        self.source_node_idx
    }

    #[inline(always)]
    pub fn target_node_index(&self) -> NodeIndex {
        self.target_node_idx
    }

    #[inline(always)]
    pub fn is_active(&self) -> bool {
        self.active
    }

    #[inline(always)]
    pub fn weight(&self) -> L {
        self.weight
    }

    #[inline(always)]
    pub fn set_weight(&mut self, new_weight: L) {
        self.weight = new_weight;
    }
}

#[derive(Clone, Debug)]
struct List {
    head: Option<LinkIndex>,
    tail: Option<LinkIndex>,
}

impl List {
    fn empty() -> Self {
        List {
            head: None,
            tail: None,
        }
    }

    fn iter<'a, L, EXTID>(&self, link_array: &'a [LinkItem<L, EXTID>]) -> LinkIter<'a, L, EXTID>
    where
        L: Copy + Debug + Send + Sized + 'a,
        EXTID: Copy + Debug + Send + Sized + Ord + 'a,
    {
        LinkIter::new(self.head, link_array)
    }
}

#[derive(Clone, Debug)]
pub struct Node<N: NodeType, EXTID: Copy + Debug + Send + Sized + Ord = ExternalId> {
    node_type: N,
    external_node_id: EXTID,
    links: List,
    // in and out degree counts disabled links!
    in_degree: u32,
    out_degree: u32,
}

impl<N: NodeType, EXTID: Copy + Debug + Send + Sized + Ord> Node<N, EXTID> {
    pub fn node_type(&self) -> &N {
        &self.node_type
    }

    pub fn set_node_type(&mut self, node_type: N) {
        self.node_type = node_type;
    }

    pub fn external_node_id(&self) -> EXTID {
        self.external_node_id
    }

    pub fn degree(&self) -> usize {
        self.in_degree as usize + self.out_degree as usize
    }

    pub fn in_degree(&self) -> u32 {
        self.in_degree
    }

    pub fn out_degree(&self) -> u32 {
        self.out_degree
    }

    pub fn in_out_degree(&self) -> (u32, u32) {
        (self.in_degree, self.out_degree)
    }
}

/// A directed, acylic network.
#[derive(Clone, Debug)]
pub struct Network<
    N: NodeType,
    L: Copy + Debug + Send + Sized,
    EXTID: Copy + Debug + Send + Sized + Ord = ExternalId,
> {
    nodes: Vec<Node<N, EXTID>>,
    links: Vec<LinkItem<L, EXTID>>, // XXX: Rename to link_items
    link_count: usize,
    active_link_count: usize,
}

impl<N: NodeType, L: Copy + Debug + Send + Sized, EXTID: Copy + Debug + Send + Sized + Ord>
    Network<N, L, EXTID> {
    pub fn new() -> Network<N, L, EXTID> {
        Network {
            nodes: Vec::new(),
            links: Vec::new(),
            link_count: 0,
            active_link_count: 0,
        }
    }

    #[inline]
    pub fn node_count(&self) -> usize {
        self.nodes.len()
    }

    #[inline]
    pub fn link_count(&self) -> usize {
        self.link_count
    }

    #[inline(always)]
    pub fn node(&self, node_idx: NodeIndex) -> &Node<N, EXTID> {
        &self.nodes[node_idx.index()]
    }

    #[inline(always)]
    pub fn node_mut(&mut self, node_idx: NodeIndex) -> &mut Node<N, EXTID> {
        &mut self.nodes[node_idx.index()]
    }

    #[inline(always)]
    fn link_item(&self, link_idx: LinkIndex) -> &LinkItem<L, EXTID> {
        &self.links[link_idx.index()]
    }

    #[inline(always)]
    pub fn link(&self, link_idx: LinkIndex) -> &Link<L, EXTID> {
        &self.link_item(link_idx).link
    }

    #[inline(always)]
    pub fn link_mut(&mut self, link_idx: LinkIndex) -> &mut Link<L, EXTID> {
        &mut (self.links[link_idx.index()].link)
    }

    #[inline(always)]
    pub fn nodes(&self) -> &[Node<N, EXTID>] {
        &self.nodes
    }

    #[inline]
    pub fn each_node_with_index<F>(&self, mut f: F)
    where
        F: FnMut(&Node<N, EXTID>, NodeIndex),
    {
        for (i, node) in self.nodes.iter().enumerate() {
            f(node, NodeIndex(i));
        }
    }

    #[inline]
    pub fn link_iter_for_node<'a>(&'a self, node_idx: NodeIndex) -> LinkIter<'a, L, EXTID> {
        self.node(node_idx).links.iter(&self.links)
    }

    #[inline]
    pub fn link_ref_iter_for_node<'a>(
        &'a self,
        node_idx: NodeIndex,
    ) -> LinkRefIter<'a, N, L, EXTID> {
        LinkRefIter::new(self.node(node_idx).links.head, self)
    }

    #[inline]
    pub fn each_active_forward_link_of_node<F>(&self, node_idx: NodeIndex, mut f: F)
    where
        F: FnMut(NodeIndex, L),
    {
        for (_, link) in self.link_iter_for_node(node_idx) {
            if link.active {
                f(link.target_node_idx, link.weight);
            }
        }
    }

    #[inline]
    pub fn each_link_ref<F>(&self, mut f: F)
    where
        F: FnMut(LinkRefItem<N, L, EXTID>),
    {
        for link_item in &self.links[..] {
            f(LinkRefItem {
                link: &&link_item.link,
                network: self,
            });
        }
    }

    #[inline]
    pub fn each_link_mut<F>(&mut self, mut f: F)
    where
        F: FnMut(&mut Link<L, EXTID>),
    {
        for link_item in &mut self.links[..] {
            f(&mut link_item.link);
        }
    }

    fn inactive_link_count(&self) -> usize {
        assert!(self.link_count >= self.active_link_count);
        self.link_count - self.active_link_count
    }

    /// # Complexity
    ///
    /// O(number of links)

    pub fn random_inactive_link_index<R: Rng>(&self, rng: &mut R) -> Option<LinkIndex> {
        let n = self.inactive_link_count();
        assert!(n <= self.link_count);
        if n > 0 {
            let mut nth_link: usize = rng.gen_range(0, n);

            for node in self.nodes.iter() {
                for (link_idx, link) in node.links.iter(&self.links) {
                    if !link.is_active() {
                        if nth_link > 0 {
                            nth_link -= 1;
                        } else {
                            return Some(link_idx);
                        }
                    }
                }
            }
        }

        return None;
    }

    /// # Complexity
    ///
    /// O(number of links)

    pub fn random_active_link_index<R: Rng>(&self, rng: &mut R) -> Option<LinkIndex> {
        let n = self.active_link_count;
        assert!(n <= self.link_count);
        if n > 0 {
            let mut nth_link: usize = rng.gen_range(0, n);

            for node in self.nodes.iter() {
                for (link_idx, link) in node.links.iter(&self.links) {
                    if link.is_active() {
                        if nth_link > 0 {
                            nth_link -= 1;
                        } else {
                            return Some(link_idx);
                        }
                    }
                }
            }
        }

        return None;
    }

    /// # Complexity
    ///
    /// O(1)

    pub fn random_link_index<R: Rng>(&self, rng: &mut R) -> Option<LinkIndex> {
        let n = self.link_count;
        if n > 0 {
            let link_idx: usize = rng.gen_range(0, n);
            return Some(LinkIndex(link_idx));
        }
        return None;
    }

    /// Removes all outgoing links of node `node_idx`.
    ///
    /// XXX: This can be optimized.
    ///
    /// # Complexity
    ///
    /// O(k), where `k` is the number of edges of `node_idx`.

    pub fn remove_all_outgoing_links_of_node(&mut self, node_idx: NodeIndex) {
        let n = self.node(node_idx).out_degree as usize;

        for _ in 0..n {
            let link_index = self.node(node_idx).links.head.unwrap();
            self.remove_link_at(link_index);
        }
        assert!(self.node(node_idx).links.head.is_none());
        assert!(self.node(node_idx).links.tail.is_none());
        assert!(self.node(node_idx).out_degree == 0);
    }

    /// Removes all incoming links to node `node_idx`.
    ///
    /// XXX: This can be optimized.

    pub fn remove_all_incoming_links_of_node(&mut self, node_idx: NodeIndex) {
        let n = self.node(node_idx).in_degree as usize;

        if n == 0 {
            // If a node does not have any incoming links, we are done!
            return;
        }

        // for each node other than `node_idx` try to delete a link to node_idx.
        for src in 0..self.node_count() {
            let src_idx = NodeIndex(src);
            if src_idx != node_idx {
                if let Some(link_index) = self.find_link_index_exact(src_idx, node_idx) {
                    self.remove_link_at(link_index);
                }
            }
        }

        assert!(self.node(node_idx).in_degree == 0);
    }

    /// Removes all links to and from node `node_idx`.

    pub fn remove_all_inout_links_of_node(&mut self, node_idx: NodeIndex) {
        self.remove_all_outgoing_links_of_node(node_idx);
        self.remove_all_incoming_links_of_node(node_idx);
    }

    /// Remove the node with index `node_idx` including
    /// all incoming and outgoing links.
    ///
    /// Moves the last node in the nodes array into the empty
    /// place and rewires all links. As such, this is a quite
    /// heavy operation!
    ///
    /// # Danger!
    ///
    /// The external NodeIndex of the last node is changed!
    ///
    /// # Complexity
    ///
    /// Worst case O(e), where `e` is the total number of edges in the graph.
    ///
    pub fn remove_node(&mut self, node_idx: NodeIndex) {
        let node_count = self.nodes.len();
        assert!(node_idx.index() < node_count);
        assert!(node_count > 0);
        self.remove_all_inout_links_of_node(node_idx);
        let last_idx = NodeIndex(node_count - 1);
        if node_idx == last_idx {
            // the node is the last! simply pop it off from the end of the array!
            let _node = self.nodes.pop();
        } else {
            // the node is not the last. move the node at `last_idx` into our position.
            let _node = self.nodes.swap_remove(node_idx.index());
            // then substitute `last_idx` by `node_idx` in every edge.

            for link_item in self.links.iter_mut() {
                if link_item.link.target_node_idx == last_idx {
                    link_item.link.target_node_idx = node_idx;
                }
                if link_item.link.source_node_idx == last_idx {
                    link_item.link.source_node_idx = node_idx;
                }
            }
        }
        assert!(self.node_count() == node_count - 1);
    }

    /// Adds a new node to the network with type `node_type` and the associated
    /// id `external_node_id`. The `external_node_id` is stored in the node and
    /// can be retrieved later on.
    ///
    pub fn add_node(&mut self, node_type: N, external_node_id: EXTID) -> NodeIndex {
        let node_idx = NodeIndex(self.nodes.len());
        self.nodes.push(Node {
            node_type: node_type,
            external_node_id: external_node_id,
            links: List::empty(),
            in_degree: 0,
            out_degree: 0,
        });
        return node_idx;
    }

    /// Returns a random link between two unconnected nodes, which would not
    /// introduce
    /// a cycle. Return None is no such exists.
    pub fn find_random_unconnected_link_no_cycle<R: Rng>(
        &self,
        rng: &mut R,
    ) -> Option<(NodeIndex, NodeIndex)> {
        let n = self.nodes.len();

        let idx = &|i, j| i * n + j;

        let mut adj_matrix = FixedBitSet::with_capacity(n * n);

        // Build up a binary, undirected adjacency matrix of the graph.
        // Every unset bit in the adj_matrix will be a potential link.
        for (i, node) in self.nodes.iter().enumerate() {
            for (_, link) in node.links.iter(&self.links) {
                let j = link.target_node_idx.index();
                adj_matrix.insert(idx(i, j));
                // include the link of reverse direction, because this would
                // create a cycle anyway.
                adj_matrix.insert(idx(j, i));
            }
        }

        let adj_matrix = adj_matrix; // make immutable

        // We now test all potential links of every node in the graph, if it would
        // introduce a cycle. For that, we shuffle the node indices (`node_order`).
        // in random order.
        // XXX: Remove deleted nodes
        let mut node_order: Vec<_> = (0..n).into_iter().collect();
        let mut edge_order: Vec<_> = (0..n).into_iter().collect();
        rng.shuffle(&mut node_order);

        let node_order = node_order; // make immutable

        let mut cycler = CycleDetector::new(self);
        for &i in &node_order {
            rng.shuffle(&mut edge_order);
            for &j in &edge_order {
                if i != j && !adj_matrix.contains(idx(i, j)) {
                    // The link (i, j) neither is reflexive, nor exists.
                    let ni = NodeIndex(i);
                    let nj = NodeIndex(j);
                    if self.valid_link(ni, nj).is_ok() && !cycler.link_would_cycle(ni, nj) {
                        // If the link is valid and does not create a cycle, we are done!
                        return Some((ni, nj));
                    }
                }
            }
        }

        return None;
    }

    /// Returns true if the introduction of this directed link would lead towards a
    /// cycle.
    pub fn link_would_cycle(&self, source_node_idx: NodeIndex, target_node_idx: NodeIndex) -> bool {
        if source_node_idx == target_node_idx {
            return true;
        }

        CycleDetector::new(self).link_would_cycle(source_node_idx, target_node_idx)
    }

    // Check if the link is valid. Doesn't check for cycles.
    pub fn valid_link(
        &self,
        source_node_idx: NodeIndex,
        target_node_idx: NodeIndex,
    ) -> Result<(), &'static str> {
        if source_node_idx == target_node_idx {
            return Err("Loops are not allowed");
        }

        if !self.nodes[source_node_idx.index()]
            .node_type
            .accept_outgoing_links()
        {
            return Err("Node does not allow outgoing links");
        }

        if !self.nodes[target_node_idx.index()]
            .node_type
            .accept_incoming_links()
        {
            return Err("Node does not allow incoming links");
        }

        Ok(())
    }

    fn allocate_link_item(&mut self, link_item: LinkItem<L, EXTID>) -> LinkIndex {
        let new_link_idx = LinkIndex(self.links.len());
        self.links.push(link_item);
        return new_link_idx;
    }

    pub fn disable_link_index(&mut self, link_idx: LinkIndex) -> bool {
        if self.link(link_idx).is_active() {
            self.active_link_count -= 1;
            self.link_mut(link_idx).active = false;
            return true;
        } else {
            return false;
        }
    }

    pub fn enable_link_index(&mut self, link_idx: LinkIndex) -> bool {
        if !self.link(link_idx).is_active() {
            self.active_link_count += 1;
            self.link_mut(link_idx).active = true;
            return true;
        } else {
            return false;
        }
    }

    pub fn disable_link(&mut self, source_node_idx: NodeIndex, target_node_idx: NodeIndex) -> bool {
        if let Some(link_idx) = self.find_link_index_exact(source_node_idx, target_node_idx) {
            return self.disable_link_index(link_idx);
        }
        return false;
    }

    pub fn enable_link(&mut self, source_node_idx: NodeIndex, target_node_idx: NodeIndex) -> bool {
        if let Some(link_idx) = self.find_link_index_exact(source_node_idx, target_node_idx) {
            return self.enable_link_index(link_idx);
        }
        return false;
    }

    pub fn first_link_of_node(&self, node_idx: NodeIndex) -> Option<&Link<L, EXTID>> {
        self.node(node_idx)
            .links
            .head
            .map(|link_idx| self.link(link_idx))
    }

    pub fn last_link_of_node(&self, node_idx: NodeIndex) -> Option<&Link<L, EXTID>> {
        self.node(node_idx)
            .links
            .tail
            .map(|link_idx| self.link(link_idx))
    }

    fn append(&mut self, node_idx: NodeIndex, link: Link<L, EXTID>) -> LinkIndex {
        match (
            self.node(node_idx).links.head,
            self.node(node_idx).links.tail,
        ) {
            (None, None) => {
                // append onto empty list
                let new_link_idx = self.allocate_link_item(LinkItem {
                    link: link,
                    prev: None,
                    next: None,
                });
                self.node_mut(node_idx).links = List {
                    head: Some(new_link_idx),
                    tail: Some(new_link_idx),
                };
                return new_link_idx;
            }
            (Some(_), Some(tail)) => {
                let new_link_idx = self.allocate_link_item(LinkItem {
                    link: link,
                    prev: Some(tail),
                    next: None,
                });
                assert!(self.links[tail.index()].next == None);
                self.links[tail.index()].next = Some(new_link_idx);
                self.node_mut(node_idx).links.tail = Some(new_link_idx);
                return new_link_idx;
            }
            _ => panic!(),
        }
    }

    fn prepend(&mut self, node_idx: NodeIndex, link: Link<L, EXTID>) -> LinkIndex {
        match (
            self.node(node_idx).links.head,
            self.node(node_idx).links.tail,
        ) {
            (None, None) => {
                // prepend to empty list. same as append
                let new_link_idx = self.allocate_link_item(LinkItem {
                    link: link,
                    prev: None,
                    next: None,
                });
                self.node_mut(node_idx).links = List {
                    head: Some(new_link_idx),
                    tail: Some(new_link_idx),
                };
                return new_link_idx;
            }
            (Some(head), Some(_tail)) => {
                let new_link_idx = self.allocate_link_item(LinkItem {
                    link: link,
                    prev: None,
                    next: Some(head),
                });
                assert!(self.links[head.index()].prev == None);
                self.links[head.index()].prev = Some(new_link_idx);
                self.node_mut(node_idx).links.head = Some(new_link_idx);
                return new_link_idx;
            }
            _ => panic!(),
        }
    }

    pub fn add_link(
        &mut self,
        source_node_idx: NodeIndex,
        target_node_idx: NodeIndex,
        weight: L,
        external_link_id: EXTID,
    ) -> LinkIndex {
        self.add_link_with_active(
            source_node_idx,
            target_node_idx,
            weight,
            external_link_id,
            true,
        )
    }

    // This will destroy the ordering relation of links.
    // Do not mix with `add_link` or `add_link_with_active`.

    pub fn add_link_unordered(
        &mut self,
        source_node_idx: NodeIndex,
        target_node_idx: NodeIndex,
        weight: L,
        external_link_id: EXTID,
    ) -> LinkIndex {
        if let Err(err) = self.valid_link(source_node_idx, target_node_idx) {
            panic!(err);
        }

        self.link_count += 1;
        self.active_link_count += 1;

        self.node_mut(source_node_idx).out_degree += 1;
        self.node_mut(target_node_idx).in_degree += 1;

        let link = Link {
            source_node_idx: source_node_idx,
            target_node_idx: target_node_idx,
            external_link_id: external_link_id,
            weight: weight,
            active: true,
        };

        return self.append(source_node_idx, link);
    }

    // Note: Doesn't check for cycles (except in the simple reflexive case).
    // Note that we keep the list of links sorted according to it's
    // external_link_id.
    // XXX: Need test cases.
    pub fn add_link_with_active(
        &mut self,
        source_node_idx: NodeIndex,
        target_node_idx: NodeIndex,
        weight: L,
        external_link_id: EXTID,
        active: bool,
    ) -> LinkIndex {
        if let Err(err) = self.valid_link(source_node_idx, target_node_idx) {
            panic!(err);
        }

        self.link_count += 1;
        if active {
            self.active_link_count += 1;
        }
        self.node_mut(source_node_idx).out_degree += 1;
        self.node_mut(target_node_idx).in_degree += 1;

        let link = Link {
            source_node_idx: source_node_idx,
            target_node_idx: target_node_idx,
            external_link_id: external_link_id,
            weight: weight,
            active: active,
        };

        match self.find_link_index_insert_before(source_node_idx, target_node_idx, external_link_id)
        {
            None => {
                if let Some(tail) = self.node(source_node_idx).links.tail {
                    // check if last element is equal
                    if self.link(tail).target_node_idx == target_node_idx {
                        assert!(self.link(tail).external_link_id == external_link_id);
                        panic!("Duplicate link");
                    }
                }
                // append at end.
                return self.append(source_node_idx, link);
            }
            Some(idx) => {
                match self.link_item(idx).prev {
                    None => {
                        return self.prepend(source_node_idx, link);
                    }
                    Some(insert_after) => {
                        // check if previous element is not equal
                        if self.link(insert_after).target_node_idx == target_node_idx {
                            assert!(self.link(insert_after).external_link_id == external_link_id);
                            panic!("Duplicate link");
                        }

                        let new_link_idx = self.allocate_link_item(LinkItem {
                            link: link,
                            prev: Some(insert_after),
                            next: Some(idx),
                        });

                        self.links[insert_after.index()].next = Some(new_link_idx);
                        self.links[idx.index()].prev = Some(new_link_idx);

                        return new_link_idx;
                    }
                }
            }
        }
    }

    // Returns the index of the first element whoose external link id >
    // `external_link_id`.
    fn find_link_index_insert_before(
        &self,
        source_node_idx: NodeIndex,
        _target_node_idx: NodeIndex,
        external_link_id: EXTID,
    ) -> Option<LinkIndex> {
        // the links are sorted according to their external link id.
        let mut link_iter = self.link_iter_for_node(source_node_idx);
        for (idx, link) in &mut link_iter {
            if link.external_link_id() > external_link_id {
                return Some(idx);
            }
        }
        return None;
    }

    pub fn has_link(&self, source_node_idx: NodeIndex, target_node_idx: NodeIndex) -> bool {
        self.find_link_index_exact(source_node_idx, target_node_idx)
            .is_some()
    }

    fn find_link_index_exact(
        &self,
        source_node_idx: NodeIndex,
        target_node_idx: NodeIndex,
    ) -> Option<LinkIndex> {
        for (link_idx, link) in self.link_iter_for_node(source_node_idx) {
            // We found the node we are looking for.
            if link.target_node_idx == target_node_idx {
                return Some(link_idx);
            }
        }
        return None;
    }

    /// Remove the link at index `link_index`.
    pub fn remove_link_at(&mut self, link_index: LinkIndex) {
        let found_idx = link_index;
        let source_node_idx = self.link(found_idx).source_node_idx;
        let target_node_idx = self.link(found_idx).target_node_idx;

        if self.link(found_idx).is_active() {
            self.active_link_count -= 1;
        }

        // remove item from chain

        match (
            self.link_item(found_idx).prev,
            self.link_item(found_idx).next,
        ) {
            (None, None) => {
                // Item is the only element of the list.
                assert!(self.node(source_node_idx).links.head == Some(found_idx));
                assert!(self.node(source_node_idx).links.tail == Some(found_idx));
                self.node_mut(source_node_idx).links = List::empty();
            }

            (None, Some(next)) => {
                // Item is the first element in the list, followed by some other element.
                assert!(self.links[next.index()].prev == Some(found_idx));
                assert!(self.node(source_node_idx).links.head == Some(found_idx));
                assert!(self.node(source_node_idx).links.tail != Some(found_idx));
                self.node_mut(source_node_idx).links.head = Some(next);
                self.links[next.index()].prev = None;
            }

            (Some(prev), None) => {
                // Item is the last element of the list, preceded by some other element.
                assert!(self.links[prev.index()].next == Some(found_idx));
                assert!(self.node(source_node_idx).links.tail == Some(found_idx));
                assert!(self.node(source_node_idx).links.head != Some(found_idx));

                // make the previous element the new tail
                self.node_mut(source_node_idx).links.tail = Some(prev);
                self.links[prev.index()].next = None;
            }

            (Some(prev), Some(next)) => {
                // Item is somewhere in the middle of the list. We don't have to
                // update the head or tail pointers.
                assert!(self.node(source_node_idx).links.head != Some(found_idx));
                assert!(self.node(source_node_idx).links.tail != Some(found_idx));

                assert!(self.links[prev.index()].next == Some(found_idx));
                assert!(self.links[next.index()].prev == Some(found_idx));

                self.links[prev.index()].next = Some(next);
                self.links[next.index()].prev = Some(prev);
            }
        }

        self.links[found_idx.index()].next = None;
        self.links[found_idx.index()].prev = None;

        // swap the item with the last one.
        let old_idx = LinkIndex(self.links.len() - 1);

        if found_idx == old_idx {
            // if we are the last element, we can just pop it
            let old = self.links.pop().unwrap();
            debug_assert!(old.link.source_node_idx == source_node_idx);
            debug_assert!(old.link.target_node_idx == target_node_idx);
        } else {
            let old = self.links.swap_remove(found_idx.index());
            debug_assert!(old.link.source_node_idx == source_node_idx);
            debug_assert!(old.link.target_node_idx == target_node_idx);

            // We have to change the linking of the newly at position `found_idx` placed
            // element.
            let new_idx = found_idx;
            // change the next pointer of the previous element
            let new_source_node_idx = self.link(new_idx).source_node_idx;

            match (self.link_item(new_idx).prev, self.link_item(new_idx).next) {
                (None, None) => {
                    // the moved element was the only element in the list.
                    assert!(self.node(new_source_node_idx).links.head == Some(old_idx));
                    assert!(self.node(new_source_node_idx).links.tail == Some(old_idx));

                    // Update both head and tail to the new element index.
                    self.node_mut(new_source_node_idx).links = List {
                        head: Some(new_idx),
                        tail: Some(new_idx),
                    };
                }

                (None, Some(next)) => {
                    // Item is the first element in the list, followed by some other element.
                    assert!(self.links[next.index()].prev == Some(old_idx));
                    assert!(self.node(new_source_node_idx).links.head == Some(old_idx));
                    assert!(self.node(new_source_node_idx).links.tail != Some(old_idx));
                    self.node_mut(new_source_node_idx).links.head = Some(new_idx);
                    self.links[next.index()].prev = Some(new_idx);
                }

                (Some(prev), None) => {
                    // Item is the last element of the list, preceded by some other element.
                    assert!(self.links[prev.index()].next == Some(old_idx));
                    assert!(self.node(new_source_node_idx).links.tail == Some(old_idx));
                    assert!(self.node(new_source_node_idx).links.head != Some(old_idx));

                    // make the previous element the new tail
                    self.node_mut(new_source_node_idx).links.tail = Some(new_idx);
                    self.links[prev.index()].next = Some(new_idx);
                }

                (Some(prev), Some(next)) => {
                    // Item is somewhere in the middle of the list. We don't have to
                    // update the head or tail pointers.
                    assert!(self.node(new_source_node_idx).links.head != Some(old_idx));
                    assert!(self.node(new_source_node_idx).links.tail != Some(old_idx));

                    assert!(self.links[prev.index()].next == Some(old_idx));
                    assert!(self.links[next.index()].prev == Some(old_idx));

                    self.links[prev.index()].next = Some(new_idx);
                    self.links[next.index()].prev = Some(new_idx);
                }
            }
        }

        assert!(self.node(source_node_idx).out_degree > 0);
        assert!(self.node(target_node_idx).in_degree > 0);
        self.node_mut(source_node_idx).out_degree -= 1;
        self.node_mut(target_node_idx).in_degree -= 1;
        self.link_count -= 1;
    }

    /// Remove the first link that matches `source_node_idx` and `target_node_idx`.
    /// XXX
    pub fn remove_link(&mut self, source_node_idx: NodeIndex, target_node_idx: NodeIndex) -> bool {
        if let Some(found_idx) = self.find_link_index_exact(source_node_idx, target_node_idx) {
            debug_assert!(self.link(found_idx).source_node_idx == source_node_idx);
            debug_assert!(self.link(found_idx).target_node_idx == target_node_idx);
            self.remove_link_at(found_idx);
            return true;
        } else {
            // link was not found
            return false;
        }
    }
}

#[cfg(test)]
mod tests {
    use rand;
    use super::{ExternalId, Network, NodeIndex, NodeType};

    #[derive(Clone, Debug, PartialEq, Eq)]
    enum NodeT {
        Input,
        Hidden,
        Output,
    }

    impl NodeType for NodeT {
        fn accept_incoming_links(&self) -> bool {
            match *self {
                NodeT::Input => false,
                _ => true,
            }
        }
        fn accept_outgoing_links(&self) -> bool {
            match *self {
                NodeT::Output => false,
                _ => true,
            }
        }
    }

    #[test]
    fn test_cycle() {
        let mut g = Network::new();
        let i1 = g.add_node(NodeT::Input, ExternalId(1));
        let h1 = g.add_node(NodeT::Hidden, ExternalId(2));
        let h2 = g.add_node(NodeT::Hidden, ExternalId(3));
        assert_eq!(true, g.valid_link(i1, i1).is_err());
        assert_eq!(true, g.valid_link(h1, h1).is_err());

        assert_eq!(true, g.valid_link(h1, i1).is_err());
        assert_eq!(Ok(()), g.valid_link(i1, h1));
        assert_eq!(Ok(()), g.valid_link(i1, h2));
        assert_eq!(Ok(()), g.valid_link(h1, h2));

        assert_eq!((0, 0), g.node(i1).in_out_degree());
        assert_eq!((0, 0), g.node(h1).in_out_degree());
        assert_eq!((0, 0), g.node(h2).in_out_degree());

        g.add_link(i1, h1, 0.0, ExternalId(1));
        assert_eq!((0, 1), g.node(i1).in_out_degree());
        assert_eq!((1, 0), g.node(h1).in_out_degree());
        assert_eq!((0, 0), g.node(h2).in_out_degree());

        assert_eq!(true, g.link_would_cycle(h1, i1));
        assert_eq!(false, g.link_would_cycle(i1, h1));
        assert_eq!(false, g.link_would_cycle(i1, h2));
        assert_eq!(true, g.link_would_cycle(i1, i1));
        assert_eq!(false, g.link_would_cycle(h1, h2));
        assert_eq!(false, g.link_would_cycle(h2, h1));
        assert_eq!(false, g.link_would_cycle(h2, i1));

        g.add_link(h1, h2, 0.0, ExternalId(2));
        assert_eq!((0, 1), g.node(i1).in_out_degree());
        assert_eq!((1, 1), g.node(h1).in_out_degree());
        assert_eq!((1, 0), g.node(h2).in_out_degree());

        assert_eq!(true, g.link_would_cycle(h2, i1));
        assert_eq!(true, g.link_would_cycle(h1, i1));
        assert_eq!(true, g.link_would_cycle(h2, h1));
        assert_eq!(false, g.link_would_cycle(i1, h2));
    }

    #[test]
    fn test_find_random_unconnected_link_no_cycle() {
        let mut g = Network::new();
        let i1 = g.add_node(NodeT::Input, ExternalId(1));
        let o1 = g.add_node(NodeT::Output, ExternalId(2));
        let o2 = g.add_node(NodeT::Output, ExternalId(3));

        let mut rng = rand::thread_rng();

        let link = g.find_random_unconnected_link_no_cycle(&mut rng);
        assert_eq!(true, link.is_some());
        let l = link.unwrap();
        assert!((i1, o1) == l || (i1, o2) == l);

        g.add_link(i1, o2, 0.0, ExternalId(1));
        let link = g.find_random_unconnected_link_no_cycle(&mut rng);
        assert_eq!(true, link.is_some());
        assert_eq!((i1, o1), link.unwrap());

        g.add_link(i1, o1, 0.0, ExternalId(2));
        let link = g.find_random_unconnected_link_no_cycle(&mut rng);
        assert_eq!(false, link.is_some());
    }

    #[test]
    fn test_remove_link() {
        let mut g = Network::new();
        let i1 = g.add_node(NodeT::Input, ExternalId(1));
        let h1 = g.add_node(NodeT::Hidden, ExternalId(2));
        let h2 = g.add_node(NodeT::Hidden, ExternalId(3));

        g.add_link(i1, h1, 0.0, ExternalId(2));
        g.add_link(i1, h2, 0.0, ExternalId(1));

        assert_eq!(
            ExternalId(1),
            g.first_link_of_node(i1).unwrap().external_link_id()
        );
        assert_eq!(
            ExternalId(2),
            g.last_link_of_node(i1).unwrap().external_link_id()
        );

        assert_eq!(2, g.node(i1).out_degree());
        assert_eq!(1, g.node(h1).in_degree());
        assert_eq!(1, g.node(h2).in_degree());
        assert_eq!(2, g.link_count());

        assert_eq!(true, g.remove_link(i1, h1));
        assert_eq!(1, g.node(i1).out_degree());
        assert_eq!(0, g.node(h1).in_degree());
        assert_eq!(1, g.node(h2).in_degree());
        assert_eq!(1, g.link_count());

        assert_eq!(
            ExternalId(1),
            g.first_link_of_node(i1).unwrap().external_link_id()
        );
        assert_eq!(
            ExternalId(1),
            g.last_link_of_node(i1).unwrap().external_link_id()
        );

        assert_eq!(false, g.remove_link(i1, h1));
        assert_eq!(1, g.node(i1).out_degree());
        assert_eq!(0, g.node(h1).in_degree());
        assert_eq!(1, g.node(h2).in_degree());
        assert_eq!(1, g.link_count());

        assert_eq!(
            ExternalId(1),
            g.first_link_of_node(i1).unwrap().external_link_id()
        );
        assert_eq!(
            ExternalId(1),
            g.last_link_of_node(i1).unwrap().external_link_id()
        );

        assert_eq!(true, g.remove_link(i1, h2));
        assert_eq!(0, g.node(i1).out_degree());
        assert_eq!(0, g.node(h1).in_degree());
        assert_eq!(0, g.node(h2).in_degree());
        assert_eq!(0, g.link_count());

        assert!(g.first_link_of_node(i1).is_none());
        assert!(g.last_link_of_node(i1).is_none());

        // XXX: test for sort order
    }

    #[test]
    fn test_add_remove_link_unordered() {
        let mut g = Network::new();
        let i1 = g.add_node(NodeT::Input, ());
        let h1 = g.add_node(NodeT::Hidden, ());
        let h2 = g.add_node(NodeT::Hidden, ());

        g.add_link_unordered(i1, h1, 0.0, ());
        g.add_link_unordered(i1, h2, 0.0, ());

        assert_eq!(h1, g.first_link_of_node(i1).unwrap().target_node_idx);
        assert_eq!(h2, g.last_link_of_node(i1).unwrap().target_node_idx);

        assert_eq!(2, g.node(i1).out_degree());
        assert_eq!(1, g.node(h1).in_degree());
        assert_eq!(1, g.node(h2).in_degree());
        assert_eq!(2, g.link_count());

        assert_eq!(true, g.remove_link(i1, h1));
        assert_eq!(1, g.node(i1).out_degree());
        assert_eq!(0, g.node(h1).in_degree());
        assert_eq!(1, g.node(h2).in_degree());
        assert_eq!(1, g.link_count());

        assert_eq!(h2, g.first_link_of_node(i1).unwrap().target_node_idx);
        assert_eq!(h2, g.last_link_of_node(i1).unwrap().target_node_idx);

        assert_eq!(false, g.remove_link(i1, h1));
        assert_eq!(1, g.node(i1).out_degree());
        assert_eq!(0, g.node(h1).in_degree());
        assert_eq!(1, g.node(h2).in_degree());
        assert_eq!(1, g.link_count());

        assert_eq!(h2, g.first_link_of_node(i1).unwrap().target_node_idx);
        assert_eq!(h2, g.last_link_of_node(i1).unwrap().target_node_idx);

        assert_eq!(true, g.remove_link(i1, h2));
        assert_eq!(0, g.node(i1).out_degree());
        assert_eq!(0, g.node(h1).in_degree());
        assert_eq!(0, g.node(h2).in_degree());
        assert_eq!(0, g.link_count());

        assert!(g.first_link_of_node(i1).is_none());
        assert!(g.last_link_of_node(i1).is_none());
    }

    #[test]
    fn test_remove_all_outgoing_links() {
        let mut g = Network::new();
        let i1 = g.add_node(NodeT::Input, ());
        let h1 = g.add_node(NodeT::Hidden, ());
        let h2 = g.add_node(NodeT::Hidden, ());
        let o1 = g.add_node(NodeT::Output, ());

        g.add_link_unordered(i1, h1, 0.0, ());
        g.add_link_unordered(i1, h2, 0.0, ());
        g.add_link_unordered(h1, o1, 0.0, ());
        g.add_link_unordered(h2, o1, 0.0, ());

        assert_eq!(2, g.node(i1).out_degree());
        assert_eq!(1, g.node(h1).in_degree());
        assert_eq!(1, g.node(h2).in_degree());
        assert_eq!(1, g.node(h1).out_degree());
        assert_eq!(1, g.node(h2).out_degree());
        assert_eq!(2, g.node(o1).in_degree());
        assert_eq!(0, g.node(o1).out_degree());
        assert_eq!(4, g.link_count());

        g.remove_all_outgoing_links_of_node(i1);

        assert!(g.first_link_of_node(i1).is_none());
        assert!(g.last_link_of_node(i1).is_none());

        assert_eq!(0, g.node(i1).out_degree());
        assert_eq!(0, g.node(h1).in_degree());
        assert_eq!(0, g.node(h2).in_degree());
        assert_eq!(1, g.node(h1).out_degree());
        assert_eq!(1, g.node(h2).out_degree());
        assert_eq!(2, g.node(o1).in_degree());
        assert_eq!(0, g.node(o1).out_degree());
        assert_eq!(2, g.link_count());
    }

    #[test]
    fn test_remove_all_incoming_links() {
        let mut g = Network::new();
        let i1 = g.add_node(NodeT::Input, ());
        let h1 = g.add_node(NodeT::Hidden, ());
        let h2 = g.add_node(NodeT::Hidden, ());
        let o1 = g.add_node(NodeT::Output, ());

        g.add_link_unordered(i1, h1, 0.0, ());
        g.add_link_unordered(i1, h2, 0.0, ());
        g.add_link_unordered(h1, o1, 0.0, ());
        g.add_link_unordered(h2, o1, 0.0, ());

        assert_eq!(2, g.node(i1).out_degree());
        assert_eq!(1, g.node(h1).in_degree());
        assert_eq!(1, g.node(h2).in_degree());
        assert_eq!(1, g.node(h1).out_degree());
        assert_eq!(1, g.node(h2).out_degree());
        assert_eq!(2, g.node(o1).in_degree());
        assert_eq!(0, g.node(o1).out_degree());
        assert_eq!(4, g.link_count());
        assert!(g.first_link_of_node(i1).is_some());
        assert!(g.last_link_of_node(i1).is_some());

        g.remove_all_incoming_links_of_node(i1);

        assert_eq!(2, g.node(i1).out_degree());
        assert_eq!(1, g.node(h1).in_degree());
        assert_eq!(1, g.node(h2).in_degree());
        assert_eq!(1, g.node(h1).out_degree());
        assert_eq!(1, g.node(h2).out_degree());
        assert_eq!(2, g.node(o1).in_degree());
        assert_eq!(0, g.node(o1).out_degree());
        assert_eq!(4, g.link_count());
        assert!(g.first_link_of_node(i1).is_some());
        assert!(g.last_link_of_node(i1).is_some());

        g.remove_all_incoming_links_of_node(h1);

        assert_eq!(1, g.node(i1).out_degree());
        assert_eq!(0, g.node(h1).in_degree());
        assert_eq!(1, g.node(h2).in_degree());
        assert_eq!(1, g.node(h1).out_degree());
        assert_eq!(1, g.node(h2).out_degree());
        assert_eq!(2, g.node(o1).in_degree());
        assert_eq!(0, g.node(o1).out_degree());
        assert_eq!(3, g.link_count());
        assert!(g.first_link_of_node(i1).is_some());
        assert!(g.last_link_of_node(i1).is_some());

        g.remove_all_incoming_links_of_node(h2);

        assert_eq!(0, g.node(i1).out_degree());
        assert_eq!(0, g.node(h1).in_degree());
        assert_eq!(0, g.node(h2).in_degree());
        assert_eq!(1, g.node(h1).out_degree());
        assert_eq!(1, g.node(h2).out_degree());
        assert_eq!(2, g.node(o1).in_degree());
        assert_eq!(0, g.node(o1).out_degree());
        assert_eq!(2, g.link_count());
        assert!(g.first_link_of_node(i1).is_none());
        assert!(g.last_link_of_node(i1).is_none());
    }

    #[test]
    fn test_remove_all_inout_links() {
        let mut g = Network::new();
        let i1 = g.add_node(NodeT::Input, ());
        let h1 = g.add_node(NodeT::Hidden, ());
        let h2 = g.add_node(NodeT::Hidden, ());
        let o1 = g.add_node(NodeT::Output, ());

        g.add_link_unordered(i1, h1, 0.0, ());
        g.add_link_unordered(i1, h2, 0.0, ());
        g.add_link_unordered(h1, o1, 0.0, ());
        g.add_link_unordered(h2, o1, 0.0, ());

        assert_eq!(2, g.node(i1).out_degree());
        assert_eq!(1, g.node(h1).in_degree());
        assert_eq!(1, g.node(h2).in_degree());
        assert_eq!(1, g.node(h1).out_degree());
        assert_eq!(1, g.node(h2).out_degree());
        assert_eq!(2, g.node(o1).in_degree());
        assert_eq!(0, g.node(o1).out_degree());
        assert_eq!(4, g.link_count());

        g.remove_all_inout_links_of_node(i1);

        assert!(g.first_link_of_node(i1).is_none());
        assert!(g.last_link_of_node(i1).is_none());

        assert_eq!(0, g.node(i1).out_degree());
        assert_eq!(0, g.node(h1).in_degree());
        assert_eq!(0, g.node(h2).in_degree());
        assert_eq!(1, g.node(h1).out_degree());
        assert_eq!(1, g.node(h2).out_degree());
        assert_eq!(2, g.node(o1).in_degree());
        assert_eq!(0, g.node(o1).out_degree());
        assert_eq!(2, g.link_count());

        g.remove_all_inout_links_of_node(h1);

        assert_eq!(0, g.node(i1).out_degree());
        assert_eq!(0, g.node(h1).in_degree());
        assert_eq!(0, g.node(h2).in_degree());
        assert_eq!(0, g.node(h1).out_degree());
        assert_eq!(1, g.node(h2).out_degree());
        assert_eq!(1, g.node(o1).in_degree());
        assert_eq!(0, g.node(o1).out_degree());
        assert_eq!(1, g.link_count());

        g.remove_all_inout_links_of_node(o1);

        assert_eq!(0, g.node(i1).out_degree());
        assert_eq!(0, g.node(h1).in_degree());
        assert_eq!(0, g.node(h2).in_degree());
        assert_eq!(0, g.node(h1).out_degree());
        assert_eq!(0, g.node(h2).out_degree());
        assert_eq!(0, g.node(o1).in_degree());
        assert_eq!(0, g.node(o1).out_degree());
        assert_eq!(0, g.link_count());
    }

    #[test]
    fn test_remove_node() {
        let mut g = Network::new();
        let i1 = g.add_node(NodeT::Input, ());
        let h1 = g.add_node(NodeT::Hidden, ());
        let h2 = g.add_node(NodeT::Hidden, ());
        let o1 = g.add_node(NodeT::Output, ());

        g.add_link_unordered(i1, h1, 0.0, ());
        g.add_link_unordered(i1, h2, 0.0, ());
        g.add_link_unordered(h1, o1, 0.0, ());
        g.add_link_unordered(h2, o1, 0.0, ());

        assert_eq!(2, g.node(i1).out_degree());
        assert_eq!(1, g.node(h1).in_degree());
        assert_eq!(1, g.node(h2).in_degree());
        assert_eq!(1, g.node(h1).out_degree());
        assert_eq!(1, g.node(h2).out_degree());
        assert_eq!(2, g.node(o1).in_degree());
        assert_eq!(0, g.node(o1).out_degree());
        assert_eq!(4, g.link_count());
        assert_eq!(4, g.node_count());

        assert_eq!(NodeIndex(0), i1);
        assert_eq!(NodeIndex(3), o1);
        g.remove_node(i1);
        let o1 = i1;
        drop(i1);
        assert_eq!(NodeIndex(0), o1);

        assert_eq!(0, g.node(h1).in_degree());
        assert_eq!(0, g.node(h2).in_degree());
        assert_eq!(1, g.node(h1).out_degree());
        assert_eq!(1, g.node(h2).out_degree());
        assert_eq!(2, g.node(o1).in_degree());
        assert_eq!(0, g.node(o1).out_degree());
        assert_eq!(2, g.link_count());
        assert_eq!(3, g.node_count());

        assert_eq!(NodeIndex(2), h2);
        g.remove_node(h2);
        drop(h2);

        assert_eq!(0, g.node(h1).in_degree());
        assert_eq!(1, g.node(h1).out_degree());
        assert_eq!(1, g.node(o1).in_degree());
        assert_eq!(0, g.node(o1).out_degree());
        assert_eq!(1, g.link_count());
        assert_eq!(2, g.node_count());

        assert_eq!(NodeIndex(0), o1);
        g.remove_node(o1);
        let h1 = o1;
        drop(o1);
        assert_eq!(NodeIndex(0), h1);

        assert_eq!(0, g.node(h1).in_degree());
        assert_eq!(0, g.node(h1).out_degree());
        assert_eq!(0, g.link_count());
        assert_eq!(1, g.node_count());

        assert_eq!(NodeIndex(0), h1);
        g.remove_node(h1);
        assert_eq!(0, g.node_count());
    }

}