rpki 0.19.3

A library for validating and creating RPKI data.
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
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
//! IP Resources for use with RPKI certificates.
//!
//! The types herein are defined in RFC 3779 for use with certificates in
//! general. RFC 6487 specifies how to use them with RPKI certificates. In
//! particular, it prohibits the use of Subsequent AFI values for address
//! families, making them always 16 bit. Additionally, if the "inherit"
//! value is not used for an address family, the set of addresses must be
//! non-empty.

use std::{error, fmt, io, iter, str};
use std::fmt::Display;
use std::net::{AddrParseError, IpAddr, Ipv4Addr, Ipv6Addr};
use std::num::ParseIntError;
use std::str::FromStr;
use std::cmp;
use bcder::{decode, encode};
use bcder::{BitString, Mode, OctetString, Tag};
use bcder::decode::{ContentError, DecodeError};
use bcder::encode::{Nothing, PrimitiveContent};
use super::super::cert::Overclaim;
use super::super::error::VerificationError;
use super::super::roa::RoaIpAddress;
use super::super::x509::encode_extension;
use super::chain::{Block, OwnedChain, SharedChain};
use super::choice::{InheritedResources, ResourcesChoice};


//------------ IpResources ---------------------------------------------------

/// The IP Address Resources of an RPKI Certificate.
///
/// This type contains the resources for one of the address families that can
/// be contained in the certificate.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IpResources(ResourcesChoice<IpBlocks>);

impl IpResources {
    /// Creates a new IpResources with a ResourcesChoice::Inherit
    pub fn inherit() -> Self {
        IpResources(ResourcesChoice::Inherit)
    }

    /// Creates a new AsResources with a ResourceChoice::Missing
    pub fn missing() -> Self {
        IpResources(ResourcesChoice::Missing)
    }

    /// Creates a new IpResources for the given blocks.
    ///
    /// If the blocks are empty, creates a missing variant in accordance with
    /// the specification.
    pub fn blocks(blocks: IpBlocks) -> Self {
        if blocks.is_empty() {
            IpResources::missing()
        }
        else {
            IpResources(ResourcesChoice::Blocks(blocks))
        }
    }

    /// Returns whether the resources are of the inherited variant.
    pub fn is_inherited(&self) -> bool {
        self.0.is_inherited()
    }

    /// Returns whether the resources are empty.
    ///
    /// Inherited resources are not empty.
    pub fn is_present(&self) -> bool {
        self.0.is_present()
    }

    /// Converts the resources into blocks or returns an error.
    ///
    /// The method returns an error for inherited resources.
    pub fn to_blocks(&self) -> Result<IpBlocks, InheritedIpResources> {
        self.0.to_blocks().map_err(Into::into)
    }
}

impl IpResources {
    /// Takes all IP resources from the beginning of a constructed value.
    ///
    /// On success, the function returns a pair of optional IP resources,
    /// the first for IPv4, the second for IPv6.
    #[allow(clippy::type_complexity)]
    pub fn take_families_from<S: decode::Source>(
        cons: &mut decode::Constructed<S>
    ) -> Result<(Option<Self>, Option<Self>), DecodeError<S::Error>> {
        cons.take_sequence(|cons| {
            let mut v4 = None;
            let mut v6 = None;
            while let Some(()) = cons.take_opt_sequence(|cons| {
                let af = AddressFamily::take_from(cons)?;
                match af {
                    AddressFamily::Ipv4 => {
                        if v4.is_some() {
                            return Err(cons.content_err(
                                "multiple IPv4 resourcess"
                            ));
                        }
                        v4 = Some(Self::take_from(cons, AddressFamily::Ipv4)?);
                    }
                    AddressFamily::Ipv6 => {
                        if v6.is_some() {
                            return Err(cons.content_err(
                                "multiple IPv6 resources"
                            ));
                        }
                        v6 = Some(Self::take_from(cons, AddressFamily::Ipv6)?);
                    }
                }
                Ok(())
            })? { }
            if v4.is_none() && v6.is_none() {
                return Err(cons.content_err(
                    "no address family in IP resources"
                ));
            }
            Ok((v4, v6))
        })
    }

    /// Takes a single set of  IP resources from a constructed value.
    pub fn take_from<S: decode::Source>(
        cons: &mut decode::Constructed<S>,
        family: AddressFamily,
    ) -> Result<Self, DecodeError<S::Error>> {
        cons.take_value(|tag, content| {
            if tag == Tag::NULL {
                content.to_null()?;
                Ok(ResourcesChoice::Inherit)
            }
            else if tag == Tag::SEQUENCE {
                IpBlocks::parse_content(content, family)
                    .map(ResourcesChoice::Blocks)
            }
            else {
                Err(content.content_err("invalid IP resources"))
            }
        }).map(IpResources)
    }

    pub fn encode(self) -> impl encode::Values {
        match self.0 {
            ResourcesChoice::Inherit => {
                encode::Choice3::One(().encode())
            }
            ResourcesChoice::Blocks(blocks) => {
                encode::Choice3::Two(blocks.encode())
            }
            ResourcesChoice::Missing => {
                encode::Choice3::Three(encode::sequence(Nothing))
            }
        }
    }

    pub fn encode_ref(&self) -> impl encode::Values + '_ {
        match self.0 {
            ResourcesChoice::Inherit => {
                encode::Choice3::One(().encode())
            }
            ResourcesChoice::Blocks(ref blocks) => {
                encode::Choice3::Two(blocks.encode_ref())
            }
            ResourcesChoice::Missing => {
                encode::Choice3::Three(encode::sequence(Nothing))
            }
        }
    }

    pub fn encode_family(
        &self, family: AddressFamily
    ) -> impl encode::Values + '_ {
        if self.is_present() {
            Some(encode::sequence((
                family.encode(), self.encode_ref()
            )))
        }
        else {
            None
        }
    }

    pub fn encode_extension<'a>(
        overclaim: Overclaim,
        v4: &'a Self,
        v6: &'a Self,
    ) -> Option<impl encode::Values + 'a> {
        if !v4.is_present() && !v6.is_present() {
            return None
        }
        Some(encode_extension(
            overclaim.ip_res_id(), true,
            encode::sequence((
                v4.encode_family(AddressFamily::Ipv4),
                v6.encode_family(AddressFamily::Ipv6)
            ))
        ))
    }
}


//------------ IpResourcesBuilder --------------------------------------------

#[derive(Clone, Debug)]
pub struct IpResourcesBuilder {
    res: Option<IpBlocksBuilder>
}

impl IpResourcesBuilder {
    pub fn new() -> Self {
        IpResourcesBuilder {
            res: Some(IpBlocksBuilder::new())
        }
    }

    pub fn inherit(&mut self) {
        self.res = None
    }

    pub fn blocks<F>(&mut self, build: F)
    where F: FnOnce(&mut IpBlocksBuilder) {
        if let Some(ref mut builder) = self.res {
            build(builder)
        }
        else {
            let mut builder = IpBlocksBuilder::new();
            build(&mut builder);
            self.res = Some(builder)
        }
    }
    
    pub fn finalize(self) -> IpResources {
        match self.res {
            Some(blocks) => IpResources::blocks(blocks.finalize()),
            None => IpResources::inherit()
        }
    }
}

impl Default for IpResourcesBuilder {
    fn default() -> Self {
        Self::new()
    }
}


//------------ IpBlocksForFamily ---------------------------------------------

/// IpBlocks for a specific family, to help formatting
pub struct IpBlocksForFamily<'a> {
    family: AddressFamily,
    blocks: &'a IpBlocks
}

impl<'a> IpBlocksForFamily<'a> {
    pub fn v4(blocks: &'a IpBlocks) -> Self {
        IpBlocksForFamily {
            family: AddressFamily::Ipv4,
            blocks
        }
    }
    pub fn v6(blocks: &'a IpBlocks) -> Self {
        IpBlocksForFamily {
            family: AddressFamily::Ipv6,
            blocks
        }
    }
}

impl fmt::Display for IpBlocksForFamily<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut blocks_iter = self.blocks.iter();

        if let Some(el) = blocks_iter.next() {
            match self.family {
                AddressFamily::Ipv4 => el.fmt_v4(f)?,
                AddressFamily::Ipv6 => el.fmt_v6(f)?,
            }
        }

        for el in blocks_iter {
            write!(f, ", ")?;
            match self.family {
                AddressFamily::Ipv4 => el.fmt_v4(f)?,
                AddressFamily::Ipv6 => el.fmt_v6(f)?,
            }
        }

        Ok(())
    }
}

//------------ IpBlocks ------------------------------------------------------

/// A sequence of address ranges for one address family.
///
/// Values of this type are guaranteed to contain a sequence of [`IpBlock`]s
/// that fulfills the requirements of RFC 3779. Specifically, the blocks will
/// not overlap, will not be consecutive (i.e., there’s at least one address
/// between neighbouring blocks), will be in order, and anything that can be
/// addressed as a prefix will be.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IpBlocks(SharedChain<IpBlock>);

impl IpBlocks {
    /// Creates an empty address blocks.
    pub fn empty() -> Self {
        IpBlocks(SharedChain::empty())
    }

    /// Creates a value covering all addresses.
    pub fn all() -> Self {
        IpBlocks(SharedChain::from_owned(
            unsafe {
                OwnedChain::from_vec_unchecked(vec![
                    IpBlock::all()
                ])
            }
        ))
    }

    /// Creates address blocks from address resources.
    ///
    /// If the resources are of the inherited variant, returns an error.
    pub fn from_resources(
        res: IpResources
    ) -> Result<Self, InheritedIpResources> {
        match res.0 {
            ResourcesChoice::Missing => Ok(IpBlocks::empty()),
            ResourcesChoice::Inherit => Err(InheritedIpResources(())),
            ResourcesChoice::Blocks(some) => Ok(some),
        }
    }

