routecore 0.7.1

A Library with Building Blocks for BGP Routing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
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
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
use core::ops::Range; 
use std::collections::HashMap;
use std::fmt::Debug;
use std::hash::Hash;
use std::marker::PhantomData;
use std::net::Ipv4Addr;

use octseq::{Octets, Parser};

use crate::bgp::message::Header;

use inetnum::asn::Asn;
use crate::bgp::aspath::AsPath;
use crate::bgp::communities::{
    ExtendedCommunity, Ipv6ExtendedCommunity, LargeCommunity,
};
use crate::bgp::message::MsgType;
use crate::bgp::path_attributes::{
    AggregatorInfo, PathAttributes, PathAttributeType,
    WireformatPathAttribute, UncheckedPathAttributes,
};
use crate::bgp::types::{
    LocalPref, MultiExitDisc, NextHop, OriginType, AfiSafiType, AddpathDirection,
    AddpathFamDir
};

use crate::bgp::nlri::afisafi::{
    AfiSafiNlri, NlriParse, NlriIter, NlriEnumIter, Nlri, NlriType
};

use crate::util::parser::ParseError;


/// BGP UPDATE message, variant of the [`Message`] enum.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct UpdateMessage<Octs: Octets> {
    octets: Octs,
    withdrawals: Range<usize>,
    attributes: Range<usize>,
    announcements: Range<usize>,
    pdu_parse_info: PduParseInfo,
}


impl<Octs: Octets> UpdateMessage<Octs> {

    pub fn octets(&self) -> &Octs {
        &self.octets
    }

    pub fn pdu_parse_info(&self) -> PduParseInfo {
        self.pdu_parse_info
    }

    ///// Returns the [`Header`] for this message.
    //pub fn header(&self) -> Header<&Octs> {
    //    Header::for_slice(&self.octets)
    //}

    /// Returns the length in bytes of the entire BGP message.
	pub fn length(&self) -> usize {
        //// marker, length, type
        16 + 2 + 1  
        // length of withdrawals
        + 2 + self.withdrawals.len()
        // length of path attributes
        + 2 + self.attributes.len()
        // remainder is announcements, no explicit length field
        + self.announcements.len()
	}
}

impl<Octs: Octets> AsRef<[u8]> for UpdateMessage<Octs> {
    fn as_ref(&self) -> &[u8] {
        self.octets.as_ref()
    }
}

/// BGP UPDATE message.
///
/// Offers methods to access and/or iterate over all the fields, and some
/// additional convenience methods.
///
/// ## Convenience methods
///
/// As the BGP standard has seen updates to support for example 32 bits ASNs
/// and other-than-IPv4 protocol information, some types of information can be
/// found in different places in the UPDATE message. The NLRIs for announced
/// prefixes can be at the end of the message, or in a `MP_REACH_NLRI` path
/// attribute. Similarly, the `NEXT_HOP` path attribute was once mandatory for
/// UPDATEs, but is now also part of the `MP_REACH_NLRI`, if present.
///
/// To accommodate for these hassles, the following methods are provided:
///
/// * [`nlris()`][`UpdateMessage::nlris`] and
///   [`withdrawals()`][`UpdateMessage::withdrawals`],
///   providing iterators over announced and withdrawn prefixes ;
/// * [`next_hop()`][`UpdateMessage::next_hop`], returning the [`NextHop`] ;
/// * [`all_communities()`][`UpdateMessage::all_communities`], returning an
///   optional `Vec` containing all conventional, Extended and Large
///   Communities, wrapped in the [`Community`] enum.
///
/// For the mandatory path attributes, we have:
///
/// * [`origin()`][`UpdateMessage::origin`]
/// * [`aspath()`][`UpdateMessage::aspath`]
///
/// Other path attributes ([`PathAttribute`] of a certain
/// [`PathAttributeType`]) can be access via the iterator provided via
/// [`path_attributes()`][`UpdateMessage::path_attributes`].
///
// ---BGP Update--------------------------------------------------------------
//
//  +-----------------------------------------------------+
//  |   Withdrawn Routes Length (2 octets)                |
//  +-----------------------------------------------------+
//  |   Withdrawn Routes (variable)                       |
//  +-----------------------------------------------------+
//  |   Total Path Attribute Length (2 octets)            |
//  +-----------------------------------------------------+
//  |   Path Attributes (variable)                        |
//  +-----------------------------------------------------+
//  |   Network Layer Reachability Information (variable) |
//  +-----------------------------------------------------+
impl<Octs: Octets> UpdateMessage<Octs> {
    /// Print the UpdateMessage in a `text2pcap` compatible way.
    pub fn print_pcap(&self) {
        println!("{}", self.fmt_pcap_string());
    }

    /// Format the UpdateMessage in a `text2pcap` compatible way.
    // Note that UpdateMessages can be created using from_octets, which will
    // contain the 16 byte marker, or via `parse`, which will include the
    // octets only from after the length+msgtype onwards.
    // We use the start range for the withdrawals (the first part of the
    // actual content) and the end range of the conventional announcements
    // (the last part of the actual content).
    pub fn fmt_pcap_string(&self) -> String {
        let mut res = String::with_capacity(
            7 + ((19 + self.octets.as_ref().len()) * 3)
        );

        res.push_str(
            "000000 ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff "
        );

        let len = u16::try_from(self.length())
            .unwrap_or(u16::MAX)
            .to_be_bytes();

        res.push_str(&format!("{:02x} {:02x} 02 ", len[0], len[1])); 

        // The length of the withdrawals is described in the two octets prior
        // to the actual withdrawn NLRI, hence the -2 here.
        for b in &self.octets.as_ref()[
            self.withdrawals.start-2..self.announcements.end
        ] {
            res.push_str(&format!("{:02x} ", b));
        }

        res
    }

    pub fn withdrawn_routes_len(&self) -> usize {
        self.withdrawals.len()
    }
}

impl<Octs: Octets> UpdateMessage<Octs> {

    /// Indicates which address families are present in this message.
    ///
    /// The tuple consists of four optional [`AfiSafi`] types, describing the
    /// presence of, respectively:
    ///     conventional withdrawals, conventional announcements,
    ///     multi-protocol withdrawals, multi-protocol announcements.
    ///
    /// While the conventional announcements/withdrawals will always be IPv4
    /// unicast NLRI, they might include ADD-PATH Path IDs or not.
    /// Once we switch over to the new AfiSafiType enum, we can signal PathId
    /// presence/absence.
    pub fn afi_safis(&self) -> (
        Option<NlriType>,
        Option<NlriType>,
        Option<NlriType>,
        Option<NlriType>,
    ) {
        (
            (!self.withdrawals.is_empty()).then_some((
                 AfiSafiType::Ipv4Unicast,
                 self.pdu_parse_info.conventional_addpath()).into()
            ),
            (!self.announcements.is_empty()).then_some((
                    AfiSafiType::Ipv4Unicast,
                    self.pdu_parse_info.conventional_addpath()).into()
            ),
            self.mp_withdrawals().ok().flatten().map(|w| w.nlri_type()),
            self.mp_announcements().ok().flatten().map(|a| a.nlri_type()),
        )
    }

    pub fn announcement_fams(&self) -> impl Iterator<Item = NlriType> {
        let afi_safis = self.afi_safis();
        [afi_safis.1, afi_safis.3].into_iter().flatten()
    }

    pub fn withdrawal_fams(&self) -> impl Iterator<Item = NlriType> {
        let afi_safis = self.afi_safis();
        [afi_safis.0, afi_safis.2].into_iter().flatten()
    }

    /// Returns an iterator over the conventional withdrawals.
    ///
    /// The withdrawals are always IPv4 Unicast, but can contain Path IDs.
    /// Therefore, iterator yields variants of `Nlri`.
    pub fn conventional_withdrawals(&self)
        -> Result<
            impl Iterator<Item = Result<Nlri<Octs::Range<'_>>, ParseError>> + '_,
            ParseError
            >
    {
        let pp = Parser::with_range(self.octets(), self.withdrawals.clone());

        let (normal_iter, addpath_iter) = match self.pdu_parse_info.conventional_addpath() {
            false => (Some(NlriIter::ipv4_unicast(pp)), None),
            true => (None, Some(NlriIter::ipv4_unicast_addpath(pp)))
        };

        Ok(normal_iter.into_iter().flatten()
            .map(|n| n.map(Nlri::from))
            .chain(
                addpath_iter.into_iter().flatten()
                .map(|n| n.map(Nlri::from))
            )
        )
    }

    /// Returns an iterator over the MultiProtocol withdrawals.
    pub fn mp_withdrawals(&self)
        -> Result<Option<NlriEnumIter<'_, Octs>>, ParseError>
    {
        let mut unchecked = UncheckedPathAttributes::from_parser(
            Parser::with_range(self.octets(), self.attributes.clone())
        );
        if let Some(pa) = unchecked.find(|pa|
            pa.type_code() == 15
        ) {
            let mut parser = pa.value_into_parser();
            let afi = parser.parse_u16_be()?;
            let safi = parser.parse_u8()?;
            let afi_safi = AfiSafiType::from((afi, safi));
            Ok(Some(NlriEnumIter::new(
                parser,
                (afi_safi, self.pdu_parse_info.mp_unreach_addpath()).into()
            )))
        } else {
            Ok(None)
        }
    }
    
    /// Returns a combined iterator of conventional and MP_UNREACH_NLRI.
    ///
    /// Note that this iterator might contain NLRI of different AFI/SAFI
    /// types and yields variants of `Nlri`.
    pub fn withdrawals(&self)
        -> Result<
            impl Iterator<Item = Result<Nlri<Octs::Range<'_>>, ParseError>>,
            ParseError
            >
    {
        let mp_iter = self.mp_withdrawals()?;
        let conventional_iter = self.conventional_withdrawals()?;

        Ok(mp_iter.into_iter().flatten()
            .chain(conventional_iter)
        )
    }

