smoltcp 0.13.1

A TCP/IP stack designed for bare-metal, real-time systems without a heap.
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
//! Implementation of the RPL packet formats. See [RFC 6550 § 6].
//!
//! [RFC 6550 § 6]: https://datatracker.ietf.org/doc/html/rfc6550#section-6

use byteorder::{ByteOrder, NetworkEndian};

use super::{Error, Result};
use crate::wire::icmpv6::Packet;
use crate::wire::ipv6::{Address, AddressExt};

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[repr(u8)]
pub enum InstanceId {
    Global(u8),
    Local(u8),
}

impl From<u8> for InstanceId {
    fn from(val: u8) -> Self {
        const MASK: u8 = 0b0111_1111;

        if ((val >> 7) & 0xb1) == 0b0 {
            Self::Global(val & MASK)
        } else {
            Self::Local(val & MASK)
        }
    }
}

impl From<InstanceId> for u8 {
    fn from(val: InstanceId) -> Self {
        match val {
            InstanceId::Global(val) => 0b0000_0000 | val,
            InstanceId::Local(val) => 0b1000_0000 | val,
        }
    }
}

impl InstanceId {
    /// Return the real part of the ID.
    pub fn id(&self) -> u8 {
        match self {
            Self::Global(val) => *val,
            Self::Local(val) => *val,
        }
    }

    /// Returns `true` when the DODAG ID is the destination address of the IPv6 packet.
    #[inline]
    pub fn dodag_is_destination(&self) -> bool {
        match self {
            Self::Global(_) => false,
            Self::Local(val) => ((val >> 6) & 0b1) == 0b1,
        }
    }

    /// Returns `true` when the DODAG ID is the source address of the IPv6 packet.
    ///
    /// *NOTE*: this only makes sense when using a local RPL Instance ID and the packet is not a
    /// RPL control message.
    #[inline]
    pub fn dodag_is_source(&self) -> bool {
        !self.dodag_is_destination()
    }
}

mod field {
    use crate::wire::field::*;

    pub const RPL_INSTANCE_ID: usize = 4;

    // DODAG information solicitation fields (DIS)
    pub const DIS_FLAGS: usize = 4;
    pub const DIS_RESERVED: usize = 5;

    // DODAG information object fields (DIO)
    pub const DIO_VERSION_NUMBER: usize = 5;
    pub const DIO_RANK: Field = 6..8;
    pub const DIO_GROUNDED: usize = 8;
    pub const DIO_MOP: usize = 8;
    pub const DIO_PRF: usize = 8;
    pub const DIO_DTSN: usize = 9;
    //pub const DIO_FLAGS: usize = 10;
    //pub const DIO_RESERVED: usize = 11;
    pub const DIO_DODAG_ID: Field = 12..12 + 16;

    // Destination advertisement object (DAO)
    pub const DAO_K: usize = 5;
    pub const DAO_D: usize = 5;
    //pub const DAO_FLAGS: usize = 5;
    //pub const DAO_RESERVED: usize = 6;
    pub const DAO_SEQUENCE: usize = 7;
    pub const DAO_DODAG_ID: Field = 8..8 + 16;

    // Destination advertisement object ack (DAO-ACK)
    pub const DAO_ACK_D: usize = 5;
    //pub const DAO_ACK_RESERVED: usize = 5;
    pub const DAO_ACK_SEQUENCE: usize = 6;
    pub const DAO_ACK_STATUS: usize = 7;
    pub const DAO_ACK_DODAG_ID: Field = 8..8 + 16;
}

enum_with_unknown! {
    /// RPL Control Message subtypes.
    pub enum RplControlMessage(u8) {
        DodagInformationSolicitation = 0x00,
        DodagInformationObject = 0x01,
        DestinationAdvertisementObject = 0x02,
        DestinationAdvertisementObjectAck = 0x03,
        SecureDodagInformationSolicitation = 0x80,
        SecureDodagInformationObject = 0x81,
        SecureDestinationAdvertisementObject = 0x82,
        SecureDestinationAdvertisementObjectAck = 0x83,
        ConsistencyCheck = 0x8a,
    }
}

impl core::fmt::Display for RplControlMessage {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            RplControlMessage::DodagInformationSolicitation => {
                write!(f, "DODAG information solicitation (DIS)")
            }
            RplControlMessage::DodagInformationObject => {
                write!(f, "DODAG information object (DIO)")
            }
            RplControlMessage::DestinationAdvertisementObject => {
                write!(f, "destination advertisement object (DAO)")
            }
            RplControlMessage::DestinationAdvertisementObjectAck => write!(
                f,
                "destination advertisement object acknowledgement (DAO-ACK)"
            ),
            RplControlMessage::SecureDodagInformationSolicitation => {
                write!(f, "secure DODAG information solicitation (DIS)")
            }
            RplControlMessage::SecureDodagInformationObject => {
                write!(f, "secure DODAG information object (DIO)")
            }
            RplControlMessage::SecureDestinationAdvertisementObject => {
                write!(f, "secure destination advertisement object (DAO)")
            }
            RplControlMessage::SecureDestinationAdvertisementObjectAck => write!(
                f,
                "secure destination advertisement object acknowledgement (DAO-ACK)"
            ),
            RplControlMessage::ConsistencyCheck => write!(f, "consistency check (CC)"),
            RplControlMessage::Unknown(id) => write!(f, "{}", id),
        }
    }
}

impl<T: AsRef<[u8]>> Packet<T> {
    /// Return the RPL instance ID.
    #[inline]
    pub fn rpl_instance_id(&self) -> InstanceId {
        get!(self.buffer, into: InstanceId, field: field::RPL_INSTANCE_ID)
    }
}

impl<'p, T: AsRef<[u8]> + ?Sized> Packet<&'p T> {
    /// Return a pointer to the options.
    pub fn options(&self) -> Result<&'p [u8]> {
        let len = self.buffer.as_ref().len();
        match RplControlMessage::from(self.msg_code()) {
            RplControlMessage::DodagInformationSolicitation if len < field::DIS_RESERVED + 1 => {
                return Err(Error);
            }
            RplControlMessage::DodagInformationObject if len < field::DIO_DODAG_ID.end => {
                return Err(Error);
            }
            RplControlMessage::DestinationAdvertisementObject
                if self.dao_dodag_id_present() && len < field::DAO_DODAG_ID.end =>
            {
                return Err(Error);
            }
            RplControlMessage::DestinationAdvertisementObject if len < field::DAO_SEQUENCE + 1 => {
                return Err(Error);
            }
            RplControlMessage::DestinationAdvertisementObjectAck
                if self.dao_ack_dodag_id_present() && len < field::DAO_ACK_DODAG_ID.end =>
            {
                return Err(Error);
            }
            RplControlMessage::DestinationAdvertisementObjectAck
                if len < field::DAO_ACK_STATUS + 1 =>
            {
                return Err(Error);
            }
            RplControlMessage::SecureDodagInformationSolicitation
            | RplControlMessage::SecureDodagInformationObject
            | RplControlMessage::SecureDestinationAdvertisementObject
            | RplControlMessage::SecureDestinationAdvertisementObjectAck
            | RplControlMessage::ConsistencyCheck => return Err(Error),
            RplControlMessage::Unknown(_) => return Err(Error),
            _ => {}
        }

        let buffer = &self.buffer.as_ref();
        Ok(match RplControlMessage::from(self.msg_code()) {
            RplControlMessage::DodagInformationSolicitation => &buffer[field::DIS_RESERVED + 1..],
            RplControlMessage::DodagInformationObject => &buffer[field::DIO_DODAG_ID.end..],
            RplControlMessage::DestinationAdvertisementObject if self.dao_dodag_id_present() => {
                &buffer[field::DAO_DODAG_ID.end..]
            }
            RplControlMessage::DestinationAdvertisementObject => &buffer[field::DAO_SEQUENCE + 1..],
            RplControlMessage::DestinationAdvertisementObjectAck
                if self.dao_ack_dodag_id_present() =>
            {
                &buffer[field::DAO_ACK_DODAG_ID.end..]
            }
            RplControlMessage::DestinationAdvertisementObjectAck => {
                &buffer[field::DAO_ACK_STATUS + 1..]
            }
            RplControlMessage::SecureDodagInformationSolicitation
            | RplControlMessage::SecureDodagInformationObject
            | RplControlMessage::SecureDestinationAdvertisementObject
            | RplControlMessage::SecureDestinationAdvertisementObjectAck
            | RplControlMessage::ConsistencyCheck => unreachable!(),
            RplControlMessage::Unknown(_) => unreachable!(),
        })
    }
}

impl<T: AsRef<[u8]> + AsMut<[u8]>> Packet<T> {
    /// Set the RPL Instance ID field.
    #[inline]
    pub fn set_rpl_instance_id(&mut self, value: u8) {
        set!(self.buffer, value, field: field::RPL_INSTANCE_ID)
    }
}

impl<'p, T: AsRef<[u8]> + AsMut<[u8]> + ?Sized> Packet<&'p mut T> {
    /// Return a pointer to the options.
    pub fn options_mut(&mut self) -> &mut [u8] {
        match RplControlMessage::from(self.msg_code()) {
            RplControlMessage::DodagInformationSolicitation => {
                &mut self.buffer.as_mut()[field::DIS_RESERVED + 1..]
            }
            RplControlMessage::DodagInformationObject => {
                &mut self.buffer.as_mut()[field::DIO_DODAG_ID.end..]
            }
            RplControlMessage::DestinationAdvertisementObject => {
                if self.dao_dodag_id_present() {
                    &mut self.buffer.as_mut()[field::DAO_DODAG_ID.end..]
                } else {
                    &mut self.buffer.as_mut()[field::DAO_SEQUENCE + 1..]
                }
            }
            RplControlMessage::DestinationAdvertisementObjectAck => {
                if self.dao_ack_dodag_id_present() {
                    &mut self.buffer.as_mut()[field::DAO_ACK_DODAG_ID.end..]
                } else {
                    &mut self.buffer.as_mut()[field::DAO_ACK_STATUS + 1..]
                }
            }
            RplControlMessage::SecureDodagInformationSolicitation
            | RplControlMessage::SecureDodagInformationObject
            | RplControlMessage::SecureDestinationAdvertisementObject
            | RplControlMessage::SecureDestinationAdvertisementObjectAck
            | RplControlMessage::ConsistencyCheck => todo!("Secure messages not supported"),
            RplControlMessage::Unknown(_) => todo!(),
        }
    }
}

/// Getters for the DODAG information solicitation (DIS) message.
///
/// ```txt
///  0                   1                   2
///  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |     Flags     |   Reserved    |   Option(s)...
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// ```
impl<T: AsRef<[u8]>> Packet<T> {
    /// Return the DIS flags field.
    #[inline]
    pub fn dis_flags(&self) -> u8 {
        get!(self.buffer, field: field::DIS_FLAGS)
    }

    /// Return the DIS reserved field.
    #[inline]
    pub fn dis_reserved(&self) -> u8 {
        get!(self.buffer, field: field::DIS_RESERVED)
    }
}

/// Setters for the DODAG information solicitation (DIS) message.
impl<T: AsRef<[u8]> + AsMut<[u8]>> Packet<T> {
    /// Clear the DIS flags field.
    pub fn clear_dis_flags(&mut self) {
        self.buffer.as_mut()[field::DIS_FLAGS] = 0;
    }