    /// Returns whether the blocks is empty.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Returns an iterator over the address ranges in the block.
    pub fn iter(&self) -> impl Iterator<Item=IpBlock> + '_ {
        self.0.iter().copied()
    }

    /// Validates IP resources issued under these blocks.
    pub fn verify_issued(
        &self,
        res: &IpResources,
        mode: Overclaim,
    ) -> Result<IpBlocks, OverclaimedIpResources> {
        match res.0 {
            ResourcesChoice::Missing => Ok(Self::empty()),
            ResourcesChoice::Inherit => Ok(self.clone()),
            ResourcesChoice::Blocks(ref blocks) => {
                match mode {
                    Overclaim::Refuse => {
                        if self.contains(blocks) {
                            Ok(blocks.clone())
                        }
                        else {
                            Err(OverclaimedIpResources::new(
                                self.clone(), blocks.clone(),
                            ))
                        }
                    }
                    Overclaim::Trim => {
                        Ok(blocks.intersection(self))
                    }
                }
            },
        }
    }

    /// Verifies that these resources are covered by an issuer’s resources.
    ///
    /// This is used by bottom-up validation, therefore, issuer resources 
    /// of the inherited kind are considered covering.
    pub fn verify_covered(
        &self,
        issuer: &IpResources
    ) -> Result<(), OverclaimedIpResources> {
        match issuer.0 {
            ResourcesChoice::Missing => {
                if self.0.is_empty() {
                    Ok(())
                }
                else {
                    Err(OverclaimedIpResources::new(
                        IpBlocks::empty(), self.clone(),
                    ))
                }
            }
            ResourcesChoice::Inherit => Ok(()),
            ResourcesChoice::Blocks(ref blocks) => {
                if self.0.is_encompassed(&blocks.0) {
                    Ok(())
                }
                else {
                    Err(OverclaimedIpResources::new(
                        blocks.clone(), self.clone(),
                    ))
                }
            }
        }
    }

    /// Returns whether the address blocks cover the given ROA address prefix.
    pub fn contains_roa(&self, addr: &RoaIpAddress) -> bool {
        let (min, max) = addr.range();
        for range in self.iter() {
            if range.min() <= min && range.max() >= max {
                return true
            }
        }
        false
    }

    /// Returns whether the address blocks cover the given address block.
    pub fn contains_block(&self, block: impl Into<IpBlock>) -> bool {
        let block = block.into();
        let (min, max) = (block.min(), block.max());
        for range in self.iter() {
            if range.min() <= min && range.max() >= max {
                return true
            }
        }
        false
    }

    /// Returns whether the address blocks intersects the given address block.
    pub fn intersects_block(&self, block: impl Into<IpBlock>) -> bool {
        let block = block.into();
        for range in self.iter() {
            if range.intersects(&block) {
                return true
            }
        }
        false
    }
}

/// # Set operations
///
impl IpBlocks {
    /// Returns whether this IpBlocks contains the other in its entirety.
    pub fn contains(&self, other: &Self) -> bool {
        other.0.is_encompassed(&self.0)
    }

    /// Return the intersection of this IpBlocks and the other. I.e. all
    /// resources which are found in both.
    pub fn intersection(&self, other: &Self) -> Self {
        match self.0.trim(&other.0) {
            Ok(()) => self.clone(),
            Err(owned) => IpBlocks(SharedChain::from_owned(owned))
        }
    }

    pub fn intersection_assign(&mut self, other: &Self) {
        if let Err(owned) = self.0.trim(&other.0) {
            self.0 = SharedChain::from_owned(owned)
        }
    }

    /// Returns a new =IpBlocks with the values found in self, but not in other.
    pub fn difference(&self, other: &Self) -> Self {
        IpBlocks(SharedChain::from_owned(self.0.difference(&other.0)))
    }

    /// Returns a new IpBlocks with the union of this and the other IpBlocks.
    ///
    /// i.e. all resources found in one or both IpBlocks.
    pub fn union(&self, other: &Self) -> Self {
        IpBlocks(
            self.0.iter().cloned().chain(other.0.iter().cloned()).collect()
        )
    }
}

impl IpBlocks {
    pub fn take_from<S: decode::Source>(
        cons: &mut decode::Constructed<S>
    ) -> Result<Self, DecodeError<S::Error>> {
        cons.take_sequence(|cons| {
            // The family is here only for checking the lengths of
            // bitstrings. Since we don’t care, IPv6 will work.
            Self::parse_cons_content(cons, AddressFamily::Ipv6)
        })
    }

    pub fn take_from_with_family<S: decode::Source>(
        cons: &mut decode::Constructed<S>,
        family: AddressFamily
    ) -> Result<Self, DecodeError<S::Error>> {
        cons.take_sequence(|cons| {
            Self::parse_cons_content(cons, family)
        })
    }

    /// Parses the content of a AS ID blocks sequence.
    fn parse_content<S: decode::Source>(
        content: &mut decode::Content<S>,
        family: AddressFamily,
    ) -> Result<Self, DecodeError<S::Error>> {
        let cons = content.as_constructed()?;
        Self::parse_cons_content(cons, family)
    }

    fn parse_cons_content<S: decode::Source>(
        cons: &mut decode::Constructed<S>,
        family: AddressFamily,
    ) -> Result<Self, DecodeError<S::Error>> {
        let mut err = None;

        let res = iter::repeat_with(||
            IpBlock::take_opt_from_with_family(cons, family)
        ).map(|item| {
            match item {
                Ok(Some(val)) => Some(val),
                Ok(None) => None,
                Err(e) => {
                    err = Some(e);
                    None
                }
            }
        }).take_while(|item| item.is_some()).map(Option::unwrap).collect();
        match err {
            Some(err) => Err(err),
            None => Ok(IpBlocks(res))
        }
    }

    pub fn encode(self) -> impl encode::Values {
        encode::sequence(encode::slice(self.0, |block| block.encode()))
    }

    pub fn encode_ref(&self) -> impl encode::Values + '_ {
        encode::sequence(encode::slice(&self.0, |block| block.encode()))
    }

    pub fn encode_family(
        &self, family: AddressFamily
    ) -> impl encode::Values + '_ {
        encode::sequence((
            family.encode(), self.encode_ref()
        ))
    }

    /// Returns an IpBlocksForFamily for IPv4 for this,
    /// to help formatting.
    pub fn as_v4(&self) -> IpBlocksForFamily<'_> {
        IpBlocksForFamily::v4(self)
    }

    /// Returns an IpBlocksForFamily for IPv4 for this,
    /// to help formatting.
    pub fn as_v6(&self) -> IpBlocksForFamily<'_> {
        IpBlocksForFamily::v6(self)
    }
}

impl Default for IpBlocks {
    fn default() -> Self {
        IpBlocks::empty()
    }
}

impl FromStr for IpBlocks {
    type Err = FromStrError;

    /// This parses comma separated IpBlocks (ranges, prefixes
    /// and single addresses). This will throw an error if the
    /// input contains a mix of AddressFamily.
    fn from_str(s: &str) -> Result<Self, Self::Err> {

        let family = if s.contains('.') {
            AddressFamily::Ipv4
        } else {
            AddressFamily::Ipv6
        };

        let mut builder = IpBlocksBuilder::default();

        for el in s.split(',') {
            let s = el.trim();
            if s.is_empty() {
                continue
            }
            match family {
                AddressFamily::Ipv4 => {
                    if let Ok(block) = IpBlock::from_v4_str(s) {
                        builder.push(block)
                    } else {
                        return Err(FromStrError::FamilyMismatch)
                    }
                },
                AddressFamily::Ipv6 => {
                    if let Ok(block) = IpBlock::from_v6_str(s) {
                        builder.push(block)
                    } else {
                        return Err(FromStrError::FamilyMismatch)
                    }
                }
            }
        }

        Ok(builder.finalize())
    }
}

impl FromIterator<IpBlock> for IpBlocks {
    fn from_iter<I: IntoIterator<Item = IpBlock>>(iter: I) -> Self {
        // SharedChain::from_iter does the hard work of ensuring the returned
        // value is correct.
        Self(SharedChain::from_iter(iter))
    }
}


//------------ IpBlocksBuilder -----------------------------------------------

#[derive(Clone, Debug)]
pub struct IpBlocksBuilder(Vec<IpBlock>);

impl IpBlocksBuilder {
    pub fn new() -> Self {
        IpBlocksBuilder(Vec::new())
    }

    pub fn push<T: Into<IpBlock>>(&mut self, block: T) {
        self.0.push(block.into())
    }

    pub fn finalize(self) -> IpBlocks {
        // collect here runs IpBlocks::from_iter to create a correct IpBlocks
        self.0.into_iter().collect()
    }
}

impl Default for IpBlocksBuilder {
    fn default() -> Self {
        IpBlocksBuilder::new()
    }
}

impl Extend<IpBlock> for IpBlocksBuilder {
    fn extend<T>(&mut self, iter: T)
    where T: IntoIterator<Item = IpBlock> {
        self.0.extend(iter)
    }
}

//------------ IpBlock -------------------------------------------------------

/// A consecutive sequence of IP addresses.
#[derive(Clone, Copy, Debug)]
pub enum IpBlock {
    /// The block is expressed as a prefix.
    Prefix(Prefix),

    /// The block is expressed as a range.
    Range(AddressRange),
}

impl IpBlock {
    /// Creates a new block covering all addresses.
    pub fn all() -> Self {
        IpBlock::Prefix(Prefix::all())
    }

    /// Creates a new block from an IPv4 representation.
    pub fn from_v4_str(s: &str) -> Result<Self, FromStrError> {
        if let Some(sep) = s.find('/') {
            Prefix::from_v4_str_sep(s, sep).map(IpBlock::Prefix)
        }
        else if let Some(sep) = s.find('-') {
            AddressRange::from_v4_str_sep(s, sep).map(IpBlock::Range)
        }
        else {
            let addr = Addr::from(Ipv4Addr::from_str(s)?);
            Ok(IpBlock::Range(AddressRange::new(addr, addr.to_max(32))))
        }
    }

    /// Creates a new block from an IPv6 representation.
    pub fn from_v6_str(s: &str) -> Result<Self, FromStrError> {
        if let Some(sep) = s.find('/') {
            Prefix::from_v6_str_sep(s, sep).map(IpBlock::Prefix)
        }
        else if let Some(sep) = s.find('-') {
            AddressRange::from_v6_str_sep(s, sep).map(IpBlock::Range)
        }
        else {
            let addr = Ipv6Addr::from_str(s)?.into();
            Ok(IpBlock::Range(AddressRange::new(addr, addr)))
        }
    }

    /// Returns whether the block is a prefix with address length zero.
    pub fn is_slash_zero(&self) -> bool {
        matches!(*self, IpBlock::Prefix(prefix) if prefix.len == 0)
    }

    /// The smallest address of the block.
    pub fn min(&self) -> Addr {
        match *self {
            IpBlock::Prefix(ref inner) => inner.min(),
            IpBlock::Range(ref inner) => inner.min(),
        }
    }

    /// The largest address of the block.
    pub fn max(&self) -> Addr {
        match *self {
            IpBlock::Prefix(ref inner) => inner.max(),
            IpBlock::Range(ref inner) => inner.max(),
        }
    }