    /// Returns an iterator yielding withdrawals of a specific NLRI type.
    pub fn typed_withdrawals<'a, O, ASP>(&'a self)
        -> Result<Option<NlriIter<'a, O, Octs, ASP>>, ParseError>
    where
        O: Octets,
        Octs: Octets<Range<'a> = O>,
        ASP: AfiSafiNlri + NlriParse<'a, O, Octs>
    {
        if ASP::afi_safi() == AfiSafiType::Ipv4Unicast && !self.withdrawals.is_empty() {
            return Ok(Some(NlriIter::<_, _, ASP>::new(
                Parser::with_range(self.octets(), self.withdrawals.clone())
            )));
        }
        if let Some(pa) = self.unchecked_path_attributes().find(|pa|
            pa.type_code() == 15
        ) {
            let mut parser = pa.value_into_parser();
            let afi = parser.parse_u16_be()?;
            let safi = parser.parse_u8()?;
            if AfiSafiType::from((afi, safi)) != ASP::afi_safi() {
                return Ok(None);
                //return Err(ParseError::form_error("different AFI+SAFI than requested"));
            }

            Ok(Some(NlriIter::<_, _, ASP>::new(parser)))
        } else {
            Ok(None)
        }
    }
    

    /// Creates a vec of all withdrawals in this message.
    ///
    /// If any of the NLRI, in the conventional part or the MP_UNREACH_NLRI
    /// attribute, is invalid in any way, returns an Error.
    /// This means the result is either the complete (possibly empty)
    /// collection of all the announced NLRI, or none at all.
    ///
    /// For more fine-grained control, consider using the
    /// `unicast_withdrawals` method.
    pub fn withdrawals_vec(&self) 
        -> Result<Vec<Nlri<Octs::Range<'_>>>, ParseError>
    {
        let conv = self.conventional_withdrawals()?;
        let mp = self.mp_withdrawals()?;

        conv.chain(mp.into_iter().flatten()).collect()
    }

    // RFC4271: A value of 0 indicates that neither the Network Layer
    // Reachability Information field nor the Path Attribute field is present
    // in this UPDATE message.
    pub fn total_path_attribute_len(&self) -> usize {
        self.attributes.len()
    }

    pub fn path_attributes(&self)
        -> Result<PathAttributes<'_, Octs>, ParseError>
    {
        let pp = Parser::with_range(self.octets(), self.attributes.clone());

        Ok(PathAttributes::new(pp, self.pdu_parse_info))
    }

    fn unchecked_path_attributes(&self) -> UncheckedPathAttributes<'_, Octs> {
        let pp = Parser::with_range(self.octets(), self.attributes.clone());
        UncheckedPathAttributes::from_parser(pp)
    }

    /// Returns the conventional announcements.
    pub fn conventional_announcements(&self)
        -> Result<
            impl Iterator<Item = Result<Nlri<Octs::Range<'_>>, ParseError>>,
            ParseError>
    {
        let pp = Parser::with_range(self.octets(), self.announcements.clone());

        let (normal_iter, addpath_iter) =
            match self.pdu_parse_info.conventional_addpath() {
                false => (Some(NlriIter::ipv4_unicast(pp)), None),
                true => (None, Some(NlriIter::ipv4_unicast_addpath(pp)))
            }
        ;

        Ok(normal_iter.into_iter().flatten()
            .map(|n| n.map(Nlri::from))
            .chain(
                addpath_iter.into_iter().flatten()
                .map(|n| n.map(Nlri::from))
        ))
    }

    /// Returns the announcements from the MP_UNREACH_NLRI attribute, if any.
    pub fn mp_announcements(&self)
        -> Result<Option<NlriEnumIter<'_, Octs>>, ParseError>
    {
        if let Some(pa) = self.unchecked_path_attributes().find(|pa|
            pa.type_code() == 14
        ) {
            let mut parser = pa.value_into_parser();
            let afi = parser.parse_u16_be()?;
            let safi = parser.parse_u8()?;
            let afi_safi = AfiSafiType::from((afi, safi));

            NextHop::skip(&mut parser)?;
            parser.advance(1)?; // 1 reserved byte
            Ok(Some(NlriEnumIter::new(
                parser,
                (afi_safi, self.pdu_parse_info.mp_reach_addpath()).into()
            )))
        } else {
            Ok(None)
        }
    }

    /// Returns a combined iterator of conventional and MP_REACH_NLRI.
    ///
    /// Consuming the returned iterator requires care. The `Item` is a
    /// Result, containing either a successfully parsed `Nlri`, or an Error
    /// describing why it failed to parse. After one such error, the iterator
    /// will return None on the next call to `next()`.
    ///
    /// This means that, if at any point an Error is returned from the
    /// iterator, there likely is unparsed data in the PDU in either the
    /// conventional part at the end of the PDU, or in the MP_REACH_NLRI
    /// attribute. So, at best, one has an incomplete view of the announced
    /// NLRI, but possibly even that incomplete view is not 100% correct
    /// depending on the exact reason the parsing failed.
    ///
    /// With the above in mind, using `.count()` on this iterator to get the
    /// number of announced prefixes might give the wrong impression, as it
    /// will count the Error case, after which the iterator fuses.
    ///
    /// To retrieve all announcements if and only if all are validly parsed,
    /// consider using `fn announcements_vec`.
    ///
    /// Note that this iterator might contain NLRI of different AFI/SAFI
    /// types.
    pub fn announcements(&self)
        -> Result<
            impl Iterator<Item = Result<Nlri<Octs::Range<'_>>, ParseError>>,
            ParseError
            >
    {
        let mp_iter = self.mp_announcements()?;
        let conventional_iter = self.conventional_announcements()?;

        Ok(mp_iter.into_iter().flatten().chain(conventional_iter))
    }


    /// Returns an iterator yielding announcements of a specific NLRI type.
    ///
    // XXX decide what to do when the 'wrong' ASP is passed:
    // - return an Err
    // - return an Ok(None),
    // - return an Ok(Some(empty-iterator))
    // 
    // Depending on what we choose, we might get rid of the Option altogether.
    pub fn typed_announcements<'a, O, ASP>(&'a self)
        -> Result<Option<NlriIter<'a, O, Octs, ASP>>, ParseError>
    where
        O: Octets,
        Octs: Octets<Range<'a> = O>,
        ASP: AfiSafiNlri + NlriParse<'a, O, Octs>
    {
        // If the requested announcements are of type Ipv4Unicast, and the
        // conventional announcements range is non-zero, return that.
        if ASP::afi_safi() == AfiSafiType::Ipv4Unicast &&
            !self.announcements.is_empty()
        {
            return Ok(Some(NlriIter::<_, _, ASP>::new(
                Parser::with_range(self.octets(), self.announcements.clone())
            )));
        }

        // Otherwise, look in the attributes for an MP_REACH_NLRI.
        if let Some(pa) = self.unchecked_path_attributes().find(|pa|
            pa.type_code() == 14
        ) {
            let mut parser = pa.value_into_parser();
            let afi = parser.parse_u16_be()?;
            let safi = parser.parse_u8()?;
            if AfiSafiType::from((afi, safi)) != ASP::afi_safi() {
                return Ok(None);
                //return Err(ParseError::form_error("different AFI+SAFI than requested"));
            }
            NextHop::skip(&mut parser)?;
            parser.advance(1)?; // 1 reserved byte

            Ok(Some(NlriIter::<_, _, ASP>::new(parser)))
        } else {
            Ok(None)
        }
    }

    /// Creates a vec of all announcements in this message.
    ///
    /// If any of the NLRI, in the conventional part or the MP_REACH_NLRI
    /// attribute, is invalid in any way, returns an Error.
    /// This means the result is either the complete (possibly empty)
    /// collection of all the announced NLRI, or none at all.
    ///
    /// For more fine-grained control, consider using the
    /// `unicast_announcements` method.
    pub fn announcements_vec(&self) 
        -> Result<Vec<Nlri<Octs::Range<'_>>>, ParseError>
    {
        let conv = self.conventional_announcements()?;
        let mp = self.mp_announcements()?;

        conv.chain(mp.into_iter().flatten()).collect()
    }

    pub fn has_conventional_nlri(&self) -> bool {
        !self.announcements.is_empty()
    }

    pub fn has_mp_nlri(&self) -> Result<bool, ParseError> {
        Ok(
            self.unchecked_path_attributes().any(|pa| pa.type_code() == 14)
        )
    }

    /// Returns `Option<(AfiSafi)>` if this UPDATE represents the End-of-RIB
    /// marker for a AFI/SAFI combination.
    pub fn is_eor(&self) -> Result<Option<AfiSafiType>, ParseError> {
        // Conventional BGP
        if self.length() == 23 {
            // minimum length for a BGP UPDATE indicates EOR
            // (no announcements, no withdrawals)
            return Ok(Some(AfiSafiType::Ipv4Unicast));
        }

        // Based on MP_UNREACH_NLRI
        if let Ok(Some(mut iter)) = self.mp_withdrawals() {
            let res = iter.afi_safi();
            if iter.next().is_none() {
                return Ok(Some(res))
            }
        }

        Ok(None)
    }

    //--- Methods to access mandatory path attributes ------------------------
    // Mandatory path attributes are ORIGIN, AS_PATH and NEXT_HOP
    // Though, in case of MP_REACH_NLRI, NEXT_HOP must be ignored if present.
    //
    // Also note that these are only present in announced routes. A BGP UPDATE
    // with only withdrawals will not have any of these mandatory path
    // attributes present.
    pub fn origin(&self) -> Result<Option<OriginType>, ParseError> {
        if let Some(WireformatPathAttribute::Origin(epa)) = self.path_attributes()?.get(PathAttributeType::Origin) {
            Ok(Some(epa.value_into_parser().parse_u8()?.into()))
        } else {
            Ok(None)
        }
    }

    /// Returns the AS4_PATH attribute.
    pub fn as4path(&self) -> Result<
        Option<AsPath<Octs::Range<'_>>>,
        ParseError
    > {
        if let Some(WireformatPathAttribute::As4Path(epa)) = self.path_attributes()?.get(PathAttributeType::As4Path) {
            let mut p = epa.value_into_parser();
            Ok(Some(AsPath::new(p.parse_octets(p.remaining())?, true)?))
        } else {
            Ok(None)
        }
    }


    /// Returns the AS_PATH path attribute.
    //
    // NOTE: This is now the AS PATH and only the AS_PATH.
    pub fn aspath(&self)
        -> Result<Option<AsPath<Octs::Range<'_>>>, ParseError>
    {
        if let Some(WireformatPathAttribute::AsPath(epa)) = self.path_attributes()?.get(PathAttributeType::AsPath) {
            let mut p = epa.value_into_parser();
            Ok(Some(
                AsPath::new(p.parse_octets(p.remaining())?,
                epa.pdu_parse_info().four_octet_enabled())?
            ))
        } else {
            Ok(None)
        }
    }

    /// Returns NextHop information from the NEXT_HOP path attribute, if any.
    pub fn conventional_next_hop(&self)
        -> Result<Option<NextHop>, ParseError>
    {
        if let Some(WireformatPathAttribute::ConventionalNextHop(epa)) = self.path_attributes()?.get(PathAttributeType::ConventionalNextHop) {
            Ok(Some(NextHop::Unicast(Ipv4Addr::from(epa.value_into_parser().parse_u32_be()?).into())))
        } else {
            Ok(None)
        }
    }

    /// Returns NextHop information from the MP_REACH_NLRI, if any.
    pub fn mp_next_hop(&self) -> Result<Option<NextHop>, ParseError> {
        if let Some(pa) = self.unchecked_path_attributes().find(|pa|
            pa.type_code() == 14
        ) {
            let mut p = pa.value_into_parser();
            let afi = p.parse_u16_be()?;
            let safi = p.parse_u8()?;
            let afi_safi = AfiSafiType::from((afi, safi));
            Ok(Some(NextHop::parse(&mut p, afi_safi)?))
        } else {
            Ok(None)
        }
    }

    fn mp_next_hop_tuple(&self) -> Result<Option<(AfiSafiType, NextHop)>, ParseError> {
        if let Some(pa) = self.unchecked_path_attributes().find(|pa|
            pa.type_code() == 14
        ) {
            let mut p = pa.value_into_parser();
            let afi = p.parse_u16_be()?;
            let safi = p.parse_u8()?;
            let afi_safi = AfiSafiType::from((afi, safi));
            Ok(Some((afi_safi, NextHop::parse(&mut p, afi_safi)?)))
        } else {
            Ok(None)
        }

    }

    pub fn find_next_hop(&self, afi_safi: AfiSafiType)
        -> Result<NextHop, ParseError>
    {
        match afi_safi {
            AfiSafiType::Ipv4Unicast => {
                // If there is Ipv4Unicast in the MP_REACH_NLRI attribute, the
                // peers must have negotiated that in the BGP OPENs, so we can
                // assume there are no NLRI in the conventional parts of the
                // PDU. We return the nexthop from the MP attribute.
                if let Ok(Some((mp_afisafi, mp))) = self.mp_next_hop_tuple() {
                    if mp_afisafi == AfiSafiType::Ipv4Unicast {
                        return Ok(mp)
                    }
                }

                // If no MP_REACH_NLRI was found for Ipv4Unicast, we look for
                // the conventional dedicated path attribute NEXT_HOP:
                if let Ok(maybe_nh) = self.conventional_next_hop() {
                    if let Some(nh) = maybe_nh {
                        Ok(nh)
                    } else {
                        Err(ParseError::form_error(
                             "no conventional NEXT_HOP"
                        ))
                    }
                } else {
                    Err(ParseError::form_error(
                            "invalid conventional NEXT_HOP"
                    ))
                }
            }
            _ => {
                if let Ok(maybe_mp) = self.mp_next_hop_tuple() {
                    if let Some((mp_afisafi, mp)) = maybe_mp {
                        if mp_afisafi != afi_safi {
                            return Err(ParseError::form_error(
                                 "MP_REACH_NLRI for different AFI/SAFI"
                            ))
                        }
                        Ok(mp)
                    } else {
                        Err(ParseError::form_error(
                             "no MP_REACH_NLRI / nexthop"
                        ))
                    }
                } else {
                    Err(ParseError::form_error(
                            "invalid MP_REACH_NLRI / nexthop"
                    ))
                }
            }
        }
    }

    //--- Non-mandatory path attribute helpers -------------------------------

    /// Returns the Multi-Exit Discriminator value, if any.
    pub fn multi_exit_disc(&self)
        -> Result<Option<MultiExitDisc>, ParseError>
    {
        if let Some(WireformatPathAttribute::MultiExitDisc(epa)) = self.path_attributes()?.get(
            PathAttributeType::MultiExitDisc
        ){
            Ok(Some(MultiExitDisc(epa.value_into_parser().parse_u32_be()?)))
        } else {
            Ok(None)
        }

    }

    /// Returns the Local Preference value, if any.
    pub fn local_pref(&self) -> Result<Option<LocalPref>, ParseError> {
        if let Some(WireformatPathAttribute::LocalPref(epa)) = self.path_attributes()?.get(
            PathAttributeType::LocalPref
        ){
            Ok(Some(LocalPref(epa.value_into_parser().parse_u32_be()?)))
        } else {
            Ok(None)
        }
    }

    /// Returns true if this UPDATE contains the ATOMIC_AGGREGATE path
    /// attribute.
    pub fn is_atomic_aggregate(&self) -> Result<bool, ParseError> {
        Ok(
            self.path_attributes()?
                .get(PathAttributeType::AtomicAggregate).is_some()
        )
    }

    /// Returns the AGGREGATOR path attribute, if any.
    // this one originally carried a 2-octet ASN, but now also possibly a
    // 4-octet one (RFC 6793, Four Octet ASN support)
    // furthermore, it was designed to carry a IPv4 address, but that does not
    // seem to have changed with RFC4760 (multiprotocol)
    //
    // As such, we can determine whether there is a 2-octet or 4-octet ASN
    // based on the size of the attribute itself.
    // 
    pub fn aggregator(&self) -> Result<Option<AggregatorInfo>, ParseError> {

        if let Some(WireformatPathAttribute::Aggregator(epa)) = self.path_attributes()?.get(
            PathAttributeType::Aggregator
        ){
            // XXX not nice that we have to do this here, also it is exactly
            // the same as in the fn parse in path_attributes.rs
            use crate::util::parser::parse_ipv4addr;
            let mut pa = epa.value_into_parser();
            let asn = if self.pdu_parse_info.four_octet_enabled() {
                Asn::from_u32(pa.parse_u32_be()?)
            } else {
                Asn::from_u32(pa.parse_u16_be()?.into())
            };

            let address = parse_ipv4addr(&mut pa)?;
            Ok(Some(AggregatorInfo::new(asn, address)))
            //Ok(Some(Aggregator::parse2(&mut epa.value_into_parser(), epa.session_config())?.inner()))
        } else {
            Ok(None)
        }
    }


    //--- Communities --------------------------------------------------------

    // Internal, generic method, users should use the non-generic ones.
    fn _communities<T: From<[u8; 4]>>(&self)
        -> Result<Option<CommunityIter<Octs::Range<'_>, T>>, ParseError>
    {
        if let Some(WireformatPathAttribute::StandardCommunities(epa)) = self.path_attributes()?.get(PathAttributeType::StandardCommunities) {
            let mut p = epa.value_into_parser();
            Ok(Some(CommunityIter::new(p.parse_octets(p.remaining())?)))
        } else {
            Ok(None)
        }
    }

    /// Returns an iterator over Standard Communities (RFC1997), if any.
    pub fn communities(&self) 
        -> Result<
            Option<CommunityIter<Octs::Range<'_>, crate::bgp::communities::StandardCommunity>>, ParseError> {
        self._communities::<crate::bgp::communities::StandardCommunity>()
    }

    /// Returns an iterator over Standard Communities (RFC1997), if any. The
    /// iterator contains the `HumanReadableCommunity` (with special
    /// Serializer implementation).
    pub fn human_readable_communities(&self) 
        -> Result<
            Option<
                CommunityIter<Octs::Range<'_>, 
                crate::bgp::communities::HumanReadableCommunity>>, 
                ParseError
            > {
        self._communities::<crate::bgp::communities::HumanReadableCommunity>()
    }

    /// Returns an iterator over Extended Communities (RFC4360), if any.
    pub fn ext_communities(&self)
        -> Result<Option<ExtCommunityIter<Octs::Range<'_>>>, ParseError>
    {
        if let Some(WireformatPathAttribute::ExtendedCommunities(epa)) = self.path_attributes()?.get(PathAttributeType::ExtendedCommunities) {
            let mut p = epa.value_into_parser();
            Ok(Some(ExtCommunityIter::new(p.parse_octets(p.remaining())?)))
        } else {
            Ok(None)
        }
    }

    /// Returns an iterator over IPv6 Address Extended Communities (RFC5701),
    /// if any.
    pub fn ipv6_ext_communities(&self)
        -> Result<Option<Ipv6ExtCommunityIter<Octs::Range<'_>>>, ParseError>
    {
        if let Some(WireformatPathAttribute::Ipv6ExtendedCommunities(epa)) = self.path_attributes()?.get(PathAttributeType::Ipv6ExtendedCommunities) {
            let mut p = epa.value_into_parser();
            Ok(Some(Ipv6ExtCommunityIter::new(p.parse_octets(p.remaining())?)))
        } else {
            Ok(None)
        }
    }


    /// Returns an iterator over Large Communities (RFC8092), if any.
    pub fn large_communities(&self)
        -> Result<Option<LargeCommunityIter<Octs::Range<'_>>>, ParseError>
    {
        if let Some(WireformatPathAttribute::LargeCommunities(epa)) = self.path_attributes()?.get(PathAttributeType::LargeCommunities) {
            let mut p = epa.value_into_parser();
            Ok(Some(LargeCommunityIter::new(p.parse_octets(p.remaining())?)))
        } else {
            Ok(None)
        }
    }

    // Generic version shouldn't be used directly, users should use the
    // non-generic ones.
    fn _all_communities<T>(&self) -> Result<Option<Vec<T>>, ParseError> 
        where T: From<[u8; 4]> + 
            From<ExtendedCommunity> + 
            From<LargeCommunity> + 
            From<Ipv6ExtendedCommunity> {
        let mut res: Vec<T> = Vec::new();

        if let Some(c) = self._communities()? {
            res.append(&mut c.collect::<Vec<_>>());
        }
        if let Some(c) = self.ext_communities()? {
            res.append(&mut c.map(|c| c.into()).collect::<Vec<_>>());
        }
        if let Some(c) = self.ipv6_ext_communities()? {
            res.append(
                &mut c.map(|c| c.into()).collect::<Vec<_>>()
            );
        }
        if let Some(c) = self.large_communities()? {
            res.append(&mut c.map(|c| c.into()).collect::<Vec<_>>());
        }

        if res.is_empty() {
            Ok(None)
        } else {
            Ok(Some(res))
        }
    }

    /// Returns an optional `Vec` containing all conventional, Extended and
    /// Large communities, if any, or None if none of the three appear in the
    /// path attributes of this message.
    pub fn all_communities(&self) -> 
        Result<Option<Vec<crate::bgp::communities::Community>>, ParseError> {
        self._all_communities::<crate::bgp::communities::Community>()
    }

    /// Returns an optional `Vec` containing all conventional, Extended and
    /// Large communities, if any, or None if none of the three appear in the
    /// path attributes of this message, in the form of
    /// `HumanReadableCommunity`.
    pub fn all_human_readable_communities(&self) -> 
        Result<Option<Vec<crate::bgp::communities::HumanReadableCommunity>>, ParseError> {
        self._all_communities::<crate::bgp::communities::HumanReadableCommunity>()
    }
}