    /// Clear the DIS rserved field.
    pub fn clear_dis_reserved(&mut self) {
        self.buffer.as_mut()[field::DIS_RESERVED] = 0;
    }
}

enum_with_unknown! {
    pub enum ModeOfOperation(u8) {
        NoDownwardRoutesMaintained = 0x00,
        NonStoringMode = 0x01,
        StoringModeWithoutMulticast = 0x02,
        StoringModeWithMulticast = 0x03,
    }
}

impl Default for ModeOfOperation {
    fn default() -> Self {
        Self::StoringModeWithoutMulticast
    }
}

/// Getters for the DODAG information object (DIO) message.
///
/// ```txt
///  0                   1                   2                   3
///  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// | RPLInstanceID |Version Number |             Rank              |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |G|0| MOP | Prf |     DTSN      |     Flags     |   Reserved    |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |                                                               |
/// +                                                               +
/// |                                                               |
/// +                            DODAGID                            +
/// |                                                               |
/// +                                                               +
/// |                                                               |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |   Option(s)...
/// +-+-+-+-+-+-+-+-+
/// ```
impl<T: AsRef<[u8]>> Packet<T> {
    /// Return the Version Number field.
    #[inline]
    pub fn dio_version_number(&self) -> u8 {
        get!(self.buffer, field: field::DIO_VERSION_NUMBER)
    }

    /// Return the Rank field.
    #[inline]
    pub fn dio_rank(&self) -> u16 {
        get!(self.buffer, u16, field: field::DIO_RANK)
    }

    /// Return the value of the Grounded flag.
    #[inline]
    pub fn dio_grounded(&self) -> bool {
        get!(self.buffer, bool, field: field::DIO_GROUNDED, shift: 7, mask: 0b01)
    }

    /// Return the mode of operation field.
    #[inline]
    pub fn dio_mode_of_operation(&self) -> ModeOfOperation {
        get!(self.buffer, into: ModeOfOperation, field: field::DIO_MOP, shift: 3, mask: 0b111)
    }

    /// Return the DODAG preference field.
    #[inline]
    pub fn dio_dodag_preference(&self) -> u8 {
        get!(self.buffer, field: field::DIO_PRF, mask: 0b111)
    }

    /// Return the destination advertisement trigger sequence number.
    #[inline]
    pub fn dio_dest_adv_trigger_seq_number(&self) -> u8 {
        get!(self.buffer, field: field::DIO_DTSN)
    }

    /// Return the DODAG id, which is an IPv6 address.
    #[inline]
    pub fn dio_dodag_id(&self) -> Address {
        Address::from_octets(
            self.buffer.as_ref()[field::DIO_DODAG_ID]
                .try_into()
                .unwrap(),
        )
    }
}

/// Setters for the DODAG information object (DIO) message.
impl<T: AsRef<[u8]> + AsMut<[u8]>> Packet<T> {
    /// Set the Version Number field.
    #[inline]
    pub fn set_dio_version_number(&mut self, value: u8) {
        set!(self.buffer, value, field: field::DIO_VERSION_NUMBER)
    }

    /// Set the Rank field.
    #[inline]
    pub fn set_dio_rank(&mut self, value: u16) {
        set!(self.buffer, value, u16, field: field::DIO_RANK)
    }

    /// Set the value of the Grounded flag.
    #[inline]
    pub fn set_dio_grounded(&mut self, value: bool) {
        set!(self.buffer, value, bool, field: field::DIO_GROUNDED, shift: 7, mask: 0b01)
    }

    ///  Set the mode of operation field.
    #[inline]
    pub fn set_dio_mode_of_operation(&mut self, mode: ModeOfOperation) {
        let raw = (self.buffer.as_ref()[field::DIO_MOP] & !(0b111 << 3)) | (u8::from(mode) << 3);
        self.buffer.as_mut()[field::DIO_MOP] = raw;
    }

    /// Set the DODAG preference field.
    #[inline]
    pub fn set_dio_dodag_preference(&mut self, value: u8) {
        set!(self.buffer, value, field: field::DIO_PRF, mask: 0b111)
    }

    /// Set the destination advertisement trigger sequence number.
    #[inline]
    pub fn set_dio_dest_adv_trigger_seq_number(&mut self, value: u8) {
        set!(self.buffer, value, field: field::DIO_DTSN)
    }

    /// Set the DODAG id, which is an IPv6 address.
    #[inline]
    pub fn set_dio_dodag_id(&mut self, address: Address) {
        set!(self.buffer, address: address, field: field::DIO_DODAG_ID)
    }
}

/// Getters for the Destination Advertisement Object (DAO) message.
///
/// ```txt
///  0                   1                   2                   3
///  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// | RPLInstanceID |K|D|   Flags   |   Reserved    | DAOSequence   |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |                                                               |
/// +                                                               +
/// |                                                               |
/// +                            DODAGID*                           +
/// |                                                               |
/// +                                                               +
/// |                                                               |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |   Option(s)...
/// +-+-+-+-+-+-+-+-+
/// ```
impl<T: AsRef<[u8]>> Packet<T> {
    /// Returns the Expect DAO-ACK flag.
    #[inline]
    pub fn dao_ack_request(&self) -> bool {
        get!(self.buffer, bool, field: field::DAO_K, shift: 7, mask: 0b1)
    }

    /// Returns the flag indicating that the DODAG ID is present or not.
    #[inline]
    pub fn dao_dodag_id_present(&self) -> bool {
        get!(self.buffer, bool, field: field::DAO_D, shift: 6, mask: 0b1)
    }

    /// Returns the DODAG sequence flag.
    #[inline]
    pub fn dao_dodag_sequence(&self) -> u8 {
        get!(self.buffer, field: field::DAO_SEQUENCE)
    }

    /// Returns the DODAG ID, an IPv6 address, when it is present.
    #[inline]
    pub fn dao_dodag_id(&self) -> Option<Address> {
        if self.dao_dodag_id_present() {
            Some(Address::from_octets(
                self.buffer.as_ref()[field::DAO_DODAG_ID]
                    .try_into()
                    .unwrap(),
            ))
        } else {
            None
        }
    }
}

/// Setters for the Destination Advertisement Object (DAO) message.
impl<T: AsRef<[u8]> + AsMut<[u8]>> Packet<T> {
    /// Set the Expect DAO-ACK flag.
    #[inline]
    pub fn set_dao_ack_request(&mut self, value: bool) {
        set!(self.buffer, value, bool, field: field::DAO_K, shift: 7, mask: 0b1,)
    }

    /// Set the flag indicating that the DODAG ID is present or not.
    #[inline]
    pub fn set_dao_dodag_id_present(&mut self, value: bool) {
        set!(self.buffer, value, bool, field: field::DAO_D, shift: 6, mask: 0b1)
    }

    /// Set the DODAG sequence flag.
    #[inline]
    pub fn set_dao_dodag_sequence(&mut self, value: u8) {
        set!(self.buffer, value, field: field::DAO_SEQUENCE)
    }

    /// Set the DODAG ID.
    #[inline]
    pub fn set_dao_dodag_id(&mut self, address: Option<Address>) {
        match address {
            Some(address) => {
                self.buffer.as_mut()[field::DAO_DODAG_ID].copy_from_slice(&address.octets());
                self.set_dao_dodag_id_present(true);
            }
            None => {
                self.set_dao_dodag_id_present(false);
            }
        }
    }
}

/// Getters for the Destination Advertisement Object acknowledgement (DAO-ACK) message.
///
/// ```txt
///  0                   1                   2                   3
///  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// | RPLInstanceID |D|  Reserved   |  DAOSequence  |    Status     |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |                                                               |
/// +                                                               +
/// |                                                               |
/// +                            DODAGID*                           +
/// |                                                               |
/// +                                                               +
/// |                                                               |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |   Option(s)...
/// +-+-+-+-+-+-+-+-+
/// ```
impl<T: AsRef<[u8]>> Packet<T> {
    /// Returns the flag indicating that the DODAG ID is present or not.
    #[inline]
    pub fn dao_ack_dodag_id_present(&self) -> bool {
        get!(self.buffer, bool, field: field::DAO_ACK_D, shift: 7, mask: 0b1)
    }

    /// Return the DODAG sequence number.
    #[inline]
    pub fn dao_ack_sequence(&self) -> u8 {
        get!(self.buffer, field: field::DAO_ACK_SEQUENCE)
    }

    /// Return the DOA status field.
    #[inline]
    pub fn dao_ack_status(&self) -> u8 {
        get!(self.buffer, field: field::DAO_ACK_STATUS)
    }

    /// Returns the DODAG ID, an IPv6 address, when it is present.
    #[inline]
    pub fn dao_ack_dodag_id(&self) -> Option<Address> {
        if self.dao_ack_dodag_id_present() {
            Some(Address::from_octets(
                self.buffer.as_ref()[field::DAO_ACK_DODAG_ID]
                    .try_into()
                    .unwrap(),
            ))
        } else {
            None
        }
    }
}

/// Setters for the Destination Advertisement Object acknowledgement (DAO-ACK) message.
impl<T: AsRef<[u8]> + AsMut<[u8]>> Packet<T> {
    /// Set the flag indicating that the DODAG ID is present or not.
    #[inline]
    pub fn set_dao_ack_dodag_id_present(&mut self, value: bool) {
        set!(self.buffer, value, bool, field: field::DAO_ACK_D, shift: 7, mask: 0b1)
    }

    /// Set the DODAG sequence number.
    #[inline]
    pub fn set_dao_ack_sequence(&mut self, value: u8) {
        set!(self.buffer, value, field: field::DAO_ACK_SEQUENCE)
    }

    /// Set the DOA status field.
    #[inline]
    pub fn set_dao_ack_status(&mut self, value: u8) {
        set!(self.buffer, value, field: field::DAO_ACK_STATUS)
    }

    /// Set the DODAG ID.
    #[inline]
    pub fn set_dao_ack_dodag_id(&mut self, address: Option<Address>) {
        match address {
            Some(address) => {
                self.buffer.as_mut()[field::DAO_ACK_DODAG_ID].copy_from_slice(&address.octets());
                self.set_dao_ack_dodag_id_present(true);
            }
            None => {
                self.set_dao_ack_dodag_id_present(false);
            }
        }
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Repr<'p> {
    DodagInformationSolicitation {
        options: &'p [u8],
    },
    DodagInformationObject {
        rpl_instance_id: InstanceId,
        version_number: u8,
        rank: u16,
        grounded: bool,
        mode_of_operation: ModeOfOperation,
        dodag_preference: u8,
        dtsn: u8,
        dodag_id: Address,
        options: &'p [u8],
    },
    DestinationAdvertisementObject {
        rpl_instance_id: InstanceId,
        expect_ack: bool,
        sequence: u8,
        dodag_id: Option<Address>,
        options: &'p [u8],
    },
    DestinationAdvertisementObjectAck {
        rpl_instance_id: InstanceId,
        sequence: u8,
        status: u8,
        dodag_id: Option<Address>,
    },
}

impl core::fmt::Display for Repr<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Repr::DodagInformationSolicitation { .. } => {
                write!(f, "DIS")?;
            }
            Repr::DodagInformationObject {
                rpl_instance_id,
                version_number,
                rank,
                grounded,
                mode_of_operation,
                dodag_preference,
                dtsn,
                dodag_id,
                ..
            } => {
                write!(
                    f,
                    "DIO \
                             IID={rpl_instance_id:?} \
                             V={version_number} \
                             R={rank} \
                             G={grounded} \
                             MOP={mode_of_operation:?} \
                             Pref={dodag_preference} \
                             DTSN={dtsn} \
                             DODAGID={dodag_id}"
                )?;
            }
            Repr::DestinationAdvertisementObject {
                rpl_instance_id,
                expect_ack,
                sequence,
                dodag_id,
                ..
            } => {
                write!(
                    f,
                    "DAO \
                             IID={rpl_instance_id:?} \
                             Ack={expect_ack} \
                             Seq={sequence} \
                             DODAGID={dodag_id:?}",
                )?;
            }
            Repr::DestinationAdvertisementObjectAck {
                rpl_instance_id,
                sequence,
                status,
                dodag_id,
                ..
            } => {
                write!(
                    f,
                    "DAO-ACK \
                             IID={rpl_instance_id:?} \
                             Seq={sequence} \
                             Status={status} \
                             DODAGID={dodag_id:?}",
                )?;
            }
        };

        Ok(())
    }
}