    /// Formats the block as a IPv4 block.
    pub fn fmt_v4(self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            IpBlock::Prefix(prefix) => prefix.fmt_v4(f),
            IpBlock::Range(range) => range.fmt_v4(f),
        }
    }

    /// Formats the block as a IPv4 block.
    pub fn fmt_v6(self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            IpBlock::Prefix(prefix) => prefix.fmt_v6(f),
            IpBlock::Range(range) => range.fmt_v6(f),
        }
    }

    /// Returns an object that displays the block as an IPv4 block.
    pub fn display_v4(self) -> DisplayV4Block {
        DisplayV4Block(self)
    }

    /// Returns an object that displays the block as an IPv6 block.
    pub fn display_v6(self) -> DisplayV6Block {
        DisplayV6Block(self)
    }
}

impl IpBlock {
    /// Takes an optional address block from the beginning of encoded value.
    pub fn take_opt_from<S: decode::Source>(
        cons: &mut decode::Constructed<S>
    ) -> Result<Option<Self>, DecodeError<S::Error>> {
        cons.take_opt_value(|tag, content| {
            if tag == Tag::BIT_STRING {
                Prefix::parse_content(content).map(IpBlock::Prefix)
            }
            else if tag == Tag::SEQUENCE {
                AddressRange::parse_content(content).map(IpBlock::Range)
            }
            else {
                Err(content.content_err("invalid IP resources"))
            }
        })
    }

    pub fn take_opt_from_with_family<S: decode::Source>(
        cons: &mut decode::Constructed<S>,
        family: AddressFamily,
    ) -> Result<Option<Self>, DecodeError<S::Error>> {
        cons.take_opt_value(|tag, content| {
            if tag == Tag::BIT_STRING {
                Prefix::parse_content_with_family(
                    content, family
                ).map(IpBlock::Prefix)
            }
            else if tag == Tag::SEQUENCE {
                AddressRange::parse_content_with_family(
                    content, family
                ).map(IpBlock::Range)
            }
            else {
                Err(content.content_err("invalid IP resources"))
            }
        })
    }

    /// Returns an encoder for the range.
    ///
    /// This encoder will produce a `IPAddressOrRange` value.
    pub fn encode(self) -> impl encode::Values {
        match self {
            IpBlock::Prefix(inner) => {
                encode::Choice2::One(inner.encode())
            }
            IpBlock::Range(inner) => {
                encode::Choice2::Two(inner.encode())
            }
        }
    }
}


//--- From and FromStr

impl From<Prefix> for IpBlock {
    fn from(prefix: Prefix) -> Self {
        IpBlock::Prefix(prefix)
    }
}

impl From<AddressRange> for IpBlock {
    fn from(range: AddressRange) -> Self {
        IpBlock::Range(range)
    }
}

impl From<(Addr, Addr)> for IpBlock {
    fn from(range: (Addr, Addr)) -> Self {
        match AddressRange::new(range.0, range.1).into_prefix() {
            Ok(prefix) => prefix.into(),
            Err(range) => range.into(),
        }
    }
}

impl str::FromStr for IpBlock {
    type Err = FromStrError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if let Some(sep) = s.find('/') {
            Prefix::from_str_sep(s, sep).map(IpBlock::Prefix)
        }
        else if let Some(sep) = s.find('-') {
            AddressRange::from_str_sep(s, sep).map(IpBlock::Range)
        }
        else {
            let (min, max) = match IpAddr::from_str(s)? {
                IpAddr::V4(addr) => {
                    let addr = Addr::from(addr);
                    (addr, addr.to_max(32))
                },
                IpAddr::V6(addr) => {
                    let addr = Addr::from(addr);
                    (addr, addr)
                }
            };
            Ok(IpBlock::Range(AddressRange::new(min, max)))
        }
    }
}


//--- PartialEq and Eq

impl PartialEq for IpBlock {
    fn eq(&self, other: &Self) -> bool {
        self.is_equivalent(other)
    }
}

impl Eq for IpBlock { }


//--- Block

impl Block for IpBlock {
    type Item = Addr;

    fn new(min: Self::Item, max: Self::Item) -> Self {
        (min, max).into()
    }

    fn min(&self) -> Self::Item {
        self.min()
    }

    fn max(&self) -> Self::Item {
        self.max()
    }

    fn next(item: Self::Item) -> Option<Self::Item> {
        item.0.checked_add(1).map(Addr)
    }

    fn previous(item: Self::Item) -> Option<Self::Item> {
        item.0.checked_sub(1).map(Addr)
    }
}


//------------ DisplayV4Block ------------------------------------------------

pub struct DisplayV4Block(IpBlock);

impl fmt::Display for DisplayV4Block {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt_v4(fmt)
    }
}


//------------ DisplayV6Block ------------------------------------------------

pub struct DisplayV6Block(IpBlock);

impl fmt::Display for DisplayV6Block {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt_v6(fmt)
    }
}


//------------ AddressRange --------------------------------------------------

/// An IP address range.
///
/// This type appears in two variants in RFC 3779, either as a single prefix
/// (IPAddress) or as a range (IPAddressRange). Both cases actually cover a
/// consecutive range of addresses, so there is a minimum and a maximum
/// address covered by them. We simply model both of them as ranges of those
/// minimums and maximums.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct AddressRange {
    /// The smallest IP address that is part of this range.
    min: Addr,

    /// The largest IP address that is part of this range.
    ///
    /// Note that this means that, unlike normal Rust ranges, our range is
    /// inclusive at the upper end. This is necessary to represent a range
    /// that goes all the way to the last address (which, for instance,
    /// `::0/0` does).
    max: Addr,
}

impl AddressRange {
    /// Creates a new address range from smallest and largest address.
    pub fn new(min: Addr, max: Addr) -> Self {
        AddressRange { min, max }
    }

    /// Creates a new range from a string with known separator position.
    fn from_str_sep(s: &str, sep: usize) -> Result<Self, FromStrError> {
        let min = IpAddr::from_str(&s[..sep])?;
        let max = IpAddr::from_str(&s[sep + 1..])?;
        match (min.is_ipv4(), max.is_ipv4()) {
            (true, true) => {
                Ok(Self::new(min.into(), Addr::from(max).to_max(32)))
            }
            (false, false) => {
                Ok(Self::new(min.into(), max.into()))
            }
            _ => Err(FromStrError::FamilyMismatch)
        }
    }

    /// Creates a new range from an IPv4 string with known separator.
    fn from_v4_str_sep(s: &str, sep: usize) -> Result<Self, FromStrError> {
        Ok(Self::new(
            Ipv4Addr::from_str(&s[..sep])?.into(),
            Addr::from(Ipv4Addr::from_str(&s[sep + 1..])?).to_max(32)
        ))
    }

    /// Creates a new range from an IPv4 string.
    pub fn from_v4_str(s: &str) -> Result<Self, FromStrError> {
        let sep = s.find('-').ok_or(FromStrError::MissingSeparator)?;
        Self::from_v4_str_sep(s, sep)
    }

    /// Creates a new range from an IPv6 string with known separator.
    fn from_v6_str_sep(s: &str, sep: usize) -> Result<Self, FromStrError> {
        Ok(Self::new(
            Ipv6Addr::from_str(&s[..sep])?.into(),
            Ipv6Addr::from_str(&s[sep + 1..])?.into()
        ))
    }

    /// Creates a new range from an IPv4 string.
    pub fn from_v6_str(s: &str) -> Result<Self, FromStrError> {
        let sep = s.find('-').ok_or(FromStrError::MissingSeparator)?;
        Self::from_v6_str_sep(s, sep)
    }

    /// Returns the smallest IP address that is part of this range.
    pub fn min(&self) -> Addr {
        self.min
    }

    /// Returns the largest IP address that is still part of this range.
    pub fn max(&self) -> Addr {
        self.max
    }

    /// Sets a new minimum IP address.
    ///
    /// # Panics
    ///
    /// If you try to set the minimum to value larger than the current
    /// maximum, the method will panic.
    pub fn set_min(&mut self, min: Addr) {
        if min <= self.max() {
            self.min = min
        }
        else {
            panic!("trying to set minimum beyond current maximum");
        }
    }

    /// Sets a new maximum IP address.
    ///
    /// # Panics
    ///
    /// If you try to set the minimum to value smaller than the current
    /// minimum, the method will panic.
    pub fn set_max(&mut self, max: Addr) {
        if max > self.min() {
            self.max = max
        }
        else {
            panic!("trying to set maximum below current minimum");
        }
    }

    /// Tries to convert the range into a prefix.
    ///
    /// If this range cannot be expresses as a prefix, returns the range
    /// itself as an error.
    pub fn into_prefix(self) -> Result<Prefix, Self> {
        let len = (self.min.to_bits() ^ self.max.to_bits()).leading_zeros();
        let prefix = Prefix::new(self.min, len as u8);
        if prefix.range() == (self.min, self.max) {
            Ok(prefix)
        }
        else {
            Err(self)
        }
    }

    /// Convert a range into a set of V6 prefixes
    pub fn to_v6_prefixes(self) -> impl Iterator<Item = Prefix> {
        let mut start = self.min.to_bits();
        let end = self.max.to_bits();

        let mut cidrs: Vec<Prefix> = vec![];
        
        loop {
            // The idea is to take the largest prefix possible from the start
            // then move the start to the address after the last address in
            // that prefix, and do it again until there are no addresses left.

            // Based loosely on <https://github.com/arineng/cidr-calc>
            if start > end {
                break;
            }
            
            // Determine how many of the last bits of the address are prefixable
            // e.g. for 2001:DB8:: that would be 99
            let addr_host_bits = start.trailing_zeros();

            // Determine how many of the first bits are shared between the
            // start and the end, to determine an upper bound for the prefix
            // e.g. 2001:DB8:: and 2001:DB8::8000 share 112 bits, so the max
            // is 16
            let mut max_allowed = 128 - (start ^ end).leading_zeros();
            if end.trailing_ones() < max_allowed {
                // Prevent overshooting the prefix
                // e.g. for 2001:DB8::8000 the trailing_ones = 0, so the max 
                // is now 15 to prevent covering space after 2001:DB8::8000
                max_allowed -= 1;
            }

            // Obtain the bits at the end that are the same, which is the
            // shortest of either the amount of 0 bits at the current address
            // or the amount of bits not shared at the start
            let same_bits = cmp::min(addr_host_bits, max_allowed);
            let prefix_len = 128 - same_bits;

            debug_assert!(prefix_len <= 128);
            let prefix = Prefix::new(Addr::from_bits(start), prefix_len as u8);
            cidrs.push(prefix);

            if prefix.max().to_bits() == end {
                break;
            }

            start += 1 << same_bits;
        }

        cidrs.into_iter()
    }

