nlink 0.24.0

Async netlink library for Linux network configuration
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
//! Core types for declarative network configuration.

use std::net::IpAddr;

pub use crate::netlink::link::{
    AdSelect as BondAdSelect, LacpRate as BondLacpRate, NetkitMode, NetkitPolicy, NetkitScrub,
    VlanProtocol,
};

/// Declarative network configuration.
///
/// Represents the desired state of network resources. Use the builder methods
/// to add links, addresses, routes, and qdiscs, then call [`diff()`](NetworkConfig::diff)
/// or [`apply()`](NetworkConfig::apply) to reconcile with the current state.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case", default))]
#[derive(Debug, Clone, Default)]
pub struct NetworkConfig {
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Vec::is_empty"))]
    pub(crate) links: Vec<DeclaredLink>,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Vec::is_empty"))]
    pub(crate) addresses: Vec<DeclaredAddress>,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Vec::is_empty"))]
    pub(crate) routes: Vec<DeclaredRoute>,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Vec::is_empty"))]
    pub(crate) qdiscs: Vec<DeclaredQdisc>,
}

impl NetworkConfig {
    /// Create an empty network configuration.
    pub fn new() -> Self {
        Self::default()
    }

    /// Parse a [`NetworkConfig`] from a JSON document.
    ///
    /// Resource fields are validated as they parse — addresses and
    /// routes from their CIDR strings (prefix bounds checked), MACs
    /// from `aa:bb:cc:dd:ee:ff` — so a malformed document is a parse
    /// error rather than a silently-wrong config. Requires the
    /// `serde` feature.
    ///
    /// ```ignore
    /// let cfg = NetworkConfig::from_json_str(r#"{
    ///     "addresses": [{ "dev": "eth0", "address": "10.0.0.1/24" }]
    /// }"#)?;
    /// ```
    #[cfg(feature = "serde")]
    pub fn from_json_str(s: &str) -> crate::netlink::Result<Self> {
        serde_json::from_str(s)
            .map_err(|e| crate::netlink::Error::InvalidMessage(format!("config JSON parse: {e}")))
    }

    /// Serialize this configuration to a compact JSON string.
    /// Requires the `serde` feature.
    #[cfg(feature = "serde")]
    pub fn to_json_string(&self) -> crate::netlink::Result<String> {
        serde_json::to_string(self).map_err(|e| {
            crate::netlink::Error::InvalidMessage(format!("config JSON serialize: {e}"))
        })
    }

    /// Serialize this configuration to a pretty-printed JSON string.
    /// Requires the `serde` feature.
    #[cfg(feature = "serde")]
    pub fn to_json_string_pretty(&self) -> crate::netlink::Result<String> {
        serde_json::to_string_pretty(self).map_err(|e| {
            crate::netlink::Error::InvalidMessage(format!("config JSON serialize: {e}"))
        })
    }

    /// Generate a [JSON Schema](https://json-schema.org) (draft 7)
    /// describing the JSON accepted by [`from_json_str`](Self::from_json_str),
    /// as a pretty-printed string. Requires the `schemars` feature.
    ///
    /// Wire this into editor tooling (VS Code's `json.schemas`,
    /// `yaml.schemas`) for autocomplete + inline validation of
    /// `NetworkConfig` files, or check it into a repo for CI
    /// validation. The schema reflects the human-facing JSON shape —
    /// addresses/routes as CIDR strings, MACs as `aa:bb:..` strings,
    /// the `default` route keyword — not the in-memory representation.
    ///
    /// ```ignore
    /// std::fs::write("network-config.schema.json",
    ///     nlink::netlink::config::NetworkConfig::json_schema())?;
    /// ```
    #[cfg(feature = "schemars")]
    pub fn json_schema() -> String {
        let schema = schemars::schema_for!(NetworkConfig);
        // `RootSchema` always serializes (no user data, no custom
        // serializers that can fail), so the unwrap is infallible.
        serde_json::to_string_pretty(&schema)
            .expect("RootSchema serialization is infallible")
    }

    /// The JSON Schema as a [`schemars::schema::RootSchema`], for
    /// callers that want to inspect or merge it rather than emit
    /// text. Requires the `schemars` feature.
    #[cfg(feature = "schemars")]
    pub fn json_schema_value() -> schemars::schema::RootSchema {
        schemars::schema_for!(NetworkConfig)
    }

    /// Add a link (interface) configuration.
    ///
    /// **Ordering note (Plan 186 §3c)**: declared order of
    /// `.link()` calls is preserved at the surface, but the
    /// internal apply step topologically sorts parent → child
    /// (e.g., a `vlan` whose parent is also being created in
    /// this apply). You can declare the VLAN before its parent
    /// dummy and the apply still works:
    ///
    /// ```ignore
    /// // Either order works — the apply sorts before sending.
    /// let cfg = NetworkConfig::new()
    ///     .link("eth0.42", |l| l.vlan("eth0", 42))
    ///     .link("eth0",    |l| l.dummy());
    /// ```
    ///
    /// # Example
    ///
    /// ```ignore
    /// let config = NetworkConfig::new()
    ///     .link("br0", |l| l.bridge().up())
    ///     .link("dummy0", |l| l.dummy())
    ///     .link("veth0", |l| l.veth("veth1").master("br0"));
    /// ```
    pub fn link(mut self, name: &str, f: impl FnOnce(LinkBuilder) -> LinkBuilder) -> Self {
        let builder = f(LinkBuilder::new(name));
        self.links.push(builder.build());
        self
    }

    /// Add an IP address to an interface.
    ///
    /// The address should be in CIDR notation (e.g., "192.168.1.1/24").
    ///
    /// # Example
    ///
    /// ```ignore
    /// let config = NetworkConfig::new()
    ///     .address("eth0", "192.168.1.1/24")?
    ///     .address("eth0", "2001:db8::1/64")?;
    /// ```
    pub fn address(mut self, dev: &str, addr: &str) -> Result<Self, AddressParseError> {
        let declared = DeclaredAddress::parse(dev, addr)?;
        self.addresses.push(declared);
        Ok(self)
    }

    /// Add a route.
    ///
    /// The destination should be in CIDR notation (e.g., "10.0.0.0/8" or "0.0.0.0/0").
    ///
    /// # Example
    ///
    /// ```ignore
    /// let config = NetworkConfig::new()
    ///     .route("10.0.0.0/8", |r| r.via("192.168.1.1"))?
    ///     .route("0.0.0.0/0", |r| r.via("192.168.1.254").dev("eth0"))?;
    /// ```
    pub fn route(
        mut self,
        dst: &str,
        f: impl FnOnce(RouteBuilder) -> RouteBuilder,
    ) -> Result<Self, RouteParseError> {
        let builder = f(RouteBuilder::new(dst)?);
        self.routes.push(builder.build());
        Ok(self)
    }

    /// Add a qdisc configuration.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use nlink::util::Percent;
    /// let config = NetworkConfig::new()
    ///     .qdisc("eth0", |q| q.netem().delay_ms(100).loss_pct(Percent::new(1.0)))
    ///     .qdisc("eth1", |q| q.htb().default_class(0x30));
    /// ```
    pub fn qdisc(mut self, dev: &str, f: impl FnOnce(QdiscBuilder) -> QdiscBuilder) -> Self {
        let builder = f(QdiscBuilder::new(dev));
        self.qdiscs.push(builder.build());
        self
    }

    /// Get the configured links.
    pub fn links(&self) -> &[DeclaredLink] {
        &self.links
    }

    /// Get the configured addresses.
    pub fn addresses(&self) -> &[DeclaredAddress] {
        &self.addresses
    }

    /// Get the configured routes.
    pub fn routes(&self) -> &[DeclaredRoute] {
        &self.routes
    }

    /// Get the configured qdiscs.
    pub fn qdiscs(&self) -> &[DeclaredQdisc] {
        &self.qdiscs
    }
}

// ============================================================================
// Link Types
// ============================================================================

/// Declared link configuration.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
#[derive(Debug, Clone)]
pub struct DeclaredLink {
    pub(crate) name: String,
    pub(crate) link_type: DeclaredLinkType,
    #[cfg_attr(feature = "serde", serde(default))]
    pub(crate) state: LinkState,
    #[cfg_attr(feature = "serde", serde(default, skip_serializing_if = "Option::is_none"))]
    pub(crate) mtu: Option<u32>,
    #[cfg_attr(feature = "serde", serde(default, skip_serializing_if = "Option::is_none"))]
    pub(crate) master: Option<String>,
    /// Hardware address, round-tripped as the canonical
    /// `aa:bb:cc:dd:ee:ff` string rather than a raw byte array.
    #[cfg_attr(
        feature = "serde",
        serde(default, with = "mac_serde", skip_serializing_if = "Option::is_none")
    )]
    // `mac_serde` renders this as the `aa:bb:..` string, so the
    // schema must say "optional string", not "array of 6 integers".
    #[cfg_attr(feature = "schemars", schemars(with = "Option<String>"))]
    pub(crate) address: Option<[u8; 6]>,
}

impl DeclaredLink {
    /// Get the interface name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the link type.
    pub fn link_type(&self) -> &DeclaredLinkType {
        &self.link_type
    }

    /// Get the desired state.
    pub fn state(&self) -> LinkState {
        self.state
    }

    /// Get the desired MTU.
    pub fn mtu(&self) -> Option<u32> {
        self.mtu
    }

    /// Get the master interface name.
    pub fn master(&self) -> Option<&str> {
        self.master.as_deref()
    }
}