impl<'p> Repr<'p> {
    pub fn set_options(&mut self, options: &'p [u8]) {
        let opts = match self {
            Repr::DodagInformationSolicitation { options } => options,
            Repr::DodagInformationObject { options, .. } => options,
            Repr::DestinationAdvertisementObject { options, .. } => options,
            Repr::DestinationAdvertisementObjectAck { .. } => unreachable!(),
        };

        *opts = options;
    }

    pub fn parse<T: AsRef<[u8]> + ?Sized>(packet: &Packet<&'p T>) -> Result<Self> {
        packet.check_len()?;

        let options = packet.options()?;
        match RplControlMessage::from(packet.msg_code()) {
            RplControlMessage::DodagInformationSolicitation => {
                Ok(Repr::DodagInformationSolicitation { options })
            }
            RplControlMessage::DodagInformationObject => Ok(Repr::DodagInformationObject {
                rpl_instance_id: packet.rpl_instance_id(),
                version_number: packet.dio_version_number(),
                rank: packet.dio_rank(),
                grounded: packet.dio_grounded(),
                mode_of_operation: packet.dio_mode_of_operation(),
                dodag_preference: packet.dio_dodag_preference(),
                dtsn: packet.dio_dest_adv_trigger_seq_number(),
                dodag_id: packet.dio_dodag_id(),
                options,
            }),
            RplControlMessage::DestinationAdvertisementObject => {
                Ok(Repr::DestinationAdvertisementObject {
                    rpl_instance_id: packet.rpl_instance_id(),
                    expect_ack: packet.dao_ack_request(),
                    sequence: packet.dao_dodag_sequence(),
                    dodag_id: packet.dao_dodag_id(),
                    options,
                })
            }
            RplControlMessage::DestinationAdvertisementObjectAck => {
                Ok(Repr::DestinationAdvertisementObjectAck {
                    rpl_instance_id: packet.rpl_instance_id(),
                    sequence: packet.dao_ack_sequence(),
                    status: packet.dao_ack_status(),
                    dodag_id: packet.dao_ack_dodag_id(),
                })
            }
            RplControlMessage::SecureDodagInformationSolicitation
            | RplControlMessage::SecureDodagInformationObject
            | RplControlMessage::SecureDestinationAdvertisementObject
            | RplControlMessage::SecureDestinationAdvertisementObjectAck
            | RplControlMessage::ConsistencyCheck => Err(Error),
            RplControlMessage::Unknown(_) => Err(Error),
        }
    }

    pub fn buffer_len(&self) -> usize {
        let mut len = 4 + match self {
            Repr::DodagInformationSolicitation { .. } => 2,
            Repr::DodagInformationObject { .. } => 24,
            Repr::DestinationAdvertisementObject { dodag_id, .. } => {
                if dodag_id.is_some() {
                    20
                } else {
                    4
                }
            }
            Repr::DestinationAdvertisementObjectAck { dodag_id, .. } => {
                if dodag_id.is_some() {
                    20
                } else {
                    4
                }
            }
        };

        let opts = match self {
            Repr::DodagInformationSolicitation { options } => &options[..],
            Repr::DodagInformationObject { options, .. } => &options[..],
            Repr::DestinationAdvertisementObject { options, .. } => &options[..],
            Repr::DestinationAdvertisementObjectAck { .. } => &[],
        };

        len += opts.len();

        len
    }

    pub fn emit<T: AsRef<[u8]> + AsMut<[u8]> + ?Sized>(&self, packet: &mut Packet<&mut T>) {
        packet.set_msg_type(crate::wire::icmpv6::Message::RplControl);

        match self {
            Repr::DodagInformationSolicitation { .. } => {
                packet.set_msg_code(RplControlMessage::DodagInformationSolicitation.into());
                packet.clear_dis_flags();
                packet.clear_dis_reserved();
            }
            Repr::DodagInformationObject {
                rpl_instance_id,
                version_number,
                rank,
                grounded,
                mode_of_operation,
                dodag_preference,
                dtsn,
                dodag_id,
                ..
            } => {
                packet.set_msg_code(RplControlMessage::DodagInformationObject.into());
                packet.set_rpl_instance_id((*rpl_instance_id).into());
                packet.set_dio_version_number(*version_number);
                packet.set_dio_rank(*rank);
                packet.set_dio_grounded(*grounded);
                packet.set_dio_mode_of_operation(*mode_of_operation);
                packet.set_dio_dodag_preference(*dodag_preference);
                packet.set_dio_dest_adv_trigger_seq_number(*dtsn);
                packet.set_dio_dodag_id(*dodag_id);
            }
            Repr::DestinationAdvertisementObject {
                rpl_instance_id,
                expect_ack,
                sequence,
                dodag_id,
                ..
            } => {
                packet.set_msg_code(RplControlMessage::DestinationAdvertisementObject.into());
                packet.set_rpl_instance_id((*rpl_instance_id).into());
                packet.set_dao_ack_request(*expect_ack);
                packet.set_dao_dodag_sequence(*sequence);
                packet.set_dao_dodag_id(*dodag_id);
            }
            Repr::DestinationAdvertisementObjectAck {
                rpl_instance_id,
                sequence,
                status,
                dodag_id,
                ..
            } => {
                packet.set_msg_code(RplControlMessage::DestinationAdvertisementObjectAck.into());
                packet.set_rpl_instance_id((*rpl_instance_id).into());
                packet.set_dao_ack_sequence(*sequence);
                packet.set_dao_ack_status(*status);
                packet.set_dao_ack_dodag_id(*dodag_id);
            }
        }

        let options = match self {
            Repr::DodagInformationSolicitation { options } => &options[..],
            Repr::DodagInformationObject { options, .. } => &options[..],
            Repr::DestinationAdvertisementObject { options, .. } => &options[..],
            Repr::DestinationAdvertisementObjectAck { .. } => &[],
        };

        packet.options_mut().copy_from_slice(options);
    }
}

pub mod options {
    use byteorder::{ByteOrder, NetworkEndian};

    use super::{Error, InstanceId, Result};
    use crate::wire::ipv6::{Address, AddressExt};

    /// A read/write wrapper around a RPL Control Message Option.
    #[derive(Debug, Clone)]
    pub struct Packet<T: AsRef<[u8]>> {
        buffer: T,
    }

    enum_with_unknown! {
        pub enum OptionType(u8) {
            Pad1 = 0x00,
            PadN = 0x01,
            DagMetricContainer = 0x02,
            RouteInformation = 0x03,
            DodagConfiguration = 0x04,
            RplTarget = 0x05,
            TransitInformation = 0x06,
            SolicitedInformation = 0x07,
            PrefixInformation = 0x08,
            RplTargetDescriptor = 0x09,
        }
    }