    /// Convert a range into a set of V4 prefixes
    pub fn to_v4_prefixes(self) -> impl Iterator<Item = Prefix> {
        let mut start = (self.min.to_bits() >> 96) as u32;
        let end = (self.max.to_bits() >> 96) as u32;
        
        let mut cidrs: Vec<Prefix> = vec![];
        
        loop {
            // This works the same as `to_v6_prefixes` above
            if start > end {
                break;
            }

            let addr_host_bits = start.trailing_zeros();
            let mut max_allowed = 32 - (start ^ end).leading_zeros();
            if end.trailing_ones() < max_allowed {
                max_allowed -= 1;
            }

            let same_bits = cmp::min(addr_host_bits, max_allowed);
            let prefix_len = 32 - same_bits;

            debug_assert!(prefix_len <= 32);
            let prefix = Prefix::new(
                Addr::from(Ipv4Addr::from(start)), 
                prefix_len as u8
            );

            cidrs.push(prefix);

            if (prefix.max().to_bits() >> 96) as u32 == end {
                break;
            }

            start += 1 << same_bits;
        }

        cidrs.into_iter()
    }

    /// Formats the range as an IPv4 range.
    pub fn fmt_v4(self, f: &mut fmt::Formatter) -> fmt::Result {
        let min = self.min.to_v4();
        let max = self.max.to_v4();

        if min == max {
            min.fmt(f)
        } else {
            write!(f, "{min}-{max}")
        }
    }

    /// Formats the range as an IPv6 range.
    pub fn fmt_v6(self, f: &mut fmt::Formatter) -> fmt::Result {
        let min = self.min.to_v6();
        let max = self.max.to_v6();

        if min == max {
            min.fmt(f)
        } else {
            write!(f, "{min}-{max}")
        }
    }
}

impl AddressRange {
    fn parse_content<S: decode::Source>(
        content: &mut decode::Content<S>
    ) -> Result<Self, DecodeError<S::Error>> {
        let cons = content.as_constructed()?;
        Ok(AddressRange {
            min: Prefix::take_from(cons)?.min(),
            max: Prefix::take_from(cons)?.max(),
        })
    }

    fn parse_content_with_family<S: decode::Source>(
        content: &mut decode::Content<S>,
        family: AddressFamily,
    ) -> Result<Self, DecodeError<S::Error>> {
        let cons = content.as_constructed()?;
        
        let min = Self::check_len(
            Prefix::take_from(cons)?, family,
        ).map_err(|err| cons.content_err(err))?;
        let max = Self::check_len(
            Prefix::take_from(cons)?, family,
        ).map_err(|err| cons.content_err(err))?;

        Ok(AddressRange {
            min: min.min(),
            max: max.max(),
        })
    }

    #[cfg(not(feature = "compat"))]
    /// Checks the length of the prefix for the given address family.
    /// Returns an error if the prefix length exceeds the maximum length
    /// for the address family.
    fn check_len(
        addr: Prefix, family: AddressFamily
     ) -> Result<Prefix, ContentError> {
        if addr.addr_len() > family.max_addr_len() {
            Err("invalid range in IP resources".into())
        }
        else {
            Ok(addr)
        }
    }

    #[cfg(feature = "compat")]
    /// Checks the length of the prefix for the given address family.
    /// This implementation under the [`compat`] feature is meant to
    /// support parsing [`Cert`] instances which were generated with
    /// an early version of this library, and which used incorrect prefix
    /// lengths.
    /// 
    /// This has issue has long been fixed, but such certificates can
    /// still be found in the history of Krill instances with history
    /// going back to Krill version 0.3.0.
    fn check_len(
        mut addr: Prefix, family: AddressFamily
    ) -> Result<Prefix, ContentError> {
        addr.len = std::cmp::min(addr.len, family.max_addr_len());
        Ok(addr)
    }

    /*
    /// Skips over the address range at the beginning of a value.
    fn skip_opt_in<S: decode::Source>(
        cons: &mut decode::Constructed<S>
    ) -> Result<Option<()>, S::Error> {
        Self::take_opt_from(cons).map(|x| x.map(|_| ()))
    }
    */

    /// Calculates the prefix for the minimum address.
    ///
    /// This is a prefix with all trailing zeros dropped.
    fn min_to_prefix(&self) -> Prefix {
        Prefix::new(self.min, 128 - self.min.0.trailing_zeros() as u8)
    }

    /// Calculates the prefix for the maximum address.
    ///
    /// This is a prefix with all trailing ones dropped.
    fn max_to_prefix(&self) -> Prefix {
        Prefix::new(self.max, 128 - (!self.max.0).trailing_zeros() as u8)
    }

    /// Returns an encoder for the range.
    ///
    /// This encoder will produce a `IPAddressOrRange` value.
    pub fn encode(self) -> impl encode::Values {
        encode::sequence((
            self.min_to_prefix().encode(),
            self.max_to_prefix().encode(),
        ))
    }
}


//--- From and FromStr

impl From<(Addr, Addr)> for AddressRange {
    fn from((min, max): (Addr, Addr)) -> Self {
        AddressRange::new(min, max)
    }
}

impl From<Prefix> for AddressRange {
    fn from(prefix: Prefix) -> Self {
        AddressRange::new(prefix.min(), prefix.max())
    }
}

impl FromStr for AddressRange {
    type Err = FromStrError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let sep = s.find('-').ok_or(FromStrError::MissingSeparator)?;
        Self::from_str_sep(s, sep)
    }
}


//--- Block

impl Block for AddressRange {
    type Item = Addr;

    fn new(min: Self::Item, max: Self::Item) -> Self {
        Self::new(min, max)
    }

    fn min(&self) -> Self::Item {
        self.min()
    }

    fn max(&self) -> Self::Item {
        self.max()
    }

    fn next(item: Self::Item) -> Option<Self::Item> {
        item.0.checked_add(1).map(Addr)
    }

    fn previous(item: Self::Item) -> Option<Self::Item> {
        item.0.checked_sub(1).map(Addr)
    }    
}


//------------ Prefix --------------------------------------------------------

/// An IP address prefix.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct Prefix {
    /// The address of the prefix.
    ///
    /// The unused bits are zero.
    addr: Addr,

    /// The length of the prefix.
    ///
    /// This will never be more than 128.
    len: u8,
}

impl Prefix {
    /// Creates a new prefix from an address and a length.
    ///
    /// # Panics
    ///
    /// This function panics of `len` is larger than 128.
    pub fn new<A: Into<Addr>>(addr: A, len: u8) -> Self {
        assert!(len <= 128);
        Prefix { 
            addr: addr.into().to_min(len),
            len
        }
    }

    /// Creates a prefix covering all addresses.
    pub fn all() -> Self {
        Prefix::new(0, 0)
    }

    /// Creates a new prefix from its encoding as a BIT STRING.
    pub fn from_bit_string(
        src: &BitString
    ) -> Result<Self, DecodePrefixError> {
        if src.octet_len() > 16 {
            return Err(DecodePrefixError(()))
        }
        let mut addr = 0;
        for octet in src.octets() {
            addr = (addr << 8) | (u128::from(octet))
        }
        for _ in src.octet_len()..16 {
            addr <<= 8;
        }
        Ok(Self::new(addr, src.bit_len() as u8))
    }

    /// Creates a prefix from a string with a known position of the slash.
    fn from_str_sep(s: &str, sep: usize) -> Result<Self, FromStrError> {
        let addr = IpAddr::from_str(&s[..sep])?;
        let len = u8::from_str(&s[sep + 1..])?;
        if addr.is_ipv4() {
            if len > 32 {
                // XXX Produce an artificial overflow error.
                let _ = u8::from_str("256")?;
            }
        }
        else if len > 128 {
            // XXX Produce an artificial overflow error.
            let _ = u8::from_str("256")?;
        }
        Ok(Prefix::new(addr, len))
    }

    /// Creates a prefix from a IPv4 string with a known position of the slash.
    fn from_v4_str_sep(s: &str, sep: usize) -> Result<Self, FromStrError> {
        let addr = Ipv4Addr::from_str(&s[..sep])?;
        let len = u8::from_str(&s[sep + 1..])?;
        if len > 32 {
            // XXX Produce an artificial overflow error.
            let _ = u8::from_str("256")?;
        }
        Ok(Prefix::new(addr, len))
    }

    /// Creates a prefix from an IPv4 string.
    pub fn from_v4_str(s: &str) -> Result<Self, FromStrError> {
        let sep = s.find('/').ok_or(FromStrError::MissingSeparator)?;
        Self::from_v4_str_sep(s, sep)
    }

    /// Creates a prefix from a IPv6 string with a known position of the slash.
    fn from_v6_str_sep(s: &str, sep: usize) -> Result<Self, FromStrError> {
        let addr = Ipv6Addr::from_str(&s[..sep])?;
        let len = u8::from_str(&s[sep + 1..])?;
        if len > 128 {
            // XXX Produce an artificial overflow error.
            let _ = u8::from_str("256")?;
        }
        Ok(Prefix::new(addr, len))
    }

    /// Creates a prefix from an IPv6 string.
    pub fn from_v6_str(s: &str) -> Result<Self, FromStrError> {
        let sep = s.find('/').ok_or(FromStrError::MissingSeparator)?;
        Self::from_v6_str_sep(s, sep)
    }

    /// Returns the raw address of the prefix.
    pub fn addr(self) -> Addr {
        self.addr
    }

    /// Returns the length of the prefix.
    pub fn addr_len(self) -> u8 {
        self.len
    }

    /// Converts the prefix into an IPv4 address.
    pub fn to_v4(self) -> Ipv4Addr {
        self.addr.into()
    }

    /// Converts the prefix into an IPv6 address.
    pub fn to_v6(self) -> Ipv6Addr {
        self.addr.into()
    }

    /// Formats the prefix as an IPv4 prefix.
    pub fn fmt_v4(self, f: &mut fmt::Formatter) -> fmt::Result {
        self.addr.fmt_v4(f)?;
        if self.len != 32 {
            write!(f, "/{}", self.len)?
        }
        Ok(())
    }

    /// Formats the prefix as an IPv4 prefix.
    pub fn fmt_v6(self, f: &mut fmt::Formatter) -> fmt::Result {
        self.addr.fmt_v6(f)?;
        if self.len != 128 {
            write!(f, "/{}", self.len)?
        }
        Ok(())
    }