impl<Octs: Octets> UpdateMessage<Octs> {
    /// Create an UpdateMessage from an octets sequence.
    ///
    /// The 16 byte marker, length and type byte must be present when parsing,
    /// and will be included from `octets`.
    ///
    /// As parsing of BGP UPDATE messages requires stateful information
    /// signalled by the BGP OPEN messages, this function requires a
    /// [`SessionConfig`].
    pub fn from_octets(octets: Octs, config: &SessionConfig)
        -> Result<Self, ParseError>
    {
        let mut parser = Parser::from_ref(&octets);
        let UpdateMessage{
            withdrawals,
            attributes,
            announcements,
            pdu_parse_info,
            ..
        } = UpdateMessage::<_>::parse(&mut parser, config)?;
        let res  = 
            Self {
                octets,
                withdrawals: (withdrawals.start +19..withdrawals.end + 19),
                attributes: (attributes.start +19..attributes.end + 19),
                announcements: (announcements.start +19..announcements.end + 19),
                pdu_parse_info
            }
        ;

        Ok(res)
    }

    /// Parses an UpdateMessage from `parser`.
    ///
    /// The 16 byte marker, length and type byte must be present when parsing,
    /// but will not be included in the resulting `Octs`.
    pub fn parse<'a, R>(
        parser: &mut Parser<'a, R>,
        session_config: &SessionConfig
    ) -> Result<UpdateMessage<R::Range<'a>>, ParseError>
    where
        R: Octets<Range<'a> = Octs>,
    {

        let header = Header::parse(parser)?;

        if header.length() < 19 {
            return Err(ParseError::form_error("message length <19"))
        }

        if header.msg_type() != MsgType::Update {
            return Err(ParseError::form_error("message not of type UPDATE"))
        }

        let start_pos = parser.pos();

        let withdrawals_len = parser.parse_u16_be()?;
        let withdrawals_start = parser.pos() - start_pos;
        if withdrawals_len > 0 {
            let wdraw_parser = parser.parse_parser(withdrawals_len.into())?;

            if session_config.rx_addpath(AfiSafiType::Ipv4Unicast) {
                NlriIter::ipv4_unicast_addpath(wdraw_parser).validate()?;
            } else {
                NlriIter::ipv4_unicast(wdraw_parser).validate()?;
            }
        }

        let withdrawals_end = parser.pos() - start_pos;
        let withdrawals = withdrawals_start..withdrawals_end;

        // To create PduParseInfo later on:
        let mut mp_reach_afisafi = None;
        let mut mp_unreach_afisafi = None;

        let attributes_len = parser.parse_u16_be()?;
        let attributes_start = parser.pos() - start_pos;
        if attributes_len > 0 {
            let pas_parser = parser.parse_parser(
                attributes_len.into()
            )?;
            // XXX this calls `validate` on every attribute, do we want to
            // error on that level here?
            for pa in PathAttributes::new(pas_parser, PduParseInfo::default()) {
               pa?;
            }

            let pas = UncheckedPathAttributes::from_parser(pas_parser);
            for pa in pas {
                match pa.type_code() {
                    14 => {
                        // MP_REACH_NLRI
                        let mut tmp_parser = pa.value_into_parser();
                        let afi = tmp_parser.parse_u16_be()?;
                        let safi = tmp_parser.parse_u8()?;
                        let afisafi = (afi, safi).into();
                        mp_reach_afisafi = Some(afisafi);
                    }
                    15 => {
                        // MP_UNREACH_NLRI
                        let mut tmp_parser = pa.value_into_parser();
                        let afi = tmp_parser.parse_u16_be()?;
                        let safi = tmp_parser.parse_u8()?;
                        let afisafi = (afi, safi).into();
                        mp_unreach_afisafi = Some(afisafi);
                    }
                    _ => {
                        // Any other attribute else we want to validate or
                        // peek in here already?
                    }
                }
            }
        }

        let attributes_end = parser.pos() - start_pos;
        let attributes = attributes_start..attributes_end;

        if usize::from(attributes_len) != attributes.len() {
            return Err(ParseError::form_error("invalid attributes length"));
        }
        let announcements_start = parser.pos() - start_pos;

        // Subtracting the 19 here is safe as we check for a minimal length of
        // 19 above.
        if announcements_start > header.length() as usize - 19 {
            return Err(ParseError::form_error("invalid path attributes section"));
        }

        let ann_parser = parser.parse_parser(
            header.length() as usize - 19 - (announcements_start)
        )?;

        if session_config.rx_addpath(AfiSafiType::Ipv4Unicast) {
            NlriIter::ipv4_unicast_addpath(ann_parser).validate()?;
        } else {
            NlriIter::ipv4_unicast(ann_parser).validate()?;
        }


        let end_pos = parser.pos() - start_pos;

        let announcements = announcements_start..end_pos;


        if end_pos != (header.length() as usize) - 19 {
            return Err(ParseError::form_error(
                "message length and parsed bytes do not match"
            ));
        }

        parser.seek(start_pos)?;

        let ppi = PduParseInfo::from_session_config(
            session_config,
            mp_reach_afisafi,
            mp_unreach_afisafi
        );

        Ok(UpdateMessage {
            octets: parser.parse_octets((header.length() - 19).into())?,
            withdrawals,
            attributes,
            announcements,
            pdu_parse_info: ppi
        })
    }

    pub fn into_octets(self) -> Octs {
        self.octets
    }


}
//--- Enums for passing config / state ---------------------------------------

//--------- SessionConfig ----------------------------------------------------

/// Configuration parameters for an established BGP session.
///
/// The `SessionConfig` is a structure holding parameters to parse messages
/// for the particular session. Storing these parameters is necessary because
/// some information crucial to correctly parsing BGP UPDATE messages is not
/// available in the UPDATE messages themselves, but are only exchanged in the
/// BGP OPEN messages when the session was established.
///
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct SessionConfig {
    four_octet_asns: FourOctetAsns,
    ipv4unicast_in_mp: Ipv4UnicastInMp,
    addpath_fams: SessionAddpaths,
}

/// Configuration parameters (state) to parse an individual UPDATE message.
///
/// This struct contains a subset of the information that the (non-Copy)
/// `SessionConfig` holds. It is attached to `UpdateMessage` to enable parsing
/// of the path attributes and NLRI.
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct PduParseInfo {
    four_octet_asns: FourOctetAsns,
    pdu_addpaths: PduAddpaths,
}

impl PduParseInfo {

    /// Creates a `PduParseInfo` for 32bit ASNs, no AddPath set.
    pub fn modern() -> Self {
        Self { four_octet_asns: FourOctetAsns(true), pdu_addpaths: PduAddpaths::default() }
    }

    /// Creates a `PduParseInfo` for 16bit ASNs, no AddPath set.
    pub fn legacy() -> Self {
        Self { four_octet_asns: FourOctetAsns(false), pdu_addpaths: PduAddpaths::default() }
    }

    /// Creates a `PduParseInfo` from a `SessionConfig` and address families.
    ///
    /// This constructor takes two optional address families, describing the
    /// `AfiSafi` for the MP_REACH and MP_UNREACH path attributes in the BGP
    /// UPDATE message. These can be used to match upon to get a typed NLRI
    /// iterator (e.g. [`typed_announcements`]) from the message.
    pub fn from_session_config(
        sc: &SessionConfig,
        mp_reach_afisafi: Option<AfiSafiType>,
        mp_unreach_afisafi: Option<AfiSafiType>,
    ) -> Self {
        Self {
            four_octet_asns: sc.four_octet_asns,
            pdu_addpaths: PduAddpaths {
                conventional: sc.rx_addpath(AfiSafiType::Ipv4Unicast),
                mp_reach: mp_reach_afisafi.map(|fam| sc.rx_addpath(fam))
                    .unwrap_or(false),
                mp_unreach: mp_unreach_afisafi.map(|fam| sc.rx_addpath(fam))
                    .unwrap_or(false),
            }
        }
    }