    impl From<&Repr<'_>> for OptionType {
        fn from(repr: &Repr) -> Self {
            match repr {
                Repr::Pad1 => Self::Pad1,
                Repr::PadN(_) => Self::PadN,
                Repr::DagMetricContainer => Self::DagMetricContainer,
                Repr::RouteInformation { .. } => Self::RouteInformation,
                Repr::DodagConfiguration { .. } => Self::DodagConfiguration,
                Repr::RplTarget { .. } => Self::RplTarget,
                Repr::TransitInformation { .. } => Self::TransitInformation,
                Repr::SolicitedInformation { .. } => Self::SolicitedInformation,
                Repr::PrefixInformation { .. } => Self::PrefixInformation,
                Repr::RplTargetDescriptor { .. } => Self::RplTargetDescriptor,
            }
        }
    }

    mod field {
        use crate::wire::field::*;

        // Generic fields.
        pub const TYPE: usize = 0;
        pub const LENGTH: usize = 1;

        pub const PADN: Rest = 2..;

        // Route Information fields.
        pub const ROUTE_INFO_PREFIX_LENGTH: usize = 2;
        pub const ROUTE_INFO_RESERVED: usize = 3;
        pub const ROUTE_INFO_PREFERENCE: usize = 3;
        pub const ROUTE_INFO_LIFETIME: Field = 4..9;

        // DODAG Configuration fields.
        pub const DODAG_CONF_FLAGS: usize = 2;
        pub const DODAG_CONF_AUTHENTICATION_ENABLED: usize = 2;
        pub const DODAG_CONF_PATH_CONTROL_SIZE: usize = 2;
        pub const DODAG_CONF_DIO_INTERVAL_DOUBLINGS: usize = 3;
        pub const DODAG_CONF_DIO_INTERVAL_MINIMUM: usize = 4;
        pub const DODAG_CONF_DIO_REDUNDANCY_CONSTANT: usize = 5;
        pub const DODAG_CONF_DIO_MAX_RANK_INCREASE: Field = 6..8;
        pub const DODAG_CONF_MIN_HOP_RANK_INCREASE: Field = 8..10;
        pub const DODAG_CONF_OBJECTIVE_CODE_POINT: Field = 10..12;
        pub const DODAG_CONF_DEFAULT_LIFETIME: usize = 13;
        pub const DODAG_CONF_LIFETIME_UNIT: Field = 14..16;

        // RPL Target fields.
        pub const RPL_TARGET_FLAGS: usize = 2;
        pub const RPL_TARGET_PREFIX_LENGTH: usize = 3;

        // Transit Information fields.
        pub const TRANSIT_INFO_FLAGS: usize = 2;
        pub const TRANSIT_INFO_EXTERNAL: usize = 2;
        pub const TRANSIT_INFO_PATH_CONTROL: usize = 3;
        pub const TRANSIT_INFO_PATH_SEQUENCE: usize = 4;
        pub const TRANSIT_INFO_PATH_LIFETIME: usize = 5;
        pub const TRANSIT_INFO_PARENT_ADDRESS: Field = 6..6 + 16;

        // Solicited Information fields.
        pub const SOLICITED_INFO_RPL_INSTANCE_ID: usize = 2;
        pub const SOLICITED_INFO_FLAGS: usize = 3;
        pub const SOLICITED_INFO_VERSION_PREDICATE: usize = 3;
        pub const SOLICITED_INFO_INSTANCE_ID_PREDICATE: usize = 3;
        pub const SOLICITED_INFO_DODAG_ID_PREDICATE: usize = 3;
        pub const SOLICITED_INFO_DODAG_ID: Field = 4..20;
        pub const SOLICITED_INFO_VERSION_NUMBER: usize = 20;

        // Prefix Information fields.
        pub const PREFIX_INFO_PREFIX_LENGTH: usize = 2;
        pub const PREFIX_INFO_RESERVED1: usize = 3;
        pub const PREFIX_INFO_ON_LINK: usize = 3;
        pub const PREFIX_INFO_AUTONOMOUS_CONF: usize = 3;
        pub const PREFIX_INFO_ROUTER_ADDRESS_FLAG: usize = 3;
        pub const PREFIX_INFO_VALID_LIFETIME: Field = 4..8;
        pub const PREFIX_INFO_PREFERRED_LIFETIME: Field = 8..12;
        pub const PREFIX_INFO_RESERVED2: Field = 12..16;
        pub const PREFIX_INFO_PREFIX: Field = 16..16 + 16;

        // RPL Target Descriptor fields.
        pub const TARGET_DESCRIPTOR: Field = 2..6;
    }

    /// Getters for the RPL Control Message Options.
    impl<T: AsRef<[u8]>> Packet<T> {
        /// Imbue a raw octet buffer with RPL Control Message Option structure.
        #[inline]
        pub fn new_unchecked(buffer: T) -> Self {
            Packet { buffer }
        }

        #[inline]
        pub fn new_checked(buffer: T) -> Result<Self> {
            if buffer.as_ref().is_empty() {
                return Err(Error);
            }

            Ok(Packet { buffer })
        }

        /// Return the type field.
        #[inline]
        pub fn option_type(&self) -> OptionType {
            OptionType::from(self.buffer.as_ref()[field::TYPE])
        }

        /// Return the length field.
        #[inline]
        pub fn option_length(&self) -> u8 {
            get!(self.buffer, field: field::LENGTH)
        }
    }

    impl<'p, T: AsRef<[u8]> + ?Sized> Packet<&'p T> {
        /// Return a pointer to the next option.
        #[inline]
        pub fn next_option(&self) -> Option<&'p [u8]> {
            if !self.buffer.as_ref().is_empty() {
                match self.option_type() {
                    OptionType::Pad1 => Some(&self.buffer.as_ref()[1..]),
                    OptionType::Unknown(_) => unreachable!(),
                    _ => {
                        let len = self.option_length();
                        Some(&self.buffer.as_ref()[2 + len as usize..])
                    }
                }
            } else {
                None
            }
        }
    }

    impl<T: AsRef<[u8]> + AsMut<[u8]>> Packet<T> {
        /// Set the Option Type field.
        #[inline]
        pub fn set_option_type(&mut self, option_type: OptionType) {
            self.buffer.as_mut()[field::TYPE] = option_type.into();
        }

        /// Set the Option Length field.
        #[inline]
        pub fn set_option_length(&mut self, length: u8) {
            self.buffer.as_mut()[field::LENGTH] = length;
        }
    }

    impl<T: AsRef<[u8]> + AsMut<[u8]>> Packet<T> {
        #[inline]
        pub fn clear_padn(&mut self, size: u8) {
            for b in &mut self.buffer.as_mut()[field::PADN][..size as usize] {
                *b = 0;
            }
        }
    }

    /// Getters for the DAG Metric Container Option Message.

    /// Getters for the Route Information Option Message.
    ///
    /// ```txt
    ///  0                   1                   2                   3
    ///  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    /// |   Type = 0x03 | Option Length | Prefix Length |Resvd|Prf|Resvd|
    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    /// |                        Route Lifetime                         |
    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    /// |                                                               |
    /// .                   Prefix (Variable Length)                    .
    /// .                                                               .
    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    /// ```
    impl<T: AsRef<[u8]>> Packet<T> {
        /// Return the Prefix Length field.
        #[inline]
        pub fn prefix_length(&self) -> u8 {
            get!(self.buffer, field: field::ROUTE_INFO_PREFIX_LENGTH)
        }

        /// Return the Route Preference field.
        #[inline]
        pub fn route_preference(&self) -> u8 {
            (self.buffer.as_ref()[field::ROUTE_INFO_PREFERENCE] & 0b0001_1000) >> 3
        }

        /// Return the Route Lifetime field.
        #[inline]
        pub fn route_lifetime(&self) -> u32 {
            get!(self.buffer, u32, field: field::ROUTE_INFO_LIFETIME)
        }
    }

    impl<'p, T: AsRef<[u8]> + ?Sized> Packet<&'p T> {
        /// Return the Prefix field.
        #[inline]
        pub fn prefix(&self) -> &'p [u8] {
            let option_len = self.option_length();
            &self.buffer.as_ref()[field::ROUTE_INFO_LIFETIME.end..]
                [..option_len as usize - field::ROUTE_INFO_LIFETIME.end]
        }
    }

    /// Setters for the Route Information Option Message.
    impl<T: AsRef<[u8]> + AsMut<[u8]>> Packet<T> {
        /// Set the Prefix Length field.
        #[inline]
        pub fn set_route_info_prefix_length(&mut self, value: u8) {
            set!(self.buffer, value, field: field::ROUTE_INFO_PREFIX_LENGTH)
        }

        /// Set the Route Preference field.
        #[inline]
        pub fn set_route_info_route_preference(&mut self, _value: u8) {
            todo!();
        }

        /// Set the Route Lifetime field.
        #[inline]
        pub fn set_route_info_route_lifetime(&mut self, value: u32) {
            set!(self.buffer, value, u32, field: field::ROUTE_INFO_LIFETIME)
        }

        /// Set the prefix field.
        #[inline]
        pub fn set_route_info_prefix(&mut self, _prefix: &[u8]) {
            todo!();
        }

        /// Clear the reserved field.
        #[inline]
        pub fn clear_route_info_reserved(&mut self) {
            self.buffer.as_mut()[field::ROUTE_INFO_RESERVED] = 0;
        }
    }

    /// Getters for the DODAG Configuration Option Message.
    ///
    /// ```txt
    ///  0                   1                   2                   3
    ///  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    /// |   Type = 0x04 |Opt Length = 14| Flags |A| PCS | DIOIntDoubl.  |
    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    /// |  DIOIntMin.   |   DIORedun.   |        MaxRankIncrease        |
    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    /// |      MinHopRankIncrease       |              OCP              |
    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    /// |   Reserved    | Def. Lifetime |      Lifetime Unit            |
    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    /// ```
    impl<T: AsRef<[u8]>> Packet<T> {
        /// Return the Authentication Enabled field.
        #[inline]
        pub fn authentication_enabled(&self) -> bool {
            get!(
                self.buffer,
                bool,
                field: field::DODAG_CONF_AUTHENTICATION_ENABLED,
                shift: 3,
                mask: 0b1
            )
        }

        /// Return the Path Control Size field.
        #[inline]
        pub fn path_control_size(&self) -> u8 {
            get!(self.buffer, field: field::DODAG_CONF_PATH_CONTROL_SIZE, mask: 0b111)
        }

        /// Return the DIO Interval Doublings field.
        #[inline]
        pub fn dio_interval_doublings(&self) -> u8 {
            get!(self.buffer, field: field::DODAG_CONF_DIO_INTERVAL_DOUBLINGS)
        }

        /// Return the DIO Interval Minimum field.
        #[inline]
        pub fn dio_interval_minimum(&self) -> u8 {
            get!(self.buffer, field: field::DODAG_CONF_DIO_INTERVAL_MINIMUM)
        }

        /// Return the DIO Redundancy Constant field.
        #[inline]
        pub fn dio_redundancy_constant(&self) -> u8 {
            get!(
                self.buffer,
                field: field::DODAG_CONF_DIO_REDUNDANCY_CONSTANT
            )
        }

        /// Return the Max Rank Increase field.
        #[inline]
        pub fn max_rank_increase(&self) -> u16 {
            get!(
                self.buffer,
                u16,
                field: field::DODAG_CONF_DIO_MAX_RANK_INCREASE
            )
        }

        /// Return the Minimum Hop Rank Increase field.
        #[inline]
        pub fn minimum_hop_rank_increase(&self) -> u16 {
            get!(
                self.buffer,
                u16,
                field: field::DODAG_CONF_MIN_HOP_RANK_INCREASE
            )
        }

        /// Return the Objective Code Point field.
        #[inline]
        pub fn objective_code_point(&self) -> u16 {
            get!(
                self.buffer,
                u16,
                field: field::DODAG_CONF_OBJECTIVE_CODE_POINT
            )
        }

        /// Return the Default Lifetime field.
        #[inline]
        pub fn default_lifetime(&self) -> u8 {
            get!(self.buffer, field: field::DODAG_CONF_DEFAULT_LIFETIME)
        }

        /// Return the Lifetime Unit field.
        #[inline]
        pub fn lifetime_unit(&self) -> u16 {
            get!(self.buffer, u16, field: field::DODAG_CONF_LIFETIME_UNIT)
        }
    }

    /// Getters for the DODAG Configuration Option Message.
    impl<T: AsRef<[u8]> + AsMut<[u8]>> Packet<T> {
        /// Clear the Flags field.
        #[inline]
        pub fn clear_dodag_conf_flags(&mut self) {
            self.buffer.as_mut()[field::DODAG_CONF_FLAGS] = 0;
        }

        /// Set the Authentication Enabled field.
        #[inline]
        pub fn set_dodag_conf_authentication_enabled(&mut self, value: bool) {
            set!(
                self.buffer,
                value,
                bool,
                field: field::DODAG_CONF_AUTHENTICATION_ENABLED,
                shift: 3,
                mask: 0b1
            )
        }

        /// Set the Path Control Size field.
        #[inline]
        pub fn set_dodag_conf_path_control_size(&mut self, value: u8) {
            set!(
                self.buffer,
                value,
                field: field::DODAG_CONF_PATH_CONTROL_SIZE,
                mask: 0b111
            )
        }

        /// Set the DIO Interval Doublings field.
        #[inline]
        pub fn set_dodag_conf_dio_interval_doublings(&mut self, value: u8) {
            set!(
                self.buffer,
                value,
                field: field::DODAG_CONF_DIO_INTERVAL_DOUBLINGS
            )
        }

        /// Set the DIO Interval Minimum field.
        #[inline]
        pub fn set_dodag_conf_dio_interval_minimum(&mut self, value: u8) {
            set!(
                self.buffer,
                value,
                field: field::DODAG_CONF_DIO_INTERVAL_MINIMUM
            )
        }

        /// Set the DIO Redundancy Constant field.
        #[inline]
        pub fn set_dodag_conf_dio_redundancy_constant(&mut self, value: u8) {
            set!(
                self.buffer,
                value,
                field: field::DODAG_CONF_DIO_REDUNDANCY_CONSTANT
            )
        }

        /// Set the Max Rank Increase field.
        #[inline]
        pub fn set_dodag_conf_max_rank_increase(&mut self, value: u16) {
            set!(
                self.buffer,
                value,
                u16,
                field: field::DODAG_CONF_DIO_MAX_RANK_INCREASE
            )
        }

        /// Set the Minimum Hop Rank Increase field.
        #[inline]
        pub fn set_dodag_conf_minimum_hop_rank_increase(&mut self, value: u16) {
            set!(
                self.buffer,
                value,
                u16,
                field: field::DODAG_CONF_MIN_HOP_RANK_INCREASE
            )
        }

        /// Set the Objective Code Point field.
        #[inline]
        pub fn set_dodag_conf_objective_code_point(&mut self, value: u16) {
            set!(
                self.buffer,
                value,
                u16,
                field: field::DODAG_CONF_OBJECTIVE_CODE_POINT
            )
        }

        /// Set the Default Lifetime field.
        #[inline]
        pub fn set_dodag_conf_default_lifetime(&mut self, value: u8) {
            set!(
                self.buffer,
                value,
                field: field::DODAG_CONF_DEFAULT_LIFETIME
            )
        }

        /// Set the Lifetime Unit field.
        #[inline]
        pub fn set_dodag_conf_lifetime_unit(&mut self, value: u16) {
            set!(
                self.buffer,
                value,
                u16,
                field: field::DODAG_CONF_LIFETIME_UNIT
            )
        }
    }

    /// Getters for the RPL Target Option Message.
    ///
    /// ```txt
    ///  0                   1                   2                   3
    ///  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    /// |   Type = 0x05 | Option Length |     Flags     | Prefix Length |
    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    /// |                                                               |
    /// +                                                               +
    /// |                Target Prefix (Variable Length)                |
    /// .                                                               .
    /// .                                                               .
    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    /// ```
    impl<T: AsRef<[u8]>> Packet<T> {
        /// Return the Target Prefix Length field.
        pub fn target_prefix_length(&self) -> u8 {
            get!(self.buffer, field: field::RPL_TARGET_PREFIX_LENGTH)
        }
    }

    impl<'p, T: AsRef<[u8]> + ?Sized> Packet<&'p T> {
        /// Return the Target Prefix field.
        #[inline]
        pub fn target_prefix(&self) -> &'p [u8] {
            let option_len = self.option_length();
            &self.buffer.as_ref()[field::RPL_TARGET_PREFIX_LENGTH + 1..]
                [..option_len as usize - field::RPL_TARGET_PREFIX_LENGTH + 1]
        }
    }

    /// Setters for the RPL Target Option Message.
    impl<T: AsRef<[u8]> + AsMut<[u8]>> Packet<T> {
        /// Clear the Flags field.
        #[inline]
        pub fn clear_rpl_target_flags(&mut self) {
            self.buffer.as_mut()[field::RPL_TARGET_FLAGS] = 0;
        }

        /// Set the Target Prefix Length field.
        #[inline]
        pub fn set_rpl_target_prefix_length(&mut self, value: u8) {
            set!(self.buffer, value, field: field::RPL_TARGET_PREFIX_LENGTH)
        }

        /// Set the Target Prefix field.
        #[inline]
        pub fn set_rpl_target_prefix(&mut self, prefix: &[u8]) {
            self.buffer.as_mut()[field::RPL_TARGET_PREFIX_LENGTH + 1..][..prefix.len()]
                .copy_from_slice(prefix);
        }
    }

    /// Getters for the Transit Information Option Message.
    ///
    /// ```txt
    ///  0                   1                   2                   3
    ///  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    /// |   Type = 0x06 | Option Length |E|    Flags    | Path Control  |
    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    /// | Path Sequence | Path Lifetime |                               |
    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+                               +
    /// |                                                               |
    /// +                                                               +
    /// |                                                               |
    /// +                        Parent Address*                        +
    /// |                                                               |
    /// +                               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    /// |                               |
    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    /// ```
    impl<T: AsRef<[u8]>> Packet<T> {
        /// Return the External flag.
        #[inline]
        pub fn is_external(&self) -> bool {
            get!(
                self.buffer,
                bool,
                field: field::TRANSIT_INFO_EXTERNAL,
                shift: 7,
                mask: 0b1,
            )
        }

        /// Return the Path Control field.
        #[inline]
        pub fn path_control(&self) -> u8 {
            get!(self.buffer, field: field::TRANSIT_INFO_PATH_CONTROL)
        }

        /// Return the Path Sequence field.
        #[inline]
        pub fn path_sequence(&self) -> u8 {
            get!(self.buffer, field: field::TRANSIT_INFO_PATH_SEQUENCE)
        }

        /// Return the Path Lifetime field.
        #[inline]
        pub fn path_lifetime(&self) -> u8 {
            get!(self.buffer, field: field::TRANSIT_INFO_PATH_LIFETIME)
        }

        /// Return the Parent Address field.
        #[inline]
        pub fn parent_address(&self) -> Option<Address> {
            if self.option_length() > 5 {
                Some(Address::from_octets(
                    self.buffer.as_ref()[field::TRANSIT_INFO_PARENT_ADDRESS]
                        .try_into()
                        .unwrap(),
                ))
            } else {
                None
            }
        }
    }

    /// Setters for the Transit Information Option Message.
    impl<T: AsRef<[u8]> + AsMut<[u8]>> Packet<T> {
        /// Clear the Flags field.
        #[inline]
        pub fn clear_transit_info_flags(&mut self) {
            self.buffer.as_mut()[field::TRANSIT_INFO_FLAGS] = 0;
        }

        /// Set the External flag.
        #[inline]
        pub fn set_transit_info_is_external(&mut self, value: bool) {
            set!(
                self.buffer,
                value,
                bool,
                field: field::TRANSIT_INFO_EXTERNAL,
                shift: 7,
                mask: 0b1
            )
        }

        /// Set the Path Control field.
        #[inline]
        pub fn set_transit_info_path_control(&mut self, value: u8) {
            set!(self.buffer, value, field: field::TRANSIT_INFO_PATH_CONTROL)
        }

        /// Set the Path Sequence field.
        #[inline]
        pub fn set_transit_info_path_sequence(&mut self, value: u8) {
            set!(self.buffer, value, field: field::TRANSIT_INFO_PATH_SEQUENCE)
        }

        /// Set the Path Lifetime field.
        #[inline]
        pub fn set_transit_info_path_lifetime(&mut self, value: u8) {
            set!(self.buffer, value, field: field::TRANSIT_INFO_PATH_LIFETIME)
        }

        /// Set the Parent Address field.
        #[inline]
        pub fn set_transit_info_parent_address(&mut self, address: Address) {
            self.buffer.as_mut()[field::TRANSIT_INFO_PARENT_ADDRESS]
                .copy_from_slice(&address.octets());
        }
    }

    /// Getters for the Solicited Information Option Message.
    ///
    /// ```txt
    ///  0                   1                   2                   3
    ///  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    /// |   Type = 0x07 |Opt Length = 19| RPLInstanceID |V|I|D|  Flags  |
    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    /// |                                                               |
    /// +                                                               +
    /// |                                                               |
    /// +                            DODAGID                            +
    /// |                                                               |
    /// +                                                               +
    /// |                                                               |
    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    /// |Version Number |
    /// +-+-+-+-+-+-+-+-+
    /// ```
    impl<T: AsRef<[u8]>> Packet<T> {
        /// Return the RPL Instance ID field.
        #[inline]
        pub fn rpl_instance_id(&self) -> u8 {
            get!(self.buffer, field: field::SOLICITED_INFO_RPL_INSTANCE_ID)
        }

        /// Return the Version Predicate flag.
        #[inline]
        pub fn version_predicate(&self) -> bool {
            get!(
                self.buffer,
                bool,
                field: field::SOLICITED_INFO_VERSION_PREDICATE,
                shift: 7,
                mask: 0b1,
            )
        }

        /// Return the Instance ID Predicate flag.
        #[inline]
        pub fn instance_id_predicate(&self) -> bool {
            get!(
                self.buffer,
                bool,
                field: field::SOLICITED_INFO_INSTANCE_ID_PREDICATE,
                shift: 6,
                mask: 0b1,
            )
        }

        /// Return the DODAG Predicate ID flag.
        #[inline]
        pub fn dodag_id_predicate(&self) -> bool {
            get!(
                self.buffer,
                bool,
                field: field::SOLICITED_INFO_DODAG_ID_PREDICATE,
                shift: 5,
                mask: 0b1,
            )
        }

        /// Return the DODAG ID field.
        #[inline]
        pub fn dodag_id(&self) -> Address {
            Address::from_octets(
                self.buffer.as_ref()[field::SOLICITED_INFO_DODAG_ID]
                    .try_into()
                    .unwrap(),
            )
        }

        /// Return the Version Number field.
        #[inline]
        pub fn version_number(&self) -> u8 {
            get!(self.buffer, field: field::SOLICITED_INFO_VERSION_NUMBER)
        }
    }

    /// Setters for the Solicited Information Option Message.
    impl<T: AsRef<[u8]> + AsMut<[u8]>> Packet<T> {
        /// Clear the Flags field.
        #[inline]
        pub fn clear_solicited_info_flags(&mut self) {
            self.buffer.as_mut()[field::SOLICITED_INFO_FLAGS] = 0;
        }

        /// Set the RPL Instance ID field.
        #[inline]
        pub fn set_solicited_info_rpl_instance_id(&mut self, value: u8) {
            set!(
                self.buffer,
                value,
                field: field::SOLICITED_INFO_RPL_INSTANCE_ID
            )
        }

        /// Set the Version Predicate flag.
        #[inline]
        pub fn set_solicited_info_version_predicate(&mut self, value: bool) {
            set!(
                self.buffer,
                value,
                bool,
                field: field::SOLICITED_INFO_VERSION_PREDICATE,
                shift: 7,
                mask: 0b1
            )
        }

        /// Set the Instance ID Predicate flag.
        #[inline]
        pub fn set_solicited_info_instance_id_predicate(&mut self, value: bool) {
            set!(
                self.buffer,
                value,
                bool,
                field: field::SOLICITED_INFO_INSTANCE_ID_PREDICATE,
                shift: 6,
                mask: 0b1
            )
        }

        /// Set the DODAG Predicate ID flag.
        #[inline]
        pub fn set_solicited_info_dodag_id_predicate(&mut self, value: bool) {
            set!(
                self.buffer,
                value,
                bool,
                field: field::SOLICITED_INFO_DODAG_ID_PREDICATE,
                shift: 5,
                mask: 0b1
            )
        }

        /// Set the DODAG ID field.
        #[inline]
        pub fn set_solicited_info_dodag_id(&mut self, address: Address) {
            set!(
                self.buffer,
                address: address,
                field: field::SOLICITED_INFO_DODAG_ID
            )
        }

        /// Set the Version Number field.
        #[inline]
        pub fn set_solicited_info_version_number(&mut self, value: u8) {
            set!(
                self.buffer,
                value,
                field: field::SOLICITED_INFO_VERSION_NUMBER
            )
        }
    }

    /// Getters for the Prefix Information Option Message.
    ///
    /// ```txt
    ///  0                   1                   2                   3
    ///  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    /// |   Type = 0x08 |Opt Length = 30| Prefix Length |L|A|R|Reserved1|
    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    /// |                         Valid Lifetime                        |
    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    /// |                       Preferred Lifetime                      |
    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    /// |                           Reserved2                           |
    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    /// |                                                               |
    /// +                                                               +
    /// |                                                               |
    /// +                            Prefix                             +
    /// |                                                               |
    /// +                                                               +
    /// |                                                               |
    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    /// ```
    impl<T: AsRef<[u8]>> Packet<T> {
        /// Return the Prefix Length field.
        #[inline]
        pub fn prefix_info_prefix_length(&self) -> u8 {
            get!(self.buffer, field: field::PREFIX_INFO_PREFIX_LENGTH)
        }

        /// Return the On-Link flag.
        #[inline]
        pub fn on_link(&self) -> bool {
            get!(
                self.buffer,
                bool,
                field: field::PREFIX_INFO_ON_LINK,
                shift: 7,
                mask: 0b1,
            )
        }

        /// Return the Autonomous Address-Configuration flag.
        #[inline]
        pub fn autonomous_address_configuration(&self) -> bool {
            get!(
                self.buffer,
                bool,
                field: field::PREFIX_INFO_AUTONOMOUS_CONF,
                shift: 6,
                mask: 0b1,
            )
        }

        /// Return the Router Address flag.
        #[inline]
        pub fn router_address(&self) -> bool {
            get!(
                self.buffer,
                bool,
                field: field::PREFIX_INFO_ROUTER_ADDRESS_FLAG,
                shift: 5,
                mask: 0b1,
            )
        }

        /// Return the Valid Lifetime field.
        #[inline]
        pub fn valid_lifetime(&self) -> u32 {
            get!(self.buffer, u32, field: field::PREFIX_INFO_VALID_LIFETIME)
        }

        /// Return the Preferred Lifetime field.
        #[inline]
        pub fn preferred_lifetime(&self) -> u32 {
            get!(
                self.buffer,
                u32,
                field: field::PREFIX_INFO_PREFERRED_LIFETIME
            )
        }
    }

    impl<'p, T: AsRef<[u8]> + ?Sized> Packet<&'p T> {
        /// Return the Prefix field.
        #[inline]
        pub fn destination_prefix(&self) -> &'p [u8] {
            &self.buffer.as_ref()[field::PREFIX_INFO_PREFIX]
        }
    }

    /// Setters for the Prefix Information Option Message.
    impl<T: AsRef<[u8]> + AsMut<[u8]>> Packet<T> {
        /// Clear the reserved fields.
        #[inline]
        pub fn clear_prefix_info_reserved(&mut self) {
            self.buffer.as_mut()[field::PREFIX_INFO_RESERVED1] = 0;
            self.buffer.as_mut()[field::PREFIX_INFO_RESERVED2].copy_from_slice(&[0; 4]);
        }

        /// Set the Prefix Length field.
        #[inline]
        pub fn set_prefix_info_prefix_length(&mut self, value: u8) {
            set!(self.buffer, value, field: field::PREFIX_INFO_PREFIX_LENGTH)
        }

        /// Set the On-Link flag.
        #[inline]
        pub fn set_prefix_info_on_link(&mut self, value: bool) {
            set!(self.buffer, value, bool, field: field::PREFIX_INFO_ON_LINK, shift: 7, mask: 0b1)
        }

        /// Set the Autonomous Address-Configuration flag.
        #[inline]
        pub fn set_prefix_info_autonomous_address_configuration(&mut self, value: bool) {
            set!(
                self.buffer,
                value,
                bool,
                field: field::PREFIX_INFO_AUTONOMOUS_CONF,
                shift: 6,
                mask: 0b1
            )
        }

        /// Set the Router Address flag.
        #[inline]
        pub fn set_prefix_info_router_address(&mut self, value: bool) {
            set!(
                self.buffer,
                value,
                bool,
                field: field::PREFIX_INFO_ROUTER_ADDRESS_FLAG,
                shift: 5,
                mask: 0b1
            )
        }

        /// Set the Valid Lifetime field.
        #[inline]
        pub fn set_prefix_info_valid_lifetime(&mut self, value: u32) {
            set!(
                self.buffer,
                value,
                u32,
                field: field::PREFIX_INFO_VALID_LIFETIME
            )
        }

        /// Set the Preferred Lifetime field.
        #[inline]
        pub fn set_prefix_info_preferred_lifetime(&mut self, value: u32) {
            set!(
                self.buffer,
                value,
                u32,
                field: field::PREFIX_INFO_PREFERRED_LIFETIME
            )
        }

        /// Set the Prefix field.
        #[inline]
        pub fn set_prefix_info_destination_prefix(&mut self, prefix: &[u8]) {
            self.buffer.as_mut()[field::PREFIX_INFO_PREFIX].copy_from_slice(prefix);
        }
    }

    /// Getters for the RPL Target Descriptor Option Message.
    ///
    /// ```txt
    ///  0                   1                   2                   3
    ///  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    /// |   Type = 0x09 |Opt Length = 4 |           Descriptor
    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    ///        Descriptor (cont.)       |
    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    /// ```
    impl<T: AsRef<[u8]>> Packet<T> {
        /// Return the Descriptor field.
        #[inline]
        pub fn descriptor(&self) -> u32 {
            get!(self.buffer, u32, field: field::TARGET_DESCRIPTOR)
        }
    }

    /// Setters for the RPL Target Descriptor Option Message.
    impl<T: AsRef<[u8]> + AsMut<[u8]>> Packet<T> {
        /// Set the Descriptor field.
        #[inline]
        pub fn set_rpl_target_descriptor_descriptor(&mut self, value: u32) {
            set!(self.buffer, value, u32, field: field::TARGET_DESCRIPTOR)
        }
    }

    #[derive(Debug, PartialEq, Eq, Clone, Copy)]
    #[cfg_attr(feature = "defmt", derive(defmt::Format))]
    pub enum Repr<'p> {
        Pad1,
        PadN(u8),
        DagMetricContainer,
        RouteInformation {
            prefix_length: u8,
            preference: u8,
            lifetime: u32,
            prefix: &'p [u8],
        },
        DodagConfiguration {
            authentication_enabled: bool,
            path_control_size: u8,
            dio_interval_doublings: u8,
            dio_interval_min: u8,
            dio_redundancy_constant: u8,
            max_rank_increase: u16,
            minimum_hop_rank_increase: u16,
            objective_code_point: u16,
            default_lifetime: u8,
            lifetime_unit: u16,
        },
        RplTarget {
            prefix_length: u8,
            prefix: crate::wire::Ipv6Address, // FIXME: this is not the correct type, because the
                                              // field can be an IPv6 address, a prefix or a
                                              // multicast group.
        },
        TransitInformation {
            external: bool,
            path_control: u8,
            path_sequence: u8,
            path_lifetime: u8,
            parent_address: Option<Address>,
        },
        SolicitedInformation {
            rpl_instance_id: InstanceId,
            version_predicate: bool,
            instance_id_predicate: bool,
            dodag_id_predicate: bool,
            dodag_id: Address,
            version_number: u8,
        },
        PrefixInformation {
            prefix_length: u8,
            on_link: bool,
            autonomous_address_configuration: bool,
            router_address: bool,
            valid_lifetime: u32,
            preferred_lifetime: u32,
            destination_prefix: &'p [u8],
        },
        RplTargetDescriptor {
            descriptor: u32,
        },
    }

    impl core::fmt::Display for Repr<'_> {
        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            match self {
                Repr::Pad1 => write!(f, "Pad1"),
                Repr::PadN(n) => write!(f, "PadN({n})"),
                Repr::DagMetricContainer => todo!(),
                Repr::RouteInformation {
                    prefix_length,
                    preference,
                    lifetime,
                    prefix,
                } => {
                    write!(
                        f,
                        "ROUTE INFO \
                        PrefixLength={prefix_length} \
                        Preference={preference} \
                        Lifetime={lifetime} \
                        Prefix={prefix:0x?}"
                    )
                }
                Repr::DodagConfiguration {
                    dio_interval_doublings,
                    dio_interval_min,
                    dio_redundancy_constant,
                    max_rank_increase,
                    minimum_hop_rank_increase,
                    objective_code_point,
                    default_lifetime,
                    lifetime_unit,
                    ..
                } => {
                    write!(
                        f,
                        "DODAG CONF \
                        IntD={dio_interval_doublings} \
                        IntMin={dio_interval_min} \
                        RedCst={dio_redundancy_constant} \
                        MaxRankIncr={max_rank_increase} \
                        MinHopRankIncr={minimum_hop_rank_increase} \
                        OCP={objective_code_point} \
                        DefaultLifetime={default_lifetime} \
                        LifeUnit={lifetime_unit}"
                    )
                }
                Repr::RplTarget {
                    prefix_length,
                    prefix,
                } => {
                    write!(
                        f,
                        "RPL Target \
                        PrefixLength={prefix_length} \
                        Prefix={prefix:0x?}"
                    )
                }
                Repr::TransitInformation {
                    external,
                    path_control,
                    path_sequence,
                    path_lifetime,
                    parent_address,
                } => {
                    write!(
                        f,
                        "Transit Info \
                        External={external} \
                        PathCtrl={path_control} \
                        PathSqnc={path_sequence} \
                        PathLifetime={path_lifetime} \
                        Parent={parent_address:0x?}"
                    )
                }
                Repr::SolicitedInformation {
                    rpl_instance_id,
                    version_predicate,
                    instance_id_predicate,
                    dodag_id_predicate,
                    dodag_id,
                    version_number,
                } => {
                    write!(
                        f,
                        "Solicited Info \
                        I={instance_id_predicate} \
                        IID={rpl_instance_id:0x?} \
                        D={dodag_id_predicate} \
                        DODAGID={dodag_id} \
                        V={version_predicate} \
                        Version={version_number}"
                    )
                }
                Repr::PrefixInformation {
                    prefix_length,
                    on_link,
                    autonomous_address_configuration,
                    router_address,
                    valid_lifetime,
                    preferred_lifetime,
                    destination_prefix,
                } => {
                    write!(
                        f,
                        "Prefix Info \
                        PrefixLength={prefix_length} \
                        L={on_link} A={autonomous_address_configuration} R={router_address} \
                        Valid={valid_lifetime} \
                        Preferred={preferred_lifetime} \
                        Prefix={destination_prefix:0x?}"
                    )
                }
                Repr::RplTargetDescriptor { .. } => write!(f, "Target Descriptor"),
            }
        }
    }

    impl<'p> Repr<'p> {
        pub fn parse<T: AsRef<[u8]> + ?Sized>(packet: &Packet<&'p T>) -> Result<Self> {
            match packet.option_type() {
                OptionType::Pad1 => Ok(Repr::Pad1),
                OptionType::PadN => Ok(Repr::PadN(packet.option_length())),
                OptionType::DagMetricContainer => todo!(),
                OptionType::RouteInformation => Ok(Repr::RouteInformation {
                    prefix_length: packet.prefix_length(),
                    preference: packet.route_preference(),
                    lifetime: packet.route_lifetime(),
                    prefix: packet.prefix(),
                }),
                OptionType::DodagConfiguration => Ok(Repr::DodagConfiguration {
                    authentication_enabled: packet.authentication_enabled(),
                    path_control_size: packet.path_control_size(),
                    dio_interval_doublings: packet.dio_interval_doublings(),
                    dio_interval_min: packet.dio_interval_minimum(),
                    dio_redundancy_constant: packet.dio_redundancy_constant(),
                    max_rank_increase: packet.max_rank_increase(),
                    minimum_hop_rank_increase: packet.minimum_hop_rank_increase(),
                    objective_code_point: packet.objective_code_point(),
                    default_lifetime: packet.default_lifetime(),
                    lifetime_unit: packet.lifetime_unit(),
                }),
                OptionType::RplTarget => Ok(Repr::RplTarget {
                    prefix_length: packet.target_prefix_length(),
                    prefix: crate::wire::Ipv6Address::from_octets(
                        packet.target_prefix().try_into().unwrap(),
                    ),
                }),
                OptionType::TransitInformation => Ok(Repr::TransitInformation {
                    external: packet.is_external(),
                    path_control: packet.path_control(),
                    path_sequence: packet.path_sequence(),
                    path_lifetime: packet.path_lifetime(),
                    parent_address: packet.parent_address(),
                }),
                OptionType::SolicitedInformation => Ok(Repr::SolicitedInformation {
                    rpl_instance_id: InstanceId::from(packet.rpl_instance_id()),
                    version_predicate: packet.version_predicate(),
                    instance_id_predicate: packet.instance_id_predicate(),
                    dodag_id_predicate: packet.dodag_id_predicate(),
                    dodag_id: packet.dodag_id(),
                    version_number: packet.version_number(),
                }),
                OptionType::PrefixInformation => Ok(Repr::PrefixInformation {
                    prefix_length: packet.prefix_info_prefix_length(),
                    on_link: packet.on_link(),
                    autonomous_address_configuration: packet.autonomous_address_configuration(),
                    router_address: packet.router_address(),
                    valid_lifetime: packet.valid_lifetime(),
                    preferred_lifetime: packet.preferred_lifetime(),
                    destination_prefix: packet.destination_prefix(),
                }),
                OptionType::RplTargetDescriptor => Ok(Repr::RplTargetDescriptor {
                    descriptor: packet.descriptor(),
                }),
                OptionType::Unknown(_) => Err(Error),
            }
        }

        pub fn buffer_len(&self) -> usize {
            match self {
                Repr::Pad1 => 1,
                Repr::PadN(size) => 2 + *size as usize,
                Repr::DagMetricContainer => todo!(),
                Repr::RouteInformation { prefix, .. } => 2 + 6 + prefix.len(),
                Repr::DodagConfiguration { .. } => 2 + 14,
                Repr::RplTarget { prefix, .. } => 2 + 2 + prefix.octets().len(),
                Repr::TransitInformation { parent_address, .. } => {
                    2 + 4 + if parent_address.is_some() { 16 } else { 0 }
                }
                Repr::SolicitedInformation { .. } => 2 + 2 + 16 + 1,
                Repr::PrefixInformation { .. } => 32,
                Repr::RplTargetDescriptor { .. } => 2 + 4,
            }
        }

        pub fn emit<T: AsRef<[u8]> + AsMut<[u8]> + ?Sized>(&self, packet: &mut Packet<&'p mut T>) {
            let mut option_length = self.buffer_len() as u8;

            packet.set_option_type(self.into());

            if !matches!(self, Repr::Pad1) {
                option_length -= 2;
                packet.set_option_length(option_length);
            }

            match self {
                Repr::Pad1 => {}
                Repr::PadN(size) => {
                    packet.clear_padn(*size);
                }
                Repr::DagMetricContainer => {
                    unimplemented!();
                }
                Repr::RouteInformation {
                    prefix_length,
                    preference,
                    lifetime,
                    prefix,
                } => {
                    packet.clear_route_info_reserved();
                    packet.set_route_info_prefix_length(*prefix_length);
                    packet.set_route_info_route_preference(*preference);
                    packet.set_route_info_route_lifetime(*lifetime);
                    packet.set_route_info_prefix(prefix);
                }
                Repr::DodagConfiguration {
                    authentication_enabled,
                    path_control_size,
                    dio_interval_doublings,
                    dio_interval_min,
                    dio_redundancy_constant,
                    max_rank_increase,
                    minimum_hop_rank_increase,
                    objective_code_point,
                    default_lifetime,
                    lifetime_unit,
                } => {
                    packet.clear_dodag_conf_flags();
                    packet.set_dodag_conf_authentication_enabled(*authentication_enabled);
                    packet.set_dodag_conf_path_control_size(*path_control_size);
                    packet.set_dodag_conf_dio_interval_doublings(*dio_interval_doublings);
                    packet.set_dodag_conf_dio_interval_minimum(*dio_interval_min);
                    packet.set_dodag_conf_dio_redundancy_constant(*dio_redundancy_constant);
                    packet.set_dodag_conf_max_rank_increase(*max_rank_increase);
                    packet.set_dodag_conf_minimum_hop_rank_increase(*minimum_hop_rank_increase);
                    packet.set_dodag_conf_objective_code_point(*objective_code_point);
                    packet.set_dodag_conf_default_lifetime(*default_lifetime);
                    packet.set_dodag_conf_lifetime_unit(*lifetime_unit);
                }
                Repr::RplTarget {
                    prefix_length,
                    prefix,
                } => {
                    packet.clear_rpl_target_flags();
                    packet.set_rpl_target_prefix_length(*prefix_length);
                    packet.set_rpl_target_prefix(&prefix.octets());
                }
                Repr::TransitInformation {
                    external,
                    path_control,
                    path_sequence,
                    path_lifetime,
                    parent_address,
                } => {
                    packet.clear_transit_info_flags();
                    packet.set_transit_info_is_external(*external);
                    packet.set_transit_info_path_control(*path_control);
                    packet.set_transit_info_path_sequence(*path_sequence);
                    packet.set_transit_info_path_lifetime(*path_lifetime);

                    if let Some(address) = parent_address {
                        packet.set_transit_info_parent_address(*address);
                    }
                }
                Repr::SolicitedInformation {
                    rpl_instance_id,
                    version_predicate,
                    instance_id_predicate,
                    dodag_id_predicate,
                    dodag_id,
                    version_number,
                } => {
                    packet.clear_solicited_info_flags();
                    packet.set_solicited_info_rpl_instance_id((*rpl_instance_id).into());
                    packet.set_solicited_info_version_predicate(*version_predicate);
                    packet.set_solicited_info_instance_id_predicate(*instance_id_predicate);
                    packet.set_solicited_info_dodag_id_predicate(*dodag_id_predicate);
                    packet.set_solicited_info_version_number(*version_number);
                    packet.set_solicited_info_dodag_id(*dodag_id);
                }
                Repr::PrefixInformation {
                    prefix_length,
                    on_link,
                    autonomous_address_configuration,
                    router_address,
                    valid_lifetime,
                    preferred_lifetime,
                    destination_prefix,
                } => {
                    packet.clear_prefix_info_reserved();
                    packet.set_prefix_info_prefix_length(*prefix_length);
                    packet.set_prefix_info_on_link(*on_link);
                    packet.set_prefix_info_autonomous_address_configuration(
                        *autonomous_address_configuration,
                    );
                    packet.set_prefix_info_router_address(*router_address);
                    packet.set_prefix_info_valid_lifetime(*valid_lifetime);
                    packet.set_prefix_info_preferred_lifetime(*preferred_lifetime);
                    packet.set_prefix_info_destination_prefix(destination_prefix);
                }
                Repr::RplTargetDescriptor { descriptor } => {
                    packet.set_rpl_target_descriptor_descriptor(*descriptor);
                }
            }
        }
    }
}