/// Link type for declared configuration.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum DeclaredLinkType {
    /// Dummy interface.
    Dummy,
    /// Veth pair with peer name.
    Veth { peer: String },
    /// Bridge interface.
    Bridge,
    /// VLAN interface. Plan 190 §2.2 added `protocol`.
    Vlan {
        parent: String,
        vlan_id: u16,
        /// VLAN tagging protocol; `None` == kernel default
        /// (802.1Q). Use [`VlanProtocol::Dot1ad`] for Q-in-Q.
        protocol: Option<VlanProtocol>,
    },
    /// VXLAN interface. Plan 190 §2.1 added `local`/`port`/`underlay_dev`.
    Vxlan {
        vni: u32,
        remote: Option<IpAddr>,
        /// Tunnel source IP (`IFLA_VXLAN_LOCAL` /
        /// `IFLA_VXLAN_LOCAL6`). IPv4 only at the imperative
        /// layer today — IPv6 source addresses ignored.
        local: Option<IpAddr>,
        /// UDP encap port (`IFLA_VXLAN_PORT`, default 4789).
        port: Option<u16>,
        /// Underlay parent device by name
        /// (`IFLA_VXLAN_LINK`).
        underlay_dev: Option<String>,
    },
    /// Macvlan interface.
    Macvlan { parent: String, mode: MacvlanMode },
    /// Bond interface. Plan 190 §8 added 5 new option knobs.
    Bond {
        mode: BondMode,
        miimon: Option<u32>,
        xmit_hash_policy: Option<u8>,
        min_links: Option<u32>,
        /// 802.3ad aggregator selection logic. Plan 190 §8.
        ad_select: Option<BondAdSelect>,
        /// LACPDU transmit rate. Plan 190 §8.
        lacp_rate: Option<BondLacpRate>,
        /// Time (ms) to wait before disabling a slave on
        /// link-down. Plan 190 §8.
        downdelay: Option<u32>,
        /// Time (ms) to wait before enabling a slave on
        /// link-up. Plan 190 §8.
        updelay: Option<u32>,
        /// Number of IGMP membership reports to resend on
        /// failover. Plan 190 §8.
        resend_igmp: Option<u32>,
    },
    /// IFB (Intermediate Functional Block).
    Ifb,
    /// VRF (Virtual Routing & Forwarding) — table-scoped
    /// forwarding domain. Members enslave via
    /// [`LinkBuilder::master`]. Plan 190 §2.3.
    Vrf { table: u32 },
    /// OpenVPN data-channel-offload link (kernel 6.16+).
    /// Link-half only — peer / cipher config goes through
    /// the GENL `ovpn` family (Plan 197 / 0.20). Plan 190 §2.3b.
    Ovpn,
    /// Netkit BPF-programmable veth pair (kernel 6.7+).
    /// Plan 190 §2.3a.
    Netkit {
        /// Name of the peer interface.
        peer: String,
        /// L2 vs L3 operating mode.
        mode: Option<NetkitMode>,
        /// Default policy on the primary peer.
        primary_policy: Option<NetkitPolicy>,
        /// Default policy on the peer interface.
        peer_policy: Option<NetkitPolicy>,
        /// Scrub mode on the primary peer (kernel 6.10+).
        scrub: Option<NetkitScrub>,
        /// Scrub mode on the peer interface (kernel 6.10+).
        peer_scrub: Option<NetkitScrub>,
    },
    /// Existing physical interface (not created, only configured).
    Physical,
}

impl DeclaredLinkType {
    /// Get the kind string for this link type.
    pub fn kind(&self) -> Option<&str> {
        match self {
            Self::Dummy => Some("dummy"),
            Self::Veth { .. } => Some("veth"),
            Self::Bridge => Some("bridge"),
            Self::Vlan { .. } => Some("vlan"),
            Self::Vxlan { .. } => Some("vxlan"),
            Self::Macvlan { .. } => Some("macvlan"),
            Self::Bond { .. } => Some("bond"),
            Self::Ifb => Some("ifb"),
            Self::Vrf { .. } => Some("vrf"),
            Self::Netkit { .. } => Some("netkit"),
            Self::Ovpn => Some("ovpn"),
            Self::Physical => None,
        }
    }
}

/// Link state (up or down).
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum LinkState {
    /// Interface should be up.
    Up,
    /// Interface should be down.
    #[default]
    Down,
    /// Don't change the state.
    Unchanged,
}

/// Macvlan mode.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum MacvlanMode {
    /// Private mode (no communication between macvlans).
    Private,
    /// VEPA mode (Virtual Ethernet Port Aggregator).
    Vepa,
    /// Bridge mode (macvlans can communicate).
    #[default]
    Bridge,
    /// Passthru mode (single macvlan, exclusive access).
    Passthru,
    /// Source mode (filter by source MAC).
    Source,
}

/// Bond mode.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum BondMode {
    /// Round-robin (balance-rr).
    #[default]
    BalanceRr,
    /// Active-backup.
    ActiveBackup,
    /// XOR (balance-xor).
    BalanceXor,
    /// Broadcast.
    Broadcast,
    /// 802.3ad (LACP).
    Ieee802_3ad,
    /// Transmit load balancing.
    BalanceTlb,
    /// Adaptive load balancing.
    BalanceAlb,
}

/// Builder for link configuration.
#[derive(Debug)]
#[must_use = "builders do nothing unless used"]
pub struct LinkBuilder {
    name: String,
    link_type: DeclaredLinkType,
    state: LinkState,
    mtu: Option<u32>,
    master: Option<String>,
    address: Option<[u8; 6]>,
}