    /// Returns the FourOctetAsns setting.
    pub fn four_octet_asns(&self) -> FourOctetAsns {
        self.four_octet_asns
    }

    /// Returns true if the sessions carries 32bit ASNs.
    pub fn four_octet_enabled(&self) -> bool {
        self.four_octet_asns.0
    }

    /// Returns true if the conventional IPv4 Unicast NLRI are AddPath.
    ///
    /// The conventional IPv4 Unicast NLRI are the withdrawals and
    /// announcements in the dedicated parts of the PDU, as opposed to
    /// MP_UNREACH and MP_REACH path attributes.
    pub fn conventional_addpath(&self) -> bool {
        self.pdu_addpaths.conventional()
    }

    /// Returns true if the announced NLRI in MP_REACH are AddPath.
    pub fn mp_reach_addpath(&self) -> bool {
        self.pdu_addpaths.mp_reach()
    }

    /// Returns true if the withdrawn NLRI in MP_UNREACH are AddPath.
    pub fn mp_unreach_addpath(&self) -> bool {
        self.pdu_addpaths.mp_unreach()
    }
}

impl Default for PduParseInfo {
    fn default() -> Self {
        Self {
            four_octet_asns: FourOctetAsns(true),
            pdu_addpaths: PduAddpaths::default(),
        }
    }
}



/// Describes which sections of the PDU contain AddPath-enabled NLRI.
///
/// As an UPDATE message can be a mix of e.g. AddPath enabled announcements
/// and non AddPath enabled withdrawals, this struct holds booleans for all
/// three sections where AddPath PathIds might or might not occur:
///
///  * the conventional IPv4 Unicast sections in the PDU, which are either
///    both AddPath enabled or not, and,
///
///  * the MP_REACH and MP_UNREACH path attributes, which might carry NLRI for
///    different address families and (thus) might differ in being AddPath
///    enabled or not.
#[derive(Copy, Clone, Default, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
struct PduAddpaths {
    conventional: bool,
    mp_reach: bool,
    mp_unreach: bool,
}

impl PduAddpaths {
    #[allow(dead_code)]
    pub(crate) fn new(conventional: bool, mp_reach: bool, mp_unreach: bool)
        -> Self
    {
        Self { conventional, mp_reach, mp_unreach }
    }

    pub(crate) fn conventional(self) -> bool {
        self.conventional
    }

    pub(crate) fn mp_reach(self) -> bool {
        self.mp_reach
    }