pub mod data {
    use super::{InstanceId, Result};
    use byteorder::{ByteOrder, NetworkEndian};

    mod field {
        use crate::wire::field::*;

        pub const FLAGS: usize = 0;
        pub const INSTANCE_ID: usize = 1;
        pub const SENDER_RANK: Field = 2..4;
    }

    /// A read/write wrapper around a RPL Packet Information send with
    /// an IPv6 Hop-by-Hop option, defined in RFC6553.
    /// ```txt
    /// 0                   1                   2                   3
    /// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
    ///                                 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    ///                                 |  Option Type  |  Opt Data Len |
    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    /// |O|R|F|0|0|0|0|0| RPLInstanceID |          SenderRank           |
    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    /// |                         (sub-TLVs)                            |
    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    /// ```
    #[derive(Debug, PartialEq, Eq, Clone, Copy)]
    pub struct Packet<T: AsRef<[u8]>> {
        buffer: T,
    }

    impl<T: AsRef<[u8]>> Packet<T> {
        #[inline]
        pub fn new_unchecked(buffer: T) -> Self {
            Self { buffer }
        }

        #[inline]
        pub fn new_checked(buffer: T) -> Result<Self> {
            let packet = Self::new_unchecked(buffer);
            packet.check_len()?;
            Ok(packet)
        }