impl LinkBuilder {
    fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
            link_type: DeclaredLinkType::Physical,
            state: LinkState::Unchanged,
            mtu: None,
            master: None,
            address: None,
        }
    }

    /// Create a dummy interface.
    pub fn dummy(mut self) -> Self {
        self.link_type = DeclaredLinkType::Dummy;
        self
    }

    /// Create a veth pair with the given peer name.
    pub fn veth(mut self, peer: &str) -> Self {
        self.link_type = DeclaredLinkType::Veth {
            peer: peer.to_string(),
        };
        self
    }

    /// Create a bridge interface.
    pub fn bridge(mut self) -> Self {
        self.link_type = DeclaredLinkType::Bridge;
        self
    }

    /// Create a VLAN interface on the given parent with the specified VLAN ID.
    pub fn vlan(mut self, parent: &str, vlan_id: u16) -> Self {
        self.link_type = DeclaredLinkType::Vlan {
            parent: parent.to_string(),
            vlan_id,
            protocol: None,
        };
        self
    }

    /// Set the VLAN tagging protocol. Defaults to 802.1Q
    /// (kernel default) when unset. Use
    /// [`VlanProtocol::Dot1ad`] for Q-in-Q stacked VLAN
    /// encap. Plan 190 §2.2. No-op if the link isn't a VLAN.
    pub fn vlan_protocol(mut self, p: VlanProtocol) -> Self {
        if let DeclaredLinkType::Vlan { protocol, .. } = &mut self.link_type {
            *protocol = Some(p);
        }
        self
    }

    /// Create a VXLAN interface with the given VNI.
    pub fn vxlan(mut self, vni: u32) -> Self {
        self.link_type = DeclaredLinkType::Vxlan {
            vni,
            remote: None,
            local: None,
            port: None,
            underlay_dev: None,
        };
        self
    }

    /// Set the VXLAN remote endpoint. No-op if the builder
    /// isn't a VXLAN.
    pub fn vxlan_remote(mut self, remote_addr: IpAddr) -> Self {
        if let DeclaredLinkType::Vxlan { remote, .. } = &mut self.link_type {
            *remote = Some(remote_addr);
        }
        self
    }

    /// Set the VXLAN tunnel source IP (`IFLA_VXLAN_LOCAL`).
    /// The local address must be configured on the underlay
    /// interface — the kernel rejects mismatches.
    /// Plan 190 §2.1.
    pub fn vxlan_local(mut self, local_addr: IpAddr) -> Self {
        if let DeclaredLinkType::Vxlan { local, .. } = &mut self.link_type {
            *local = Some(local_addr);
        }
        self
    }

    /// Set the VXLAN UDP encap port (`IFLA_VXLAN_PORT`,
    /// default 4789). Plan 190 §2.1.
    pub fn vxlan_port(mut self, udp_port: u16) -> Self {
        if let DeclaredLinkType::Vxlan { port, .. } = &mut self.link_type {
            *port = Some(udp_port);
        }
        self
    }

    /// Set the VXLAN underlay parent device name
    /// (`IFLA_VXLAN_LINK`). Plan 190 §2.1.
    pub fn vxlan_underlay_dev(mut self, dev: impl Into<String>) -> Self {
        if let DeclaredLinkType::Vxlan {
            underlay_dev, ..
        } = &mut self.link_type
        {
            *underlay_dev = Some(dev.into());
        }
        self
    }

    /// Create a macvlan interface on the given parent.
    pub fn macvlan(mut self, parent: &str) -> Self {
        self.link_type = DeclaredLinkType::Macvlan {
            parent: parent.to_string(),
            mode: MacvlanMode::default(),
        };
        self
    }

    /// Set the macvlan mode.
    pub fn macvlan_mode(mut self, mode: MacvlanMode) -> Self {
        if let DeclaredLinkType::Macvlan { parent, .. } = &self.link_type {
            self.link_type = DeclaredLinkType::Macvlan {
                parent: parent.clone(),
                mode,
            };
        }
        self
    }

    /// Create a bond interface.
    pub fn bond(mut self) -> Self {
        self.link_type = DeclaredLinkType::Bond {
            mode: BondMode::default(),
            miimon: None,
            xmit_hash_policy: None,
            min_links: None,
            ad_select: None,
            lacp_rate: None,
            downdelay: None,
            updelay: None,
            resend_igmp: None,
        };
        self
    }

    /// Set the bond mode.
    pub fn bond_mode(mut self, mode: BondMode) -> Self {
        if let DeclaredLinkType::Bond {
            mode: ref mut m, ..
        } = self.link_type
        {
            *m = mode;
        }
        self
    }

    /// Set the MII monitoring interval in milliseconds.
    pub fn miimon(mut self, ms: u32) -> Self {
        if let DeclaredLinkType::Bond { miimon, .. } = &mut self.link_type {
            *miimon = Some(ms);
        }
        self
    }

    /// Set the transmit hash policy (0=Layer2, 1=Layer34, 2=Layer23).
    pub fn xmit_hash_policy(mut self, policy: u8) -> Self {
        if let DeclaredLinkType::Bond {
            xmit_hash_policy, ..
        } = &mut self.link_type
        {
            *xmit_hash_policy = Some(policy);
        }
        self
    }

    /// Set the minimum number of active links.
    pub fn min_links(mut self, count: u32) -> Self {
        if let DeclaredLinkType::Bond { min_links, .. } = &mut self.link_type {
            *min_links = Some(count);
        }
        self
    }

    /// Set the 802.3ad aggregator selection logic.
    /// No-op on non-Bond builders. Plan 190 §8.
    pub fn bond_ad_select(mut self, sel: BondAdSelect) -> Self {
        if let DeclaredLinkType::Bond { ad_select, .. } = &mut self.link_type {
            *ad_select = Some(sel);
        }
        self
    }

    /// Set the LACPDU transmit rate (Slow=30s, Fast=1s).
    /// No-op on non-Bond builders. Plan 190 §8.
    pub fn bond_lacp_rate(mut self, rate: BondLacpRate) -> Self {
        if let DeclaredLinkType::Bond { lacp_rate, .. } = &mut self.link_type {
            *lacp_rate = Some(rate);
        }
        self
    }

    /// Set the time (ms) to wait before disabling a slave on
    /// link-down. No-op on non-Bond builders. Plan 190 §8.
    pub fn bond_downdelay(mut self, ms: u32) -> Self {
        if let DeclaredLinkType::Bond { downdelay, .. } = &mut self.link_type {
            *downdelay = Some(ms);
        }
        self
    }

    /// Set the time (ms) to wait before enabling a slave on
    /// link-up. No-op on non-Bond builders. Plan 190 §8.
    pub fn bond_updelay(mut self, ms: u32) -> Self {
        if let DeclaredLinkType::Bond { updelay, .. } = &mut self.link_type {
            *updelay = Some(ms);
        }
        self
    }

    /// Set the number of IGMP membership reports to resend
    /// on failover. No-op on non-Bond builders. Plan 190 §8.
    pub fn bond_resend_igmp(mut self, count: u32) -> Self {
        if let DeclaredLinkType::Bond { resend_igmp, .. } = &mut self.link_type {
            *resend_igmp = Some(count);
        }
        self
    }

    /// Create an IFB interface.
    pub fn ifb(mut self) -> Self {
        self.link_type = DeclaredLinkType::Ifb;
        self
    }

    /// Build an OpenVPN data-channel-offload link (kernel
    /// 6.16+). Link half only — peer / cipher config goes
    /// through the GENL `ovpn` family (deferred to Plan
    /// 197). Plan 190 §2.3b.
    pub fn ovpn(mut self) -> Self {
        self.link_type = DeclaredLinkType::Ovpn;
        self
    }

    /// Build a netkit BPF-programmable veth pair (kernel
    /// 6.7+). The `peer` argument names the peer interface;
    /// both ends are created atomically. Use
    /// [`LinkBuilder::netkit_mode`] / `netkit_primary_policy` /
    /// `netkit_peer_policy` / `netkit_scrub` /
    /// `netkit_peer_scrub` to refine. Plan 190 §2.3a.
    pub fn netkit(mut self, peer: impl Into<String>) -> Self {
        self.link_type = DeclaredLinkType::Netkit {
            peer: peer.into(),
            mode: None,
            primary_policy: None,
            peer_policy: None,
            scrub: None,
            peer_scrub: None,
        };
        self
    }

    /// Set netkit L2 vs L3 mode. No-op on non-netkit builders.
    pub fn netkit_mode(mut self, m: NetkitMode) -> Self {
        if let DeclaredLinkType::Netkit { mode, .. } = &mut self.link_type {
            *mode = Some(m);
        }
        self
    }

    /// Set the netkit primary-peer default policy. No-op on
    /// non-netkit builders.
    pub fn netkit_primary_policy(mut self, p: NetkitPolicy) -> Self {
        if let DeclaredLinkType::Netkit { primary_policy, .. } = &mut self.link_type {
            *primary_policy = Some(p);
        }
        self
    }

    /// Set the netkit peer default policy. No-op on
    /// non-netkit builders.
    pub fn netkit_peer_policy(mut self, p: NetkitPolicy) -> Self {
        if let DeclaredLinkType::Netkit { peer_policy, .. } = &mut self.link_type {
            *peer_policy = Some(p);
        }
        self
    }

    /// Set the netkit primary-peer scrub mode (kernel 6.10+).
    /// No-op on non-netkit builders.
    pub fn netkit_scrub(mut self, s: NetkitScrub) -> Self {
        if let DeclaredLinkType::Netkit { scrub, .. } = &mut self.link_type {
            *scrub = Some(s);
        }
        self
    }

    /// Set the netkit peer scrub mode (kernel 6.10+). No-op
    /// on non-netkit builders.
    pub fn netkit_peer_scrub(mut self, s: NetkitScrub) -> Self {
        if let DeclaredLinkType::Netkit { peer_scrub, .. } = &mut self.link_type {
            *peer_scrub = Some(s);
        }
        self
    }

    /// Build a VRF link bound to routing-table `table`.
    ///
    /// VRF (Virtual Routing & Forwarding) groups interfaces
    /// under a per-table forwarding domain; common in
    /// multi-tenant networks. Members enslave via
    /// [`LinkBuilder::master`].
    ///
    /// Requires the kernel `vrf` module. Plan 190 §2.3.
    pub fn vrf(mut self, table: u32) -> Self {
        self.link_type = DeclaredLinkType::Vrf { table };
        self
    }

    /// Set the interface state to up.
    pub fn up(mut self) -> Self {
        self.state = LinkState::Up;
        self
    }

    /// Set the interface state to down.
    pub fn down(mut self) -> Self {
        self.state = LinkState::Down;
        self
    }

    /// Set the MTU.
    pub fn mtu(mut self, mtu: u32) -> Self {
        self.mtu = Some(mtu);
        self
    }

    /// Set the master interface (for bridging/bonding).
    pub fn master(mut self, master: &str) -> Self {
        self.master = Some(master.to_string());
        self
    }

    /// Set the MAC address.
    pub fn address(mut self, addr: [u8; 6]) -> Self {
        self.address = Some(addr);
        self
    }

    fn build(self) -> DeclaredLink {
        DeclaredLink {
            name: self.name,
            link_type: self.link_type,
            state: self.state,
            mtu: self.mtu,
            master: self.master,
            address: self.address,
        }
    }
}

// ============================================================================
// Address Types
// ============================================================================

/// Declared address configuration.
///
/// Round-trips through serde as `{ dev, address }` where `address`
/// is CIDR notation (`10.0.0.1/24`). Deserialization goes through
/// [`DeclaredAddress::parse`], so prefix-length bounds are validated
/// rather than bypassed — an out-of-range prefix is a deserialize
/// error, not a silently-accepted struct.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(into = "AddressRepr", try_from = "AddressRepr"))]
// JsonSchema is NOT derived here. The JSON shape goes through
// `AddressRepr` (a CIDR string), so a *derived* schema would wrongly
// expose the parsed `address`/`prefix_len` fields. schemars 0.8's
// `with` is field-level only, so the container override is a no-op —
// the manual impl below delegates to `AddressRepr` instead, keeping
// the schema faithful to the wire.
#[derive(Debug, Clone)]
pub struct DeclaredAddress {
    pub(crate) dev: String,
    pub(crate) address: IpAddr,
    pub(crate) prefix_len: u8,
}

/// Serde shadow for [`DeclaredAddress`] — the human-facing
/// `{ dev, address: "<cidr>" }` form. Also the schema source for
/// [`DeclaredAddress`] (see its manual `JsonSchema` impl).
#[cfg(feature = "serde")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
struct AddressRepr {
    /// `dev` the address is attached to.
    dev: String,
    /// CIDR-notation address, e.g. `"10.0.0.1/24"` or `"fd00::1/64"`.
    address: String,
}

// Delegate `DeclaredAddress`'s schema to `AddressRepr` so it
// describes the actual `{ dev, address: "<cidr>" }` JSON.
#[cfg(feature = "schemars")]
impl schemars::JsonSchema for DeclaredAddress {
    fn schema_name() -> String {
        AddressRepr::schema_name()
    }
    fn schema_id() -> std::borrow::Cow<'static, str> {
        AddressRepr::schema_id()
    }
    fn json_schema(g: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema {
        AddressRepr::json_schema(g)
    }
    fn is_referenceable() -> bool {
        AddressRepr::is_referenceable()
    }
}

#[cfg(feature = "serde")]
impl From<DeclaredAddress> for AddressRepr {
    fn from(a: DeclaredAddress) -> Self {
        AddressRepr {
            dev: a.dev,
            address: format!("{}/{}", a.address, a.prefix_len),
        }
    }
}

#[cfg(feature = "serde")]
impl TryFrom<AddressRepr> for DeclaredAddress {
    type Error = AddressParseError;

    fn try_from(r: AddressRepr) -> Result<Self, Self::Error> {
        DeclaredAddress::parse(&r.dev, &r.address)
    }
}

impl DeclaredAddress {
    /// Parse an address from CIDR notation.
    pub fn parse(dev: &str, addr: &str) -> Result<Self, AddressParseError> {
        let (ip_str, prefix_str) = addr
            .split_once('/')
            .ok_or_else(|| AddressParseError::MissingPrefix(addr.to_string()))?;

        let address: IpAddr = ip_str
            .parse()
            .map_err(|_| AddressParseError::InvalidAddress(ip_str.to_string()))?;

        let prefix_len: u8 = prefix_str
            .parse()
            .map_err(|_| AddressParseError::InvalidPrefix(prefix_str.to_string()))?;

        // Validate prefix length
        let max_prefix = if address.is_ipv4() { 32 } else { 128 };
        if prefix_len > max_prefix {
            return Err(AddressParseError::PrefixTooLarge {
                prefix: prefix_len,
                max: max_prefix,
            });
        }

        Ok(Self {
            dev: dev.to_string(),
            address,
            prefix_len,
        })
    }

    /// Get the device name.
    pub fn dev(&self) -> &str {
        &self.dev
    }

    /// Get the IP address.
    pub fn address(&self) -> IpAddr {
        self.address
    }