    /// Returns the range of addresses covered by this prefix.
    ///
    /// The first element of the returned pair is the smallest covered
    /// address, the second element is the largest.
    pub fn range(self) -> (Addr, Addr) {
        // self.addr has all unused bits cleared, so we don’t need to
        // explicitly do that for min.
        (self.addr, self.addr.to_max(self.len))
    }

    /// Returns the smallest address covered by the prefix.
    pub fn min(self) -> Addr {
        self.addr
    }

    /// Returns the largest address covered by the prefix.
    pub fn max(self) -> Addr {
        self.addr.to_max(self.addr_len())
    }

    /// Takes an encoded prefix from a source.
    pub fn take_from<S: decode::Source>(
        cons: &mut decode::Constructed<S>
    ) -> Result<Self, DecodeError<S::Error>> {
        Self::from_bit_string(
            &BitString::take_from(cons)?
        ).map_err(|err| cons.content_err(err))
    }

    /// Parses the content of a prefix.
    pub fn parse_content<S: decode::Source>(
        content: &mut decode::Content<S>
    ) -> Result<Self, DecodeError<S::Error>> {
        Self::from_bit_string(
            &BitString::from_content(content)?
        ).map_err(|err| content.content_err(err))
    }

    pub fn parse_content_with_family<S: decode::Source>(
        content: &mut decode::Content<S>,
        family: AddressFamily,
    ) -> Result<Self, DecodeError<S::Error>> {
        let res = Self::from_bit_string(
            &BitString::from_content(content)?
        ).map_err(|err| content.content_err(err))?;
        if res.addr_len() > family.max_addr_len() {
            return Err(content.content_err("invalid prefix in IP resources"))
        }
        Ok(res)
    }
}


//--- FromStr

impl FromStr for Prefix {
    type Err = FromStrError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let sep = s.find('/').ok_or(FromStrError::MissingSeparator)?;
        Self::from_str_sep(s, sep)
    }
}


//--- PrimitiveContent

impl encode::PrimitiveContent for Prefix {
    const TAG: Tag = Tag::BIT_STRING;

    fn encoded_len(&self, _: Mode) -> usize {
        if self.len % 8 == 0 {
            self.len as usize / 8 + 1
        }
        else {
            self.len as usize / 8 + 2
        }
    }

    fn write_encoded<W: io::Write>(
        &self, 
        _: Mode, 
        target: &mut W
    ) -> Result<(), io::Error> {
        // The type ensures that all the unused bits are zero, so we don’t
        // need to take care of that here.
        /*
        let len = if self.len % 8 == 0 { self.len / 8 }
                  else { self.len / 8 + 1 };
        if self.len % 8 == 0 {
            target.write_all(&[0])?;
        }
        else {
            target.write_all(&[(8 - self.len % 8) as u8])?;
        }
        let addr = self.addr.to_bytes();
        target.write_all(&addr[..len as usize])
        */

        let addr = self.addr.to_bytes();
        if self.len % 8 == 0 {
            target.write_all(&[0])?;
            target.write_all(&addr[..(self.len / 8) as usize])
        }
        else {
            target.write_all(&[8 - (self.len % 8)])?;
            target.write_all(&addr[..(self.len / 8 + 1) as usize])
        }
    }
}


//------------ Addr ----------------------------------------------------------

/// An address.
///
/// This can be both an IPv4 and IPv6 address. It keeps the address internally
/// as a 128 bit unsigned integer. IPv6 address are kept in there in host byte
/// order while IPv4 addresses are kept in the upper four bytes. This makes it
/// possible to count prefix lengths the same way for both addresses, i.e., 
/// starting from the top of the raw integer.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Addr(u128);

impl Addr {
    /// Creates a new address from 128 raw bits in host byte order.
    pub fn from_bits(bits: u128) -> Self {
        Addr(bits)
    }

    /// Creates a new address value for an IPv4 address.
    pub fn from_v4(addr: Ipv4Addr) -> Self {
        Addr::from_bits(u128::from(u32::from(addr)) << 96)
    }

    /// Creates a new address value for an IPv4 address.
    pub fn from_v6(addr: Ipv6Addr) -> Self {
        Addr::from_bits(u128::from(addr))
    }

    /// Creates a new address from a IPv4 string representation.
    pub fn from_v4_str(s: &str) -> Result<Self, AddrParseError> {
        Ipv4Addr::from_str(s).map(Into::into)
    }

    /// Creates a new address from a IPv4 string representation.
    pub fn from_v6_str(s: &str) -> Result<Self, AddrParseError> {
        Ipv6Addr::from_str(s).map(Into::into)
    }

    /// Returns the raw bits of the underlying integer.
    pub fn to_bits(self) -> u128 {
        self.0
    }

    /// Converts the address value into an IPv4 address.
    ///
    /// The methods disregards the lower twelve bytes of the value.
    pub fn to_v4(self) -> Ipv4Addr {
        ((self.0 >> 96) as u32).into()
    }

    /// Converts the address value into an IPv6 address.
    pub fn to_v6(self) -> Ipv6Addr {
        self.0.into()
    }

    /// Returns a byte array for the address.
    pub fn to_bytes(self) -> [u8; 16] {
        self.0.to_be_bytes()
    }

    /// Returns an address with all but the first `prefix_len` bits cleared.
    ///
    /// The first `prefix_len` bits are retained. Thus, the returned address
    /// is the smallest address in a prefix of this length.
    pub fn to_min(self, prefix_len: u8) -> Self {
        if prefix_len >= 128 {
            self
        }
        else {
            Addr(self.0 & !(!0 >> u32::from(prefix_len)))
        }
    }

    /// Returns an address with all but the first `prefix_len` bits set.
    ///
    /// The first `prefix_len` bits are retained. Thus, the returned address
    /// is the largest address in a prefix of this length.
    pub fn to_max(self, prefix_len: u8) -> Self {
        if prefix_len >= 128 {
            self
        }
        else {
            Addr(self.0 | (!0 >> prefix_len as usize))
        }
    }

    /// Formats the address as a IPv4 address.
    pub fn fmt_v4(self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&Ipv4Addr::from(self), f)
    }

    /// Formats the address as a IPv4 address.
    pub fn fmt_v6(self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&Ipv6Addr::from(self), f)
    }

}


//--- From and FromStr

impl From<u128> for Addr {
    fn from(addr: u128) -> Addr {
        Addr::from_bits(addr)
    }
}

impl From<Ipv4Addr> for Addr {
    fn from(addr: Ipv4Addr) -> Addr {
        Addr::from_v4(addr)
    }
}

impl From<Ipv6Addr> for Addr {
    fn from(addr: Ipv6Addr) -> Addr {
        Addr::from_v6(addr)
    }
}

impl From<IpAddr> for Addr {
    fn from(addr: IpAddr) -> Addr {
        match addr {
            IpAddr::V4(addr) => Addr::from(addr),
            IpAddr::V6(addr) => Addr::from(addr)
        }
    }
}

impl From<Addr> for u128 {
    fn from(addr: Addr) -> u128 {
        addr.to_bits()
    }
}

impl From<Addr> for Ipv4Addr {
    fn from(addr: Addr) -> Ipv4Addr {
        addr.to_v4()
    }
}

impl From<Addr> for Ipv6Addr {
    fn from(addr: Addr) -> Ipv6Addr {
        addr.to_v6()
    }
}


impl FromStr for Addr {
    type Err = AddrParseError;

    fn from_str(s: &str) -> Result<Self, AddrParseError> {
        IpAddr::from_str(s).map(Into::into)
    }
}



//------------ AddressFamily -------------------------------------------------

/// The address family of an IP resources value.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AddressFamily {
    /// IPv4.
    ///
    /// This is encoded by a two byte octet string with value `0x00 0x01`.
    Ipv4,

    /// IPv6.
    ///
    /// This is encoded by a two byte octet string with value `0x00 0x02`.
    Ipv6
}

impl AddressFamily {
    /// Takes a single address family from the beginning of a value.
    pub fn take_from<S: decode::Source>(
        cons: &mut decode::Constructed<S>
    ) -> Result<Self, DecodeError<S::Error>> {
        let octet_string = OctetString::take_from(cons)?;
        let afi = Self::decode_octet_string(
            octet_string
        ).map_err(|err| cons.content_err(err))?;
        Ok(afi)
    }

    pub fn take_opt_from<S: decode::Source>(
        cons: &mut decode::Constructed<S>
    ) -> Result<Option<Self>, DecodeError<S::Error>> {
        match OctetString::take_opt_from(cons)? {
            None => Ok(None),
            Some(octet_string) => {
                let afi = Self::decode_octet_string(
                    octet_string
                ).map_err(|err| cons.content_err(err))?;
                Ok(Some(afi))
            }
        }
    }

    pub fn skip_opt_in<S: decode::Source>(
        cons: &mut decode::Constructed<S>
    ) -> Result<Option<()>, DecodeError<S::Error>> {
        Self::take_opt_from(cons).map(|opt| opt.map(|_| ()))
    }

    fn decode_octet_string(
        octet_string: OctetString
    ) -> Result<AddressFamily, DecodeFamilyError> {
        let mut octets = octet_string.octets();
        let first = match octets.next() {
            Some(first) => first,
            None => return Err(DecodeFamilyError(())),
        };
        let second = match octets.next() {
            Some(second) => second,
            None => return Err(DecodeFamilyError(())),
        };
        if octets.next().is_some() {
            return Err(DecodeFamilyError(()))
        }
        match (first, second) {
            (0, 1) => Ok(AddressFamily::Ipv4),
            (0, 2) => Ok(AddressFamily::Ipv6),
            _ => Err(DecodeFamilyError(())),
        }
    }

    pub fn encode(self) -> impl encode::Values {
        OctetString::encode_slice(
            match self {
                AddressFamily::Ipv4 => b"\x00\x01",
                AddressFamily::Ipv6 => b"\x00\x02",
            }
        )
    }

    /// Returns the maximum prefix length for this family.
    pub fn max_addr_len(self) -> u8 {
        match self {
            AddressFamily::Ipv4 => 32,
            AddressFamily::Ipv6 => 128
        }
    }
}


//------------ Ipv4Block -----------------------------------------------------

/// A consecutive sequence of IPv4 addresses.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Ipv4Block(IpBlock);

impl Ipv4Block {
    /// Creates a new block covering all IPv4 addresses.
    pub fn all() -> Self {
        Self(IpBlock::all())
    }

    /// Returns whether the block is prefix with address length zero.
    pub fn is_slash_zero(&self) -> bool {
        self.0.is_slash_zero()
    }