        #[inline]
        pub fn check_len(&self) -> Result<()> {
            if self.buffer.as_ref().len() == 4 {
                Ok(())
            } else {
                Err(crate::wire::Error)
            }
        }

        #[inline]
        pub fn is_down(&self) -> bool {
            get!(self.buffer, bool, field: field::FLAGS, shift: 7, mask: 0b1)
        }

        #[inline]
        pub fn has_rank_error(&self) -> bool {
            get!(self.buffer, bool, field: field::FLAGS, shift: 6, mask: 0b1)
        }

        #[inline]
        pub fn has_forwarding_error(&self) -> bool {
            get!(self.buffer, bool, field: field::FLAGS, shift: 5, mask: 0b1)
        }

        #[inline]
        pub fn rpl_instance_id(&self) -> InstanceId {
            get!(self.buffer, into: InstanceId, field: field::INSTANCE_ID)
        }

        #[inline]
        pub fn sender_rank(&self) -> u16 {
            get!(self.buffer, u16, field: field::SENDER_RANK)
        }
    }

    impl<T: AsRef<[u8]> + AsMut<[u8]>> Packet<T> {
        #[inline]
        pub fn set_is_down(&mut self, value: bool) {
            set!(self.buffer, value, bool, field: field::FLAGS, shift: 7, mask: 0b1)
        }