    /// Get the prefix length.
    pub fn prefix_len(&self) -> u8 {
        self.prefix_len
    }

    /// Check if this is an IPv4 address.
    pub fn is_ipv4(&self) -> bool {
        self.address.is_ipv4()
    }

    /// Check if this is an IPv6 address.
    pub fn is_ipv6(&self) -> bool {
        self.address.is_ipv6()
    }
}

/// Error parsing an address.
#[derive(Debug, Clone, thiserror::Error)]
#[non_exhaustive]
pub enum AddressParseError {
    /// Address is missing prefix (no "/").
    #[error("address missing prefix: {0} (expected format: 192.168.1.1/24)")]
    MissingPrefix(String),
    /// Invalid IP address.
    #[error("invalid IP address: {0}")]
    InvalidAddress(String),
    /// Invalid prefix length.
    #[error("invalid prefix length: {0}")]
    InvalidPrefix(String),
    /// Prefix length too large.
    #[error("prefix length {prefix} exceeds maximum {max}")]
    PrefixTooLarge { prefix: u8, max: u8 },
}

// ============================================================================
// Route Types
// ============================================================================

/// Declared route configuration.
///
/// Round-trips through serde with `destination` (and `gateway`) as
/// strings: a CIDR like `10.0.0.0/8`, or the bare keyword `default`
/// for `0.0.0.0/0` / `::/0` (family inferred from the gateway, IPv4
/// when there is none). Deserialization validates the prefix length
/// and the gateway address, so malformed input is a deserialize error.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(into = "RouteRepr", try_from = "RouteRepr"))]
// JsonSchema delegated to `RouteRepr` via the manual impl below (the
// JSON shape is string destination/gateway, not the parsed fields).
#[derive(Debug, Clone)]
pub struct DeclaredRoute {
    pub(crate) destination: IpAddr,
    pub(crate) prefix_len: u8,
    pub(crate) gateway: Option<IpAddr>,
    pub(crate) dev: Option<String>,
    pub(crate) metric: Option<u32>,
    pub(crate) table: Option<u32>,
    pub(crate) route_type: DeclaredRouteType,
}

/// Serde shadow for [`DeclaredRoute`] — string `destination`/`gateway`
/// plus the optional knobs, with `type` omitted when it is the
/// default `unicast`.
#[cfg(feature = "serde")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
struct RouteRepr {
    /// CIDR-notation destination, or the bare keyword `"default"`.
    destination: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    gateway: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    dev: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    metric: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    table: Option<u32>,
    #[serde(
        rename = "type",
        default,
        skip_serializing_if = "DeclaredRouteType::is_unicast"
    )]
    route_type: DeclaredRouteType,
}

// Delegate `DeclaredRoute`'s schema to `RouteRepr` so it describes
// the actual string-destination/gateway JSON, not the parsed fields.
#[cfg(feature = "schemars")]
impl schemars::JsonSchema for DeclaredRoute {
    fn schema_name() -> String {
        RouteRepr::schema_name()
    }
    fn schema_id() -> std::borrow::Cow<'static, str> {
        RouteRepr::schema_id()
    }
    fn json_schema(g: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema {
        RouteRepr::json_schema(g)
    }
    fn is_referenceable() -> bool {
        RouteRepr::is_referenceable()
    }
}

#[cfg(feature = "serde")]
impl From<DeclaredRoute> for RouteRepr {
    fn from(r: DeclaredRoute) -> Self {
        // A `0.0.0.0/0` or `::/0` destination renders as the iproute2
        // `default` keyword for readability.
        let destination = if r.prefix_len == 0 && r.destination.is_unspecified() {
            "default".to_string()
        } else {
            format!("{}/{}", r.destination, r.prefix_len)
        };
        RouteRepr {
            destination,
            gateway: r.gateway.map(|g| g.to_string()),
            dev: r.dev,
            metric: r.metric,
            table: r.table,
            route_type: r.route_type,
        }
    }
}

#[cfg(feature = "serde")]
impl TryFrom<RouteRepr> for DeclaredRoute {
    type Error = RouteParseError;

    fn try_from(r: RouteRepr) -> Result<Self, Self::Error> {
        // Parse the gateway first; its family disambiguates a bare
        // `default` destination.
        let gateway = match r.gateway.as_deref() {
            Some(g) => Some(
                g.parse::<IpAddr>()
                    .map_err(|_| RouteParseError::InvalidGateway(g.to_string()))?,
            ),
            None => None,
        };

        let (destination, prefix_len) = if r.destination == "default" {
            if matches!(gateway, Some(IpAddr::V6(_))) {
                (IpAddr::V6(std::net::Ipv6Addr::UNSPECIFIED), 0)
            } else {
                (IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED), 0)
            }
        } else {
            let (ip_str, prefix_str) = r
                .destination
                .split_once('/')
                .ok_or_else(|| RouteParseError::MissingPrefix(r.destination.clone()))?;
            let dst: IpAddr = ip_str
                .parse()
                .map_err(|_| RouteParseError::InvalidDestination(ip_str.to_string()))?;
            let plen: u8 = prefix_str
                .parse()
                .map_err(|_| RouteParseError::InvalidPrefix(prefix_str.to_string()))?;
            let max = if dst.is_ipv4() { 32 } else { 128 };
            if plen > max {
                return Err(RouteParseError::PrefixTooLarge { prefix: plen, max });
            }
            (dst, plen)
        };

        Ok(DeclaredRoute {
            destination,
            prefix_len,
            gateway,
            dev: r.dev,
            metric: r.metric,
            table: r.table,
            route_type: r.route_type,
        })
    }
}

impl DeclaredRoute {
    /// Get the destination address.
    pub fn destination(&self) -> IpAddr {
        self.destination
    }

    /// Get the prefix length.
    pub fn prefix_len(&self) -> u8 {
        self.prefix_len
    }

    /// Get the gateway address.
    pub fn gateway(&self) -> Option<IpAddr> {
        self.gateway
    }

    /// Get the output device.
    pub fn dev(&self) -> Option<&str> {
        self.dev.as_deref()
    }

    /// Get the route metric.
    pub fn metric(&self) -> Option<u32> {
        self.metric
    }

    /// Get the routing table.
    pub fn table(&self) -> Option<u32> {
        self.table
    }

    /// Get the route type.
    pub fn route_type(&self) -> DeclaredRouteType {
        self.route_type
    }

    /// Check if this is an IPv4 route.
    pub fn is_ipv4(&self) -> bool {
        self.destination.is_ipv4()
    }

    /// Check if this is an IPv6 route.
    pub fn is_ipv6(&self) -> bool {
        self.destination.is_ipv6()
    }
}

/// Route type for declared configuration.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum DeclaredRouteType {
    /// Normal unicast route.
    #[default]
    Unicast,
    /// Blackhole (silently drop).
    Blackhole,
    /// Unreachable (ICMP unreachable).
    Unreachable,
    /// Prohibit (ICMP prohibited).
    Prohibit,
}

impl DeclaredRouteType {
    /// True for the default `unicast` type — lets serde omit the
    /// redundant `type: unicast` field from serialized routes.
    #[cfg(feature = "serde")]
    fn is_unicast(&self) -> bool {
        matches!(self, Self::Unicast)
    }
}

/// Error parsing a route.
#[derive(Debug, Clone, thiserror::Error)]
#[non_exhaustive]
pub enum RouteParseError {
    /// Destination is missing prefix.
    #[error("destination missing prefix: {0} (expected format: 10.0.0.0/8)")]
    MissingPrefix(String),
    /// Invalid destination address.
    #[error("invalid destination address: {0}")]
    InvalidDestination(String),
    /// Invalid prefix length.
    #[error("invalid prefix length: {0}")]
    InvalidPrefix(String),
    /// Prefix length too large.
    #[error("prefix length {prefix} exceeds maximum {max}")]
    PrefixTooLarge { prefix: u8, max: u8 },
    /// Invalid gateway address.
    #[error("invalid gateway address: {0}")]
    InvalidGateway(String),
}

/// Builder for route configuration.
#[derive(Debug)]
#[must_use = "builders do nothing unless used"]
pub struct RouteBuilder {
    destination: IpAddr,
    prefix_len: u8,
    gateway: Option<IpAddr>,
    dev: Option<String>,
    metric: Option<u32>,
    table: Option<u32>,
    route_type: DeclaredRouteType,
}

impl RouteBuilder {
    /// `RouteBuilder` whose destination is `0.0.0.0/0` — the
    /// IPv4 default route. Mirrors [`crate::Ipv4Route::default_route`]
    /// (Plan 184) on the declarative side. Pairs with `.via()` to
    /// set the gateway:
    ///
    /// ```ignore
    /// use nlink::netlink::config::RouteBuilder;
    /// let r = RouteBuilder::default_v4().via("192.0.2.1");
    /// ```
    ///
    /// Plan 188 §2.3.
    pub fn default_v4() -> Self {
        // 0.0.0.0/0 is always a valid IPv4 CIDR; expect is safe.
        Self::new("0.0.0.0/0").expect("0.0.0.0/0 is a valid IPv4 CIDR")
    }

    /// `RouteBuilder` whose destination is `::/0` — the IPv6
    /// default route. Mirrors [`crate::Ipv6Route::default_route`].
    ///
    /// Plan 188 §2.3.
    pub fn default_v6() -> Self {
        Self::new("::/0").expect("::/0 is a valid IPv6 CIDR")
    }

    fn new(dst: &str) -> Result<Self, RouteParseError> {
        let (ip_str, prefix_str) = dst
            .split_once('/')
            .ok_or_else(|| RouteParseError::MissingPrefix(dst.to_string()))?;

        let destination: IpAddr = ip_str
            .parse()
            .map_err(|_| RouteParseError::InvalidDestination(ip_str.to_string()))?;

        let prefix_len: u8 = prefix_str
            .parse()
            .map_err(|_| RouteParseError::InvalidPrefix(prefix_str.to_string()))?;

        let max_prefix = if destination.is_ipv4() { 32 } else { 128 };
        if prefix_len > max_prefix {
            return Err(RouteParseError::PrefixTooLarge {
                prefix: prefix_len,
                max: max_prefix,
            });
        }

        Ok(Self {
            destination,
            prefix_len,
            gateway: None,
            dev: None,
            metric: None,
            table: None,
            route_type: DeclaredRouteType::default(),
        })
    }