    /// The smallest address of the block.
    pub fn min(&self) -> Ipv4Addr {
        self.0.min().into()
    }

    /// The largest address of the block.
    pub fn max(&self) -> Ipv4Addr {
        self.0.max().into()
    }
}


//--- From and FromStr

impl From<Ipv4Block> for IpBlock {
    fn from(src: Ipv4Block) -> IpBlock {
        src.0
    }
}

impl str::FromStr for Ipv4Block {
    type Err = FromStrError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self(IpBlock::from_v4_str(s)?))
    }
}


//--- Display

impl fmt::Display for Ipv4Block {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt_v4(f)
    }
}


//------------ Ipv6Block -----------------------------------------------------

/// A consecutive sequence of IPv6 addresses.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Ipv6Block(IpBlock);

impl Ipv6Block {
    /// Creates a new block covering all IPv6 addresses.
    pub fn all() -> Self {
        Self(IpBlock::all())
    }

    /// Returns whether the block is prefix with address length zero.
    pub fn is_slash_zero(&self) -> bool {
        self.0.is_slash_zero()
    }

    /// The smallest address of the block.
    pub fn min(&self) -> Ipv6Addr {
        self.0.min().into()
    }

    /// The largest address of the block.
    pub fn max(&self) -> Ipv6Addr {
        self.0.max().into()
    }
}


//--- From and FromStr

impl From<Ipv6Block> for IpBlock {
    fn from(src: Ipv6Block) -> IpBlock {
        src.0
    }
}

impl str::FromStr for Ipv6Block {
    type Err = FromStrError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self(IpBlock::from_v6_str(s)?))
    }
}


//--- Display

impl fmt::Display for Ipv6Block {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt_v6(f)
    }
}


//------------ Ipv4Blocks ----------------------------------------------------

/// Multiple consecutive sequences of IPv4 addresses.
///
/// Values of this type are guaranteed to contain a sequence of
/// [`Ipv4Block`]s that fulfills the requirements of RFC 3779. Specifically,
/// the blocks will not overlap, will not be consecutive (i.e., there’s at
/// least one address between neighbouring blocks), will be in order, and
/// anything that can be addressed as a prefix will be.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Ipv4Blocks(IpBlocks);

impl Ipv4Blocks {
    pub fn empty() -> Self {
        Ipv4Blocks(IpBlocks::empty())
    }

    /// Creates a value covering all addresses.
    pub fn all() -> Self {
        Ipv4Blocks(IpBlocks::all())
    }

    pub fn to_ip_resources(&self) -> IpResources {
        IpResources::blocks(self.0.clone())
    }
}

//--- Display

impl fmt::Display for Ipv4Blocks {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.as_v4().fmt(f)
    }
}

//--- FromStr and FromIterator

impl FromStr for Ipv4Blocks {
    type Err = FromStrError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut builder = IpBlocksBuilder::default();

        for el in s.split(',') {
            let s = el.trim();
            if s.is_empty() {
                continue
            } else if s.contains(':') {
                // smells like IPv6
                return Err(FromStrError::FamilyMismatch);
            } else {
                builder.push(IpBlock::from_v4_str(s)?);
            }
        }

        Ok(Ipv4Blocks(builder.finalize()))
    }
}

impl FromIterator<Ipv4Block> for Ipv4Blocks {
    fn from_iter<I: IntoIterator<Item = Ipv4Block>>(iter: I) -> Self {
        Self(IpBlocks::from_iter(iter.into_iter().map(Into::into)))
    }
}

//--- Serialize and Deserialize

#[cfg(feature = "serde")]
impl serde::Serialize for Ipv4Blocks {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where S: serde::Serializer {
        self.to_string().serialize(serializer)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Ipv4Blocks {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where D: serde::Deserializer<'de> {
        let string = String::deserialize(deserializer)?;
        Ipv4Blocks::from_str(&string).map_err(serde::de::Error::custom)
    }
}

impl From<IpBlocks> for Ipv4Blocks {
    fn from(blocks: IpBlocks) -> Self {
        Ipv4Blocks(blocks)
    }
}

//--- Deref

impl std::ops::Deref for Ipv4Blocks {
    type Target = IpBlocks;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}


//------------ Ipv6Blocks ----------------------------------------------------

/// Multiple consecutive sequences of IPv6 addresses.
///
/// Values of this type are guaranteed to contain a sequence of
/// [`Ipv6Block`]s that fulfills the requirements of RFC 3779. Specifically,
/// the blocks will not overlap, will not be consecutive (i.e., there’s at
/// least one address between neighbouring blocks), will be in order, and
/// anything that can be addressed as a prefix will be.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Ipv6Blocks(IpBlocks);

impl Ipv6Blocks {
    pub fn empty() -> Self {
        Ipv6Blocks(IpBlocks::empty())
    }

    /// Creates a value covering all addresses.
    pub fn all() -> Self {
        Ipv6Blocks(IpBlocks::all())
    }

    pub fn to_ip_resources(&self) -> IpResources {
        IpResources::blocks(self.0.clone())
    }
}

//--- Display

impl fmt::Display for Ipv6Blocks {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.as_v6().fmt(f)
    }
}

//--- FromStr and FromIterator

impl FromStr for Ipv6Blocks {
    type Err = FromStrError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut builder = IpBlocksBuilder::default();

        for el in s.split(',') {
            let s = el.trim();
            if s.is_empty() {
                continue
            } else if s.contains('.') {
                // smells like IPv4
                return Err(FromStrError::FamilyMismatch);
            } else {
                builder.push(IpBlock::from_v6_str(s)?);
            }
        }

        Ok(Ipv6Blocks(builder.finalize()))
    }
}

impl FromIterator<Ipv6Block> for Ipv6Blocks {
    fn from_iter<I: IntoIterator<Item = Ipv6Block>>(iter: I) -> Self {
        Self(IpBlocks::from_iter(iter.into_iter().map(Into::into)))
    }
}

//--- Serialize and Deserialize

#[cfg(feature = "serde")]
impl serde::Serialize for Ipv6Blocks {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where S: serde::Serializer {
        self.to_string().serialize(serializer)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Ipv6Blocks {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where D: serde::Deserializer<'de> {
        let string = String::deserialize(deserializer)?;
        Ipv6Blocks::from_str(&string).map_err(serde::de::Error::custom)
    }
}

impl From<IpBlocks> for Ipv6Blocks {
    fn from(blocks: IpBlocks) -> Self {
        Ipv6Blocks(blocks)
    }
}

//--- Deref

impl std::ops::Deref for Ipv6Blocks {
    type Target = IpBlocks;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}


//------------ DecodePrefixError ---------------------------------------------

#[derive(Clone, Copy, Debug)]
pub struct DecodePrefixError(());

impl From<DecodePrefixError> for ContentError {
    fn from(_: DecodePrefixError) -> Self {
        ContentError::from_static(
            "invalid prefix in IP resources"
        )
    }
}

impl fmt::Display for DecodePrefixError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("invalid prefix in IP resources")
    }
}


//------------ DecodeFamilyError ---------------------------------------------

#[derive(Clone, Copy, Debug)]
pub struct DecodeFamilyError(());

impl From<DecodeFamilyError> for ContentError {
    fn from(_: DecodeFamilyError) -> Self {
        ContentError::from_static(
            "invalid address family in IP resources"
        )
    }
}

impl fmt::Display for DecodeFamilyError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("invalid address family in IP resources")
    }
}


//============ Errors ========================================================

//------------ FromStrError --------------------------------------------------

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum FromStrError {
    Addr(AddrParseError),
    PrefixLen(ParseIntError),
    MissingSeparator,
    FamilyMismatch,
    BadBlocks,
}

impl From<AddrParseError> for FromStrError {
    fn from(err: AddrParseError) -> Self {
        FromStrError::Addr(err)
    }
}

impl From<ParseIntError> for FromStrError {
    fn from(err: ParseIntError) -> Self {
        FromStrError::PrefixLen(err)
    }
}

impl fmt::Display for FromStrError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            FromStrError::Addr(ref err) => err.fmt(f),
            FromStrError::PrefixLen(ref err)
                => write!(f, "bad prefix length: {err}"),
            FromStrError::MissingSeparator
                => f.write_str("missing separator"),
            FromStrError::FamilyMismatch
                => f.write_str("address family mismatch"),
            FromStrError::BadBlocks
                => f.write_str("cannot parse blocks"),
        }
    }
}

impl error::Error for FromStrError { }


//------------ InheritedIpResources ------------------------------------------

/// Inherited AS resources encountered where they are not allowed.
#[derive(Clone, Copy, Debug)]
pub struct InheritedIpResources(());

impl From<InheritedResources> for InheritedIpResources {
    fn from(_: InheritedResources) -> InheritedIpResources {
        InheritedIpResources(())
    }
}

impl fmt::Display for InheritedIpResources {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("inherited IP resources")
    }
}

impl error::Error for InheritedIpResources { }

impl From<InheritedIpResources> for VerificationError {
    fn from(_: InheritedIpResources) -> Self {
        VerificationError::new("inherited IP resources")
    }
}


//------------ OverclaimedIpResources ----------------------------------------

/// The AS resources of a certificate are not covered by its issuer.
#[derive(Clone, Debug)]
pub struct OverclaimedIpResources {
    issuer: IpBlocks,
    subject: IpBlocks,
}

impl OverclaimedIpResources {
    fn new(issuer: IpBlocks, subject: IpBlocks) -> Self {
        OverclaimedIpResources { issuer, subject }
    }

    pub fn v4(self) -> OverclaimedIpv4Resources {
        OverclaimedIpv4Resources(self)
    }

    pub fn v6(self) -> OverclaimedIpv6Resources {
        OverclaimedIpv6Resources(self)
    }
}


//------------ OverclaimedIpv4Resources --------------------------------------

/// The AS resources of a certificate are not covered by its issuer.
#[derive(Clone, Debug)]
pub struct OverclaimedIpv4Resources(OverclaimedIpResources);


impl fmt::Display for OverclaimedIpv4Resources {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "overclaimed IPv4 resources: {}",
            Ipv4Blocks(self.0.subject.difference(&self.0.issuer))
        )
    }
}

impl error::Error for OverclaimedIpv4Resources { }

impl From<OverclaimedIpv4Resources> for VerificationError {
    fn from(err: OverclaimedIpv4Resources) -> Self {
        ContentError::from_boxed(Box::new(err)).into()
    }
}


//------------ OverclaimedIpv6Resources --------------------------------------

/// The AS resources of a certificate are not covered by its issuer.
#[derive(Clone, Debug)]
pub struct OverclaimedIpv6Resources(OverclaimedIpResources);