        #[inline]
        pub fn set_has_rank_error(&mut self, value: bool) {
            set!(self.buffer, value, bool, field: field::FLAGS, shift: 6, mask: 0b1)
        }

        #[inline]
        pub fn set_has_forwarding_error(&mut self, value: bool) {
            set!(self.buffer, value, bool, field: field::FLAGS, shift: 5, mask: 0b1)
        }

        #[inline]
        pub fn set_rpl_instance_id(&mut self, value: u8) {
            set!(self.buffer, value, field: field::INSTANCE_ID)
        }

        #[inline]
        pub fn set_sender_rank(&mut self, value: u16) {
            set!(self.buffer, value, u16, field: field::SENDER_RANK)
        }
    }

    /// A high-level representation of an IPv6 Extension Header Option.
    #[derive(Debug, PartialEq, Eq, Clone, Copy)]
    #[cfg_attr(feature = "defmt", derive(defmt::Format))]
    pub struct HopByHopOption {
        pub down: bool,
        pub rank_error: bool,
        pub forwarding_error: bool,
        pub instance_id: InstanceId,
        pub sender_rank: u16,
    }

    impl HopByHopOption {
        /// Parse an IPv6 Extension Header Option and return a high-level representation.
        pub fn parse<T>(opt: &Packet<&T>) -> Self
        where
            T: AsRef<[u8]> + ?Sized,
        {
            Self {
                down: opt.is_down(),
                rank_error: opt.has_rank_error(),
                forwarding_error: opt.has_forwarding_error(),
                instance_id: opt.rpl_instance_id(),
                sender_rank: opt.sender_rank(),
            }
        }

        /// Return the length of a header that will be emitted from this high-level representation.
        pub const fn buffer_len(&self) -> usize {
            4
        }

        /// Emit a high-level representation into an IPv6 Extension Header Option.
        pub fn emit<T: AsRef<[u8]> + AsMut<[u8]> + ?Sized>(&self, opt: &mut Packet<&mut T>) {
            opt.set_is_down(self.down);
            opt.set_has_rank_error(self.rank_error);
            opt.set_has_forwarding_error(self.forwarding_error);
            opt.set_rpl_instance_id(self.instance_id.into());
            opt.set_sender_rank(self.sender_rank);
        }
    }

    impl core::fmt::Display for HopByHopOption {
        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            write!(
                f,
                "down={} rank_error={} forw_error={} IID={:?} sender_rank={}",
                self.down,
                self.rank_error,
                self.forwarding_error,
                self.instance_id,
                self.sender_rank
            )
        }
    }
}