    /// Set the gateway address.
    pub fn via(mut self, gateway: &str) -> Self {
        if let Ok(addr) = gateway.parse() {
            self.gateway = Some(addr);
        }
        self
    }

    /// Set the output device.
    pub fn dev(mut self, dev: &str) -> Self {
        self.dev = Some(dev.to_string());
        self
    }

    /// Set the route metric (priority).
    pub fn metric(mut self, metric: u32) -> Self {
        self.metric = Some(metric);
        self
    }

    /// Set the routing table.
    pub fn table(mut self, table: u32) -> Self {
        self.table = Some(table);
        self
    }

    /// Make this a blackhole route.
    pub fn blackhole(mut self) -> Self {
        self.route_type = DeclaredRouteType::Blackhole;
        self
    }

    /// Make this an unreachable route.
    pub fn unreachable(mut self) -> Self {
        self.route_type = DeclaredRouteType::Unreachable;
        self
    }

    /// Make this a prohibit route.
    pub fn prohibit(mut self) -> Self {
        self.route_type = DeclaredRouteType::Prohibit;
        self
    }

    fn build(self) -> DeclaredRoute {
        DeclaredRoute {
            destination: self.destination,
            prefix_len: self.prefix_len,
            gateway: self.gateway,
            dev: self.dev,
            metric: self.metric,
            table: self.table,
            route_type: self.route_type,
        }
    }
}

// ============================================================================
// Qdisc Types
// ============================================================================

/// Declared qdisc configuration.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
#[derive(Debug, Clone)]
pub struct DeclaredQdisc {
    pub(crate) dev: String,
    #[cfg_attr(feature = "serde", serde(default))]
    pub(crate) parent: QdiscParent,
    pub(crate) qdisc_type: DeclaredQdiscType,
}

impl DeclaredQdisc {
    /// Get the device name.
    pub fn dev(&self) -> &str {
        &self.dev
    }

    /// Get the parent.
    pub fn parent(&self) -> QdiscParent {
        self.parent
    }

    /// Get the qdisc type.
    pub fn qdisc_type(&self) -> &DeclaredQdiscType {
        &self.qdisc_type
    }
}

/// Qdisc parent location.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum QdiscParent {
    /// Root qdisc.
    #[default]
    Root,
    /// Ingress qdisc.
    Ingress,
}

/// Qdisc type for declared configuration.
///
/// Note: the percentage fields on [`DeclaredQdiscType::Netem`] are
/// stored as raw `f64`. When built through [`QdiscBuilder`] they pass
/// through [`crate::util::Percent`] (clamped to `0..=100`); a value
/// deserialized directly here is range-checked by the kernel at
/// apply time rather than on construction.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum DeclaredQdiscType {
    /// Network emulator.
    Netem {
        delay_us: Option<u32>,
        jitter_us: Option<u32>,
        loss_percent: Option<f64>,
        limit: Option<u32>,
        /// Packet-duplication probability (netem `duplicate`).
        duplicate_percent: Option<f64>,
        /// Packet-corruption probability (netem `corrupt`).
        corrupt_percent: Option<f64>,
        /// Packet-reorder probability (netem `reorder`).
        reorder_percent: Option<f64>,
        /// Loss-correlation between adjacent packets
        /// (netem `loss <p>% <corr>%`).
        loss_correlation: Option<f64>,
        /// Delay-correlation between adjacent packets
        /// (netem `delay <t> <jitter> <corr>%`).
        delay_correlation: Option<f64>,
    },
    /// Hierarchical Token Bucket.
    Htb { default_class: u32 },
    /// Fair Queueing Controlled Delay.
    FqCodel {
        limit: Option<u32>,
        target_us: Option<u32>,
        interval_us: Option<u32>,
    },
    /// Token Bucket Filter.
    Tbf {
        rate_bps: u64,
        burst_bytes: u32,
        limit_bytes: Option<u32>,
    },
    /// Stochastic Fair Queueing.
    Sfq { perturb_secs: Option<u32> },
    /// Priority qdisc.
    Prio { bands: Option<u8> },
    /// Ingress qdisc.
    Ingress,
    /// Clsact qdisc (for BPF).
    Clsact,
}

impl DeclaredQdiscType {
    /// Get the kind string.
    pub fn kind(&self) -> &str {
        match self {
            Self::Netem { .. } => "netem",
            Self::Htb { .. } => "htb",
            Self::FqCodel { .. } => "fq_codel",
            Self::Tbf { .. } => "tbf",
            Self::Sfq { .. } => "sfq",
            Self::Prio { .. } => "prio",
            Self::Ingress => "ingress",
            Self::Clsact => "clsact",
        }
    }
}

/// Builder for qdisc configuration.
#[derive(Debug)]
#[must_use = "builders do nothing unless used"]
pub struct QdiscBuilder {
    dev: String,
    parent: QdiscParent,
    qdisc_type: Option<DeclaredQdiscType>,
}

impl QdiscBuilder {
    fn new(dev: &str) -> Self {
        Self {
            dev: dev.to_string(),
            parent: QdiscParent::Root,
            qdisc_type: None,
        }
    }

    /// Configure as netem qdisc.
    pub fn netem(mut self) -> Self {
        self.qdisc_type = Some(DeclaredQdiscType::Netem {
            delay_us: None,
            jitter_us: None,
            loss_percent: None,
            limit: None,
            duplicate_percent: None,
            corrupt_percent: None,
            reorder_percent: None,
            loss_correlation: None,
            delay_correlation: None,
        });
        self
    }

    /// Set netem delay in milliseconds.
    pub fn delay_ms(mut self, ms: u32) -> Self {
        if let Some(DeclaredQdiscType::Netem { delay_us, .. }) = &mut self.qdisc_type {
            *delay_us = Some(ms * 1000);
        }
        self
    }

    /// Set netem delay in microseconds.
    pub fn delay_us(mut self, us: u32) -> Self {
        if let Some(DeclaredQdiscType::Netem { delay_us, .. }) = &mut self.qdisc_type {
            *delay_us = Some(us);
        }
        self
    }

    /// Set netem jitter in milliseconds.
    pub fn jitter_ms(mut self, ms: u32) -> Self {
        if let Some(DeclaredQdiscType::Netem { jitter_us, .. }) = &mut self.qdisc_type {
            *jitter_us = Some(ms * 1000);
        }
        self
    }

    /// Set netem packet loss as a typed [`crate::util::Percent`].
    ///
    /// Internally stores the clamped `f64` so the wire-format diff
    /// machinery (which compares with `PartialEq` on `Option<f64>`)
    /// stays stable. The typed boundary at the setter is what kills
    /// the wrong-units footgun.
    ///
    /// (The 0.20.1 deprecated `loss(f64)` form was removed in 0.21
    /// per the typed-units rollout. Construct the argument with
    /// `Percent::new(1.5)` for percent values or
    /// `Percent::from_fraction(0.015)` for fractional values — both
    /// produce identical wire bytes.)
    pub fn loss_pct(mut self, percent: crate::util::Percent) -> Self {
        if let Some(DeclaredQdiscType::Netem { loss_percent, .. }) = &mut self.qdisc_type {
            *loss_percent = Some(percent.as_percent());
        }
        self
    }

    /// Set netem packet-duplication probability.
    ///
    /// Mirror of `NetemConfig::duplicate(Percent)` for the
    /// declarative path (Plan 228 extension, 0.21).
    pub fn duplicate_pct(mut self, percent: crate::util::Percent) -> Self {
        if let Some(DeclaredQdiscType::Netem { duplicate_percent, .. }) =
            &mut self.qdisc_type
        {
            *duplicate_percent = Some(percent.as_percent());
        }
        self
    }

    /// Set netem packet-corruption probability.
    ///
    /// Mirror of `NetemConfig::corrupt(Percent)` for the
    /// declarative path (Plan 228 extension, 0.21).
    pub fn corrupt_pct(mut self, percent: crate::util::Percent) -> Self {
        if let Some(DeclaredQdiscType::Netem { corrupt_percent, .. }) =
            &mut self.qdisc_type
        {
            *corrupt_percent = Some(percent.as_percent());
        }
        self
    }

    /// Set netem packet-reorder probability.
    ///
    /// Mirror of `NetemConfig::reorder(Percent, …)` for the
    /// declarative path (Plan 228 extension, 0.21). The
    /// declarative form takes only the primary reorder
    /// probability; reorder correlation is a separate setter
    /// (`reorder_correlation_pct`) for symmetry with the other
    /// correlation knobs — call both to mirror the imperative
    /// 2-arg form.
    pub fn reorder_pct(mut self, percent: crate::util::Percent) -> Self {
        if let Some(DeclaredQdiscType::Netem { reorder_percent, .. }) =
            &mut self.qdisc_type
        {
            *reorder_percent = Some(percent.as_percent());
        }
        self
    }

    /// Set netem loss correlation (correlation between adjacent
    /// packets' loss outcomes).
    ///
    /// Mirror of `NetemConfig::loss_correlation(Percent)` for the
    /// declarative path (Plan 228 extension, 0.21).
    pub fn loss_correlation_pct(mut self, percent: crate::util::Percent) -> Self {
        if let Some(DeclaredQdiscType::Netem { loss_correlation, .. }) =
            &mut self.qdisc_type
        {
            *loss_correlation = Some(percent.as_percent());
        }
        self
    }

    /// Set netem delay correlation (correlation between adjacent
    /// packets' delay outcomes).
    ///
    /// Mirror of `NetemConfig::delay_correlation(Percent)` for the
    /// declarative path (Plan 228 extension, 0.21).
    pub fn delay_correlation_pct(mut self, percent: crate::util::Percent) -> Self {
        if let Some(DeclaredQdiscType::Netem { delay_correlation, .. }) =
            &mut self.qdisc_type
        {
            *delay_correlation = Some(percent.as_percent());
        }
        self
    }