impl fmt::Display for OverclaimedIpv6Resources {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "overclaimed IPv6 resources: {}",
            Ipv6Blocks(self.0.subject.difference(&self.0.issuer))
        )
    }
}

impl error::Error for OverclaimedIpv6Resources { }

impl From<OverclaimedIpv6Resources> for VerificationError {
    fn from(err: OverclaimedIpv6Resources) -> Self {
        ContentError::from_boxed(Box::new(err)).into()
    }
}


//============ Tests =========================================================

#[cfg(test)]
mod tests {
    use bcder::encode::Values;
    use super::*;

    #[test]
    fn ip_blocks_all() {
        assert_eq!(Ipv4Blocks::all().to_string(), "0.0.0.0/0");
        assert_eq!(Ipv6Blocks::all().to_string(), "::/0");
    }

    #[test]
    fn ip_blocks_to_v4_str() {
        let expected_str = "10.0.0.0, 10.1.0.0-10.1.2.255, 192.168.0.0/16";
        let blocks = IpBlocks::from_str(expected_str).unwrap();
        assert_eq!(expected_str, &blocks.as_v4().to_string())
    }

    #[test]
    fn ip_blocks_to_v6_str() {
        let expected_str = "::1, 2001:db8::/32";
        let blocks = IpBlocks::from_str(expected_str).unwrap();
        assert_eq!(expected_str, &blocks.as_v6().to_string())
    }

    #[test]
    fn parse_v4range_as_prefix_if_possible() {
        let range_str = "10.0.0.0-10.0.0.255";
        let prefix_str = "10.0.0.0/24";
        let blocks = IpBlocks::from_str(range_str).unwrap();
        assert_eq!(prefix_str, &blocks.as_v4().to_string())
    }

    #[test]
    fn parse_v6range_as_prefix_if_possible() {
        let range_str = "2001:db8:0:0:0:0:0:0-\
                         2001:db8:ffff:ffff:ffff:ffff:ffff:ffff";
        let prefix_str = "2001:db8::/32";
        let blocks = IpBlocks::from_str(range_str).unwrap();
        assert_eq!(prefix_str, &blocks.as_v6().to_string())
    }

    #[test]
    fn parse_overlapping_v4() {
        let input = "10.20.0.0, 10.0.0.0/16, 10.30.0.0-10.30.0.255, \
                     10.0.10.0/24";
        let output = "10.0.0.0/16, 10.20.0.0, 10.30.0.0/24";
        let encoded = [
            0x30, 18,
                0x03, 3, 0, 10, 0,
                0x03, 5, 0, 10, 20, 0, 0,
                0x03, 4, 0, 10, 30, 0
        ];

        let blocks = IpBlocks::from_str(input).unwrap();

        assert_eq!(
            blocks.as_v4().to_string(),
            output
        );
        assert_eq!(
            blocks.encode().to_captured(Mode::Der).as_slice(),
            &encoded
        );
    }

    #[test]
    fn parse_overlapping_v6() {
        let input = "2001:db8:0:20::, \
                     2001:db8:0:10::/64, \
                     2001:db8:0:30::-2001:db8:0:30::FF, \
                     2001:db8:0:10::/72";
        let output = "2001:db8:0:10::/64, 2001:db8:0:20::, \
                      2001:db8:0:30::/120"; 

        assert_eq!(
            IpBlocks::from_str(input).unwrap().as_v6().to_string(),
            output
        );
    }

    #[test]
    fn ip_blocks_cannot_parse_mix() {
        let input = "10.0.0.0, ::1, 2001:db8::/32";
        assert_eq!(
            IpBlocks::from_str(input).err(),
            Some(FromStrError::FamilyMismatch)
        );
    }

    #[test]
    fn ip_blocks_from_empty_str() {
        let expected_str = "";
        let blocks = IpBlocks::from_str("").unwrap();
        assert_eq!(expected_str, blocks.as_v4().to_string());
        assert_eq!(expected_str, blocks.as_v6().to_string());
    }

    #[test]
    fn ip_blocks_contains() {
        let super_set = IpBlocks::from_str("10.0.0.0/16, 192.168.0.0/16").unwrap();
        let same = IpBlocks::from_str("10.0.0.0/16, 192.168.0.0/16").unwrap();
        let higher_block = IpBlocks::from_str("192.168.0.0/16").unwrap();
        let smaller_left = IpBlocks::from_str("10.0.0.0/17").unwrap();
        let smaller_right = IpBlocks::from_str("10.0.0.0/17").unwrap();
        let smaller = IpBlocks::from_str("10.0.0.1-10.0.255.254").unwrap();
        let bigger_left = IpBlocks::from_str("19.9.9.255-10.0.255.255").unwrap();
        let bigger_right = IpBlocks::from_str("19.9.9.255-10.1.0.0").unwrap();
        let bigger = IpBlocks::from_str("19.9.9.255-10.1.0.0").unwrap();

        assert!(super_set.contains(&same));
        assert!(super_set.contains(&higher_block));
        assert!(super_set.contains(&smaller_left));
        assert!(super_set.contains(&smaller_right));
        assert!(super_set.contains(&smaller));
        assert!(!super_set.contains(&bigger_left));
        assert!(!super_set.contains(&bigger_right));
        assert!(!super_set.contains(&bigger ));
    }

    #[test]
    fn ip_blocks_neighbours() {
        let super_set = IpBlocks::from_str(
            "10.0.0.0-10.0.0.10, 10.0.0.11-10.0.0.20"
        ).unwrap();
        let between = IpBlocks::from_str("10.0.0.5-10.0.0.15").unwrap();

        assert!(super_set.contains(&between));
    }

    #[test]
    fn ip_blocks_intersection() {
        // Note: the IpBlocks::intersection function delegates to Chain::trim
        // which has been well fuzzed. Adding these tests here though for
        // readability and regression testing.

        // this:            |----
        // other:     |---|
        let this = IpBlocks::from_str("10.0.1.0-10.0.1.255").unwrap();
        let other = IpBlocks::from_str("10.0.0.0-10.0.0.255").unwrap();
        let expected = IpBlocks::empty();

        assert_eq!(this.intersection(&other), expected);
        assert_eq!(other.intersection(&this), expected);

        // this:            |----
        // other:     |-----|
        let this = IpBlocks::from_str("10.0.1.0/24").unwrap();
        let other = IpBlocks::from_str("10.0.0.0-10.0.1.0").unwrap();
        let expected = IpBlocks::from_str("10.0.1.0-10.0.1.0").unwrap();
        assert_eq!(expected, this.intersection(&other));
        assert_eq!(expected, other.intersection(&this));

        // this:          |----
        // other:     |-----|
        let this = IpBlocks::from_str("10.0.1.0/24").unwrap();
        let other = IpBlocks::from_str("10.0.0.0-10.0.1.27").unwrap();
        let expected = IpBlocks::from_str("10.0.1.0-10.0.1.27").unwrap();
        assert_eq!(expected, this.intersection(&other));
        assert_eq!(expected, other.intersection(&this));

        // this:          |----|
        // other:       |~{----|
        let this = IpBlocks::from_str("10.0.1.0/24").unwrap();
        let other = IpBlocks::from_str("10.0.0.0/23").unwrap();
        let expected = IpBlocks::from_str("10.0.1.0/24").unwrap();
        assert_eq!(expected, this.intersection(&other));
        assert_eq!(expected, other.intersection(&this));

        // this:          |----|
        // other:       |~{-----|
        let this = IpBlocks::from_str("10.0.1.0/24").unwrap();
        let other = IpBlocks::from_str("10.0.0.0-10.0.2.0").unwrap();
        let expected = IpBlocks::from_str("10.0.1.0/24").unwrap();
        assert_eq!(expected, this.intersection(&other));
        assert_eq!(expected, other.intersection(&this));

        // this:   |----------|
        // other:  |~~{-----|
        let this = IpBlocks::from_str("10.0.1.0/24").unwrap();
        let other = IpBlocks::from_str("10.0.1.3-10.0.1.98").unwrap();
        let expected = IpBlocks::from_str("10.0.1.3-10.0.1.98").unwrap();
        assert_eq!(expected, this.intersection(&other));
        assert_eq!(expected, other.intersection(&this));

        let this = IpBlocks::from_str("10.0.1.0/24").unwrap();
        let other = IpBlocks::from_str("10.0.1.0-10.0.1.98").unwrap();
        let expected = IpBlocks::from_str("10.0.1.0-10.0.1.98").unwrap();
        assert_eq!(expected, this.intersection(&other));
        assert_eq!(expected, other.intersection(&this));

        // this:   |----------|
        // other:  |~~{-------|
        let this = IpBlocks::from_str("10.0.1.0/24").unwrap();
        let other = IpBlocks::from_str("10.0.1.3-10.0.1.255").unwrap();
        let expected = IpBlocks::from_str("10.0.1.3-10.0.1.255").unwrap();
        assert_eq!(expected, this.intersection(&other));
        assert_eq!(expected, other.intersection(&this));

        let this = IpBlocks::from_str("10.0.1.0/24").unwrap();
        let other = IpBlocks::from_str("10.0.1.0-10.0.1.255").unwrap();
        let expected = IpBlocks::from_str("10.0.1.0-10.0.1.255").unwrap();
        assert_eq!(expected, this.intersection(&other));
        assert_eq!(expected, other.intersection(&this));

        // this:   |----------|
        // other:  |~~{----------|
        let this = IpBlocks::from_str("10.0.1.0/24").unwrap();
        let other = IpBlocks::from_str("10.0.1.3-10.0.2.0").unwrap();
        let expected = IpBlocks::from_str("10.0.1.3-10.0.1.255").unwrap();
        // Looking at the number, IPv4 is modelled as the left most 4 bytes in a u128
        // so the max number of the intersection comes out as 10.0.1.255 with the
        // remaining bytes set to FF. This is not significant but is not treated
        // as equals.
        //
        // In short we assert here that the as_v4().to_string() is equal, because
        // then these bytes are dropped.
        assert_eq!(
            this.intersection(&other).as_v4().to_string(),
            expected.as_v4().to_string()
        );
        assert_eq!(
            other.intersection(&this).as_v4().to_string(),
            expected.as_v4().to_string()
        );

        // this:   |------|
        // other:         |---------|
        let this = IpBlocks::from_str("10.0.0.0/24").unwrap();
        let other = IpBlocks::from_str("10.0.0.255-10.0.1.0").unwrap();
        let expected = IpBlocks::from_str("10.0.0.255/32").unwrap();
        assert_eq!(
            this.intersection(&other).as_v4().to_string(),
            expected.as_v4().to_string()
        );
        assert_eq!(
            other.intersection(&this).as_v4().to_string(),
            expected.as_v4().to_string()
        );

        // this:     |-----|
        // other:            |---
        let this = IpBlocks::from_str("10.0.0.0/24").unwrap();
        let other = IpBlocks::from_str("10.0.1.0/24").unwrap();
        let expected = IpBlocks::empty();
        assert_eq!(expected, this.intersection(&other));
        assert_eq!(expected, other.intersection(&this));
    }