#[cfg(test)]
mod tests {
    use super::Repr as RplRepr;
    use super::options::{Packet as OptionPacket, Repr as OptionRepr};
    use super::*;
    use crate::phy::ChecksumCapabilities;
    use crate::wire::{icmpv6::*, *};

    #[test]
    fn dis_packet() {
        let data = [0x7a, 0x3b, 0x3a, 0x1a, 0x9b, 0x00, 0x00, 0x00, 0x00, 0x00];

        let ll_src_address =
            Ieee802154Address::Extended([0x9e, 0xd3, 0xa2, 0x9c, 0x57, 0x1a, 0x4f, 0xe4]);
        let ll_dst_address = Ieee802154Address::Short([0xff, 0xff]);

        let packet = SixlowpanIphcPacket::new_checked(&data).unwrap();
        let repr =
            SixlowpanIphcRepr::parse(&packet, Some(ll_src_address), Some(ll_dst_address), &[])
                .unwrap();

        let icmp_repr = match repr.next_header {
            SixlowpanNextHeader::Uncompressed(IpProtocol::Icmpv6) => {
                let icmp_packet = Icmpv6Packet::new_checked(packet.payload()).unwrap();
                match Icmpv6Repr::parse(
                    &repr.src_addr,
                    &repr.dst_addr,
                    &icmp_packet,
                    &ChecksumCapabilities::ignored(),
                ) {
                    Ok(icmp @ Icmpv6Repr::Rpl(RplRepr::DodagInformationSolicitation { .. })) => {
                        icmp
                    }
                    _ => unreachable!(),
                }
            }
            _ => unreachable!(),
        };

        // We also try to emit the packet:
        let mut buffer = vec![0u8; repr.buffer_len() + icmp_repr.buffer_len()];
        repr.emit(&mut SixlowpanIphcPacket::new_unchecked(
            &mut buffer[..repr.buffer_len()],
        ));
        icmp_repr.emit(
            &repr.src_addr.into(),
            &repr.dst_addr.into(),
            &mut Icmpv6Packet::new_unchecked(
                &mut buffer[repr.buffer_len()..][..icmp_repr.buffer_len()],
            ),
            &ChecksumCapabilities::ignored(),
        );

        assert_eq!(&data[..], &buffer[..]);
    }

    /// Parsing of DIO packets.
    #[test]
    fn dio_packet() {
        let data = [
            0x9b, 0x01, 0x00, 0x00, 0x00, 0xf0, 0x00, 0x80, 0x08, 0xf0, 0x00, 0x00, 0xfd, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01,
            0x04, 0x0e, 0x00, 0x08, 0x0c, 0x00, 0x04, 0x00, 0x00, 0x80, 0x00, 0x01, 0x00, 0x1e,
            0x00, 0x3c, 0x08, 0x1e, 0x40, 0x40, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0x00, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        ];

        let addr = Address::from_octets([
            0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x01, 0x00, 0x01, 0x00, 0x01,
            0x00, 0x01,
        ]);

        let dest_prefix = [
            0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00,
        ];

        let packet = Packet::new_checked(&data[..]).unwrap();
        assert_eq!(packet.msg_type(), Message::RplControl);
        assert_eq!(
            RplControlMessage::from(packet.msg_code()),
            RplControlMessage::DodagInformationObject
        );

        let mut dio_repr = RplRepr::parse(&packet).unwrap();
        match dio_repr {
            RplRepr::DodagInformationObject {
                rpl_instance_id,
                version_number,
                rank,
                grounded,
                mode_of_operation,
                dodag_preference,
                dtsn,
                dodag_id,
                ..
            } => {
                assert_eq!(rpl_instance_id, InstanceId::from(0));
                assert_eq!(version_number, 240);
                assert_eq!(rank, 128);
                assert!(!grounded);
                assert_eq!(mode_of_operation, ModeOfOperation::NonStoringMode);
                assert_eq!(dodag_preference, 0);
                assert_eq!(dtsn, 240);
                assert_eq!(dodag_id, addr);
            }
            _ => unreachable!(),
        }

        let option = OptionPacket::new_unchecked(packet.options().unwrap());
        let dodag_conf_option = OptionRepr::parse(&option).unwrap();
        match dodag_conf_option {
            OptionRepr::DodagConfiguration {
                authentication_enabled,
                path_control_size,
                dio_interval_doublings,
                dio_interval_min,
                dio_redundancy_constant,
                max_rank_increase,
                minimum_hop_rank_increase,
                objective_code_point,
                default_lifetime,
                lifetime_unit,
            } => {
                assert!(!authentication_enabled);
                assert_eq!(path_control_size, 0);
                assert_eq!(dio_interval_doublings, 8);
                assert_eq!(dio_interval_min, 12);
                assert_eq!(dio_redundancy_constant, 0);
                assert_eq!(max_rank_increase, 1024);
                assert_eq!(minimum_hop_rank_increase, 128);
                assert_eq!(objective_code_point, 1);
                assert_eq!(default_lifetime, 30);
                assert_eq!(lifetime_unit, 60);
            }
            _ => unreachable!(),
        }

        let option = OptionPacket::new_unchecked(option.next_option().unwrap());
        let prefix_info_option = OptionRepr::parse(&option).unwrap();
        match prefix_info_option {
            OptionRepr::PrefixInformation {
                prefix_length,
                on_link,
                autonomous_address_configuration,
                valid_lifetime,
                preferred_lifetime,
                destination_prefix,
                ..
            } => {
                assert_eq!(prefix_length, 64);
                assert!(!on_link);
                assert!(autonomous_address_configuration);
                assert_eq!(valid_lifetime, u32::MAX);
                assert_eq!(preferred_lifetime, u32::MAX);
                assert_eq!(destination_prefix, &dest_prefix[..]);
            }
            _ => unreachable!(),
        }

        let mut options_buffer =
            vec![0u8; dodag_conf_option.buffer_len() + prefix_info_option.buffer_len()];

        dodag_conf_option.emit(&mut OptionPacket::new_unchecked(
            &mut options_buffer[..dodag_conf_option.buffer_len()],
        ));
        prefix_info_option.emit(&mut OptionPacket::new_unchecked(
            &mut options_buffer[dodag_conf_option.buffer_len()..]
                [..prefix_info_option.buffer_len()],
        ));

        dio_repr.set_options(&options_buffer[..]);

        let mut buffer = vec![0u8; dio_repr.buffer_len()];
        dio_repr.emit(&mut Packet::new_unchecked(&mut buffer[..]));

        assert_eq!(&data[..], &buffer[..]);
    }

    /// Parsing of DAO packets.
    #[test]
    fn dao_packet() {
        let data = [
            0x9b, 0x02, 0x00, 0x00, 0x00, 0x80, 0x00, 0xf1, 0x05, 0x12, 0x00, 0x80, 0xfd, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x02, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02,
            0x06, 0x14, 0x00, 0x00, 0x00, 0x1e, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x02, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01,
        ];

        let target_prefix = [
            0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x02, 0x00, 0x02, 0x00, 0x02,
            0x00, 0x02,
        ];

        let parent_addr = Address::from_octets([
            0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x01, 0x00, 0x01, 0x00, 0x01,
            0x00, 0x01,
        ]);

        let packet = Packet::new_checked(&data[..]).unwrap();
        let mut dao_repr = RplRepr::parse(&packet).unwrap();
        match dao_repr {
            RplRepr::DestinationAdvertisementObject {
                rpl_instance_id,
                expect_ack,
                sequence,
                dodag_id,
                ..
            } => {
                assert_eq!(rpl_instance_id, InstanceId::from(0));
                assert!(expect_ack);
                assert_eq!(sequence, 241);
                assert_eq!(dodag_id, None);
            }
            _ => unreachable!(),
        }

        let option = OptionPacket::new_unchecked(packet.options().unwrap());

        let rpl_target_option = OptionRepr::parse(&option).unwrap();
        match rpl_target_option {
            OptionRepr::RplTarget {
                prefix_length,
                prefix,
            } => {
                assert_eq!(prefix_length, 128);
                assert_eq!(prefix.octets(), target_prefix);
            }
            _ => unreachable!(),
        }

        let option = OptionPacket::new_unchecked(option.next_option().unwrap());
        let transit_info_option = OptionRepr::parse(&option).unwrap();
        match transit_info_option {
            OptionRepr::TransitInformation {
                external,
                path_control,
                path_sequence,
                path_lifetime,
                parent_address,
            } => {
                assert!(!external);
                assert_eq!(path_control, 0);
                assert_eq!(path_sequence, 0);
                assert_eq!(path_lifetime, 30);
                assert_eq!(parent_address, Some(parent_addr));
            }
            _ => unreachable!(),
        }

        let mut options_buffer =
            vec![0u8; rpl_target_option.buffer_len() + transit_info_option.buffer_len()];

        rpl_target_option.emit(&mut OptionPacket::new_unchecked(
            &mut options_buffer[..rpl_target_option.buffer_len()],
        ));
        transit_info_option.emit(&mut OptionPacket::new_unchecked(
            &mut options_buffer[rpl_target_option.buffer_len()..]
                [..transit_info_option.buffer_len()],
        ));

        dao_repr.set_options(&options_buffer[..]);

        let mut buffer = vec![0u8; dao_repr.buffer_len()];
        dao_repr.emit(&mut Packet::new_unchecked(&mut buffer[..]));

        assert_eq!(&data[..], &buffer[..]);
    }

    /// Parsing of DAO-ACK packets.
    #[test]
    fn dao_ack_packet() {
        let data = [0x9b, 0x03, 0x00, 0x00, 0x00, 0x00, 0xf1, 0x00];

        let packet = Packet::new_checked(&data[..]).unwrap();
        let dao_ack_repr = RplRepr::parse(&packet).unwrap();
        match dao_ack_repr {
            RplRepr::DestinationAdvertisementObjectAck {
                rpl_instance_id,
                sequence,
                status,
                dodag_id,
                ..
            } => {
                assert_eq!(rpl_instance_id, InstanceId::from(0));
                assert_eq!(sequence, 241);
                assert_eq!(status, 0);
                assert_eq!(dodag_id, None);
            }
            _ => unreachable!(),
        }

        let mut buffer = vec![0u8; dao_ack_repr.buffer_len()];
        dao_ack_repr.emit(&mut Packet::new_unchecked(&mut buffer[..]));

        assert_eq!(&data[..], &buffer[..]);

        let data = [
            0x9b, 0x03, 0x0, 0x0, 0x1e, 0x80, 0xf0, 0x00, 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
        ];

        let packet = Packet::new_checked(&data[..]).unwrap();
        let dao_ack_repr = RplRepr::parse(&packet).unwrap();
        match dao_ack_repr {
            RplRepr::DestinationAdvertisementObjectAck {
                rpl_instance_id,
                sequence,
                status,
                dodag_id,
                ..
            } => {
                assert_eq!(rpl_instance_id, InstanceId::from(30));
                assert_eq!(sequence, 240);
                assert_eq!(status, 0x0);
                assert_eq!(
                    dodag_id,
                    Some(Ipv6Address::new(0xfe80, 0, 0, 0, 0x0200, 0, 0, 1))
                );
            }
            _ => unreachable!(),
        }

        let mut buffer = vec![0u8; dao_ack_repr.buffer_len()];
        dao_ack_repr.emit(&mut Packet::new_unchecked(&mut buffer[..]));

        assert_eq!(&data[..], &buffer[..]);
    }
}