    /// Set netem queue limit.
    pub fn limit(mut self, packets: u32) -> Self {
        if let Some(DeclaredQdiscType::Netem { limit, .. }) = &mut self.qdisc_type {
            *limit = Some(packets);
        }
        self
    }

    /// Configure as HTB qdisc.
    pub fn htb(mut self) -> Self {
        self.qdisc_type = Some(DeclaredQdiscType::Htb { default_class: 0 });
        self
    }

    /// Set HTB default class.
    pub fn default_class(mut self, class: u32) -> Self {
        if let Some(DeclaredQdiscType::Htb { default_class }) = &mut self.qdisc_type {
            *default_class = class;
        }
        self
    }

    /// Configure as fq_codel qdisc.
    pub fn fq_codel(mut self) -> Self {
        self.qdisc_type = Some(DeclaredQdiscType::FqCodel {
            limit: None,
            target_us: None,
            interval_us: None,
        });
        self
    }

    /// Configure as TBF qdisc.
    pub fn tbf(mut self, rate_bps: u64, burst_bytes: u32) -> Self {
        self.qdisc_type = Some(DeclaredQdiscType::Tbf {
            rate_bps,
            burst_bytes,
            limit_bytes: None,
        });
        self
    }

    /// Configure as SFQ qdisc.
    pub fn sfq(mut self) -> Self {
        self.qdisc_type = Some(DeclaredQdiscType::Sfq { perturb_secs: None });
        self
    }

    /// Configure as prio qdisc.
    pub fn prio(mut self) -> Self {
        self.qdisc_type = Some(DeclaredQdiscType::Prio { bands: None });
        self
    }

    /// Configure as ingress qdisc.
    pub fn ingress(mut self) -> Self {
        self.parent = QdiscParent::Ingress;
        self.qdisc_type = Some(DeclaredQdiscType::Ingress);
        self
    }

    /// Configure as clsact qdisc.
    pub fn clsact(mut self) -> Self {
        self.qdisc_type = Some(DeclaredQdiscType::Clsact);
        self
    }

    fn build(self) -> DeclaredQdisc {
        DeclaredQdisc {
            dev: self.dev,
            parent: self.parent,
            qdisc_type: self.qdisc_type.unwrap_or(DeclaredQdiscType::FqCodel {
                limit: None,
                target_us: None,
                interval_us: None,
            }),
        }
    }
}

#[cfg(test)]
mod plan_190_tests {
    //! Plan 190 — LinkBuilder gaps.
    //! Unit-level coverage for new DeclaredLinkType variants
    //! + LinkBuilder setters.

    use super::*;

    #[test]
    fn vrf_builder_sets_table() {
        let link = LinkBuilder::new("vrf-red").vrf(100).build();
        match link.link_type {
            DeclaredLinkType::Vrf { table } => assert_eq!(table, 100),
            other => panic!("expected DeclaredLinkType::Vrf, got {other:?}"),
        }
    }

    #[test]
    fn vrf_kind_string_is_vrf() {
        let lt = DeclaredLinkType::Vrf { table: 7 };
        assert_eq!(lt.kind(), Some("vrf"));
    }

    // -------- Plan 190 §2.3b — ovpn link half --------

    #[test]
    fn ovpn_builder_creates_ovpn_variant() {
        let link = LinkBuilder::new("ovpn0").ovpn().build();
        assert!(matches!(link.link_type, DeclaredLinkType::Ovpn));
    }

    #[test]
    fn ovpn_kind_string_is_ovpn() {
        assert_eq!(DeclaredLinkType::Ovpn.kind(), Some("ovpn"));
    }

    // -------- end Plan 190 §2.3b --------

    // -------- Plan 190 §2.3a — netkit --------

    #[test]
    fn netkit_builder_peer_carried_others_default_none() {
        let link = LinkBuilder::new("nk0").netkit("nk1").build();
        match link.link_type {
            DeclaredLinkType::Netkit {
                peer,
                mode,
                primary_policy,
                peer_policy,
                scrub,
                peer_scrub,
            } => {
                assert_eq!(peer, "nk1");
                assert!(mode.is_none());
                assert!(primary_policy.is_none());
                assert!(peer_policy.is_none());
                assert!(scrub.is_none());
                assert!(peer_scrub.is_none());
            }
            other => panic!("expected Netkit, got {other:?}"),
        }
    }

    #[test]
    fn netkit_builder_full_setter_chain() {
        let link = LinkBuilder::new("nk0")
            .netkit("nk1")
            .netkit_mode(NetkitMode::L2)
            .netkit_primary_policy(NetkitPolicy::Forward)
            .netkit_peer_policy(NetkitPolicy::Blackhole)
            .netkit_scrub(NetkitScrub::Default)
            .netkit_peer_scrub(NetkitScrub::None)
            .build();
        match link.link_type {
            DeclaredLinkType::Netkit {
                peer,
                mode,
                primary_policy,
                peer_policy,
                scrub,
                peer_scrub,
            } => {
                assert_eq!(peer, "nk1");
                assert_eq!(mode, Some(NetkitMode::L2));
                assert_eq!(primary_policy, Some(NetkitPolicy::Forward));
                assert_eq!(peer_policy, Some(NetkitPolicy::Blackhole));
                assert_eq!(scrub, Some(NetkitScrub::Default));
                assert_eq!(peer_scrub, Some(NetkitScrub::None));
            }
            other => panic!("expected Netkit, got {other:?}"),
        }
    }

    #[test]
    fn netkit_kind_string_is_netkit() {
        let lt = DeclaredLinkType::Netkit {
            peer: "x".into(),
            mode: None,
            primary_policy: None,
            peer_policy: None,
            scrub: None,
            peer_scrub: None,
        };
        assert_eq!(lt.kind(), Some("netkit"));
    }

    // -------- end Plan 190 §2.3a --------

    // -------- Plan 190 §8 — Bond options gap-fill --------

    #[test]
    fn bond_builder_defaults_all_new_knobs_to_none() {
        let link = LinkBuilder::new("bond0").bond().build();
        match link.link_type {
            DeclaredLinkType::Bond {
                ad_select,
                lacp_rate,
                downdelay,
                updelay,
                resend_igmp,
                ..
            } => {
                assert!(ad_select.is_none());
                assert!(lacp_rate.is_none());
                assert!(downdelay.is_none());
                assert!(updelay.is_none());
                assert!(resend_igmp.is_none());
            }
            other => panic!("expected Bond, got {other:?}"),
        }
    }

    #[test]
    fn bond_builder_all_5_setters_round_trip() {
        let link = LinkBuilder::new("bond0")
            .bond()
            .bond_ad_select(BondAdSelect::Bandwidth)
            .bond_lacp_rate(BondLacpRate::Fast)
            .bond_downdelay(200)
            .bond_updelay(500)
            .bond_resend_igmp(3)
            .build();
        match link.link_type {
            DeclaredLinkType::Bond {
                ad_select,
                lacp_rate,
                downdelay,
                updelay,
                resend_igmp,
                ..
            } => {
                assert_eq!(ad_select, Some(BondAdSelect::Bandwidth));
                assert_eq!(lacp_rate, Some(BondLacpRate::Fast));
                assert_eq!(downdelay, Some(200));
                assert_eq!(updelay, Some(500));
                assert_eq!(resend_igmp, Some(3));
            }
            other => panic!("expected Bond, got {other:?}"),
        }
    }

    #[test]
    fn bond_setters_no_op_on_non_bond() {
        let link = LinkBuilder::new("eth0")
            .dummy()
            .bond_ad_select(BondAdSelect::Stable)
            .bond_lacp_rate(BondLacpRate::Slow)
            .bond_downdelay(100)
            .bond_updelay(100)
            .bond_resend_igmp(1)
            .build();
        assert!(matches!(link.link_type, DeclaredLinkType::Dummy));
    }

    // -------- end Plan 190 §8 --------

    // -------- Plan 190 §2.1 — VXLAN extras --------

    #[test]
    fn vxlan_builder_defaults_to_none_for_new_knobs() {
        let link = LinkBuilder::new("vx0").vxlan(42).build();
        match link.link_type {
            DeclaredLinkType::Vxlan {
                vni,
                remote,
                local,
                port,
                underlay_dev,
            } => {
                assert_eq!(vni, 42);
                assert!(remote.is_none());
                assert!(local.is_none());
                assert!(port.is_none());
                assert!(underlay_dev.is_none());
            }
            other => panic!("expected Vxlan, got {other:?}"),
        }
    }