    #[test]
    fn ip_blocks_difference() {
        // This delegates to Chain::difference which is well tested
        // There is no difference ultimately between IPv4 and IPv6 for this,
        // it's all based on min and max numbers. So we can just test
        // with v4 to have a more readable example of this.
        let v4_left = "10.0.0.0, 10.1.0.0-10.1.2.255, 192.168.0.0/16";
        let v4_right = "10.0.0.0/24, 192.168.255.0/24";
        let v4_expected = "10.1.0.0-10.1.2.255, 192.168.0.0-192.168.254.255";

        let v4_left = IpBlocks::from_str(v4_left).unwrap();
        let v4_right = IpBlocks::from_str(v4_right).unwrap();
        let v4_expected = IpBlocks::from_str(v4_expected).unwrap();

        let v4_found = v4_left.difference(&v4_right);

        assert_eq!(v4_expected, v4_found);
    }    

    #[test]
    fn ip_block_from_v4_str() {
        fn check(s: &str, prefix: bool, min: &str, max: &str) {
            let block = IpBlock::from_v4_str(s).unwrap();
            let is_prefix = matches!(block, IpBlock::Prefix(_));
            assert_eq!(prefix, is_prefix);
            assert_eq!(
                block.min(),
                Addr::from(Ipv4Addr::from_str(min).unwrap()).to_min(32)
            );
            assert_eq!(
                block.max(),
                Addr::from(Ipv4Addr::from_str(max).unwrap()).to_max(32)
            );
        }

        check(
            "127.0.0.0/8", true,
            "127.0.0.0", "127.255.255.255"
        );
        check(
            "127.0.0.0-199.0.0.0", false,
            "127.0.0.0", "199.0.0.0"
        );
        check(
            "127.0.0.0", false,
            "127.0.0.0", "127.0.0.0"
        );
        assert!(IpBlock::from_v4_str("127.0.0.0/82").is_err());
        assert!(IpBlock::from_v4_str("127.0.0.0/282").is_err());
        assert!(IpBlock::from_v4_str("127.0.0.0/-282").is_err());
        assert!(IpBlock::from_v4_str("::32/82").is_err());
        assert!(IpBlock::from_v4_str("::32-::1").is_err());
    }

    #[test]
    fn ip_block_from_v6_str() {
        assert_eq!(
            IpBlock::from_v6_str("7f00::").unwrap(),
            IpBlock::Range((Addr(127 << 120), Addr(127 << 120)).into())
        );
        assert_eq!(
            IpBlock::from_v6_str("7f00::/8").unwrap(),
            IpBlock::Prefix(Prefix::new(Addr(127 << 120), 8))
        );
        assert_eq!(
            IpBlock::from_v6_str("7f00::-c700::").unwrap(),
            IpBlock::Range((Addr(127 << 120), Addr(199 << 120)).into())
        );
        assert!(IpBlock::from_v6_str("f700::/282").is_err());
        assert!(IpBlock::from_v6_str("f700:/-282").is_err());
        assert!(IpBlock::from_v6_str("127.0.0.0/8").is_err());
        assert!(IpBlock::from_v6_str("127.0.0.0-199.0.0.0").is_err());
    }

    #[test]
    fn ip_block_from_str() {
        fn check_v4(s: &str, prefix: bool, min: &str, max: &str) {
            let block = IpBlock::from_str(s).unwrap();
            let is_prefix = matches!(block, IpBlock::Prefix(_));
            assert_eq!(prefix, is_prefix);
            assert_eq!(
                block.min(),
                Addr::from(Ipv4Addr::from_str(min).unwrap()).to_min(32)
            );
            assert_eq!(
                block.max(),
                Addr::from(Ipv4Addr::from_str(max).unwrap()).to_max(32)
            );
        }

        check_v4(
            "127.0.0.0/8", true,
            "127.0.0.0", "127.255.255.255"
        );
        check_v4(
            "127.0.0.0-199.0.0.0", false,
            "127.0.0.0", "199.0.0.0"
        );
        check_v4(
            "127.0.0.0", false,
            "127.0.0.0", "127.0.0.0"
        );

        assert_eq!(
            IpBlock::from_str("7f00::").unwrap(),
            IpBlock::Range((Addr(127 << 120), Addr(127 << 120)).into())
        );
        assert_eq!(
            IpBlock::from_str("7f00::/8").unwrap(),
            IpBlock::Prefix(Prefix::new(Addr(127 << 120), 8))
        );
        assert_eq!(
            IpBlock::from_str("7f00::-c700::").unwrap(),
            IpBlock::Range((Addr(127 << 120), Addr(199 << 120)).into())
        );

        assert!(IpBlock::from_str("127.0.0.0/82").is_err());
        assert!(IpBlock::from_str("127.0.0.0/282").is_err());
        assert!(IpBlock::from_str("127.0.0.0/-282").is_err());
        assert!(IpBlock::from_str("f700::/282").is_err());
        assert!(IpBlock::from_str("f700:/-282").is_err());
    }

    #[test]
    fn block_is_slash_zero() {
        assert!(IpBlock::from_str("0.0.0.0/0").unwrap().is_slash_zero());
        assert!(IpBlock::from_str("::/0").unwrap().is_slash_zero());
        assert!(!IpBlock::from_str("0.0.0.0/10").unwrap().is_slash_zero());
        assert!(!IpBlock::from_str("::/10").unwrap().is_slash_zero());
        assert!(
            !IpBlock::from_str(
                "0.0.0.0-255.255.255.255"
            ).unwrap().is_slash_zero()
        );
    }

    #[test]
    fn prefix_encode() {
        assert_eq!(
            Prefix::new(Ipv4Addr::new(192, 168, 103, 0), 0)
                .encode().to_captured(Mode::Der).as_slice(),
            b"\x03\x01\x00".as_ref()
        );
        assert_eq!(
            Prefix::new(Ipv4Addr::new(192, 168, 103, 0), 18)
                .encode().to_captured(Mode::Der).as_slice(),
            b"\x03\x04\x06\xC0\xA8\x40".as_ref()
        );
        assert_eq!(
            Prefix::new(Ipv4Addr::new(192, 168, 103, 0), 16)
                .encode().to_captured(Mode::Der).as_slice(),
            b"\x03\x03\x00\xC0\xA8".as_ref()
        );
        assert_eq!(
            Prefix::new(Ipv4Addr::new(192, 168, 103, 0), 32)
                .encode().to_captured(Mode::Der).as_slice(),
            b"\x03\x05\x00\xC0\xA8\x67\x00".as_ref()
        );
    }

    #[test]
    fn addr_from() {
        assert_eq!(
            Addr::from(0x1234_5678_1234_5678),
            Addr(0x1234_5678_1234_5678)
        );
        assert_eq!(
            u128::from(Addr(0x1234_5678_1234_5678)),
            0x1234_5678_1234_5678
        );
        assert_eq!(
            Addr::from(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1))),
            Addr(0x7F00_0001_0000_0000_0000_0000_0000_0000)
        );
        assert_eq!(
            Ipv4Addr::from(Addr(0x7F00_0001_0000_0000_0000_0000_0000_0000)),
            Ipv4Addr::new(127, 0, 0, 1)
        );
        assert_eq!(
            Addr::from(IpAddr::V6(Ipv6Addr::new(
                0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56
            ))),
            Addr(0x00120034005600780090001200340056)
        );
        assert_eq!(
            Ipv6Addr::from(Addr(0x00120034005600780090001200340056)),
            Ipv6Addr::new(
                0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56
            )
        );
    }
    
    #[test]
    fn addr_to_min_max() {
        assert_eq!(
            Addr(0x1234_5678_1234_5678_1234_5678_1234_5678).to_min(11).0,
            0x1220_0000_0000_0000_0000_0000_0000_0000
        );
        assert_eq!(
            Addr(0x1234_5678_1234_5678_1234_5678_1234_5678).to_max(11).0,
            0x123f_ffff_ffff_ffff_ffff_ffff_ffff_ffff
        );
    }

    #[test]
    fn to_prefixes() {
        {
            let range = AddressRange::new(
                Addr::from(Ipv6Addr::from_str("::1").unwrap()), 
                Addr::from(Ipv6Addr::from_str("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe").unwrap())
            );

            let prefixes = range.to_v6_prefixes();

            assert_eq!(254, prefixes.count());
        }
        {
            let range = AddressRange::new(
                Addr::from(Ipv4Addr::from_str("192.168.0.0").unwrap()), 
                Addr::from(Ipv4Addr::from_str("192.168.2.255").unwrap())
            );

            let prefixes = range.to_v4_prefixes();

            assert_eq!(2, prefixes.count());
        }
        {
            let range = AddressRange::new(
                Addr::from(Ipv4Addr::from_str("192.168.2.255").unwrap()), 
                Addr::from(Ipv4Addr::from_str("192.168.0.0").unwrap())
            );

            let prefixes = range.to_v4_prefixes();

            assert_eq!(0, prefixes.count());
        }
    }

    #[test]
    fn to_full_prefixes() {
        {
            let range = AddressRange::new(
                Addr::from(Ipv6Addr::from_str("::").unwrap()), 
                Addr::from(Ipv6Addr::from_str("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff").unwrap())
            );

            let prefixes = range.to_v6_prefixes();

            assert_eq!(1, prefixes.count());
        }
        {
            let range = AddressRange::new(
                Addr::from(Ipv4Addr::from_str("0.0.0.0").unwrap()), 
                Addr::from(Ipv4Addr::from_str("255.255.255.255").unwrap())
            );

            let prefixes = range.to_v4_prefixes();

            assert_eq!(1, prefixes.count());
        }
    }
}

#[cfg(all(test, feature="compat"))]
mod compat_test {

    #[test]
    fn compat_incorrect_prefix_in_early_cert() {
        use bytes::Bytes;
        use crate::repository::cert::Cert;

        let der = include_bytes!("../../../test-data/compat/res_incorrect.cer");
        Cert::decode(Bytes::from_static(der)).unwrap();
    }
}