    pub(crate) fn mp_unreach(self) -> bool {
        self.mp_unreach
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
struct SessionAddpaths(HashMap<AfiSafiType, AddpathDirection>);
impl SessionAddpaths {
    fn new() -> Self {
        Self(HashMap::new())
    }

    fn set(&mut self, afisafi: AfiSafiType, dir: AddpathDirection) {
        self.0.insert(afisafi, dir);
    }

    fn get(&self, afisafi: AfiSafiType) -> Option<AddpathDirection> {
        self.0.get(&afisafi).copied()
    }

    fn enabled_addpaths(&self)
        -> impl Iterator<Item = (AfiSafiType, AddpathDirection)> + '_
    {
        self.0.iter().map(|(&k, &v)| (k, v))
    }
}

impl SessionConfig {
    /// Creates a SessionConfig for 32bit ASNs, IPv4 Unicast in MultiProtocol.
    pub fn modern() -> Self {
        Self {
            four_octet_asns: FourOctetAsns(true),
            ipv4unicast_in_mp: Ipv4UnicastInMp(false),
            addpath_fams: SessionAddpaths::new(),
        }
    }

    /// Creates a SessionConfig for 16 bit ASNs.
    pub fn legacy() -> Self {
        Self {
            four_octet_asns: FourOctetAsns(false),
            ipv4unicast_in_mp: Ipv4UnicastInMp(false),
            addpath_fams: SessionAddpaths::new(),
        }
    }

    /// Returns true if IPv4 Unicast is carried as MultiProtocol attribute.
    pub fn ipv4_unicast_in_mp(&self) -> bool {
        self.ipv4unicast_in_mp.0
    }

    /// Returns the FourOctetAsns setting.
    pub fn four_octet_asns(&self) -> FourOctetAsns {
        self.four_octet_asns
    }

    /// Returns true if the sessions carries 32bit ASNs.
    pub fn four_octet_enabled(&self) -> bool {
        self.four_octet_asns.0
    }

    /// Changes the FourOctetAsns setting.
    pub fn set_four_octet_asns(&mut self, v: FourOctetAsns) {
        self.four_octet_asns = v
    }

    /// Sets AddPath in a specific direction for a specific address family.
    pub fn add_addpath(&mut self, fam: AfiSafiType, dir: AddpathDirection) {
        self.addpath_fams.set(fam, dir);
    }

    /// Sets AddPath in a specific direction for a specific address family.
    pub fn add_famdir(&mut self, famdir: AddpathFamDir) {
        self.addpath_fams.set(famdir.fam(), famdir.dir());
    }

    /// Sets AddPath bidirectionally for a specific address family.
    pub fn add_addpath_rxtx(&mut self, fam: AfiSafiType) {
        self.addpath_fams.set(fam, AddpathDirection::SendReceive);
    }

    /// Returns the `AddpathDirection` for this address family, if any.
    pub fn get_addpath(&self, fam: AfiSafiType) -> Option<AddpathDirection> {
        self.addpath_fams.get(fam)
    }

    /// Returns true if incoming NLRI for this address family are AddPath.
    pub fn rx_addpath(&self, fam: AfiSafiType) -> bool {
        if let Some(dir) = self.get_addpath(fam) {
            match dir {
                AddpathDirection::Receive |
                    AddpathDirection::SendReceive => true,
                AddpathDirection::Send => false
            }
        } else {
            false
        }
    }

    /// Returns an iterator for all AddPath-enabled address families.
    pub fn enabled_addpaths(&self)
        -> impl Iterator<Item = (AfiSafiType, AddpathDirection)> + '_
    {
        self.addpath_fams.enabled_addpaths()
    }
    
    /// Set all address families to be not AddPath-enabled.
    pub fn clear_addpaths(&mut self) {
        self.addpath_fams = SessionAddpaths::new()
    }

}

/// Indicates whether this session is Four Octet capable (32bit ASNs).
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct FourOctetAsns(pub bool);

/// Indicates whether Ipv4Unicast NLRI are carried in the MP attribute.
///
/// Upon the introduction of BGP Multi-Protocol (RFC4760, MP_REACH/MP_UNREACH
/// path attributes), IPv4 Unicast NLRI can go in either the new path
/// attributes, or in the conventional sections in the PDU. This boolean
/// indicates where to look.
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Ipv4UnicastInMp(pub bool);

/// Iterator for BGP UPDATE Communities.
///
/// Returns values of enum or struct [`T`], where T wraps or has variants
/// [`StandardCommunity`], [`ExtendedCommunity`], [`LargeCommunity`] or a
/// well-known community. T are most notably `Community` or
/// `HumanReadableCommunity`. In most cases you will need to explicitly state
/// the type of T.
pub struct CommunityIter<Octs: Octets, T> {
    slice: Octs,
    pos: usize,
    _t: PhantomData<T>
}

impl<Octs: Octets, T: From<[u8; 4]>> CommunityIter<Octs, T> {
    fn new(slice: Octs) -> Self {
        CommunityIter { slice, pos: 0, _t: PhantomData }
    }

    fn get_community(&mut self) -> T {
        let mut buf = [0u8; 4];
        buf[..].copy_from_slice(&self.slice.as_ref()[self.pos..self.pos+4]);
        self.pos += 4;
        buf.into()
    }
}

impl<Octs: Octets, T: From<[u8; 4]>> Iterator for CommunityIter<Octs, T> {
    type Item = T;
    
    fn next(&mut self) -> Option<T> {
        if self.pos == self.slice.as_ref().len() {
            return None
        }
        Some(self.get_community())
    }
}

/// Iterator over [`ExtendedCommunity`]s.
pub struct ExtCommunityIter<Octs: Octets> {
    slice: Octs,
    pos: usize,
}

impl<Octs: Octets> ExtCommunityIter<Octs> {
    fn new(slice: Octs) -> Self {
        ExtCommunityIter { slice, pos: 0 }
    }

    fn get_community(&mut self) -> ExtendedCommunity {
        let res = ExtendedCommunity::from_raw(
            self.slice.as_ref()[self.pos..self.pos+8].try_into().expect("parsed before")
            );
        self.pos += 8;
        res
    }
}

impl<Octs: Octets> Iterator for ExtCommunityIter<Octs> {
    type Item = ExtendedCommunity;

    fn next(&mut self) -> Option<ExtendedCommunity> {
        if self.pos == self.slice.as_ref().len() {
            return None
        }
        Some(self.get_community())
    }
}

/// Iterator over [`Ipv6ExtendedCommunity`]s.
pub struct Ipv6ExtCommunityIter<Octs: Octets> {
    slice: Octs,
    pos: usize,
}

impl<Octs: Octets> Ipv6ExtCommunityIter<Octs> {
    fn new(slice: Octs) -> Self {
        Ipv6ExtCommunityIter { slice, pos: 0 }
    }

    fn get_community(&mut self) -> Ipv6ExtendedCommunity {
        let res = Ipv6ExtendedCommunity::from_raw(
            self.slice.as_ref()[self.pos..self.pos+20].try_into().expect("parsed before")
            );
        self.pos += 20;
        res
    }
}

impl<Octs: Octets> Iterator for Ipv6ExtCommunityIter<Octs> {
    type Item = Ipv6ExtendedCommunity;

    fn next(&mut self) -> Option<Ipv6ExtendedCommunity> {
        if self.pos == self.slice.as_ref().len() {
            return None
        }
        Some(self.get_community())
    }
}

/// Iterator over [`LargeCommunity`]s.
pub struct LargeCommunityIter<Octs: Octets> {
    slice: Octs,
    pos: usize,
}

impl<Octs: Octets> LargeCommunityIter<Octs> {
    fn new(slice: Octs) -> Self {
        LargeCommunityIter { slice, pos: 0 }
    }

    fn get_community(&mut self) -> LargeCommunity {
        let res = LargeCommunity::from_raw(
            self.slice.as_ref()[self.pos..self.pos+12].try_into().expect("parsed before")
            );
        self.pos += 12;
        res
    }
}

impl<Octs: Octets> Iterator for LargeCommunityIter<Octs> {
    type Item = LargeCommunity;

    fn next(&mut self) -> Option<LargeCommunity> {
        if self.pos == self.slice.as_ref().len() {
            return None
        }
        Some(self.get_community())
    }
}

//--- Tests ------------------------------------------------------------------

#[cfg(test)]
mod tests {

    use super::*;
    use std::str::FromStr;
    use std::net::Ipv6Addr;
    use crate::bgp::communities::{
        StandardCommunity,
        ExtendedCommunityType,
        ExtendedCommunitySubType,
        Tag, Wellknown,
    };

    use crate::bgp::nlri::afisafi::{AfiSafiNlri, Nlri, Ipv4UnicastNlri, Ipv4MulticastNlri};
    use crate::bgp::types::{PathId, RouteDistinguisher};
    use crate::bgp::message::Message;
    use inetnum::addr::Prefix;



    use bytes::Bytes;

    #[allow(dead_code)]
    fn print_pcap<T: AsRef<[u8]>>(buf: T) {
        print!("000000 ");
        for b in buf.as_ref() {
            print!("{:02x} ", b);
        }
        println!();
    }


    //TODO:
    // X generic
    // - incomplete msg
    // - path attributes:
    //   - aspath
    //   - attributeset
    // - announcements:
    //   X single conventional
    //   X multiple conventional 
    //   x bgp-mp
    // - withdrawals
    //   - single conventional
    //   X multiple conventional
    //   x bgp-mp
    // - communities
    //   x normal
    //   x extended
    //   x large
    //   x chained iter
    // - MP NLRI types:
    //   announcements:
    //   x v4 mpls unicast
    //   - v4 mpls unicast unreach **missing**
    //   - v4 mpls vpn unicast
    //   - v6 mpls unicast addpath 
    //   X v6 mpls vpn unicast
    //   - multicast **missing
    //   - vpls
    //   - flowspec
    //   - routetarget
    //   withdrawals:
    //   - v4 mpls vpn unicast unreach
    //   - v6 mpls unicast addpath unreach
    //   - v6 mpls vpn unicast
    //
    //
    // x legacy stuff:
    //    as4path
    //


    #[test]
    fn incomplete_msg() {
        let buf = vec![
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0x00, 0x88, 0x02, 
        ];
        assert!(Message::from_octets(&buf, None).is_err());
    }

    #[test]
    fn conventional() {
        let buf = vec![
            // BGP UPDATE, single conventional announcement, MultiExitDisc
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x37, 0x02,
            0x00, 0x00, 0x00, 0x1b, 0x40, 0x01, 0x01, 0x00, 0x40, 0x02,
            0x06, 0x02, 0x01, 0x00, 0x01, 0x00, 0x00, 0x40, 0x03, 0x04,
            0x0a, 0xff, 0x00, 0x65, 0x80, 0x04, 0x04, 0x00, 0x00, 0x00,
            0x01, 0x20, 0x0a, 0x0a, 0x0a, 0x02
        ];

        //let update: UpdateMessage<_> = parse_msg(&buf);
        let bytes = Bytes::from(buf);
        let update: UpdateMessage<_> = Message::from_octets(
            bytes,
            Some(&SessionConfig::modern())
            ).unwrap().try_into().unwrap();

        assert_eq!(update.length(), 55);
        assert_eq!(update.total_path_attribute_len(), 27);

        //let mut pa_iter = update.path_attributes().iter();
        let pas = update.path_attributes().unwrap();
        let mut pa_iter = pas.into_iter();

        let pa1 = pa_iter.next().unwrap().unwrap();
        assert_eq!(pa1.type_code(), u8::from(PathAttributeType::Origin));
        assert_eq!(pa1.flags(), 0x40.into());
        assert!(!pa1.flags().is_optional());
        assert!(pa1.flags().is_transitive());
        assert!(!pa1.flags().is_partial());
        assert!(!pa1.flags().is_extended_length());

        assert_eq!(pa1.length(), 1);

        let pa2 = pa_iter.next().unwrap().unwrap();
        assert_eq!(pa2.type_code(), u8::from(PathAttributeType::AsPath));
        assert_eq!(pa2.flags(), 0x40.into());
        assert_eq!(pa2.length(), 6);

        //assert_eq!(pa2.as_ref(), [0x02, 0x01, 0x00, 0x01, 0x00, 0x00]);

        let mut pb = crate::bgp::aspath::HopPath::new();
        pb.prepend(Asn::from_u32(65536));
        let asp: AsPath<Bytes> = pb.to_as_path().unwrap();

        assert_eq!(update.aspath().unwrap().unwrap(), asp);

        let pa3 = pa_iter.next().unwrap().unwrap();
        assert_eq!(pa3.type_code(), u8::from(PathAttributeType::ConventionalNextHop));
        assert_eq!(pa3.flags(), 0x40.into());
        assert_eq!(pa3.length(), 4);
        //assert_eq!(pa3.as_ref(), &[10, 255, 0, 101]);
        assert_eq!(
            update.conventional_next_hop().unwrap(),
            Some(NextHop::Unicast(Ipv4Addr::new(10, 255, 0, 101).into()))
            );

        let pa4 = pa_iter.next().unwrap().unwrap();
        assert_eq!(pa4.type_code(), u8::from(PathAttributeType::MultiExitDisc));
        assert_eq!(pa4.flags(), 0x80.into());
        assert!( pa4.flags().is_optional());
        assert!(!pa4.flags().is_transitive());
        assert!(!pa4.flags().is_partial());
        assert!(!pa4.flags().is_extended_length());
        assert_eq!(pa4.length(), 4);
        //assert_eq!(pa4.as_ref(), &[0x00, 0x00, 0x00, 0x01]);
        assert_eq!(update.multi_exit_disc().unwrap(), Some(MultiExitDisc(1)));

        assert!(pa_iter.next().is_none());

        let mut nlri_iter = update.announcements().unwrap();
        let nlri1 = nlri_iter.next().unwrap();

        let unwrapped = nlri1.unwrap();
        let tmp_n =  Ipv4UnicastNlri::try_from(Prefix::from_str("10.10.10.2/32").unwrap()).unwrap();
        let tmp_n2 = Nlri::<&[u8]>::from(tmp_n);

        assert_eq!(unwrapped, tmp_n2);
        assert!(nlri_iter.next().is_none());
    }

    #[test]
    fn conventional_parsed() {
        let buf = vec![
            // Two BGP UPDATEs
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x37, 0x02,
            0x00, 0x00, 0x00, 0x1b, 0x40, 0x01, 0x01, 0x00, 0x40, 0x02,
            0x06, 0x02, 0x01, 0x00, 0x01, 0x00, 0x00, 0x40, 0x03, 0x04,
            0x0a, 0xff, 0x00, 0x65, 0x80, 0x04, 0x04, 0x00, 0x00, 0x00,
            0x01, 0x20, 0x0a, 0x0a, 0x0a, 0x02,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0x00, 0x3c, 0x02, 0x00, 0x00, 0x00, 0x1b, 0x40,
            0x01, 0x01, 0x00, 0x40, 0x02, 0x06, 0x02, 0x01,
            0x00, 0x01, 0x00, 0x00, 0x40, 0x03, 0x04, 0x0a,
            0xff, 0x00, 0x65, 0x80, 0x04, 0x04, 0x00, 0x00,
            0x07, 0x6c, 0x20, 0x0a, 0x0a, 0x0a, 0x09, 0x1e,
            0xc0, 0xa8, 0x61, 0x00
        ];

        let bytes = Bytes::from(buf);
        let mut parser = Parser::from_ref(&bytes);
        let update = UpdateMessage::parse(
            &mut parser,
            &SessionConfig::modern()
        ).unwrap();

        update.print_pcap();
        assert_eq!(update.length(), 55);
        assert_eq!(update.total_path_attribute_len(), 27);

        let update = UpdateMessage::parse(
            &mut parser,
            &SessionConfig::modern(),
        ).unwrap();

        update.print_pcap();
        assert_eq!(update.total_path_attribute_len(), 27);
        assert_eq!(update.announcements().unwrap().count(), 2);
        
    }

    use std::fs::File;
    use memmap2::Mmap;

    #[test]
    #[ignore]
    fn parse_bulk() {
        let filename = "examples/raw_bgp_updates";
        let file = File::open(filename).unwrap();
        let mmap = unsafe { Mmap::map(&file).unwrap()  };
        let fh = &mmap[..];
        let mut parser = Parser::from_ref(&fh);

        let mut n = 0;
        const MAX: usize = 10_000_000;

        while parser.remaining() > 0 && n < MAX {
            if let Err(e) = UpdateMessage::<_>::parse(
                &mut parser, &SessionConfig::modern(),
            ) {
                eprintln!("failed to parse: {e}");
            }
            n += 1;
            eprint!("\r{n} ");
        }
        eprintln!("parsed {n}");
        //dbg!(parser);
    }


    #[test]
    fn conventional_multiple_nlri() {
        let buf = vec![
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0x00, 0x3c, 0x02, 0x00, 0x00, 0x00, 0x1b, 0x40,
            0x01, 0x01, 0x00, 0x40, 0x02, 0x06, 0x02, 0x01,
            0x00, 0x01, 0x00, 0x00, 0x40, 0x03, 0x04, 0x0a,
            0xff, 0x00, 0x65, 0x80, 0x04, 0x04, 0x00, 0x00,
            0x07, 0x6c, 0x20, 0x0a, 0x0a, 0x0a, 0x09, 0x1e,
            0xc0, 0xa8, 0x61, 0x00
        ];

        //let update: UpdateMessage<_> = parse_msg(&buf);
        let update: UpdateMessage<_> = Message::from_octets(
            &buf,
            Some(&SessionConfig::modern())
        ).unwrap().try_into().unwrap();

        assert_eq!(update.total_path_attribute_len(), 27);
        assert_eq!(update.announcements().unwrap().count(), 2);
        let prefixes = ["10.10.10.9/32", "192.168.97.0/30"]
            .map(|p| Nlri::unicast_from_str(p).unwrap());

        assert!(prefixes.into_iter().eq(update.announcements().unwrap().map(|n| n.unwrap())));

    }

    #[test]
    fn multiple_mp_reach() {
        // BGP UPDATE message containing MP_REACH_NLRI path attribute,
        // comprising 5 IPv6 NLRIs
        let buf = vec![
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0x00, 0x88, 0x02, 0x00, 0x00, 0x00, 0x71, 0x80,
            0x0e, 0x5a, 0x00, 0x02, 0x01, 0x20, 0xfc, 0x00,
            0x00, 0x10, 0x00, 0x01, 0x00, 0x10, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0xfe, 0x80,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80,
            0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,
            0x40, 0x20, 0x01, 0x0d, 0xb8, 0xff, 0xff, 0x00,
            0x00, 0x40, 0x20, 0x01, 0x0d, 0xb8, 0xff, 0xff,
            0x00, 0x01, 0x40, 0x20, 0x01, 0x0d, 0xb8, 0xff,
            0xff, 0x00, 0x02, 0x40, 0x20, 0x01, 0x0d, 0xb8,
            0xff, 0xff, 0x00, 0x03, 0x40, 0x01, 0x01, 0x00,
            0x40, 0x02, 0x06, 0x02, 0x01, 0x00, 0x00, 0x00,
            0xc8, 0x80, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00
        ];
        let update = UpdateMessage::from_octets(
            &buf,
            &SessionConfig::modern()
        ).unwrap();

        assert_eq!(update.withdrawn_routes_len(), 0);
        assert_eq!(update.total_path_attribute_len(), 113);

        assert!(!update.has_conventional_nlri());
        assert!(update.has_mp_nlri().unwrap());
        
        let nlri_iter = update.announcements().unwrap();
        assert_eq!(nlri_iter.count(), 5);

        let prefixes = [
            "fc00::10/128",
            "2001:db8:ffff::/64",
            "2001:db8:ffff:1::/64",
            "2001:db8:ffff:2::/64",
            "2001:db8:ffff:3::/64",
        ].map(|p| Nlri::unicast_from_str(p).unwrap());

        assert!(prefixes.clone().into_iter().eq(
                update.announcements().unwrap().map(|n| n.unwrap())
        ));

        assert!(prefixes.into_iter().eq(
                update.announcements_vec().unwrap().into_iter()
        ));

        assert!(update.find_next_hop(AfiSafiType::Ipv6Multicast).is_err());

    }

    #[test]
    fn conventional_withdrawals() {
        // BGP UPDATE with 12 conventional withdrawals
        let buf = vec![
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0x00, 0x53, 0x02, 0x00, 0x3c, 0x20, 0x0a, 0x0a,
            0x0a, 0x0a, 0x1e, 0xc0, 0xa8, 0x00, 0x1c, 0x20,
            0x0a, 0x0a, 0x0a, 0x65, 0x1e, 0xc0, 0xa8, 0x00,
            0x18, 0x20, 0x0a, 0x0a, 0x0a, 0x09, 0x20, 0x0a,
            0x0a, 0x0a, 0x08, 0x1e, 0xc0, 0xa8, 0x61, 0x00,
            0x20, 0x0a, 0x0a, 0x0a, 0x66, 0x1e, 0xc0, 0xa8,
            0x00, 0x20, 0x1e, 0xc0, 0xa8, 0x62, 0x00, 0x1e,
            0xc0, 0xa8, 0x00, 0x10, 0x1e, 0xc0, 0xa8, 0x63,
            0x00, 0x00, 0x00
        ];
        //let update: UpdateMessage<_> = parse_msg(&buf);
        let update: UpdateMessage<_> = Message::from_octets(
            &buf,
            Some(&SessionConfig::modern())
            ).unwrap().try_into().unwrap();

        assert_eq!(update.withdrawals().unwrap().count(), 12);

        let ws = [
            "10.10.10.10/32",
            "192.168.0.28/30",
            "10.10.10.101/32",
            "192.168.0.24/30",
            "10.10.10.9/32",
            "10.10.10.8/32",
            "192.168.97.0/30",
            "10.10.10.102/32",
            "192.168.0.32/30",
            "192.168.98.0/30",
            "192.168.0.16/30",
            "192.168.99.0/30",
        ].map(|w| Ok(Nlri::unicast_from_str(w).unwrap()));

        assert!(ws.into_iter().eq(update.withdrawals().unwrap()));
    }

    #[test]
    fn multiple_mp_unreach() {
        // BGP UPDATE with 4 MP_UNREACH_NLRI
        let buf = vec![
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0x00, 0x41, 0x02, 0x00, 0x00, 0x00, 0x2a, 0x80,
            0x0f, 0x27, 0x00, 0x02, 0x01, 0x40, 0x20, 0x01,
            0x0d, 0xb8, 0xff, 0xff, 0x00, 0x00, 0x40, 0x20,
            0x01, 0x0d, 0xb8, 0xff, 0xff, 0x00, 0x01, 0x40,
            0x20, 0x01, 0x0d, 0xb8, 0xff, 0xff, 0x00, 0x02,
            0x40, 0x20, 0x01, 0x0d, 0xb8, 0xff, 0xff, 0x00,
            0x03
        ];
        //let update: UpdateMessage<_> = parse_msg(&buf);
        let update: UpdateMessage<_> = Message::from_octets(
            &buf,
            Some(&SessionConfig::modern())
            ).unwrap().try_into().unwrap();

        assert_eq!(update.withdrawals().unwrap().count(), 4);

        let ws = [
            "2001:db8:ffff::/64",
            "2001:db8:ffff:1::/64",
            "2001:db8:ffff:2::/64",
            "2001:db8:ffff:3::/64",
        ].map(|w| Ok(Nlri::unicast_from_str(w).unwrap()));
        assert!(ws.into_iter().eq(update.withdrawals().unwrap()));
    }

    //--- Path Attributes ------------------------------------------------

    #[test]
    fn local_pref_multi_exit_disc() {
        // BGP UPDATE with 5 conventional announcements, MULTI_EXIT_DISC
        // and LOCAL_PREF path attributes
        let buf = vec![
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0x00, 0x60, 0x02, 0x00, 0x00, 0x00, 0x30, 0x40,
            0x01, 0x01, 0x00, 0x40, 0x02, 0x14, 0x03, 0x01,
            0x00, 0x00, 0xfd, 0xea, 0x02, 0x03, 0x00, 0x00,
            0x01, 0x90, 0x00, 0x00, 0x01, 0x2c, 0x00, 0x00,
            0x01, 0xf4, 0x40, 0x03, 0x04, 0x0a, 0x04, 0x05,
            0x05, 0x80, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00,
            0x40, 0x05, 0x04, 0x00, 0x00, 0x00, 0x64, 0x20,
            0x0a, 0x00, 0x00, 0x09, 0x1a, 0xc6, 0x33, 0x64,
            0x00, 0x1a, 0xc6, 0x33, 0x64, 0x40, 0x1a, 0xc6,
            0x33, 0x64, 0x80, 0x1a, 0xc6, 0x33, 0x64, 0xc0
        ];
        //let update: UpdateMessage<_> = parse_msg(&buf);
        let update: UpdateMessage<_> = Message::from_octets(
            &buf,
            Some(&SessionConfig::modern())
            ).unwrap().try_into().unwrap();
        assert_eq!(update.multi_exit_disc().unwrap(), Some(MultiExitDisc(0)));
        assert_eq!(update.local_pref().unwrap(), Some(LocalPref(100)));
    }

    #[test]
    fn atomic_aggregate() {
        // BGP UPDATE with AGGREGATOR and ATOMIC_AGGREGATE
        let buf = vec![
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0x00, 0x44, 0x02, 0x00, 0x00, 0x00, 0x29, 0x40,
            0x01, 0x01, 0x00, 0x40, 0x02, 0x06, 0x02, 0x01,
            0x00, 0x00, 0x00, 0x65, 0xc0, 0x07, 0x08, 0x00,
            0x00, 0x00, 0x65, 0xc6, 0x33, 0x64, 0x01, 0x40,
            0x06, 0x00, 0x40, 0x03, 0x04, 0x0a, 0x01, 0x02,
            0x01, 0x80, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00,
            0x18, 0xc6, 0x33, 0x64
        ];
        //let update: UpdateMessage<_> = parse_msg(&buf);
        let update: UpdateMessage<_> = Message::from_octets(
            &buf,
            Some(&SessionConfig::modern())
            ).unwrap().try_into().unwrap();
        let aggr = update.aggregator().unwrap();

        assert!(update.is_atomic_aggregate().unwrap());
        assert_eq!(aggr.unwrap().asn(), Asn::from(101));
        assert_eq!(
            aggr.unwrap().address(),
            Ipv4Addr::from_str("198.51.100.1").unwrap()
            );
    }

    #[test]
    fn as4path() {
        // BGP UPDATE with AS_PATH and AS4_PATH, both containing one
        // SEQUENCE of length 10. First four in AS_PATH are actual ASNs,
        // last six are AS_TRANS.
        let buf = vec![
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0x00, 0x6e, 0x02, 0x00, 0x00, 0x00, 0x53, 0x40,
            0x01, 0x01, 0x00, 0x50, 0x02, 0x00, 0x16, 0x02,
            0x0a, 0xfb, 0xf0, 0xfb, 0xf1, 0xfb, 0xf2, 0xfb,
            0xf3, 0x5b, 0xa0, 0x5b, 0xa0, 0x5b, 0xa0, 0x5b,
            0xa0, 0x5b, 0xa0, 0x5b, 0xa0, 0x40, 0x03, 0x04,
            0xc0, 0xa8, 0x01, 0x01, 0xd0, 0x11, 0x00, 0x2a,
            0x02, 0x0a, 0x00, 0x00, 0xfb, 0xf0, 0x00, 0x00,
            0xfb, 0xf1, 0x00, 0x00, 0xfb, 0xf2, 0x00, 0x00,
            0xfb, 0xf3, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
            0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
            0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01,
            0x00, 0x0a, 0x16, 0x0a, 0x01, 0x04
        ];

        let sc = SessionConfig::legacy();
        let update: UpdateMessage<_> = Message::from_octets(&buf, Some(&sc))
            .unwrap().try_into().unwrap();

        update.path_attributes().iter();//.count();
        if let Some(Ok(aspath)) = update.path_attributes().unwrap()
            .find(|pa| pa.as_ref().unwrap().type_code() == u8::from(PathAttributeType::AsPath))
        {
            assert_eq!(aspath.flags(), 0x50.into());
            assert!(aspath.flags().is_transitive());
            assert!(aspath.flags().is_extended_length());
            assert_eq!(aspath.length(), 22);
            //TODO check actual aspath
        } else {
            panic!("ASPATH path attribute not found")
        }

        if let Some(Ok(as4path)) = update.path_attributes().unwrap()
            .find(|pa| pa.as_ref().unwrap().type_code() == u8::from(PathAttributeType::As4Path))
        {
            assert_eq!(as4path.flags(), 0xd0.into());
            assert_eq!(as4path.length(), 42);
            //TODO check actual aspath
        } else {
            panic!("AS4PATH path attribute not found")
        }

        assert_eq!(
            update.aspath().unwrap().unwrap().hops().collect::<Vec<_>>(),
            AsPath::vec_from_asns([
                0xfbf0, 0xfbf1, 0xfbf2, 0xfbf3, 0x5ba0, 0x5ba0,
                0x5ba0, 0x5ba0, 0x5ba0, 0x5ba0
            ]).hops().collect::<Vec<_>>(),
        );
        assert_eq!(
            update.as4path().unwrap().unwrap().hops().collect::<Vec<_>>(),
            AsPath::vec_from_asns([
                0xfbf0, 0xfbf1, 0xfbf2, 0xfbf3, 0x10000, 0x10000,
                0x10000, 0x10000, 0x10001, 0x1000a,
            ]).hops().collect::<Vec<_>>(),
        );
    }

    //--- Communities ----------------------------------------------------

    #[test]
    fn pa_communities() {
        // BGP UPDATE with 9 path attributes for 1 NLRI with Path Id,
        // includes both normal communities and extended communities.
        let buf = vec![
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0x00, 0x82, 0x02, 0x00, 0x00, 0x00, 0x62, 0x40,
            0x01, 0x01, 0x00, 0x40, 0x02, 0x16, 0x02, 0x05,
            0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x01, 0x2d,
            0x00, 0x00, 0x01, 0x2c, 0x00, 0x00, 0x02, 0x58,
            0x00, 0x00, 0x02, 0xbc, 0x40, 0x03, 0x04, 0x0a,
            0x01, 0x03, 0x01, 0x80, 0x04, 0x04, 0x00, 0x00,
            0x00, 0x00, 0x40, 0x05, 0x04, 0x00, 0x00, 0x00,
            0x64, 0xc0, 0x08, 0x0c, 0x00, 0x2a, 0x02, 0x06,
            0xff, 0xff, 0xff, 0x01, 0xff, 0xff, 0xff, 0x03,
            0xc0, 0x10, 0x10, 0x00, 0x06, 0x00, 0x00, 0x44,
            0x9c, 0x40, 0x00, 0x40, 0x04, 0x00, 0x00, 0x44,
            0x9c, 0x40, 0x00, 0x80, 0x0a, 0x04, 0x0a, 0x00,
            0x00, 0x04, 0x80, 0x09, 0x04, 0x0a, 0x00, 0x00,
            0x03, 0x00, 0x00, 0x00, 0x01, 0x19, 0xc6, 0x33,
            0x64, 0x00
        ];
        let mut sc = SessionConfig::modern();
        sc.add_addpath(AfiSafiType::Ipv4Unicast, AddpathDirection::Receive);
        let upd: UpdateMessage<_> = Message::from_octets(&buf, Some(&sc))
            .unwrap().try_into().unwrap();

        let nlri1 = upd.announcements().unwrap().next().unwrap();
        assert_eq!(
            nlri1.unwrap(),
            Nlri::<&[u8]>::from(
                Ipv4UnicastNlri::from_str("198.51.100.0/25").unwrap()
                .into_addpath(PathId(1))
            )
        );

        assert!(upd.communities().unwrap().is_some());
        for c in upd.communities().unwrap().unwrap() { 
            println!("{:?}", c);
        }
        assert!(upd.communities().unwrap().unwrap()
            .eq([
                StandardCommunity::new(42.into(), Tag::new(518)).into(),
                Wellknown::NoExport.into(),
                Wellknown::NoExportSubconfed.into()
            ])
        );

        assert!(upd.ext_communities().unwrap().is_some());
        let mut ext_comms = upd.ext_communities().unwrap().unwrap();
        let ext_comm1 = ext_comms.next().unwrap();
        assert!(ext_comm1.is_transitive());

        assert_eq!(
            ext_comm1.types(),
            (ExtendedCommunityType::TransitiveTwoOctetSpecific,
             ExtendedCommunitySubType::OtherSubType(0x06))
            );

        use inetnum::asn::Asn16;
        assert_eq!(ext_comm1.as2(), Some(Asn16::from_u16(0)));

        let ext_comm2 = ext_comms.next().unwrap();
        assert!(!ext_comm2.is_transitive());
        assert_eq!(
            ext_comm2.types(),
            (ExtendedCommunityType::NonTransitiveTwoOctetSpecific,
             ExtendedCommunitySubType::OtherSubType(0x04))
            );
        assert_eq!(ext_comm2.as2(), Some(Asn16::from_u16(0)));

        assert!(ext_comms.next().is_none());

    }

    #[test]
    fn large_communities() {
        // BGP UPDATE with several path attributes, including Large
        // Communities with three communities: 65536:1:1, 65536:1:2, 65536:1:3
        let buf = vec![
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0x00, 0x57, 0x02, 0x00, 0x00, 0x00, 0x3b, 0x40,
            0x01, 0x01, 0x00, 0x40, 0x02, 0x06, 0x02, 0x01,
            0x00, 0x01, 0x00, 0x00, 0x40, 0x03, 0x04, 0xc0,
            0x00, 0x02, 0x02, 0xc0, 0x20, 0x24, 0x00, 0x01,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
            0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
            0x00, 0x03, 0x20, 0xcb, 0x00, 0x71, 0x0d
        ];
        let update: UpdateMessage<_> = Message::from_octets(
            &buf,
            Some(&SessionConfig::modern())
            ).unwrap().try_into().unwrap();

        let mut lcs = update.large_communities().unwrap().unwrap();
        let lc1 = lcs.next().unwrap();
        assert_eq!(lc1.global(), 65536);
        assert_eq!(lc1.local1(), 1);
        assert_eq!(lc1.local2(), 1);

        let lc2 = lcs.next().unwrap();
        assert_eq!(lc2.global(), 65536);
        assert_eq!(lc2.local1(), 1);
        assert_eq!(lc2.local2(), 2);

        let lc3 = lcs.next().unwrap();
        assert_eq!(lc3.global(), 65536);
        assert_eq!(lc3.local1(), 1);
        assert_eq!(lc3.local2(), 3);

        assert_eq!(format!("{}", lc3), "65536:1:3");

        assert!(lcs.next().is_none());

    }

    #[test]
    fn chained_community_iters() {
        let buf = vec![
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0x00, 0x82, 0x02, 0x00, 0x00, 0x00, 0x62, 0x40,
            0x01, 0x01, 0x00, 0x40, 0x02, 0x16, 0x02, 0x05,
            0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x01, 0x2d,
            0x00, 0x00, 0x01, 0x2c, 0x00, 0x00, 0x02, 0x58,
            0x00, 0x00, 0x02, 0xbc, 0x40, 0x03, 0x04, 0x0a,
            0x01, 0x03, 0x01, 0x80, 0x04, 0x04, 0x00, 0x00,
            0x00, 0x00, 0x40, 0x05, 0x04, 0x00, 0x00, 0x00,
            0x64, 0xc0, 0x08, 0x0c, 0x00, 0x2a, 0x02, 0x06,
            0xff, 0xff, 0xff, 0x01, 0xff, 0xff, 0xff, 0x03,
            0xc0, 0x10, 0x10, 0x00, 0x06, 0x00, 0x00, 0x44,
            0x9c, 0x40, 0x00, 0x40, 0x04, 0x00, 0x00, 0x44,
            0x9c, 0x40, 0x00, 0x80, 0x0a, 0x04, 0x0a, 0x00,
            0x00, 0x04, 0x80, 0x09, 0x04, 0x0a, 0x00, 0x00,
            0x03, 0x00, 0x00, 0x00, 0x01, 0x19, 0xc6, 0x33,
            0x64, 0x00
        ];
        let mut sc = SessionConfig::modern();
        sc.add_addpath(AfiSafiType::Ipv4Unicast, AddpathDirection::Receive);
        let upd: UpdateMessage<_> = Message::from_octets(&buf, Some(&sc))
            .unwrap().try_into().unwrap();

        for c in upd.all_communities().unwrap().unwrap() {
            println!("{}", c);
        }
        assert!(upd.all_communities().unwrap().unwrap()
            .eq(&[
                StandardCommunity::new(42.into(), Tag::new(518)).into(),
                Wellknown::NoExport.into(),
                Wellknown::NoExportSubconfed.into(),
                [0x00, 0x06, 0x00, 0x00, 0x44, 0x9c, 0x40, 0x00].into(),
                [0x40, 0x04, 0x00, 0x00, 0x44, 0x9c, 0x40, 0x00].into(),
        ]))
    }

    #[test]
    fn bgpsec() {
        let buf = vec![
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0x00, 0xab, 0x02, 0x00, 0x00, 0x00, 0x94, 0x90,
            0x0e, 0x00, 0x11, 0x00, 0x01, 0x01, 0x04, 0xac,
            0x12, 0x00, 0x02, 0x00, 0x18, 0xc0, 0x00, 0x02,
            0x18, 0xc0, 0x00, 0x03, 0x40, 0x01, 0x01, 0x00,
            0x40, 0x03, 0x04, 0x00, 0x00, 0x00, 0x00, 0x80,
            0x04, 0x04, 0x00, 0x00, 0x00, 0x00, 0x90, 0x21,
            0x00, 0x69, 0x00, 0x08, 0x01, 0x00, 0x00, 0x00,
            0xfb, 0xf0, 0x00, 0x61, 0x01, 0xab, 0x4d, 0x91,
            0x0f, 0x55, 0xca, 0xe7, 0x1a, 0x21, 0x5e, 0xf3,
            0xca, 0xfe, 0x3a, 0xcc, 0x45, 0xb5, 0xee, 0xc1,
            0x54, 0x00, 0x48, 0x30, 0x46, 0x02, 0x21, 0x00,
            0xe7, 0xb7, 0x0b, 0xaf, 0x00, 0x0d, 0xe1, 0xce,
            0x8b, 0xb2, 0x11, 0xaf, 0xd4, 0x8f, 0xc3, 0x76,
            0x59, 0x54, 0x3e, 0xa5, 0x80, 0x5c, 0xa2, 0xa2,
            0x06, 0x3a, 0xc9, 0x2e, 0x12, 0xfa, 0xc0, 0x67,
            0x02, 0x21, 0x00, 0xa5, 0x8c, 0x0f, 0x37, 0x0e,
            0xe9, 0x77, 0xae, 0xd4, 0x11, 0xbd, 0x3f, 0x0f,
            0x47, 0xbb, 0x1f, 0x38, 0xcf, 0xde, 0x09, 0x49,
            0xd5, 0x97, 0xcd, 0x2e, 0x41, 0xa4, 0x8a, 0x94,
            0x1b, 0x7e, 0xbf
            ];

        let mut sc = SessionConfig::modern();
        sc.add_addpath(AfiSafiType::Ipv4Unicast, AddpathDirection::Receive);
        let _upd: UpdateMessage<_> = Message::from_octets(&buf, Some(&sc))
            .unwrap().try_into().unwrap();
        //for pa in upd.path_attributes() {
        //    println!("{}", pa.type_code());
        //    println!("{:#x?}", pa.value());
        //}
    }

    #[test]
    fn mp_ipv4_multicast() {
        let buf = vec![
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0x00, 0x52, 0x02, 0x00, 0x00, 0x00, 0x3b, 0x80,
            0x0e, 0x1d, 0x00, 0x01, 0x02, 0x04, 0x0a, 0x09,
            0x0a, 0x09, 0x00, 0x1a, 0xc6, 0x33, 0x64, 0x00,
            0x1a, 0xc6, 0x33, 0x64, 0x40, 0x1a, 0xc6, 0x33,
            0x64, 0x80, 0x1a, 0xc6, 0x33, 0x64, 0xc0, 0x40,
            0x01, 0x01, 0x00, 0x40, 0x02, 0x06, 0x02, 0x01,
            0x00, 0x00, 0x01, 0xf4, 0x40, 0x03, 0x04, 0x0a,
            0x09, 0x0a, 0x09, 0x80, 0x04, 0x04, 0x00, 0x00,
            0x00, 0x00
        ];
        let sc = SessionConfig::modern();
        let upd: UpdateMessage<_> = Message::from_octets(&buf, Some(&sc))
            .unwrap().try_into().unwrap();
        assert_eq!(
            upd.mp_announcements().unwrap().unwrap().afi_safi(),
            AfiSafiType::Ipv4Multicast
        );
        let prefixes = [
            "198.51.100.0/26",
            "198.51.100.64/26",
            "198.51.100.128/26",
            "198.51.100.192/26",
        ].map(|p| Nlri::<&[u8]>::Ipv4Multicast(
                Ipv4MulticastNlri::from_str(p).unwrap()
        ));

        assert!(prefixes.into_iter().eq(upd.announcements().unwrap().map(|n| n.unwrap())));
    }

    #[test]
    fn mp_unreach_ipv4_multicast() {
        let buf = vec![
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0x00, 0x1d+5, 0x02, 0x00, 0x00, 0x00, 0x06+5, 0x80,
            0x0f, 0x03+5, 0x00, 0x01, 0x02,
            0x1a, 0xc6, 0x33, 0x64, 0x00
        ]; 
        let sc = SessionConfig::modern();
        let upd: UpdateMessage<_> = Message::from_octets(&buf, Some(&sc))
            .unwrap().try_into().unwrap();
        assert_eq!(
            upd.mp_withdrawals().unwrap().unwrap().afi_safi(),
            AfiSafiType::Ipv4Multicast
        );
        assert_eq!(upd.mp_withdrawals().unwrap().iter().count(), 1);
    }

    #[test]
    fn evpn() {
        let buf = vec![
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0x00, 0x89, 0x02, 0x00, 0x00, 0x00, 0x72, 0x40,
            0x01, 0x01, 0x00, 0x40, 0x02, 0x00, 0x40, 0x05,
            0x04, 0x00, 0x00, 0x00, 0x64, 0xc0, 0x10, 0x08,
            0x00, 0x02, 0x00, 0x64, 0x00, 0x00, 0x00, 0x64,
            0x80, 0x09, 0x04, 0x78, 0x00, 0x02, 0x05, 0x80,
            0x0a, 0x04, 0x78, 0x00, 0x01, 0x01, 0x90, 0x0e,
            0x00, 0x47, 0x00, 0x19, 0x46, 0x04, 0x78, 0x00,
            0x02, 0x05, 0x00, 0x01, 0x19, 0x00, 0x01, 0x78,
            0x00, 0x02, 0x05, 0x00, 0x64, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x05, 0x00,
            0x00, 0x00, 0x00, 0x49, 0x35, 0x01, 0x02, 0x21,
            0x00, 0x01, 0x78, 0x00, 0x02, 0x05, 0x00, 0x64,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x30, 0x00,
            0x0c, 0x29, 0x82, 0xc2, 0xa9, 0x00, 0x49, 0x30,
            0x01
        ];

        let upd = UpdateMessage::from_octets(&buf, &SessionConfig::modern())
            .unwrap();

        /* // now tested in bgp::nlri::evpn
        for n in upd.announcements().unwrap() {
            println!("{:?}", n.unwrap());
        }
        let mut announcements = upd.announcements().unwrap();
        if let Some(Ok(Nlri::L2VpnEvpn(e))) = announcements.next() {
            assert_eq!(
                e.nlri().route_type(),
                EvpnRouteType::EthernetAutoDiscovery
            )
        } else { panic!() }
        if let Some(Ok(Nlri::L2VpnEvpn(e))) = announcements.next() {
            assert_eq!(
                e.nlri().route_type(),
                EvpnRouteType::MacIpAdvertisement
            )
        } else { panic!() }
        assert!(announcements.next().is_none());
        */

        assert_eq!(
            upd.mp_next_hop().unwrap(),
            Some(NextHop::Unicast(Ipv4Addr::from_str("120.0.2.5").unwrap().into()))
        );
    }

    // the MP_REACH_NLRI currently ends up as a ::Invalid path attribute
    // variant, so the call to .mp_announcements() yields a Ok(None) and thus
    // the second unwrap fails. Therefore, ignore for now:
    #[ignore = "need to rethink this one because of API change"]
    #[test]
    fn unknown_afi_safi_announcements() {
        // botched BGP UPDATE message containing MP_REACH_NLRI path attribute,
        // comprising 5 (originally) IPv6 unicast NLRIs, but with the AFI/SAFI
        // changed to 255/1
        // and
        // 2 conventional nlri
        let buf = vec![
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0x00, 0x88 + 6, 0x02, 0x00, 0x00, 0x00, 0x71, 0x80,
            0x0e, 0x5a,
            //0x00, 0x02,
            0x00, 0xff,
            0x01,
            0x20, 0xfc, 0x00,
            0x00, 0x10, 0x00, 0x01, 0x00, 0x10, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0xfe, 0x80,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80,
            0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,
            0x40, 0x20, 0x01, 0x0d, 0xb8, 0xff, 0xff, 0x00,
            0x00, 0x40, 0x20, 0x01, 0x0d, 0xb8, 0xff, 0xff,
            0x00, 0x01, 0x40, 0x20, 0x01, 0x0d, 0xb8, 0xff,
            0xff, 0x00, 0x02, 0x40, 0x20, 0x01, 0x0d, 0xb8,
            0xff, 0xff, 0x00, 0x03, 0x40, 0x01, 0x01, 0x00,
            0x40, 0x02, 0x06, 0x02, 0x01, 0x00, 0x00, 0x00,
            0xc8, 0x80, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00,
            // conventional NLRI
            16, 10, 10, // 10.10.0.0/16
            16, 10, 11, // 10.11.0.0/16
        ];
        //let update: UpdateMessage<_> = parse_msg(&buf);
        let update = UpdateMessage::from_octets(
            &buf,
            &SessionConfig::modern()
        ).unwrap();

        assert_eq!(update.mp_announcements().unwrap().unwrap().count(), 1);
        assert!(update.mp_announcements().unwrap().unwrap().next().unwrap().is_err());

        // We expect only the two conventional announcements here:
        //assert_eq!(update.unicast_announcements().unwrap().count(), 2);

    }

    // this test used to return 4 NLRI: the good one and the first invalid one
    // from MP, and the two valid conventional ones.
    #[ignore = "we need to figure out how we deal with invalid NLRI"]
    #[test]
    fn invalid_nlri_length_in_announcements() {
        // botched BGP UPDATE message containing MP_REACH_NLRI path attribute,
        // comprising 5 (originally) IPv6 unicast NLRIs, with the second one
        // having a prefix len of 129
        // and
        // 2 conventional nlri
        let buf = vec![
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0x00, 0x88 + 6, 0x02, 0x00, 0x00, 0x00, 0x71, 0x80,
            0x0e, 0x5a,
            0x00, 0x02, // AFI
            0x01, // SAFI
            // NextHop:
            0x20,
            0xfc, 0x00, 0x00, 0x10, 0x00, 0x01, 0x00, 0x10,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,
            0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,
            0x00, // reserved byte
            0x80, 
            0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,
            0x81, // was 0x40, changed to 0x81 (/129)
            0x20, 0x01, 0x0d, 0xb8, 0xff, 0xff, 0x00, 0x00,
            0x40,
            0x20, 0x01, 0x0d, 0xb8, 0xff, 0xff, 0x00, 0x01,
            0x40,
            0x20, 0x01, 0x0d, 0xb8, 0xff, 0xff, 0x00, 0x02,
            0x40,
            0x20, 0x01, 0x0d, 0xb8, 0xff, 0xff, 0x00, 0x03,
            0x40,
            0x01, 0x01, 0x00, 0x40, 0x02, 0x06, 0x02, 0x01, 0x00, 0x00, 0x00,
            0xc8, 0x80, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00,
            // conventional NLRI
            16, 10, 10, // 10.10.0.0/16
            16, 10, 11, // 10.11.0.0/16
        ];

        let update = UpdateMessage::from_octets(
            &buf,
            &SessionConfig::modern()
        ).unwrap();

        assert!(matches!(
            update.announcements_vec(),
            Err(ParseError::Form(..))
        ));

        /*
        assert!(matches!(
            update.unicast_announcements_vec(),
            Err(ParseError::Form(..))
        ));
        */

        for a in update.announcements().unwrap() {
            dbg!(a.unwrap());
        }
        assert_eq!(update.announcements().unwrap().count(), 4);
        //assert_eq!(update.unicast_announcements().unwrap().count(), 4);

        /*
        assert!(
            update.unicast_announcements().unwrap().eq(
            [
                Ok(BasicNlri::new(Prefix::from_str("fc00::10/128").unwrap())),
                Err(ParseError::form_error("illegal byte size for IPv6 NLRI")), 
                Ok(BasicNlri::new(Prefix::from_str("10.10.0.0/16").unwrap())),
                Ok(BasicNlri::new(Prefix::from_str("10.11.0.0/16").unwrap())),
            ]
            )
        );
        */
    }

    #[ignore = "does not Err anymore, we need to figure out what we want"]
    #[test]
    fn unknown_afi_safi_withdrawals() {
        // botched BGP UPDATE with 4 MP_UNREACH_NLRI
        let buf = vec![
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0x00, 0x41, 0x02, 0x00, 0x00, 0x00, 0x2a, 0x80,
            0x0f, 0x27,
            //0x00, 0x02, // AFI
            0x00, 0xff, // changed to unknown 255
            0x01,       // SAFI
            0x40,
            0x20, 0x01, 0x0d, 0xb8, 0xff, 0xff, 0x00, 0x00,
            0x40,
            0x20, 0x01, 0x0d, 0xb8, 0xff, 0xff, 0x00, 0x01,
            0x40,
            0x20, 0x01, 0x0d, 0xb8, 0xff, 0xff, 0x00, 0x02,
            0x40,
            0x20, 0x01, 0x0d, 0xb8, 0xff, 0xff, 0x00, 0x03
        ];

        assert!(
            UpdateMessage::from_octets(&buf, &SessionConfig::modern()).is_err()
        );
    }

    #[ignore = "see others wrt invalid NLRI"]
    #[test]
    fn invalid_withdrawals() {
        // botched BGP UPDATE with 4 MP_UNREACH_NLRI
        let buf = vec![
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0x00, 0x41, 0x02, 0x00, 0x00, 0x00, 0x2a, 0x80,
            0x0f, 0x27,
            0x00, 0x02,
            0x01,
            0x40,
            0x20, 0x01, 0x0d, 0xb8, 0xff, 0xff, 0x00, 0x00,
            //0x40,
            0x41, // changed to 0x41, leading to a parse error somewhere in
                  // the remainder of the attribute.
            0x20, 0x01, 0x0d, 0xb8, 0xff, 0xff, 0x00, 0x01,
            0x40,
            0x20, 0x01, 0x0d, 0xb8, 0xff, 0xff, 0x00, 0x02,
            0x40,
            0x20, 0x01, 0x0d, 0xb8, 0xff, 0xff, 0x00, 0x03
        ];

        assert!(
            UpdateMessage::from_octets(&buf, &SessionConfig::modern()).is_err()
        );

        /*
        assert!(matches!(
            update.unicast_announcements_vec(),
            Ok(Vec { .. })
        ));

        assert!(matches!(
            update.unicast_withdrawals_vec(),
            Err(ParseError::Form(..))
        ));

        assert_eq!(update.withdrawals().unwrap().count(), 2);
        assert_eq!(update.unicast_withdrawals().unwrap().count(), 2);

        assert!(
            update.unicast_withdrawals().unwrap().eq(
            [
                Ok(BasicNlri::new(
                        Prefix::from_str("2001:db8:ffff::/64").unwrap())
                ),
                Err(ParseError::form_error("non-zero host portion")), 
            ]
            )
        );
        */

    }

    #[test]
    fn format_as_pcap() {
        let buf = vec![
            // Two identical BGP UPDATEs
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x37, 0x02,
            0x00, 0x00, 0x00, 0x1b, 0x40, 0x01, 0x01, 0x00, 0x40, 0x02,
            0x06, 0x02, 0x01, 0x00, 0x01, 0x00, 0x00, 0x40, 0x03, 0x04,
            0x0a, 0xff, 0x00, 0x65, 0x80, 0x04, 0x04, 0x00, 0x00, 0x00,
            0x01, 0x20, 0x0a, 0x0a, 0x0a, 0x02,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x37, 0x02,
            0x00, 0x00, 0x00, 0x1b, 0x40, 0x01, 0x01, 0x00, 0x40, 0x02,
            0x06, 0x02, 0x01, 0x00, 0x01, 0x00, 0x00, 0x40, 0x03, 0x04,
            0x0a, 0xff, 0x00, 0x65, 0x80, 0x04, 0x04, 0x00, 0x00, 0x00,
            0x01, 0x20, 0x0a, 0x0a, 0x0a, 0x02,
        ];

        let bytes = Bytes::from(buf);
        let mut parser = Parser::from_ref(&bytes);
        let update = UpdateMessage::parse(
            &mut parser,
            &SessionConfig::modern()
        ).unwrap();

        let update2 = UpdateMessage::from_octets(
            parser.peek_all(),
            &SessionConfig::modern()
        ).unwrap();

        assert_eq!(update.fmt_pcap_string(), update2.fmt_pcap_string());
    }

    #[test]
    fn v4_mpls_unicast() {
        let raw = vec![
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0x00, 0x5c, 0x02, 0x00, 0x00, 0x00, 0x45, 0x80,
            0x0e, 0x31, 0x00, 0x01, 0x04, 0x04, 0x0a, 0x07,
            0x08, 0x08, 0x00, 0x38, 0x01, 0xf4, 0x01, 0x0a,
            0x00, 0x00, 0x09, 0x32, 0x01, 0xf4, 0x11, 0xc6,
            0x33, 0x64, 0x00, 0x32, 0x01, 0xf4, 0x21, 0xc6,
            0x33, 0x64, 0x40, 0x32, 0x01, 0xf4, 0x31, 0xc6,
            0x33, 0x64, 0x80, 0x32, 0x01, 0xf4, 0x91, 0xc6,
            0x33, 0x64, 0xc0, 0x40, 0x01, 0x01, 0x00, 0x40,
            0x02, 0x0a, 0x02, 0x02, 0x00, 0x00, 0x01, 0x2c,
            0x00, 0x00, 0x01, 0xf4
        ];

        let upd = UpdateMessage::from_octets(
            &raw,
            &SessionConfig::modern()
        ).unwrap();
        if let Ok(Some(NextHop::Unicast(a))) = upd.mp_next_hop() {
            assert_eq!(a, Ipv4Addr::from_str("10.7.8.8").unwrap());
        } else {
            panic!("wrong");
        }
        let mut ann = upd.mp_announcements().unwrap().unwrap();
        if let Some(Ok(Nlri::Ipv4MplsUnicast(n1))) = ann.next() {
            assert_eq!(
                n1.nlri().prefix(),
                Prefix::from_str("10.0.0.9/32").unwrap()
            );
            assert_eq!(
                n1.nlri().labels().iter().next().unwrap().value(), 
                8000
            );
        } else {
            panic!("wrong");
        }

        // and 4 more:
        assert_eq!(ann.count(), 4);
    }

    #[test]
    fn v6_mpls_vpn_unicast() {

        // BGP UPDATE for 2/128, one single announced NLRI 
        let raw = vec![
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0x00, 0x9a, 0x02, 0x00, 0x00, 0x00, 0x83, 0x80,
            0x0e, 0x39, 0x00, 0x02, 0x80, 0x18, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0xff, 0xff, 0x0a, 0x00, 0x00, 0x02, 0x00, 0xd8,
            0x00, 0x7d, 0xc1, 0x00, 0x00, 0x00, 0x64, 0x00,
            0x00, 0x00, 0x01, 0xfc, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x01, 0x40, 0x01, 0x01, 0x00, 0x40,
            0x02, 0x06, 0x02, 0x01, 0x00, 0x00, 0x00, 0x01,
            0x80, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00, 0x40,
            0x05, 0x04, 0x00, 0x00, 0x00, 0x64, 0xc0, 0x10,
            0x18, 0x00, 0x02, 0x00, 0x64, 0x00, 0x00, 0x00,
            0x01, 0x00, 0x09, 0x00, 0x64, 0x00, 0x00, 0x00,
            0x00, 0x01, 0x0b, 0x0a, 0x00, 0x00, 0x02, 0x00,
            0x01, 0xc0, 0x14, 0x0e, 0x00, 0x01, 0x00, 0x00,
            0x00, 0x64, 0x00, 0x00, 0x00, 0x01, 0x0a, 0x00,
            0x00, 0x02
        ];

        let upd = UpdateMessage::from_octets(
            &raw,
            &SessionConfig::modern()
        ).unwrap();
        if let Ok(Some(NextHop::MplsVpnUnicast(rd, a))) = upd.mp_next_hop() {
            assert_eq!(rd, RouteDistinguisher::new([0; 8]));
            assert_eq!(a, Ipv6Addr::from_str("::ffff:10.0.0.2").unwrap());
        } else {
            panic!("wrong");
        }
        let mut ann = upd.mp_announcements().unwrap().unwrap();
        if let Some(Ok(Nlri::Ipv6MplsVpnUnicast(n1))) = ann.next() {
            assert_eq!(
                n1.nlri().prefix(),
                Prefix::from_str("fc00::1/128").unwrap()
            );
            assert_eq!(
                n1.nlri().labels().iter().next().unwrap().value(),
                2012
            );
            assert_eq!(
                n1.nlri().rd(),
                RouteDistinguisher::new([0, 0, 0, 100, 0, 0, 0, 1])
            );
        } else {
            panic!("wrong");
        }

        assert!(ann.next().is_none());
    }


    #[test]
    fn route_target_nlri() {
        let raw = vec![
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0x00, 0x5f, 0x02, 0x00, 0x00, 0x00, 0x48, 0x80,
            0x0e, 0x30, 0x00, 0x01, 0x84, 0x04, 0x0a, 0x00,
            0x00, 0x02, 0x00, 0x60, 0x00, 0x00, 0x00, 0x64,
            0x00, 0x02, 0x00, 0x64, 0x00, 0x00, 0x00, 0x01,
            0x60, 0x00, 0x00, 0x00, 0x64, 0x01, 0x02, 0x0a,
            0x00, 0x00, 0x02, 0x00, 0x00, 0x60, 0x00, 0x00,
            0x00, 0x64, 0x01, 0x02, 0x0a, 0x00, 0x00, 0x02,
            0x00, 0x01, 0x40, 0x01, 0x01, 0x00, 0x40, 0x02,
            0x00, 0x80, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00,
            0x40, 0x05, 0x04, 0x00, 0x00, 0x00, 0x64
        ];

        let upd = UpdateMessage::from_octets(
            &raw,
            &SessionConfig::modern()
        ).unwrap();

        assert_eq!(
            upd.mp_announcements().unwrap().unwrap().count(),
            3
        );
    }

    #[ignore = "from_octets currently does not validate the attributes"] 
    #[test]
    fn invalid_mp_unreach_nlri() {
        let raw = vec![
            255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
            255, 255, 255, 0, 36, 2, 0, 0, 0, 13, 255, 255, 0, 0, 0, 15, 6, 0,
            2, 133, 43, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 1, 0, 255, 255, 255, 254
        ];
        print_pcap(&raw);

        assert!(
            UpdateMessage::from_octets(&raw, &SessionConfig::modern()).is_err()
        );
    }

    #[ignore = "this could/should now happen on PduParseInfo level?"]
    #[test]
    fn session_addpaths() {
        let mut aps = SessionAddpaths::new();
        aps.set(AfiSafiType::Ipv4Unicast, AddpathDirection::SendReceive);
        aps.set(AfiSafiType::L2VpnEvpn, AddpathDirection::Receive);
        assert_eq!(
            aps.get(AfiSafiType::Ipv4Unicast), Some(AddpathDirection::SendReceive)
        );
        assert_eq!(
            aps.get(AfiSafiType::L2VpnEvpn), Some(AddpathDirection::Receive)
        );
        assert_eq!(
            aps.get(AfiSafiType::Ipv6Unicast), None
        );

        assert_eq!(aps.enabled_addpaths().count(), 2);

        //let inv_aps = aps.inverse();
        //assert_eq!(inv_aps.enabled_addpaths().count(), 16 - 2);
    }

    #[ignore = "see previous"]
    #[test]
    fn session_config_addpaths() {
        /*
        let mut sc = SessionConfig::modern();
        sc.add_addpath_rxtx(AfiSafiType::Ipv4Unicast);
        sc.add_addpath_rxtx(AfiSafiType::Ipv6MplsUnicast);
        assert_eq!(sc.enabled_addpaths().count(), 2);
        sc.inverse_addpath(AfiSafiType::Ipv4Unicast);
        assert_eq!(sc.enabled_addpaths().count(), 1);
        sc.inverse_addpath(AfiSafiType::Ipv4Unicast);
        sc.inverse_addpaths();
        assert_eq!(sc.enabled_addpaths().count(), 14);
        sc.inverse_addpath(AfiSafiType::Ipv4Unicast);
        assert_eq!(sc.enabled_addpaths().count(), 15);
        */
    }

    #[test]
    fn announcement_fams() {
        // UPDATE with 5 ipv6 nlri + 2 conventional
        let raw = vec![
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0x00, 0x95,
            0x02, 0x00, 0x00, 0x00, 0x78,
            0x80,
            0x0e, 0x5a, 0x00, 0x02, 0x01, 0x20, 0xfc, 0x00,
            0x00, 0x10, 0x00, 0x01, 0x00, 0x10, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0xfe, 0x80,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80,
            0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,
            0x40, 0x20, 0x01, 0x0d, 0xb8, 0xff, 0xff, 0x00,
            0x00, 0x40, 0x20, 0x01, 0x0d, 0xb8, 0xff, 0xff,
            0x00, 0x01, 0x40, 0x20, 0x01, 0x0d, 0xb8, 0xff,
            0xff, 0x00, 0x02, 0x40, 0x20, 0x01, 0x0d, 0xb8,
            0xff, 0xff, 0x00, 0x03, 0x40, 0x01, 0x01, 0x00,
            0x40, 0x02, 0x06, 0x02, 0x01, 0x00, 0x00, 0x00,
            0xc8,
            0x40, 0x03, 0x04, 0x01, 0x02, 0x03, 0x04, // NEXT_HOP
            0x80, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00,
            16, 1, 2,
            16, 10, 20
        ];
        let pdu = UpdateMessage::from_octets(&raw, &SessionConfig::modern())
            .unwrap();
        assert_eq!(pdu.announcement_fams().count(), 2);
    }
}