    #[test]
    fn vxlan_builder_local_port_underlay_round_trip() {
        use std::net::Ipv4Addr;
        let link = LinkBuilder::new("vx0")
            .vxlan(100)
            .vxlan_remote(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1)))
            .vxlan_local(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 2)))
            .vxlan_port(4790)
            .vxlan_underlay_dev("eth0")
            .build();
        match link.link_type {
            DeclaredLinkType::Vxlan {
                vni,
                remote,
                local,
                port,
                underlay_dev,
            } => {
                assert_eq!(vni, 100);
                assert_eq!(remote, Some(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1))));
                assert_eq!(local, Some(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 2))));
                assert_eq!(port, Some(4790));
                assert_eq!(underlay_dev.as_deref(), Some("eth0"));
            }
            other => panic!("expected Vxlan, got {other:?}"),
        }
    }

    #[test]
    fn vxlan_setters_no_op_on_non_vxlan() {
        // Each new setter must early-return if the builder
        // isn't a VXLAN — same shape as vlan_protocol.
        use std::net::Ipv4Addr;
        let link = LinkBuilder::new("eth0")
            .dummy()
            .vxlan_local(IpAddr::V4(Ipv4Addr::new(1, 2, 3, 4)))
            .vxlan_port(4790)
            .vxlan_underlay_dev("ignored")
            .build();
        assert!(matches!(link.link_type, DeclaredLinkType::Dummy));
    }

    // -------- end Plan 190 §2.1 --------

    // -------- Plan 190 §2.2 — VLAN protocol --------

    #[test]
    fn vlan_builder_protocol_defaults_to_none() {
        let link = LinkBuilder::new("eth0.100").vlan("eth0", 100).build();
        match link.link_type {
            DeclaredLinkType::Vlan { protocol, .. } => assert!(protocol.is_none()),
            other => panic!("expected Vlan, got {other:?}"),
        }
    }

    #[test]
    fn vlan_builder_protocol_setter_records_dot1ad() {
        let link = LinkBuilder::new("eth0.100")
            .vlan("eth0", 100)
            .vlan_protocol(VlanProtocol::Dot1ad)
            .build();
        match link.link_type {
            DeclaredLinkType::Vlan { protocol, .. } => {
                assert_eq!(protocol, Some(VlanProtocol::Dot1ad));
            }
            other => panic!("expected Vlan, got {other:?}"),
        }
    }

    #[test]
    fn vlan_protocol_setter_no_op_on_non_vlan() {
        // Calling vlan_protocol() on a builder that isn't a
        // VLAN should leave the link_type unchanged.
        let link = LinkBuilder::new("eth0")
            .dummy()
            .vlan_protocol(VlanProtocol::Dot1ad)
            .build();
        assert!(matches!(link.link_type, DeclaredLinkType::Dummy));
    }

    #[test]
    fn vlan_protocol_wire_values() {
        // 802.1Q == 0x8100, 802.1ad == 0x88a8. Pins the wire
        // contract for IFLA_VLAN_PROTOCOL emission.
        assert_eq!(VlanProtocol::Dot1q.as_u16(), 0x8100);
        assert_eq!(VlanProtocol::Dot1ad.as_u16(), 0x88a8);
    }

    // -------- end Plan 190 §2.2 --------

    #[test]
    fn vrf_in_network_config_carries_master_chain() {
        // The master() chain works alongside vrf(); confirms
        // recipes that enslave a dummy into a VRF via the
        // declarative path compose correctly.
        let cfg = NetworkConfig::new()
            .link("vrf-red", |b| b.vrf(100))
            .link("eth0", |b| b.dummy().master("vrf-red"));
        assert_eq!(cfg.links.len(), 2);
        assert!(matches!(
            cfg.links[0].link_type,
            DeclaredLinkType::Vrf { table: 100 }
        ));
        assert_eq!(cfg.links[1].master.as_deref(), Some("vrf-red"));
    }
}

#[cfg(test)]
mod plan_228_tests {
    //! Plan 228 — typed Percent on declarative QdiscBuilder.
    //!
    //! Adversarial coverage that the new `loss_pct(Percent)` and the
    //! deprecated `loss(f64)` produce identical stored state for sane
    //! inputs, and that the typed sibling clamps adversarial floats
    //! while the raw f64 path lets them through.

    use super::*;
    use crate::util::Percent;

    fn netem_loss(q: &DeclaredQdisc) -> Option<f64> {
        match &q.qdisc_type {
            DeclaredQdiscType::Netem { loss_percent, .. } => *loss_percent,
            _ => None,
        }
    }

    #[test]
    fn loss_pct_stores_clamped_f64_internally() {
        // The typed boundary kills the bug at construction; the f64
        // that lands in DeclaredQdiscType is what wire-format diff
        // compares.
        let q = QdiscBuilder::new("eth0").netem().loss_pct(Percent::new(1.5));
        let built = q.build();
        assert_eq!(netem_loss(&built), Some(1.5));
    }

    #[test]
    fn loss_pct_clamps_supra_100() {
        let q = QdiscBuilder::new("eth0")
            .netem()
            .loss_pct(Percent::new(150.0))
            .build();
        assert_eq!(netem_loss(&q), Some(100.0));
    }

    #[test]
    fn loss_pct_clamps_negative() {
        let q = QdiscBuilder::new("eth0")
            .netem()
            .loss_pct(Percent::new(-1.5))
            .build();
        assert_eq!(netem_loss(&q), Some(0.0));
    }

    #[test]
    fn loss_pct_handles_nan() {
        // Percent::new uses clamp which for f64 NaN returns NaN.
        // Document the behaviour at the typed boundary — adversarial
        // callers learn the failure mode here rather than discovering
        // a kernel rejection at apply time.
        let q = QdiscBuilder::new("eth0")
            .netem()
            .loss_pct(Percent::new(f64::NAN))
            .build();
        // NaN propagates through clamp; verify the stored value is NaN.
        let v = netem_loss(&q).expect("loss_percent set");
        assert!(v.is_nan(), "Percent::new(NaN) → stored NaN (documented)");
    }

    #[test]
    fn loss_pct_handles_infinity() {
        let q = QdiscBuilder::new("eth0")
            .netem()
            .loss_pct(Percent::new(f64::INFINITY))
            .build();
        // Infinity clamps to 100.
        assert_eq!(netem_loss(&q), Some(100.0));
    }

    #[test]
    fn loss_pct_from_fraction_distinguishes_units() {
        // The headline footgun the typed boundary kills: f64 mixed
        // fraction-vs-percent. Percent::from_fraction(0.015) = 1.5%.
        let q = QdiscBuilder::new("eth0")
            .netem()
            .loss_pct(Percent::from_fraction(0.015))
            .build();
        assert_eq!(netem_loss(&q), Some(1.5));
    }

    // Plan 228 extension (0.21) — netem parity setters.
    // Each takes Percent; the stored f64 must equal the percent value.

    fn netem_field<F>(q: &DeclaredQdisc, project: F) -> Option<f64>
    where
        F: Fn(&DeclaredQdiscType) -> Option<f64>,
    {
        project(&q.qdisc_type)
    }

    #[test]
    fn duplicate_pct_stores_percent() {
        let q = QdiscBuilder::new("eth0")
            .netem()
            .duplicate_pct(Percent::new(2.5))
            .build();
        let v = netem_field(&q, |t| match t {
            DeclaredQdiscType::Netem { duplicate_percent, .. } => *duplicate_percent,
            _ => None,
        });
        assert_eq!(v, Some(2.5));
    }

    #[test]
    fn corrupt_pct_stores_percent() {
        let q = QdiscBuilder::new("eth0")
            .netem()
            .corrupt_pct(Percent::new(0.75))
            .build();
        let v = netem_field(&q, |t| match t {
            DeclaredQdiscType::Netem { corrupt_percent, .. } => *corrupt_percent,
            _ => None,
        });
        assert_eq!(v, Some(0.75));
    }

    #[test]
    fn reorder_pct_stores_percent() {
        let q = QdiscBuilder::new("eth0")
            .netem()
            .reorder_pct(Percent::new(5.0))
            .build();
        let v = netem_field(&q, |t| match t {
            DeclaredQdiscType::Netem { reorder_percent, .. } => *reorder_percent,
            _ => None,
        });
        assert_eq!(v, Some(5.0));
    }

    #[test]
    fn loss_correlation_pct_stores_percent() {
        let q = QdiscBuilder::new("eth0")
            .netem()
            .loss_correlation_pct(Percent::new(25.0))
            .build();
        let v = netem_field(&q, |t| match t {
            DeclaredQdiscType::Netem { loss_correlation, .. } => *loss_correlation,
            _ => None,
        });
        assert_eq!(v, Some(25.0));
    }

    #[test]
    fn delay_correlation_pct_stores_percent() {
        let q = QdiscBuilder::new("eth0")
            .netem()
            .delay_correlation_pct(Percent::new(50.0))
            .build();
        let v = netem_field(&q, |t| match t {
            DeclaredQdiscType::Netem { delay_correlation, .. } => *delay_correlation,
            _ => None,
        });
        assert_eq!(v, Some(50.0));
    }

    #[test]
    fn all_netem_setters_clamp_via_percent() {
        // Out-of-range values clamp at the Percent boundary, not at
        // the storage f64.
        let q = QdiscBuilder::new("eth0")
            .netem()
            .duplicate_pct(Percent::new(200.0))   // → 100.0
            .corrupt_pct(Percent::new(-10.0))     // → 0.0
            .reorder_pct(Percent::new(50.0))
            .build();
        let dup = netem_field(&q, |t| match t {
            DeclaredQdiscType::Netem { duplicate_percent, .. } => *duplicate_percent,
            _ => None,
        });
        let cor = netem_field(&q, |t| match t {
            DeclaredQdiscType::Netem { corrupt_percent, .. } => *corrupt_percent,
            _ => None,
        });
        assert_eq!(dup, Some(100.0));
        assert_eq!(cor, Some(0.0));
    }
}

#[cfg(all(test, feature = "serde"))]
mod serde_roundtrip_tests {
    use super::*;
    use crate::netlink::link::VlanProtocol;

    /// A config that round-trips must serialize, deserialize, and
    /// re-serialize to a byte-identical document. (The `Declared*`
    /// types don't all implement `PartialEq` — `DeclaredQdiscType`
    /// carries `f64` — so re-serialization equality is the round-trip
    /// oracle.)
    fn assert_roundtrips(cfg: &NetworkConfig) {
        let json = cfg.to_json_string().expect("serialize");
        let back = NetworkConfig::from_json_str(&json).expect("deserialize");
        let json2 = back.to_json_string().expect("re-serialize");
        assert_eq!(json, json2, "round-trip changed the document:\n{json}\n{json2}");
    }

    #[test]
    fn full_config_roundtrips() {
        let cfg = NetworkConfig::new()
            .link("br0", |l| l.bridge().up().mtu(1500))
            .link("eth0.42", |l| {
                l.vlan("eth0", 42).vlan_protocol(VlanProtocol::Dot1ad)
            })
            .link("bond0", |l| l.bond().bond_mode(BondMode::Ieee802_3ad))
            .link("dummy0", |l| l.dummy().address([0xaa, 0xbb, 0xcc, 0x11, 0x22, 0x33]))
            .address("br0", "10.0.0.1/24")
            .expect("addr")
            .address("br0", "2001:db8::1/64")
            .expect("addr6")
            .route("0.0.0.0/0", |r| r.via("10.0.0.254"))
            .expect("route")
            .route("10.10.0.0/16", |r| r.blackhole().metric(100))
            .expect("blackhole")
            .qdisc("eth0", |q| q.netem().delay_ms(100));
        assert_roundtrips(&cfg);
    }

    #[test]
    fn address_roundtrips_as_cidr_string() {
        let cfg = NetworkConfig::new()
            .address("eth0", "192.168.1.5/24")
            .unwrap();
        let json = cfg.to_json_string().unwrap();
        assert!(json.contains(r#""address":"192.168.1.5/24""#), "{json}");
        let back = NetworkConfig::from_json_str(&json).unwrap();
        assert_eq!(back.addresses()[0].address().to_string(), "192.168.1.5");
        assert_eq!(back.addresses()[0].prefix_len(), 24);
    }

    #[test]
    fn address_rejects_out_of_range_prefix() {
        // /99 is invalid for IPv4 — the try_from must surface it as a
        // deserialize error rather than silently accepting it.
        let err = NetworkConfig::from_json_str(
            r#"{"addresses":[{"dev":"eth0","address":"10.0.0.1/99"}]}"#,
        )
        .unwrap_err();
        assert!(err.to_string().contains("prefix"), "{err}");
    }

    #[test]
    fn route_default_keyword_roundtrips() {
        let cfg = NetworkConfig::new()
            .route("0.0.0.0/0", |r| r.via("192.0.2.1"))
            .unwrap();
        let json = cfg.to_json_string().unwrap();
        // A 0.0.0.0/0 destination renders as the `default` keyword.
        assert!(json.contains(r#""destination":"default""#), "{json}");
        let back = NetworkConfig::from_json_str(&json).unwrap();
        assert!(back.routes()[0].destination().is_unspecified());
        assert_eq!(back.routes()[0].prefix_len(), 0);
    }

    #[test]
    fn route_default_infers_v6_from_gateway() {
        let back = NetworkConfig::from_json_str(
            r#"{"routes":[{"destination":"default","gateway":"2001:db8::1"}]}"#,
        )
        .unwrap();
        assert!(back.routes()[0].destination().is_ipv6());
    }

    #[test]
    fn route_rejects_bad_gateway() {
        let err = NetworkConfig::from_json_str(
            r#"{"routes":[{"destination":"10.0.0.0/8","gateway":"not-an-ip"}]}"#,
        )
        .unwrap_err();
        assert!(err.to_string().contains("gateway"), "{err}");
    }

    #[test]
    fn mac_roundtrips_as_colon_string() {
        let cfg = NetworkConfig::new()
            .link("dummy0", |l| l.dummy().address([0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff]));
        let json = cfg.to_json_string().unwrap();
        assert!(json.contains(r#""address":"aa:bb:cc:dd:ee:ff""#), "{json}");
        assert_roundtrips(&cfg);
    }

    #[test]
    fn mac_rejects_malformed_string() {
        let err = NetworkConfig::from_json_str(
            r#"{"links":[{"name":"d0","link-type":"dummy","address":"aa:bb:cc"}]}"#,
        )
        .unwrap_err();
        assert!(err.to_string().contains("MAC"), "{err}");
    }

    #[test]
    fn empty_config_omits_empty_sections() {
        let json = NetworkConfig::new().to_json_string().unwrap();
        assert_eq!(json, "{}");
        // And an empty document deserializes back to an empty config.
        let back = NetworkConfig::from_json_str("{}").unwrap();
        assert!(back.links().is_empty() && back.addresses().is_empty());
    }

    #[test]
    fn documented_json_example_parses() {
        // Pins the exact JSON shown in docs/library.md "Declarative
        // Network Configuration" so the docs can't drift from the
        // Deserialize impl (veth is externally-tagged, address/route
        // are CIDR strings, the bridge is a bare-string unit variant).
        let cfg = NetworkConfig::from_json_str(
            r#"{
                "links": [
                    { "name": "br0", "link-type": "bridge", "state": "up" },
                    { "name": "veth0", "link-type": { "veth": { "peer": "veth1" } } }
                ],
                "addresses": [ { "dev": "br0", "address": "10.0.0.1/24" } ],
                "routes":    [ { "destination": "10.1.0.0/16", "gateway": "10.0.0.254", "dev": "br0" } ]
            }"#,
        )
        .expect("documented JSON must parse");
        assert_eq!(cfg.links().len(), 2);
        assert_eq!(cfg.addresses().len(), 1);
        assert_eq!(cfg.routes().len(), 1);
        assert_eq!(cfg.links()[1].name(), "veth0");
    }

    #[test]
    fn unit_link_type_keeps_bare_string_shape() {
        // Plan 189 shape: a unit link-type serializes as the bare
        // string "dummy", not {"dummy": null}.
        let cfg = NetworkConfig::new().link("d0", |l| l.dummy());
        let json = cfg.to_json_string().unwrap();
        assert!(json.contains(r#""link-type":"dummy""#), "{json}");
    }
}

/// Serde adapter for [`DeclaredLink::address`] — represents the
/// `Option<[u8; 6]>` hardware address as a canonical
/// `aa:bb:cc:dd:ee:ff` string (or absent) rather than a raw byte
/// array, and validates the string form on the way back in.
#[cfg(feature = "serde")]
mod mac_serde {
    use serde::{Deserialize, Deserializer, Serializer};

    pub(super) fn serialize<S>(mac: &Option<[u8; 6]>, s: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match mac {
            Some(m) => s.serialize_some(&format!(
                "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
                m[0], m[1], m[2], m[3], m[4], m[5]
            )),
            None => s.serialize_none(),
        }
    }

    pub(super) fn deserialize<'de, D>(d: D) -> Result<Option<[u8; 6]>, D::Error>
    where
        D: Deserializer<'de>,
    {
        match Option::<String>::deserialize(d)? {
            None => Ok(None),
            Some(s) => parse_mac(&s).map(Some).map_err(serde::de::Error::custom),
        }
    }

    fn parse_mac(s: &str) -> Result<[u8; 6], String> {
        let mut out = [0u8; 6];
        let mut n = 0;
        for (i, part) in s.split(':').enumerate() {
            if i >= 6 {
                return Err(format!(
                    "invalid MAC `{s}`: expected 6 colon-separated octets"
                ));
            }
            out[i] = u8::from_str_radix(part, 16)
                .map_err(|_| format!("invalid MAC `{s}`: octet `{part}` is not hex"))?;
            n = i + 1;
        }
        if n != 6 {
            return Err(format!(
                "invalid MAC `{s}`: expected 6 colon-separated octets, got {n}"
            ));
        }
        Ok(out)
    }
}

#[cfg(all(test, feature = "schemars"))]
mod schemars_tests {
    use super::*;

    fn schema_value() -> serde_json::Value {
        serde_json::from_str(&NetworkConfig::json_schema()).expect("schema is valid JSON")
    }

    /// schemars 0.8 emits draft-07 with a `definitions` map; tolerate
    /// `$defs` in case the default changes.
    fn defs(schema: &serde_json::Value) -> &serde_json::Map<String, serde_json::Value> {
        schema
            .get("definitions")
            .or_else(|| schema.get("$defs"))
            .and_then(|d| d.as_object())
            .expect("schema exposes a definitions/$defs map")
    }

    #[test]
    fn schema_generates_and_titles_the_config_root() {
        let s = schema_value();
        assert_eq!(
            s.get("title").and_then(|t| t.as_str()),
            Some("NetworkConfig"),
            "root schema title should be the type name"
        );
        let d = defs(&s);
        for t in ["DeclaredLink", "DeclaredLinkType", "DeclaredQdiscType"] {
            assert!(
                d.contains_key(t),
                "schema missing definition for {t}; has {:?}",
                d.keys().collect::<Vec<_>>()
            );
        }
        // The Repr shadow types must appear — proof the manual
        // `JsonSchema` delegation to `*Repr` took effect (addresses /
        // routes describe the string wire shape, not parsed fields).
        assert!(d.contains_key("AddressRepr"), "schema must route addresses through AddressRepr");
        assert!(d.contains_key("RouteRepr"), "schema must route routes through RouteRepr");
        // And the parsed structs must NOT leak into the schema.
        assert!(!d.contains_key("DeclaredAddress"), "DeclaredAddress parsed fields must not appear");
        assert!(!d.contains_key("DeclaredRoute"), "DeclaredRoute parsed fields must not appear");
    }

    #[test]
    fn address_and_route_describe_cidr_strings_not_parsed_fields() {
        // The correctness guard: DeclaredAddress / DeclaredRoute
        // serialize THROUGH their `*Repr` (a CIDR string), so the
        // schema must say "string", not expose the in-memory
        // `{ address: <ip>, prefix_len: <u8> }` fields. A schema that
        // didn't match the real JSON would be worse than none.
        let s = schema_value();
        let d = defs(&s);
        assert_eq!(
            d["AddressRepr"].pointer("/properties/address/type").and_then(|v| v.as_str()),
            Some("string"),
            "AddressRepr.address must be a (CIDR) string"
        );
        assert_eq!(
            d["RouteRepr"].pointer("/properties/destination/type").and_then(|v| v.as_str()),
            Some("string"),
            "RouteRepr.destination must be a (CIDR/default) string"
        );
    }

    #[test]
    fn mac_field_is_a_string_not_a_byte_array() {
        // DeclaredLink.address is Option<[u8; 6]> but `mac_serde`
        // renders it as the `aa:bb:..` string. The schema must agree.
        let s = schema_value();
        let d = defs(&s);
        let mac = d["DeclaredLink"]
            .pointer("/properties/address")
            .expect("DeclaredLink.address present in schema");
        let rendered = serde_json::to_string(mac).unwrap();
        assert!(rendered.contains("string"), "MAC must be string-typed: {rendered}");
        assert!(
            !rendered.contains("integer") && !rendered.contains("\"array\""),
            "MAC must NOT be modelled as a byte array: {rendered}"
        );
    }

    #[test]
    fn schema_value_helper_matches_string_helper() {
        let from_value = serde_json::to_value(NetworkConfig::json_schema_value()).unwrap();
        let from_string = schema_value();
        assert_eq!(from_value, from_string, "the two json_schema accessors must agree");
    }
}