ostrya 0.17.0

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

use std::collections::HashSet;
use std::net::SocketAddr;
use std::path::{Component, Path};

use ostrya_core::{KeyFile, RefPattern, RepoMode};

use super::{
    GroupRef, SignVerify, SizeSpec, SizeUnit, Tristate, parse_sign_verify, parse_size, trust,
};
use crate::access::{
    AllowItem, AuthItem, ForwardedHeader, IpNet, is_header_name, parse_allow_item, parse_deny_item,
    parse_item, parse_net,
};
use crate::error::Error;

/// The text form of a config value.
///
/// [`parse`](Value::parse) reads the raw text of a value, as the key file
/// holds it, with its escape sequences. [`format`](Value::format) gives raw
/// text that a key file can hold. For each value `v` that `parse` gives,
/// `parse(&v.format())` gives `v` again.
///
/// A value type that holds text decodes the raw text first, with the
/// helper functions of the module: [`decode_string`], [`decode_bool`],
/// [`decode_integer`], and [`decode_string_list`]. Its `format` encodes the
/// text with [`encode_string`], [`encode_bool`], [`encode_integer`], or
/// [`encode_string_list`]. A value type that reads the text as written,
/// such as [`SizeSpec`], uses no helper function.
///
/// A value that needs more than its text, such as a path relative to the
/// repository, parses to its text form. The code that uses the value
/// resolves it.
///
/// # Examples
///
/// ```
/// use ostrya::config::{Value, ValueError, decode_string, encode_string};
///
/// /// A host name with no space.
/// #[derive(Debug, PartialEq)]
/// struct Host {
///     name: String,
/// }
///
/// impl Value for Host {
///     fn parse(raw: &str) -> Result<Host, ValueError> {
///         let name = decode_string(raw)?;
///         if name.is_empty() || name.contains(' ') {
///             return Err(ValueError::new(format!("value '{name}' is not a host name")));
///         }
///         Ok(Host { name })
///     }
///
///     fn format(&self) -> String {
///         encode_string(&self.name)
///     }
/// }
///
/// let host = Host::parse("example.com").unwrap();
/// assert_eq!(Host::parse(&host.format()), Ok(host));
/// assert!(Host::parse("a b").is_err());
/// ```
pub trait Value: Sized {
    /// Parses the raw text of a value, as the key file holds it.
    ///
    /// # Errors
    ///
    /// A [`ValueError`] if the text is not a value of the type.
    fn parse(raw: &str) -> Result<Self, ValueError>;

    /// Returns the raw text of the value, as a key file holds it.
    fn format(&self) -> String;
}

/// The reason why the raw text of a value does not parse.
///
/// A typed read of [`RepoConfig`](super::RepoConfig) and of
/// [`Section`](super::Section) adds the group and the key to the reason:
///
/// - A text that is not a boolean gives [`Error::Core`] with the text
///   `value 'VALUE' for GROUP.KEY is not a boolean`, as
///   [`KeyFile::get_bool`] gives it. An integer gives `is not an integer` in
///   the same form.
/// - A malformed escape sequence gives [`Error::Core`] with the text of
///   [`KeyFile::get_string`].
/// - An error of [`malformed_item`](ValueError::malformed_item) or
///   [`malformed_value`](ValueError::malformed_value) gives
///   [`Error::InvalidFormat`] with the text `malformed [GROUP] KEY item
///   'TEXT': WHY` or `malformed [GROUP] KEY value 'TEXT': WHY`.
/// - Each other reason gives [`Error::InvalidFormat`] with the text
///   `[GROUP] KEY REASON`. `GROUP` is the group header, for example `core`
///   or `remote "origin"`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValueError {
    kind: Kind,
}

/// The kind of a [`ValueError`].
#[derive(Debug, Clone, PartialEq, Eq)]
enum Kind {
    /// The text is not a boolean.
    NotBoolean,
    /// The text is not an integer.
    NotInteger,
    /// A key-file escape error, with its text.
    KeyFile(String),
    /// Another refusal, with its reason.
    Invalid(String),
    /// A malformed item of a list or a malformed value: the word `item` or
    /// `value`, the text, and the reason.
    Malformed {
        part: &'static str,
        text: String,
        why: String,
    },
}

impl ValueError {
    /// Returns an error with the reason `reason`.
    ///
    /// The reason is a predicate on the value, for example `is empty`, or
    /// `value 'x' is not a host name`. A typed read writes it after the group
    /// and the key: `[GROUP] KEY REASON`.
    pub fn new(reason: impl Into<String>) -> ValueError {
        ValueError {
            kind: Kind::Invalid(reason.into()),
        }
    }

    /// Returns the error of the malformed item `text` of a list value, with
    /// the reason `why`.
    ///
    /// A typed read gives the text `malformed [GROUP] KEY item 'TEXT': WHY`.
    /// The [`Display`](std::fmt::Display) form of the error alone is
    /// `malformed item 'TEXT': WHY`.
    ///
    /// # Examples
    ///
    /// ```
    /// use ostrya::config::ValueError;
    ///
    /// let err = ValueError::malformed_item("x", "the item is a number");
    /// assert_eq!(err.to_string(), "malformed item 'x': the item is a number");
    /// ```
    pub fn malformed_item(text: impl Into<String>, why: impl Into<String>) -> ValueError {
        ValueError {
            kind: Kind::Malformed {
                part: "item",
                text: text.into(),
                why: why.into(),
            },
        }
    }

    /// Returns the error of the malformed value `text`, with the reason
    /// `why`.
    ///
    /// A typed read gives the text `malformed [GROUP] KEY value 'TEXT':
    /// WHY`. The [`Display`](std::fmt::Display) form of the error alone is
    /// `malformed value 'TEXT': WHY`.
    ///
    /// # Examples
    ///
    /// ```
    /// use ostrya::config::ValueError;
    ///
    /// let err = ValueError::malformed_value("x", "the value is a number");
    /// assert_eq!(err.to_string(), "malformed value 'x': the value is a number");
    /// ```
    pub fn malformed_value(text: impl Into<String>, why: impl Into<String>) -> ValueError {
        ValueError {
            kind: Kind::Malformed {
                part: "value",
                text: text.into(),
                why: why.into(),
            },
        }
    }
}

impl std::fmt::Display for ValueError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.kind {
            Kind::NotBoolean => f.write_str("is not a boolean"),
            Kind::NotInteger => f.write_str("is not an integer"),
            Kind::KeyFile(text) | Kind::Invalid(text) => f.write_str(text),
            Kind::Malformed { part, text, why } => write!(f, "malformed {part} '{text}': {why}"),
        }
    }
}

impl std::error::Error for ValueError {}

/// Returns the crate error of `err`, the refusal of the raw text `raw` of the
/// key `key` in the group with the header `group`.
pub(crate) fn value_error(group: &str, key: &str, raw: &str, err: ValueError) -> Error {
    match err.kind {
        Kind::NotBoolean => Error::Core(ostrya_core::Error::KeyFile(format!(
            "value '{raw}' for {group}.{key} is not a boolean"
        ))),
        Kind::NotInteger => Error::Core(ostrya_core::Error::KeyFile(format!(
            "value '{raw}' for {group}.{key} is not an integer"
        ))),
        Kind::KeyFile(text) => Error::Core(ostrya_core::Error::KeyFile(text)),
        Kind::Invalid(reason) => Error::InvalidFormat(format!("[{group}] {key} {reason}")),
        Kind::Malformed { part, text, why } => {
            Error::InvalidFormat(format!("malformed [{group}] {key} {part} '{text}': {why}"))
        }
    }
}

/// Returns the value error of a key-file error.
fn keyfile_error(err: ostrya_core::Error) -> ValueError {
    match err {
        ostrya_core::Error::KeyFile(text) => ValueError {
            kind: Kind::KeyFile(text),
        },
        other => ValueError {
            kind: Kind::KeyFile(other.to_string()),
        },
    }
}

/// Decodes the raw text of a string value.
///
/// The function replaces each escape sequence of the key file with its
/// character: `\s` with a space, `\t` with a tab, `\n` with a newline, `\r`
/// with a carriage return, `\\` with a backslash, and `\;` with a `;`.
/// [`KeyFile::get_string`] reads a value in the same way.
///
/// # Errors
///
/// A [`ValueError`] with the text of [`KeyFile::get_string`] if the text
/// holds a backslash that starts no escape sequence.
pub fn decode_string(raw: &str) -> Result<String, ValueError> {
    KeyFile::decode_string(raw).map_err(keyfile_error)
}

/// Encodes a string value as raw text.
///
/// The function escapes the value as [`KeyFile::set_string`] does, so
/// [`decode_string`] gives the value again.
pub fn encode_string(value: &str) -> String {
    KeyFile::encode_string(value)
}

/// Decodes the raw text of a boolean value.
///
/// `true` and `1` give `true`, and `false` and `0` give `false`. The match
/// is exact. [`KeyFile::get_bool`] reads a value in the same way.
///
/// # Errors
///
/// A [`ValueError`] if the text is not one of the four values.
pub fn decode_bool(raw: &str) -> Result<bool, ValueError> {
    KeyFile::decode_bool(raw).ok_or(ValueError {
        kind: Kind::NotBoolean,
    })
}

/// Encodes a boolean value as raw text: `true` or `false`.
pub fn encode_bool(value: bool) -> String {
    if value { "true" } else { "false" }.to_owned()
}

/// Decodes the raw text of an integer value.
///
/// The text is a decimal `i64` with an optional `-` sign.
/// [`KeyFile::get_integer`] reads a value in the same way.
///
/// # Errors
///
/// A [`ValueError`] if the text is not a decimal `i64`. White space in the
/// text and a leading `+` sign cause this error.
pub fn decode_integer(raw: &str) -> Result<i64, ValueError> {
    KeyFile::decode_integer(raw).ok_or(ValueError {
        kind: Kind::NotInteger,
    })
}

/// Encodes an integer value as raw text, in decimal.
pub fn encode_integer(value: i64) -> String {
    value.to_string()
}

/// Decodes the raw text of a list value.
///
/// A `;` separates two items, and `\;` is a `;` in an item. A trailing `;`
/// adds no empty item. The function decodes each item as [`decode_string`]
/// does. [`KeyFile::get_string_list`] reads a value in the same way.
///
/// # Errors
///
/// A [`ValueError`] with the text of [`KeyFile::get_string_list`] if the
/// text holds a backslash that starts no escape sequence.
pub fn decode_string_list(raw: &str) -> Result<Vec<String>, ValueError> {
    KeyFile::decode_string_list(raw).map_err(keyfile_error)
}

/// Encodes a list value as raw text.
///
/// The function escapes each item as [`encode_string`] does, writes `\;` for
/// a `;` in an item, and writes a `;` after each item, also after the last
/// item. [`KeyFile::set_string_list`] writes a list in the same way, and
/// [`decode_string_list`] gives the list again.
pub fn encode_string_list(items: &[impl AsRef<str>]) -> String {
    KeyFile::encode_string_list(items)
}

impl Value for bool {
    fn parse(raw: &str) -> Result<bool, ValueError> {
        decode_bool(raw)
    }

    fn format(&self) -> String {
        encode_bool(*self)
    }
}

impl Value for i64 {
    fn parse(raw: &str) -> Result<i64, ValueError> {
        decode_integer(raw)
    }

    fn format(&self) -> String {
        encode_integer(*self)
    }
}

/// Implements [`Value`] for an integer type through `i64`. A value outside
/// the range of the type is refused.
macro_rules! value_through_i64 {
    ($($int:ty),*) => {$(
        impl Value for $int {
            fn parse(raw: &str) -> Result<$int, ValueError> {
                let n = decode_integer(raw)?;
                <$int>::try_from(n).map_err(|_| {
                    ValueError::new(format!(
                        "{n} is out of the range {}-{}",
                        <$int>::MIN,
                        <$int>::MAX
                    ))
                })
            }

            fn format(&self) -> String {
                self.to_string()
            }
        }
    )*};
}

value_through_i64!(i8, i16, i32, u8, u16, u32);

/// The text rules are the rules of [`decode_integer`]: decimal digits with
/// an optional `-` sign, and no `+` sign. The full range of `u64` parses. A
/// negative value is refused with the range of the type, as for the other
/// integer types.
impl Value for u64 {
    fn parse(raw: &str) -> Result<u64, ValueError> {
        let n = match decode_integer(raw) {
            Ok(n) => n,
            // A value above `i64::MAX` is not an `i64`. `str::parse` takes a
            // leading `+`, which `decode_integer` refuses.
            Err(err) if raw.starts_with('+') => return Err(err),
            Err(err) => return raw.parse::<u64>().map_err(|_| err),
        };
        u64::try_from(n).map_err(|_| {
            ValueError::new(format!("{n} is out of the range {}-{}", u64::MIN, u64::MAX))
        })
    }

    fn format(&self) -> String {
        self.to_string()
    }
}

impl Value for String {
    fn parse(raw: &str) -> Result<String, ValueError> {
        decode_string(raw)
    }

    fn format(&self) -> String {
        encode_string(self)
    }
}

impl Value for Vec<String> {
    fn parse(raw: &str) -> Result<Vec<String>, ValueError> {
        decode_string_list(raw)
    }

    fn format(&self) -> String {
        encode_string_list(self)
    }
}

/// The text is `no`, `maybe`, or `yes`, after the decode of the escape
/// sequences.
impl Value for Tristate {
    fn parse(raw: &str) -> Result<Tristate, ValueError> {
        let value = decode_string(raw)?;
        match value.as_str() {
            "no" => Ok(Tristate::No),
            "maybe" => Ok(Tristate::Maybe),
            "yes" => Ok(Tristate::Yes),
            _ => Err(ValueError::new(format!(
                "value '{value}' is not no, maybe, or yes"
            ))),
        }
    }

    fn format(&self) -> String {
        match self {
            Tristate::No => "no",
            Tristate::Maybe => "maybe",
            Tristate::Yes => "yes",
        }
        .to_owned()
    }
}

/// The text is decoded, and then read as the `sign-verify` key of a remote
/// reads it. Each text is a value, so `parse` refuses only a malformed
/// escape sequence.
///
/// [`SignVerify::Off`] gives `false`, [`SignVerify::All`] gives `true`, and
/// [`SignVerify::Engines`] gives the names as [`encode_string_list`] writes
/// them, with a `;` after each name. Thus a list of one name, for example
/// `true` or `0`, parses as that list again. An empty list of engines gives
/// the empty text, which parses as [`SignVerify::Off`].
impl Value for SignVerify {
    fn parse(raw: &str) -> Result<SignVerify, ValueError> {
        Ok(parse_sign_verify(Some(&decode_string(raw)?)))
    }

    fn format(&self) -> String {
        match self {
            SignVerify::Off => encode_bool(false),
            SignVerify::All => encode_bool(true),
            SignVerify::Engines(names) => encode_string_list(names),
        }
    }
}

/// The text is read as written, with no decode, and matches
/// `^([0-9]+)(G|M|T)B$`. The `ostree` command reads the value in the same
/// way.
impl Value for SizeSpec {
    fn parse(raw: &str) -> Result<SizeSpec, ValueError> {
        parse_size(raw).ok_or_else(|| {
            ValueError::new(format!(
                "value '{raw}' is not of the form 123MB, 123GB, or 123TB"
            ))
        })
    }

    fn format(&self) -> String {
        let unit = match self.unit {
            SizeUnit::Mega => "MB",
            SizeUnit::Giga => "GB",
            SizeUnit::Tera => "TB",
        };
        format!("{}{unit}", self.value)
    }
}

/// The text is decoded, and then read as a mode name of
/// [`RepoMode::from_mode_str`]. `format` gives the name of
/// [`RepoMode::as_mode_str`].
impl Value for RepoMode {
    fn parse(raw: &str) -> Result<RepoMode, ValueError> {
        let value = decode_string(raw)?;
        RepoMode::from_mode_str(&value)
            .ok_or_else(|| ValueError::new(format!("'{value}' names no repository mode")))
    }

    fn format(&self) -> String {
        self.as_mode_str().to_owned()
    }
}

/// The value of `[core] lock-timeout-secs`: a number of seconds, `-1` or
/// more.
///
/// The value `-1` means no limit. A value less than `-1` cannot be built.
///
/// # Examples
///
/// ```
/// use ostrya::config::LockTimeout;
///
/// assert_eq!(LockTimeout::try_from(-1).unwrap().get(), -1);
/// assert!(LockTimeout::try_from(-2).is_err());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct LockTimeout {
    secs: i64,
}

impl LockTimeout {
    /// Returns the value for a built-in default. The value must be `-1` or
    /// more.
    pub(crate) const fn new_const(secs: i64) -> LockTimeout {
        assert!(secs >= -1);
        LockTimeout { secs }
    }

    /// Returns the number of seconds, or `-1` for no limit.
    pub fn get(self) -> i64 {
        self.secs
    }
}

impl TryFrom<i64> for LockTimeout {
    type Error = ValueError;

    /// # Errors
    ///
    /// A [`ValueError`] if `secs` is less than `-1`.
    fn try_from(secs: i64) -> Result<LockTimeout, ValueError> {
        if secs < -1 {
            return Err(ValueError::new(format!("{secs} is below -1")));
        }
        Ok(LockTimeout { secs })
    }
}

impl Value for LockTimeout {
    fn parse(raw: &str) -> Result<LockTimeout, ValueError> {
        LockTimeout::try_from(decode_integer(raw)?)
    }

    fn format(&self) -> String {
        encode_integer(self.secs)
    }
}

/// The value of `[core] min-free-space-percent`: a percentage from `0` to
/// `100`.
///
/// A value outside the range cannot be built.
///
/// # Examples
///
/// ```
/// use ostrya::config::FreeSpacePercent;
///
/// assert_eq!(FreeSpacePercent::try_from(100).unwrap().get(), 100);
/// assert!(FreeSpacePercent::try_from(101).is_err());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct FreeSpacePercent {
    percent: u32,
}

impl FreeSpacePercent {
    /// Returns the value for a built-in default. The value must be in the
    /// range `0` to `100`.
    pub(crate) const fn new_const(percent: u32) -> FreeSpacePercent {
        assert!(percent <= 100);
        FreeSpacePercent { percent }
    }

    /// Returns the percentage.
    pub fn get(self) -> u32 {
        self.percent
    }
}

impl TryFrom<i64> for FreeSpacePercent {
    type Error = ValueError;

    /// # Errors
    ///
    /// A [`ValueError`] if `percent` is outside the range `0` to `100`.
    fn try_from(percent: i64) -> Result<FreeSpacePercent, ValueError> {
        match u32::try_from(percent) {
            Ok(percent) if percent <= 100 => Ok(FreeSpacePercent { percent }),
            _ => Err(ValueError::new(format!(
                "{percent} is out of the range 0-100"
            ))),
        }
    }
}

impl Value for FreeSpacePercent {
    fn parse(raw: &str) -> Result<FreeSpacePercent, ValueError> {
        FreeSpacePercent::try_from(decode_integer(raw)?)
    }

    fn format(&self) -> String {
        encode_integer(i64::from(self.percent))
    }
}

/// The value of `[core] collection-id`: a collection id that passes
/// [`is_valid_collection_id`](crate::is_valid_collection_id).
///
/// An id that fails the rule cannot be built.
///
/// # Examples
///
/// ```
/// use ostrya::config::CollectionIdValue;
///
/// let id = CollectionIdValue::try_from("org.example.Os").unwrap();
/// assert_eq!(id.as_str(), "org.example.Os");
/// assert!(CollectionIdValue::try_from("a b").is_err());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CollectionIdValue {
    id: String,
}

impl CollectionIdValue {
    /// Returns the id.
    pub fn as_str(&self) -> &str {
        &self.id
    }

    /// Returns the id by value.
    pub fn into_string(self) -> String {
        self.id
    }
}

impl TryFrom<String> for CollectionIdValue {
    type Error = ValueError;

    /// # Errors
    ///
    /// A [`ValueError`] if `id` fails the collection-id rule.
    fn try_from(id: String) -> Result<CollectionIdValue, ValueError> {
        if !ostrya_core::is_valid_collection_id(&id) {
            return Err(ValueError::new(format!(
                "value '{id}' is not a valid collection id"
            )));
        }
        Ok(CollectionIdValue { id })
    }
}

impl TryFrom<&str> for CollectionIdValue {
    type Error = ValueError;

    /// # Errors
    ///
    /// A [`ValueError`] if `id` fails the collection-id rule.
    fn try_from(id: &str) -> Result<CollectionIdValue, ValueError> {
        CollectionIdValue::try_from(id.to_owned())
    }
}

impl Value for CollectionIdValue {
    fn parse(raw: &str) -> Result<CollectionIdValue, ValueError> {
        CollectionIdValue::try_from(decode_string(raw)?)
    }

    fn format(&self) -> String {
        encode_string(&self.id)
    }
}

/// The value of `[ex-ostrya] remotes-config-dir`: the path of the remotes
/// directory, as the key holds it.
///
/// The path is not empty and holds no NUL byte. A relative path has no `..`
/// component, and it names a directory relative to the repository. A path
/// that breaks a rule cannot be built.
///
/// # Examples
///
/// ```
/// use ostrya::config::RemotesConfigPath;
///
/// assert!(RemotesConfigPath::try_from("/etc/ostree/remotes.d").is_ok());
/// assert!(RemotesConfigPath::try_from("/etc/../remotes.d").is_ok());
/// assert!(RemotesConfigPath::try_from("../remotes.d").is_err());
/// assert!(RemotesConfigPath::try_from("").is_err());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct RemotesConfigPath {
    path: String,
}

impl RemotesConfigPath {
    /// Returns the path as text.
    pub fn as_str(&self) -> &str {
        &self.path
    }

    /// Returns the path.
    pub fn as_path(&self) -> &Path {
        Path::new(&self.path)
    }
}

impl TryFrom<String> for RemotesConfigPath {
    type Error = ValueError;

    /// # Errors
    ///
    /// A [`ValueError`] if `path` is empty, holds a NUL byte, or is a
    /// relative path with a `..` component.
    fn try_from(path: String) -> Result<RemotesConfigPath, ValueError> {
        if path.is_empty() {
            return Err(ValueError::new("is empty"));
        }
        if path.contains('\0') {
            return Err(ValueError::new("holds a NUL byte"));
        }
        let value = Path::new(&path);
        if value.is_relative() && value.components().any(|c| c == Component::ParentDir) {
            return Err(ValueError::new(format!(
                "{path} has a `..` component, which a relative path in a config cannot have"
            )));
        }
        Ok(RemotesConfigPath { path })
    }
}

impl TryFrom<&str> for RemotesConfigPath {
    type Error = ValueError;

    /// # Errors
    ///
    /// A [`ValueError`] if `path` is empty, holds a NUL byte, or is a
    /// relative path with a `..` component.
    fn try_from(path: &str) -> Result<RemotesConfigPath, ValueError> {
        RemotesConfigPath::try_from(path.to_owned())
    }
}

impl Value for RemotesConfigPath {
    fn parse(raw: &str) -> Result<RemotesConfigPath, ValueError> {
        RemotesConfigPath::try_from(decode_string(raw)?)
    }

    fn format(&self) -> String {
        encode_string(&self.path)
    }
}

/// Refuses `path`, a path of a config, if it is a relative path with a `..`
/// component.
fn check_config_path(path: &str) -> Result<(), ValueError> {
    if super::relative_with_parent(Path::new(path)) {
        return Err(ValueError::new(format!(
            "{path} has a `..` component, which a relative path in a config cannot have"
        )));
    }
    Ok(())
}

/// The value of a key that names a file, as the key holds it.
///
/// The path can be empty. A relative path has no `..` component. A path
/// that breaks the rule cannot be built. The code that reads the file
/// resolves a relative path, by the rules of
/// [`config::remote`](super::remote#paths).
///
/// # Examples
///
/// ```
/// use ostrya::config::ConfigPath;
///
/// assert!(ConfigPath::try_from("/etc/ca.pem").is_ok());
/// assert!(ConfigPath::try_from("/etc/../ca.pem").is_ok());
/// assert!(ConfigPath::try_from("").is_ok());
/// assert!(ConfigPath::try_from("../ca.pem").is_err());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ConfigPath {
    path: String,
}

impl ConfigPath {
    /// Returns the path as text.
    pub fn as_str(&self) -> &str {
        &self.path
    }

    /// Returns the path.
    pub fn as_path(&self) -> &Path {
        Path::new(&self.path)
    }

    /// Returns the path as text by value.
    pub fn into_string(self) -> String {
        self.path
    }
}

impl TryFrom<String> for ConfigPath {
    type Error = ValueError;

    /// # Errors
    ///
    /// A [`ValueError`] if `path` is a relative path with a `..` component.
    fn try_from(path: String) -> Result<ConfigPath, ValueError> {
        check_config_path(&path)?;
        Ok(ConfigPath { path })
    }
}

impl TryFrom<&str> for ConfigPath {
    type Error = ValueError;

    /// # Errors
    ///
    /// A [`ValueError`] if `path` is a relative path with a `..` component.
    fn try_from(path: &str) -> Result<ConfigPath, ValueError> {
        ConfigPath::try_from(path.to_owned())
    }
}

/// The text is decoded, and then checked as [`ConfigPath::try_from`] checks
/// it.
impl Value for ConfigPath {
    fn parse(raw: &str) -> Result<ConfigPath, ValueError> {
        ConfigPath::try_from(decode_string(raw)?)
    }

    fn format(&self) -> String {
        encode_string(&self.path)
    }
}

/// The value of the key `gpgkeypath`: the list of the GPG keyrings that a
/// remote or a trust group trusts.
///
/// [`remote::GpgKeyPath`](super::remote::GpgKeyPath) states the rules of the
/// list. A list is the result of [`Value::parse`] or the empty list of
/// [`Default`].
///
/// # Examples
///
/// ```
/// use ostrya::config::{KeyringPaths, Value};
///
/// let paths = KeyringPaths::parse(r"/etc/one.gpg;k\s.gpg;").unwrap();
/// assert_eq!(paths.entries(), ["/etc/one.gpg", r"k\s.gpg"]);
/// assert!(KeyringPaths::parse("../k.gpg").is_err());
/// assert!(KeyringPaths::default().entries().is_empty());
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
pub struct KeyringPaths {
    entries: Vec<String>,
}

impl KeyringPaths {
    /// Returns the entries, in the order of the value.
    pub fn entries(&self) -> &[String] {
        &self.entries
    }

    /// Returns the entries by value.
    pub fn into_entries(self) -> Vec<String> {
        self.entries
    }
}

/// The text is read as written, with no decode. A `;` separates the
/// entries. The parse removes one empty entry at the end of the list and
/// keeps each other empty entry, so an empty text gives one empty entry.
/// The parse refuses an entry that is a relative path with a `..`
/// component.
///
/// `format` joins the entries with `;`, and adds a `;` if the list has more
/// than one entry and its last entry is empty. The empty list gives the
/// empty text, which parses as one empty entry.
impl Value for KeyringPaths {
    fn parse(raw: &str) -> Result<KeyringPaths, ValueError> {
        let mut entries: Vec<String> = raw.split(';').map(str::to_owned).collect();
        if entries.len() > 1 && entries.last().is_some_and(String::is_empty) {
            entries.pop();
        }
        for entry in &entries {
            check_config_path(entry)?;
        }
        Ok(KeyringPaths { entries })
    }

    fn format(&self) -> String {
        let mut text = self.entries.join(";");
        if self.entries.len() > 1 && self.entries.last().is_some_and(String::is_empty) {
            text.push(';');
        }
        text
    }
}

/// The value of the key `mirrored-collection-ids`: a list of collection
/// ids that is not empty.
///
/// Each id passes [`is_valid_collection_id`](crate::is_valid_collection_id),
/// and each id occurs one time. A list that breaks a rule cannot be built.
///
/// # Examples
///
/// ```
/// use ostrya::config::{CollectionIdList, Value};
///
/// let ids = CollectionIdList::parse("org.ex.B;org.ex.A;org.ex.B;").unwrap();
/// assert_eq!(ids.ids(), ["org.ex.B", "org.ex.A"]);
/// assert!(CollectionIdList::parse("").is_err());
/// assert!(CollectionIdList::parse("org/ex").is_err());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CollectionIdList {
    ids: Vec<String>,
}

impl CollectionIdList {
    /// Returns the ids, in the order of the value.
    pub fn ids(&self) -> &[String] {
        &self.ids
    }

    /// Returns the ids by value.
    pub fn into_ids(self) -> Vec<String> {
        self.ids
    }
}

impl TryFrom<Vec<String>> for CollectionIdList {
    type Error = ValueError;

    /// Keeps the first copy of an id that occurs again.
    ///
    /// # Errors
    ///
    /// A [`ValueError`] if `ids` is empty, or if an id fails the
    /// collection-id rule.
    fn try_from(ids: Vec<String>) -> Result<CollectionIdList, ValueError> {
        if ids.is_empty() {
            return Err(ValueError::new("holds no collection id"));
        }
        let mut seen = HashSet::with_capacity(ids.len());
        let mut out: Vec<String> = Vec::with_capacity(ids.len());
        for id in ids {
            if !ostrya_core::is_valid_collection_id(&id) {
                return Err(ValueError::new(format!(
                    "holds the invalid collection id '{id}'"
                )));
            }
            if seen.insert(id.clone()) {
                out.push(id);
            }
        }
        Ok(CollectionIdList { ids: out })
    }
}

/// The text is a `;` list with the escape sequences of a key file. The
/// list is decoded, and then checked as [`CollectionIdList::try_from`]
/// checks it.
impl Value for CollectionIdList {
    fn parse(raw: &str) -> Result<CollectionIdList, ValueError> {
        CollectionIdList::try_from(decode_string_list(raw)?)
    }

    fn format(&self) -> String {
        encode_string_list(&self.ids)
    }
}

/// The value of `[ex-ostrya server] listen`: a list of socket addresses
/// that is not empty.
///
/// Each item is `ADDR:PORT`, an IP address and a port. An IPv6 address is
/// written in brackets, for example `[::1]:8080`. A host name is not an
/// item. An empty list cannot be built.
///
/// # Examples
///
/// ```
/// use ostrya::config::{ListenAddrs, Value};
///
/// let addrs = ListenAddrs::parse("127.0.0.1:8080;[::1]:8080")?;
/// assert_eq!(addrs.addrs().len(), 2);
/// assert_eq!(addrs.format(), "127.0.0.1:8080;[::1]:8080;");
/// assert!(ListenAddrs::parse("").is_err());
/// assert!(ListenAddrs::parse("localhost:8080").is_err());
/// # Ok::<(), ostrya::config::ValueError>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ListenAddrs {
    addrs: Vec<SocketAddr>,
}

impl ListenAddrs {
    /// Returns the addresses, in the order of the value.
    pub fn addrs(&self) -> &[SocketAddr] {
        &self.addrs
    }

    /// Returns the addresses by value.
    pub fn into_addrs(self) -> Vec<SocketAddr> {
        self.addrs
    }
}

impl TryFrom<Vec<SocketAddr>> for ListenAddrs {
    type Error = ValueError;

    /// # Errors
    ///
    /// A [`ValueError`] if `addrs` is empty, and a [`ValueError`] of
    /// [`ValueError::malformed_item`] if an IPv6 address has a flow label,
    /// a `flowinfo` that is not zero. The text of a value cannot hold a
    /// flow label.
    fn try_from(addrs: Vec<SocketAddr>) -> Result<ListenAddrs, ValueError> {
        if addrs.is_empty() {
            return Err(ValueError::new(
                "is empty; remove the key for the default address",
            ));
        }
        if let Some(addr) = addrs
            .iter()
            .find(|addr| matches!(addr, SocketAddr::V6(v6) if v6.flowinfo() != 0))
        {
            return Err(ValueError::malformed_item(
                addr.to_string(),
                "the address has a flow label, which a config cannot hold",
            ));
        }
        Ok(ListenAddrs { addrs })
    }
}

/// The text is a `;` list with the escape sequences of a key file. Each
/// item is read as a [`SocketAddr`]. The parse refuses an item that is not
/// `ADDR:PORT` with [`ValueError::malformed_item`], and an empty list.
impl Value for ListenAddrs {
    fn parse(raw: &str) -> Result<ListenAddrs, ValueError> {
        let addrs = decode_string_list(raw)?
            .iter()
            .map(|text| {
                text.parse::<SocketAddr>().map_err(|_| {
                    ValueError::malformed_item(
                        text.as_str(),
                        "the item is ADDR:PORT, an IP address and a port",
                    )
                })
            })
            .collect::<Result<Vec<_>, _>>()?;
        ListenAddrs::try_from(addrs)
    }

    fn format(&self) -> String {
        let items: Vec<String> = self.addrs.iter().map(SocketAddr::to_string).collect();
        encode_string_list(&items)
    }
}

/// The value of `[ex-ostrya server] trusted-proxy`: a list of networks that
/// is not empty.
///
/// Each item is a network in the form of [`IpNet`]. An empty list cannot be
/// built.
///
/// # Examples
///
/// ```
/// use ostrya::config::{TrustedNets, Value};
///
/// let nets = TrustedNets::parse("10.0.0.0/8;2001:db8::1")?;
/// assert_eq!(nets.format(), "10.0.0.0/8;2001:db8::1/128;");
/// assert!(TrustedNets::parse("").is_err());
/// assert!(TrustedNets::parse("10.0.0.1/24").is_err());
/// # Ok::<(), ostrya::config::ValueError>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TrustedNets {
    nets: Vec<IpNet>,
}

impl TrustedNets {
    /// Returns the networks, in the order of the value.
    pub fn nets(&self) -> &[IpNet] {
        &self.nets
    }

    /// Returns the networks by value.
    pub fn into_nets(self) -> Vec<IpNet> {
        self.nets
    }
}

impl TryFrom<Vec<IpNet>> for TrustedNets {
    type Error = ValueError;

    /// # Errors
    ///
    /// A [`ValueError`] if `nets` is empty.
    fn try_from(nets: Vec<IpNet>) -> Result<TrustedNets, ValueError> {
        if nets.is_empty() {
            return Err(ValueError::new(
                "is empty; remove the key or name a network",
            ));
        }
        Ok(TrustedNets { nets })
    }
}

/// The text is a `;` list with the escape sequences of a key file. Each
/// item is read as an [`IpNet`]. The parse refuses an item that is not a
/// network with [`ValueError::malformed_item`], and an empty list.
impl Value for TrustedNets {
    fn parse(raw: &str) -> Result<TrustedNets, ValueError> {
        let nets = decode_string_list(raw)?
            .iter()
            .map(|text| {
                parse_net(text).map_err(|why| ValueError::malformed_item(text.as_str(), why))
            })
            .collect::<Result<Vec<_>, _>>()?;
        TrustedNets::try_from(nets)
    }

    fn format(&self) -> String {
        let items: Vec<String> = self.nets.iter().map(IpNet::to_string).collect();
        encode_string_list(&items)
    }
}

/// The text is decoded, and then read as
/// [`ForwardedHeader::parse`] reads it: `forwarded`, `x-forwarded-for`, or
/// `x-real-ip`. The parse refuses each other text with
/// [`ValueError::malformed_value`]. `format` gives the name of
/// [`ForwardedHeader::as_str`].
impl Value for ForwardedHeader {
    fn parse(raw: &str) -> Result<ForwardedHeader, ValueError> {
        let text = decode_string(raw)?;
        ForwardedHeader::parse(&text).map_err(|_| {
            ValueError::malformed_value(
                text,
                "the value is forwarded, x-forwarded-for, or x-real-ip",
            )
        })
    }

    fn format(&self) -> String {
        self.as_str().to_owned()
    }
}

/// The value of `[ex-ostrya server] trusted-proxy-client-cert`: the name of
/// an HTTP header.
///
/// The name passes [`is_header_name`]. A name that fails the check cannot
/// be built.
///
/// # Examples
///
/// ```
/// use ostrya::config::HeaderName;
///
/// assert_eq!(HeaderName::try_from("X-SSL-Client-Cert").unwrap().as_str(), "X-SSL-Client-Cert");
/// assert!(HeaderName::try_from("X Client").is_err());
/// assert!(HeaderName::try_from("").is_err());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct HeaderName {
    name: String,
}

impl HeaderName {
    /// Returns the name.
    pub fn as_str(&self) -> &str {
        &self.name
    }

    /// Returns the name by value.
    pub fn into_string(self) -> String {
        self.name
    }
}

impl TryFrom<String> for HeaderName {
    type Error = ValueError;

    /// # Errors
    ///
    /// A [`ValueError`] of [`ValueError::malformed_value`] if `name` fails
    /// [`is_header_name`].
    fn try_from(name: String) -> Result<HeaderName, ValueError> {
        if !is_header_name(&name) {
            return Err(ValueError::malformed_value(
                name,
                "the value is a header name, one or more letters, digits, and the \
                 characters !#$%&'*+-.^_`|~",
            ));
        }
        Ok(HeaderName { name })
    }
}

impl TryFrom<&str> for HeaderName {
    type Error = ValueError;

    /// # Errors
    ///
    /// A [`ValueError`] of [`ValueError::malformed_value`] if `name` fails
    /// [`is_header_name`].
    fn try_from(name: &str) -> Result<HeaderName, ValueError> {
        HeaderName::try_from(name.to_owned())
    }
}

/// The text is decoded, and then checked as [`HeaderName::try_from`] checks
/// it.
impl Value for HeaderName {
    fn parse(raw: &str) -> Result<HeaderName, ValueError> {
        HeaderName::try_from(decode_string(raw)?)
    }

    fn format(&self) -> String {
        encode_string(&self.name)
    }
}

/// The value of a key of `[ex-ostrya server]` that names a PEM file:
/// `tls-cert`, `tls-key`, or `tls-client-ca`.
///
/// The path is not empty. A relative path has no `..` component, and it is
/// relative to the repository root. A path that breaks a rule cannot be
/// built.
///
/// # Examples
///
/// ```
/// use ostrya::config::PemPath;
///
/// assert!(PemPath::try_from("certs/server.pem").is_ok());
/// assert!(PemPath::try_from("/etc/../server.pem").is_ok());
/// assert!(PemPath::try_from("../server.pem").is_err());
/// assert!(PemPath::try_from("").is_err());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PemPath {
    path: String,
}

impl PemPath {
    /// Returns the path as text.
    pub fn as_str(&self) -> &str {
        &self.path
    }

    /// Returns the path.
    pub fn as_path(&self) -> &Path {
        Path::new(&self.path)
    }

    /// Returns the path as text by value.
    pub fn into_string(self) -> String {
        self.path
    }
}

impl TryFrom<String> for PemPath {
    type Error = ValueError;

    /// # Errors
    ///
    /// A [`ValueError`] if `path` is empty, or is a relative path with a `..`
    /// component.
    fn try_from(path: String) -> Result<PemPath, ValueError> {
        if path.is_empty() {
            return Err(ValueError::new("is empty; remove the key or name a file"));
        }
        check_config_path(&path)?;
        Ok(PemPath { path })
    }
}

impl TryFrom<&str> for PemPath {
    type Error = ValueError;

    /// # Errors
    ///
    /// A [`ValueError`] if `path` is empty, or is a relative path with a `..`
    /// component.
    fn try_from(path: &str) -> Result<PemPath, ValueError> {
        PemPath::try_from(path.to_owned())
    }
}

/// The text is decoded, and then checked as [`PemPath::try_from`] checks it.
impl Value for PemPath {
    fn parse(raw: &str) -> Result<PemPath, ValueError> {
        PemPath::try_from(decode_string(raw)?)
    }

    fn format(&self) -> String {
        encode_string(&self.path)
    }
}

/// A positive integer: `1` to `i64::MAX`.
///
/// The value of `[ex-ostrya server]` `session-timeout`, `max-sessions`, and
/// `body-timeout`. A value outside the range cannot be built.
///
/// # Examples
///
/// ```
/// use ostrya::config::PositiveInt;
///
/// assert_eq!(PositiveInt::try_from(1).unwrap().get(), 1);
/// assert!(PositiveInt::try_from(0).is_err());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PositiveInt {
    value: u64,
}

impl PositiveInt {
    /// Returns the value.
    pub fn get(self) -> u64 {
        self.value
    }
}

impl TryFrom<i64> for PositiveInt {
    type Error = ValueError;

    /// # Errors
    ///
    /// A [`ValueError`] if `value` is less than `1`.
    fn try_from(value: i64) -> Result<PositiveInt, ValueError> {
        match u64::try_from(value) {
            Ok(n) if n >= 1 => Ok(PositiveInt { value: n }),
            _ => Err(ValueError::new(format!(
                "is {value}; the value is a positive integer"
            ))),
        }
    }
}

/// The text is read with [`decode_integer`], and then checked as
/// [`PositiveInt::try_from`] checks it. A value above `i64::MAX` is not an
/// integer.
impl Value for PositiveInt {
    fn parse(raw: &str) -> Result<PositiveInt, ValueError> {
        PositiveInt::try_from(decode_integer(raw)?)
    }

    fn format(&self) -> String {
        self.value.to_string()
    }
}

/// The value of `[ex-ostrya server] parallel-uploads`: the number of object
/// streams of a push session, `1` to `31`.
///
/// A value outside the range cannot be built.
///
/// # Examples
///
/// ```
/// use ostrya::config::UploadStreams;
///
/// assert_eq!(UploadStreams::try_from(31).unwrap().get(), 31);
/// assert!(UploadStreams::try_from(32).is_err());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct UploadStreams {
    streams: u32,
}

impl UploadStreams {
    /// Returns the number of streams.
    pub fn get(self) -> u32 {
        self.streams
    }
}

impl TryFrom<i64> for UploadStreams {
    type Error = ValueError;

    /// # Errors
    ///
    /// A [`ValueError`] if `streams` is outside the range `1` to `31`.
    fn try_from(streams: i64) -> Result<UploadStreams, ValueError> {
        match u32::try_from(streams) {
            Ok(n) if (1..=31).contains(&n) => Ok(UploadStreams { streams: n }),
            _ => Err(ValueError::new(format!(
                "is {streams}; the value is 1 to 31"
            ))),
        }
    }
}

/// The text is read with [`decode_integer`], and then checked as
/// [`UploadStreams::try_from`] checks it.
impl Value for UploadStreams {
    fn parse(raw: &str) -> Result<UploadStreams, ValueError> {
        UploadStreams::try_from(decode_integer(raw)?)
    }

    fn format(&self) -> String {
        self.streams.to_string()
    }
}

/// The value of `[ex-ostrya server] sign-summary` and of
/// `[ex-ostrya client "NAME"] sign`: a list of key group names that is not
/// empty.
///
/// A name is the quoted part of the header of a group
/// `[ex-ostrya key "NAME"]`, a section of [`key::Group`](super::key::Group).
/// The names are text, and
/// [`GroupRef::new`](super::GroupRef::new) makes a reference of a name.
/// Each name occurs one time. An item can be
/// empty. The value type does not check that a group of the name exists.
/// [`ClientAccess::from_config`](crate::access::ClientAccess::from_config)
/// checks it.
///
/// # Examples
///
/// ```
/// use ostrya::config::{KeyGroupNames, Value};
///
/// let names = KeyGroupNames::parse("b;a;b")?;
/// assert_eq!(names.names(), ["b", "a"]);
/// assert!(KeyGroupNames::parse("").is_err());
/// # Ok::<(), ostrya::config::ValueError>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct KeyGroupNames {
    names: Vec<String>,
}

impl KeyGroupNames {
    /// Returns the names, in the order of the value.
    pub fn names(&self) -> &[String] {
        &self.names
    }

    /// Returns the names by value.
    pub fn into_names(self) -> Vec<String> {
        self.names
    }
}

impl TryFrom<Vec<String>> for KeyGroupNames {
    type Error = ValueError;

    /// Keeps the first copy of a name that occurs again.
    ///
    /// # Errors
    ///
    /// A [`ValueError`] if `names` is empty.
    fn try_from(names: Vec<String>) -> Result<KeyGroupNames, ValueError> {
        if names.is_empty() {
            return Err(ValueError::new(
                "is empty; remove the key or name a key group",
            ));
        }
        let mut seen = HashSet::with_capacity(names.len());
        let kept: Vec<String> = names
            .into_iter()
            .filter(|name| seen.insert(name.clone()))
            .collect();
        Ok(KeyGroupNames { names: kept })
    }
}

/// The text is a `;` list with the escape sequences of a key file. The list
/// is decoded, and then checked as [`KeyGroupNames::try_from`] checks it.
impl Value for KeyGroupNames {
    fn parse(raw: &str) -> Result<KeyGroupNames, ValueError> {
        KeyGroupNames::try_from(decode_string_list(raw)?)
    }

    fn format(&self) -> String {
        encode_string_list(&self.names)
    }
}

/// The value of `[ex-ostrya client "NAME"] auth`: a list of authentication
/// items.
///
/// Each item occurs one time, also an item that the value gives in two
/// spellings, such as two forms of one network. The list can be empty.
/// [`ClientAccess::from_config`](crate::access::ClientAccess::from_config)
/// refuses a client group with no item.
///
/// # Examples
///
/// ```
/// use ostrya::access::AuthItem;
/// use ostrya::config::{AuthItems, Value};
///
/// let items = AuthItems::parse("ssh:ci;anonymous;ssh:ci;")?;
/// assert_eq!(items.items(), [AuthItem::Ssh("ci".into()), AuthItem::Anonymous]);
/// assert!(AuthItems::parse("").unwrap().items().is_empty());
/// assert!(AuthItems::parse("bogus").is_err());
/// # Ok::<(), ostrya::config::ValueError>(())
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct AuthItems {
    items: Vec<AuthItem>,
}

impl AuthItems {
    /// Returns the items, in the order of the value.
    pub fn items(&self) -> &[AuthItem] {
        &self.items
    }

    /// Returns the items by value.
    pub fn into_items(self) -> Vec<AuthItem> {
        self.items
    }
}

/// The text is a `;` list with the escape sequences of a key file. Each
/// item is read as [`AuthItem::parse`] reads it. The parse refuses an item
/// that is not an authentication item with [`ValueError::malformed_item`],
/// and keeps the first copy of an item that occurs again.
impl Value for AuthItems {
    fn parse(raw: &str) -> Result<AuthItems, ValueError> {
        let entries = decode_string_list(raw)?;
        let mut seen = HashSet::with_capacity(entries.len());
        let mut items = Vec::with_capacity(entries.len());
        for text in entries {
            let item =
                parse_item(&text).map_err(|why| ValueError::malformed_item(text.as_str(), why))?;
            if seen.insert(item.clone()) {
                items.push(item);
            }
        }
        Ok(AuthItems { items })
    }

    fn format(&self) -> String {
        let items: Vec<String> = self.items.iter().map(AuthItem::to_string).collect();
        encode_string_list(&items)
    }
}

/// The value of `[ex-ostrya client "NAME"] allow`: a list of allow items.
///
/// Each entry is an [`AllowItem`] and the collection id of an item in the
/// form `[MODES:]@ID:PATTERN`, or no id for an item in the form
/// `[MODES:]PATTERN`. The list keeps each entry in the order of the value,
/// also an entry that occurs again. The default is the empty list, which
/// gives no right on a ref.
///
/// # Examples
///
/// ```
/// use ostrya::config::{AllowItems, Value};
///
/// let items = AllowItems::parse("r:os/**;wd:@org.ex.A:os/x")?;
/// let entries: Vec<(Option<&str>, String)> = items
///     .entries()
///     .map(|(id, item)| (id, item.to_string()))
///     .collect();
/// assert_eq!(
///     entries,
///     [(None, "r:os/**".to_owned()), (Some("org.ex.A"), "wd:os/x".to_owned())]
/// );
/// assert_eq!(items.format(), "r:os/**;wd:@org.ex.A:os/x;");
/// assert!(AllowItems::parse("R:a").is_err());
/// # Ok::<(), ostrya::config::ValueError>(())
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct AllowItems {
    entries: Vec<(Option<String>, AllowItem)>,
}

impl AllowItems {
    /// Returns each entry, in the order of the value: the collection id of
    /// the item, or `None` for an item with no `@ID:`, and the item.
    pub fn entries(&self) -> impl Iterator<Item = (Option<&str>, &AllowItem)> {
        self.entries.iter().map(|(id, item)| (id.as_deref(), item))
    }

    /// Returns each entry by value, in the order of the value: the
    /// collection id of the item, or `None` for an item with no `@ID:`, and
    /// the item.
    ///
    /// # Examples
    ///
    /// ```
    /// use ostrya::config::{AllowItems, Value};
    ///
    /// let items = AllowItems::parse("r:os/**;wd:@org.ex.A:os/x")?;
    /// let entries: Vec<(Option<String>, String)> = items
    ///     .into_entries()
    ///     .map(|(id, item)| (id, item.to_string()))
    ///     .collect();
    /// assert_eq!(
    ///     entries,
    ///     [
    ///         (None, "r:os/**".to_owned()),
    ///         (Some("org.ex.A".to_owned()), "wd:os/x".to_owned()),
    ///     ]
    /// );
    /// # Ok::<(), ostrya::config::ValueError>(())
    /// ```
    pub fn into_entries(self) -> impl Iterator<Item = (Option<String>, AllowItem)> {
        self.entries.into_iter()
    }
}

/// The text is a `;` list with the escape sequences of a key file. Each
/// item is `[MODES:]PATTERN` or `[MODES:]@ID:PATTERN`. The parse refuses an
/// item with a bad mode, a bad collection id, or a bad pattern with
/// [`ValueError::malformed_item`].
impl Value for AllowItems {
    fn parse(raw: &str) -> Result<AllowItems, ValueError> {
        let entries = decode_string_list(raw)?
            .iter()
            .map(|text| {
                parse_allow_item(text).map_err(|why| ValueError::malformed_item(text.as_str(), why))
            })
            .collect::<Result<Vec<_>, _>>()?;
        Ok(AllowItems { entries })
    }

    fn format(&self) -> String {
        let items: Vec<String> = self
            .entries
            .iter()
            .map(|(id, item)| match id {
                Some(id) => format!("{}:@{id}:{}", item.modes, item.pattern.as_str()),
                None => item.to_string(),
            })
            .collect();
        encode_string_list(&items)
    }
}

/// The value of `[ex-ostrya client "NAME"] deny`: a list of deny items.
///
/// Each entry is a [`RefPattern`] and the collection id of an item in the
/// form `@ID:PATTERN`, or no id for an item in the form `PATTERN`. The list
/// keeps each entry in the order of the value, also an entry that occurs
/// again. The default is the empty list.
///
/// # Examples
///
/// ```
/// use ostrya::config::{DenyItems, Value};
///
/// let items = DenyItems::parse("os/secret/**;@org.ex.A:x")?;
/// let entries: Vec<(Option<&str>, &str)> = items
///     .entries()
///     .map(|(id, pattern)| (id, pattern.as_str()))
///     .collect();
/// assert_eq!(entries, [(None, "os/secret/**"), (Some("org.ex.A"), "x")]);
/// assert!(DenyItems::parse("r:a").is_err());
/// # Ok::<(), ostrya::config::ValueError>(())
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DenyItems {
    entries: Vec<(Option<String>, RefPattern)>,
}

impl DenyItems {
    /// Returns each entry, in the order of the value: the collection id of
    /// the item, or `None` for an item with no `@ID:`, and the pattern.
    pub fn entries(&self) -> impl Iterator<Item = (Option<&str>, &RefPattern)> {
        self.entries
            .iter()
            .map(|(id, pattern)| (id.as_deref(), pattern))
    }

    /// Returns each entry by value, in the order of the value: the
    /// collection id of the item, or `None` for an item with no `@ID:`, and
    /// the pattern.
    ///
    /// # Examples
    ///
    /// ```
    /// use ostrya::config::{DenyItems, Value};
    ///
    /// let items = DenyItems::parse("os/secret/**;@org.ex.A:x")?;
    /// let entries: Vec<(Option<String>, String)> = items
    ///     .into_entries()
    ///     .map(|(id, pattern)| (id, pattern.as_str().to_owned()))
    ///     .collect();
    /// assert_eq!(
    ///     entries,
    ///     [
    ///         (None, "os/secret/**".to_owned()),
    ///         (Some("org.ex.A".to_owned()), "x".to_owned()),
    ///     ]
    /// );
    /// # Ok::<(), ostrya::config::ValueError>(())
    /// ```
    pub fn into_entries(self) -> impl Iterator<Item = (Option<String>, RefPattern)> {
        self.entries.into_iter()
    }
}

/// The text is a `;` list with the escape sequences of a key file. Each
/// item is `PATTERN` or `@ID:PATTERN`. The parse refuses an item with a bad
/// collection id or a bad pattern with [`ValueError::malformed_item`].
impl Value for DenyItems {
    fn parse(raw: &str) -> Result<DenyItems, ValueError> {
        let entries = decode_string_list(raw)?
            .iter()
            .map(|text| {
                parse_deny_item(text).map_err(|why| ValueError::malformed_item(text.as_str(), why))
            })
            .collect::<Result<Vec<_>, _>>()?;
        Ok(DenyItems { entries })
    }

    fn format(&self) -> String {
        let items: Vec<String> = self
            .entries
            .iter()
            .map(|(id, pattern)| match id {
                Some(id) => format!("@{id}:{}", pattern.as_str()),
                None => pattern.as_str().to_owned(),
            })
            .collect();
        encode_string_list(&items)
    }
}

/// The value of `[ex-ostrya client "NAME"] verify`: `trust:NAME`, a
/// reference to the group `[ex-ostrya trust "NAME"]`.
///
/// The value type does not check that the group exists.
/// [`ClientAccess::from_config`](crate::access::ClientAccess::from_config)
/// checks it, and [`RepoConfig::resolve`](super::RepoConfig::resolve) gives
/// the section of the group.
///
/// # Examples
///
/// ```
/// use ostrya::config::{GroupRef, TrustRef, Value, trust};
///
/// let verify = TrustRef::parse("trust:ci")?;
/// assert_eq!(verify.group().name(), "ci");
/// assert_eq!(verify.format(), "trust:ci");
/// let group = GroupRef::<trust::Group>::new("ci").unwrap();
/// assert_eq!(TrustRef::from(group), verify);
/// assert!(TrustRef::parse("off").is_err());
/// assert!(TrustRef::parse("remote:origin").is_err());
/// # Ok::<(), ostrya::config::ValueError>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TrustRef {
    group: GroupRef<trust::Group>,
}

impl TrustRef {
    /// Returns the reference to the trust group.
    pub fn group(&self) -> &GroupRef<trust::Group> {
        &self.group
    }

    /// Returns the reference to the trust group by value.
    pub fn into_group(self) -> GroupRef<trust::Group> {
        self.group
    }
}

impl From<GroupRef<trust::Group>> for TrustRef {
    fn from(group: GroupRef<trust::Group>) -> TrustRef {
        TrustRef { group }
    }
}

/// The text is decoded, and is `trust:NAME` with a `NAME` that is not
/// empty. The parse refuses each other text with
/// [`ValueError::malformed_value`]. A text that starts with `remote:` gets a
/// reason that names the form `trust:NAME`.
impl Value for TrustRef {
    fn parse(raw: &str) -> Result<TrustRef, ValueError> {
        let text = decode_string(raw)?;
        if let Some(name) = text.strip_prefix("trust:")
            && let Ok(group) = GroupRef::new(name)
        {
            return Ok(TrustRef { group });
        }
        let why = if text.starts_with("remote:") {
            "the remote:NAME form is removed; name a trust group with trust:NAME"
        } else {
            "the value is trust:NAME; leave out the key for no verification"
        };
        Err(ValueError::malformed_value(text, why))
    }

    fn format(&self) -> String {
        encode_string(&format!("trust:{}", self.group.name()))
    }
}

/// The value of `[remote "NAME"] trust`: the name of a trust group.
///
/// The name is not empty, and holds no `"` and no control character. A name
/// that breaks the rule cannot be built. The value does not show that the
/// trust group exists.
/// [`RepoConfig::resolve`](super::RepoConfig::resolve) gives the section of
/// the group.
///
/// # Examples
///
/// ```
/// use ostrya::config::{TrustGroupName, Value};
///
/// let name = TrustGroupName::parse("release")?;
/// assert_eq!(name.group().name(), "release");
/// assert_eq!(name.format(), "release");
/// assert!(TrustGroupName::parse("").is_err());
/// assert!(TrustGroupName::try_from("a\"b").is_err());
/// # Ok::<(), ostrya::config::ValueError>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TrustGroupName {
    group: GroupRef<trust::Group>,
}

impl TrustGroupName {
    /// Returns the reference to the trust group.
    pub fn group(&self) -> &GroupRef<trust::Group> {
        &self.group
    }

    /// Returns the reference to the trust group by value.
    pub fn into_group(self) -> GroupRef<trust::Group> {
        self.group
    }
}

impl TryFrom<String> for TrustGroupName {
    type Error = ValueError;

    /// # Errors
    ///
    /// A [`ValueError`] of [`ValueError::malformed_value`] if `name` is
    /// empty, or holds a `"` or a control character.
    fn try_from(name: String) -> Result<TrustGroupName, ValueError> {
        if name.is_empty() || name.chars().any(|c| c == '"' || c.is_control()) {
            return Err(ValueError::malformed_value(
                name,
                "the value names a trust group, is not empty, and holds no '\"' and no \
                 control character",
            ));
        }
        Ok(TrustGroupName {
            group: GroupRef::new(name)?,
        })
    }
}

impl TryFrom<&str> for TrustGroupName {
    type Error = ValueError;

    /// # Errors
    ///
    /// The errors of [`TrustGroupName::try_from`] for a `String`.
    fn try_from(name: &str) -> Result<TrustGroupName, ValueError> {
        TrustGroupName::try_from(name.to_owned())
    }
}

/// The text is decoded, and then checked as [`TrustGroupName::try_from`]
/// checks it.
impl Value for TrustGroupName {
    fn parse(raw: &str) -> Result<TrustGroupName, ValueError> {
        TrustGroupName::try_from(decode_string(raw)?)
    }

    fn format(&self) -> String {
        encode_string(self.group.name())
    }
}

/// The value of `[ex-ostrya key "NAME"] type`: the type of a signing key.
///
/// Each variant is in each build. A build with no engine for a type refuses
/// a key group of that type when it builds the signing keys.
///
/// # Examples
///
/// ```
/// use ostrya::config::{SigningKeyType, Value};
///
/// assert_eq!(SigningKeyType::parse("spki")?, SigningKeyType::Spki);
/// assert_eq!(SigningKeyType::Gpg.format(), "gpg");
/// assert!(SigningKeyType::parse("ED25519").is_err());
/// assert!(SigningKeyType::parse("dummy").is_err());
/// # Ok::<(), ostrya::config::ValueError>(())
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SigningKeyType {
    /// `ed25519`: one ed25519 key in `secret-key-file`.
    Ed25519,
    /// `spki`: the PEM `PRIVATE KEY` blocks of `secret-key-file`.
    Spki,
    /// `gpg`: the GnuPG secret key that `gpg-key` selects.
    Gpg,
}

impl SigningKeyType {
    /// Returns the text of the type: `ed25519`, `spki`, or `gpg`.
    pub fn as_str(self) -> &'static str {
        match self {
            SigningKeyType::Ed25519 => "ed25519",
            SigningKeyType::Spki => "spki",
            SigningKeyType::Gpg => "gpg",
        }
    }
}

/// The text is decoded, and is `ed25519`, `spki`, or `gpg`, with no other
/// bytes. The parse refuses each other text with
/// [`ValueError::malformed_value`]. The text `dummy` gets a reason that
/// names the dummy engine.
impl Value for SigningKeyType {
    fn parse(raw: &str) -> Result<SigningKeyType, ValueError> {
        let text = decode_string(raw)?;
        match text.as_str() {
            "ed25519" => Ok(SigningKeyType::Ed25519),
            "spki" => Ok(SigningKeyType::Spki),
            "gpg" => Ok(SigningKeyType::Gpg),
            "dummy" => Err(ValueError::malformed_value(
                text,
                "the dummy engine is not a signing key, its signature is its key",
            )),
            _ => Err(ValueError::malformed_value(
                text,
                "the type is ed25519, spki, or gpg",
            )),
        }
    }

    fn format(&self) -> String {
        self.as_str().to_owned()
    }
}

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

    /// Checks that `parse(format(v)) == v`.
    fn round_trips<V: Value + PartialEq + std::fmt::Debug>(value: V) {
        let text = value.format();
        assert_eq!(V::parse(&text), Ok(value), "{text:?}");
    }

    #[test]
    fn trust_group_name_values() {
        let name = TrustGroupName::parse(r"a\sb").unwrap();
        assert_eq!(name.group().name(), "a b");
        round_trips(name);
        round_trips(TrustGroupName::try_from("release").unwrap());
        let why = "the value names a trust group, is not empty, and holds no '\"' and no \
                   control character";
        for (raw, text) in [
            ("", ""),
            ("a\"b", "a\"b"),
            (r"a\tb", "a\tb"),
            (r"a\nb", "a\nb"),
        ] {
            assert_eq!(
                TrustGroupName::parse(raw).unwrap_err(),
                ValueError::malformed_value(text, why),
                "{raw:?}"
            );
        }
        assert_eq!(
            value_error(
                "remote \"o\"",
                "trust",
                "",
                TrustGroupName::parse("").unwrap_err()
            )
            .to_string(),
            "invalid format: malformed [remote \"o\"] trust value '': the value names a trust \
             group, is not empty, and holds no '\"' and no control character"
        );
        assert_eq!(
            TrustGroupName::parse(r"\q").unwrap_err().to_string(),
            r"invalid escape '\q'"
        );
    }

    #[test]
    fn signing_key_type_values() {
        for (text, kind) in [
            ("ed25519", SigningKeyType::Ed25519),
            ("spki", SigningKeyType::Spki),
            ("gpg", SigningKeyType::Gpg),
        ] {
            assert_eq!(SigningKeyType::parse(text), Ok(kind));
            assert_eq!(kind.as_str(), text);
            round_trips(kind);
        }
        assert_eq!(
            SigningKeyType::parse("dummy").unwrap_err().to_string(),
            "malformed value 'dummy': the dummy engine is not a signing key, its signature is \
             its key"
        );
        for raw in ["", "rsa", "ED25519", " gpg", r"\sgpg"] {
            let text = decode_string(raw).unwrap();
            assert_eq!(
                SigningKeyType::parse(raw).unwrap_err().to_string(),
                format!("malformed value '{text}': the type is ed25519, spki, or gpg"),
                "{raw:?}"
            );
        }
        assert_eq!(
            SigningKeyType::parse(r"ed\q").unwrap_err().to_string(),
            r"invalid escape '\q'"
        );
    }

    #[test]
    fn helpers_decode_and_encode() {
        assert_eq!(decode_string(r"a\sb\;c").unwrap(), "a b;c");
        assert_eq!(
            decode_string(r"\q").unwrap_err().to_string(),
            r"invalid escape '\q'"
        );
        assert_eq!(encode_string("  a;b"), r"\s\sa;b");
        assert_eq!(decode_bool("1"), Ok(true));
        assert_eq!(decode_bool("0"), Ok(false));
        assert_eq!(
            decode_bool("yes").unwrap_err().to_string(),
            "is not a boolean"
        );
        assert_eq!(encode_bool(true), "true");
        assert_eq!(encode_bool(false), "false");
        assert_eq!(decode_integer("-5"), Ok(-5));
        assert_eq!(
            decode_integer("+5").unwrap_err().to_string(),
            "is not an integer"
        );
        assert_eq!(encode_integer(-5), "-5");
        assert_eq!(
            decode_string_list(r"a;b\;c;").unwrap(),
            ["a".to_owned(), "b;c".to_owned()]
        );
        assert_eq!(
            decode_string_list("a\\").unwrap_err().to_string(),
            "value ends with a lone backslash"
        );
        assert_eq!(encode_string_list(&["a", "b;c", " d"]), r"a;b\;c;\sd;");
    }

    #[test]
    fn value_error_renders_with_the_group_and_the_key() {
        let render = |err| value_error("core", "fsync", "x", err).to_string();
        assert_eq!(
            render(decode_bool("x").unwrap_err()),
            "keyfile: value 'x' for core.fsync is not a boolean"
        );
        assert_eq!(
            render(decode_integer("x").unwrap_err()),
            "keyfile: value 'x' for core.fsync is not an integer"
        );
        assert_eq!(
            render(decode_string(r"\q").unwrap_err()),
            r"keyfile: invalid escape '\q'"
        );
        assert_eq!(
            render(ValueError::new("is empty")),
            "invalid format: [core] fsync is empty"
        );
    }

    #[test]
    fn bool_integer_and_text_values() {
        assert_eq!(bool::parse("1"), Ok(true));
        assert!(bool::parse("yes").is_err());
        round_trips(true);
        round_trips(false);
        assert_eq!(i64::parse("-9223372036854775808"), Ok(i64::MIN));
        round_trips(i64::MIN);
        round_trips(i64::MAX);
        assert_eq!(u8::parse("255"), Ok(255));
        assert_eq!(
            u8::parse("256").unwrap_err().to_string(),
            "256 is out of the range 0-255"
        );
        assert_eq!(
            i8::parse("-129").unwrap_err().to_string(),
            "-129 is out of the range -128-127"
        );
        assert_eq!(
            u32::parse("-1").unwrap_err().to_string(),
            "-1 is out of the range 0-4294967295"
        );
        round_trips(7u16);
        round_trips(-7i32);
        assert_eq!(String::parse(r"\sa"), Ok(" a".to_owned()));
        round_trips("  a\\b\nc;".to_owned());
        round_trips(String::new());
        assert_eq!(
            Vec::<String>::parse("a;b;"),
            Ok(vec!["a".to_owned(), "b".to_owned()])
        );
        round_trips(vec!["a;b".to_owned(), " c".to_owned(), String::new()]);
        round_trips(Vec::<String>::new());
    }

    #[test]
    fn u64_reads_its_full_range() {
        let above = u64::try_from(i64::MAX).unwrap() + 1;
        assert_eq!(u64::parse("9223372036854775808"), Ok(above));
        assert_eq!(u64::parse("18446744073709551615"), Ok(u64::MAX));
        for value in [0, u64::try_from(i64::MAX).unwrap(), above, u64::MAX] {
            round_trips(value);
        }
        assert_eq!(
            u64::parse("-1").unwrap_err().to_string(),
            "-1 is out of the range 0-18446744073709551615"
        );
        for bad in [
            "+1",
            "+18446744073709551615",
            "18446744073709551616",
            "x",
            "",
        ] {
            assert_eq!(
                u64::parse(bad).unwrap_err().to_string(),
                "is not an integer",
                "{bad:?}"
            );
        }
    }

    #[test]
    fn tristate_values() {
        assert_eq!(<Tristate as Value>::parse("yes"), Ok(Tristate::Yes));
        assert_eq!(<Tristate as Value>::parse("maybe"), Ok(Tristate::Maybe));
        assert_eq!(
            <Tristate as Value>::parse("true").unwrap_err().to_string(),
            "value 'true' is not no, maybe, or yes"
        );
        for value in [Tristate::No, Tristate::Maybe, Tristate::Yes] {
            round_trips(value);
        }
    }

    #[test]
    fn sign_verify_values() {
        assert_eq!(SignVerify::parse("1"), Ok(SignVerify::All));
        assert_eq!(SignVerify::parse(""), Ok(SignVerify::Off));
        assert_eq!(
            SignVerify::parse(r"ed25519,\sspki"),
            Ok(SignVerify::Engines(vec![
                "ed25519".to_owned(),
                " spki".to_owned()
            ]))
        );
        assert!(SignVerify::parse(r"\q").is_err());
        round_trips(SignVerify::Off);
        round_trips(SignVerify::All);
        round_trips(SignVerify::Engines(vec![
            " ed25519".to_owned(),
            "spki".to_owned(),
        ]));
        for names in [&["true"][..], &["0"], &["1"], &["false"], &["a", "b"]] {
            round_trips(SignVerify::Engines(
                names.iter().map(|name| (*name).to_owned()).collect(),
            ));
        }
        assert_eq!(
            SignVerify::Engines(vec!["a".to_owned(), "b".to_owned()]).format(),
            "a;b;"
        );
        assert_eq!(SignVerify::Engines(Vec::new()).format(), "");
        assert_eq!(SignVerify::parse(""), Ok(SignVerify::Off));
    }

    #[test]
    fn size_values_read_the_raw_text() {
        assert_eq!(
            SizeSpec::parse("2GB"),
            Ok(SizeSpec {
                value: 2,
                unit: SizeUnit::Giga
            })
        );
        assert_eq!(
            SizeSpec::parse(r"\s1GB").unwrap_err().to_string(),
            r"value '\s1GB' is not of the form 123MB, 123GB, or 123TB"
        );
        for unit in [SizeUnit::Mega, SizeUnit::Giga, SizeUnit::Tera] {
            round_trips(SizeSpec { value: 500, unit });
        }
    }

    #[test]
    fn mode_values() {
        assert_eq!(RepoMode::parse("archive"), Ok(RepoMode::Archive));
        assert_eq!(RepoMode::Archive.format(), "archive-z2");
        assert_eq!(
            RepoMode::parse("bogus").unwrap_err().to_string(),
            "'bogus' names no repository mode"
        );
        for mode in [
            RepoMode::Bare,
            RepoMode::BareUser,
            RepoMode::BareUserOnly,
            RepoMode::BareSplitXattrs,
            RepoMode::Archive,
            RepoMode::BareUserShared,
            RepoMode::BareUserPrivate,
        ] {
            round_trips(mode);
        }
    }

    #[test]
    fn newtypes_keep_their_bounds() {
        assert_eq!(LockTimeout::parse("-1").map(LockTimeout::get), Ok(-1));
        assert_eq!(
            LockTimeout::parse("-2").unwrap_err().to_string(),
            "-2 is below -1"
        );
        assert!(LockTimeout::parse("x").is_err());
        round_trips(LockTimeout::new_const(300));
        round_trips(LockTimeout::new_const(-1));

        assert_eq!(
            FreeSpacePercent::parse("0").map(FreeSpacePercent::get),
            Ok(0)
        );
        assert_eq!(
            FreeSpacePercent::parse("100").map(FreeSpacePercent::get),
            Ok(100)
        );
        for bad in ["-1", "101", "4294967296"] {
            assert_eq!(
                FreeSpacePercent::parse(bad).unwrap_err().to_string(),
                format!("{bad} is out of the range 0-100")
            );
        }
        round_trips(FreeSpacePercent::new_const(3));

        assert_eq!(
            CollectionIdValue::parse("org.ex.C").map(CollectionIdValue::into_string),
            Ok("org.ex.C".to_owned())
        );
        assert_eq!(
            CollectionIdValue::parse("a b").unwrap_err().to_string(),
            "value 'a b' is not a valid collection id"
        );
        round_trips(CollectionIdValue::try_from("org.ex.C").unwrap());

        assert_eq!(
            RemotesConfigPath::parse("").unwrap_err().to_string(),
            "is empty"
        );
        assert_eq!(
            RemotesConfigPath::try_from("a\0b").unwrap_err().to_string(),
            "holds a NUL byte"
        );
        assert_eq!(
            RemotesConfigPath::parse("../x").unwrap_err().to_string(),
            "../x has a `..` component, which a relative path in a config cannot have"
        );
        let path = RemotesConfigPath::parse("/abs/../x").unwrap();
        assert_eq!(path.as_path(), Path::new("/abs/../x"));
        assert_eq!(RemotesConfigPath::parse(r"\sr.d").unwrap().as_str(), " r.d");
        round_trips(path);
        round_trips(RemotesConfigPath::try_from(" r.d").unwrap());
    }

    #[test]
    fn config_paths_refuse_a_relative_parent() {
        assert_eq!(
            ConfigPath::parse("").map(ConfigPath::into_string),
            Ok(String::new())
        );
        assert_eq!(ConfigPath::parse(r"a\sb").unwrap().as_str(), "a b");
        assert_eq!(
            ConfigPath::parse("../x").unwrap_err().to_string(),
            "../x has a `..` component, which a relative path in a config cannot have"
        );
        assert!(ConfigPath::parse(r"\q").is_err());
        let path = ConfigPath::parse("/abs/../x").unwrap();
        assert_eq!(path.as_path(), Path::new("/abs/../x"));
        round_trips(path);
        round_trips(ConfigPath::try_from(" k.pem").unwrap());
        round_trips(ConfigPath::try_from("").unwrap());
    }

    /// `gpgkeypath` is the raw value split on `;`: no escape is decoded, one
    /// empty entry at the end is removed, and each other empty entry stays.
    #[test]
    fn keyring_paths_split_the_raw_value() {
        let cases: &[(&str, &[&str])] = &[
            (r"k\sspace.gpg", &[r"k\sspace.gpg"]),
            (r"\q", &[r"\q"]),
            ("", &[""]),
            (";", &[""]),
            (";a", &["", "a"]),
            ("a;;b", &["a", "", "b"]),
            ("a;", &["a"]),
            ("a;;", &["a", ""]),
            ("a;b", &["a", "b"]),
            (";;", &["", ""]),
        ];
        for (raw, want) in cases {
            let paths = KeyringPaths::parse(raw).unwrap();
            assert_eq!(paths.entries(), *want, "{raw:?}");
            round_trips(paths);
        }
        assert_eq!(
            KeyringPaths::parse("/a;../k").unwrap_err().to_string(),
            "../k has a `..` component, which a relative path in a config cannot have"
        );
        assert!(KeyringPaths::parse("/etc/../k").is_ok());
        assert_eq!(KeyringPaths::default().format(), "");
        assert_eq!(KeyringPaths::parse("a;;").unwrap().format(), "a;;");
    }

    #[test]
    fn malformed_errors_render_with_the_group_and_the_key() {
        let render = |err| value_error("ex-ostrya server", "listen", "x", err).to_string();
        assert_eq!(
            render(ValueError::malformed_item("x", "why")),
            "invalid format: malformed [ex-ostrya server] listen item 'x': why"
        );
        assert_eq!(
            render(ValueError::malformed_value("x", "why")),
            "invalid format: malformed [ex-ostrya server] listen value 'x': why"
        );
        assert_eq!(
            ValueError::malformed_item("x", "why").to_string(),
            "malformed item 'x': why"
        );
        assert_eq!(
            ValueError::malformed_value("x", "why").to_string(),
            "malformed value 'x': why"
        );
    }

    #[test]
    fn listen_addresses_are_checked() {
        let addrs = ListenAddrs::parse("127.0.0.1:80;[::1]:81;").unwrap();
        assert_eq!(
            addrs.addrs(),
            [
                "127.0.0.1:80".parse::<SocketAddr>().unwrap(),
                "[::1]:81".parse().unwrap()
            ]
        );
        assert_eq!(addrs.format(), "127.0.0.1:80;[::1]:81;");
        round_trips(addrs);
        assert_eq!(
            ListenAddrs::parse("").unwrap_err().to_string(),
            "is empty; remove the key for the default address"
        );
        assert_eq!(
            ListenAddrs::parse("localhost:80").unwrap_err(),
            ValueError::malformed_item(
                "localhost:80",
                "the item is ADDR:PORT, an IP address and a port"
            )
        );
        assert_eq!(
            ListenAddrs::parse("a\\").unwrap_err().to_string(),
            "value ends with a lone backslash"
        );
        assert_eq!(
            ListenAddrs::try_from(Vec::new()).unwrap_err().to_string(),
            "is empty; remove the key for the default address"
        );
    }

    #[test]
    fn listen_addresses_refuse_a_flow_label() {
        let addr: SocketAddr =
            std::net::SocketAddrV6::new(std::net::Ipv6Addr::LOCALHOST, 80, 5, 0).into();
        let err = ListenAddrs::try_from(vec![addr]).unwrap_err();
        assert_eq!(
            err.to_string(),
            "malformed item '[::1]:80': the address has a flow label, which a config \
             cannot hold"
        );
        assert_eq!(
            value_error("ex-ostrya server", "listen", "x", err).to_string(),
            "invalid format: malformed [ex-ostrya server] listen item '[::1]:80': the \
             address has a flow label, which a config cannot hold"
        );
        let parsed = ListenAddrs::parse("[::1]:80").unwrap();
        assert!(matches!(parsed.addrs(), [SocketAddr::V6(v6)] if v6.flowinfo() == 0));
        assert_eq!(parsed.format(), "[::1]:80;");
        round_trips(parsed);
    }

    #[test]
    fn trusted_networks_are_checked() {
        let nets = TrustedNets::parse("10.0.0.0/8;2001:db8::1").unwrap();
        assert_eq!(nets.format(), "10.0.0.0/8;2001:db8::1/128;");
        assert_eq!(nets.nets().len(), 2);
        round_trips(nets);
        assert_eq!(
            TrustedNets::parse("").unwrap_err().to_string(),
            "is empty; remove the key or name a network"
        );
        assert_eq!(
            TrustedNets::parse("10.0.0.1/24").unwrap_err(),
            ValueError::malformed_item("10.0.0.1/24", "the address has host bits set")
        );
        assert_eq!(
            TrustedNets::try_from(Vec::new()).unwrap_err().to_string(),
            "is empty; remove the key or name a network"
        );
    }

    #[test]
    fn forwarded_headers_and_header_names_are_checked() {
        for header in [
            ForwardedHeader::Forwarded,
            ForwardedHeader::XForwardedFor,
            ForwardedHeader::XRealIp,
        ] {
            round_trips(header);
        }
        assert_eq!(
            ForwardedHeader::parse("x-real-ip").ok(),
            <ForwardedHeader as Value>::parse("x-real-ip").ok()
        );
        assert_eq!(
            <ForwardedHeader as Value>::parse("X-Real-IP").unwrap_err(),
            ValueError::malformed_value(
                "X-Real-IP",
                "the value is forwarded, x-forwarded-for, or x-real-ip"
            )
        );
        assert_eq!(
            <ForwardedHeader as Value>::parse("")
                .unwrap_err()
                .to_string(),
            "malformed value '': the value is forwarded, x-forwarded-for, or x-real-ip"
        );

        let name = HeaderName::parse("X-SSL-Client-Cert").unwrap();
        assert_eq!(name.as_str(), "X-SSL-Client-Cert");
        round_trips(name);
        for bad in ["", "X Client", "X:Client"] {
            assert_eq!(
                HeaderName::try_from(bad).unwrap_err(),
                ValueError::malformed_value(
                    bad,
                    "the value is a header name, one or more letters, digits, and the \
                     characters !#$%&'*+-.^_`|~"
                ),
                "{bad:?}"
            );
        }
        assert_eq!(
            HeaderName::parse(r"X\sClient").unwrap_err().to_string(),
            "malformed value 'X Client': the value is a header name, one or more letters, \
             digits, and the characters !#$%&'*+-.^_`|~"
        );
    }

    #[test]
    fn pem_paths_refuse_an_empty_path_and_a_relative_parent() {
        assert_eq!(
            PemPath::parse("").unwrap_err().to_string(),
            "is empty; remove the key or name a file"
        );
        assert_eq!(
            PemPath::parse("../c.pem").unwrap_err().to_string(),
            "../c.pem has a `..` component, which a relative path in a config cannot have"
        );
        assert_eq!(
            PemPath::parse(r"\q").unwrap_err().to_string(),
            r"invalid escape '\q'"
        );
        let path = PemPath::parse(r"\sc.pem").unwrap();
        assert_eq!(path.as_path(), Path::new(" c.pem"));
        round_trips(path);
        round_trips(PemPath::try_from("/etc/../c.pem").unwrap());
        assert_eq!(
            PemPath::try_from("~/c.pem").map(PemPath::into_string),
            Ok("~/c.pem".to_owned())
        );
    }

    #[test]
    fn positive_integers_and_upload_streams_keep_their_bounds() {
        assert_eq!(PositiveInt::parse("1").map(PositiveInt::get), Ok(1));
        assert_eq!(
            PositiveInt::parse("9223372036854775807").map(PositiveInt::get),
            Ok(9_223_372_036_854_775_807)
        );
        for bad in ["0", "-1", "-9223372036854775808"] {
            assert_eq!(
                PositiveInt::parse(bad).unwrap_err().to_string(),
                format!("is {bad}; the value is a positive integer")
            );
        }
        for bad in ["9223372036854775808", "+1", "1 ", "x", ""] {
            assert_eq!(
                PositiveInt::parse(bad).unwrap_err().to_string(),
                "is not an integer",
                "{bad:?}"
            );
        }
        round_trips(PositiveInt::try_from(1).unwrap());
        round_trips(PositiveInt::try_from(i64::MAX).unwrap());

        assert_eq!(UploadStreams::parse("1").map(UploadStreams::get), Ok(1));
        assert_eq!(UploadStreams::parse("31").map(UploadStreams::get), Ok(31));
        for bad in ["0", "32", "-1", "4294967297"] {
            assert_eq!(
                UploadStreams::parse(bad).unwrap_err().to_string(),
                format!("is {bad}; the value is 1 to 31")
            );
        }
        assert_eq!(
            UploadStreams::parse("0x4").unwrap_err().to_string(),
            "is not an integer"
        );
        for n in [1, 16, 31] {
            round_trips(UploadStreams::try_from(n).unwrap());
        }
    }

    #[test]
    fn key_group_names_drop_a_repeated_name() {
        let names = KeyGroupNames::parse("b;a;b;").unwrap();
        assert_eq!(names.names(), ["b", "a"]);
        let names = KeyGroupNames::parse("c;a;c;b;a;c;").unwrap();
        assert_eq!(names.names(), ["c", "a", "b"]);
        round_trips(names);
        let names = KeyGroupNames::parse(";").unwrap();
        assert_eq!(names.names(), [""]);
        round_trips(names);
        round_trips(KeyGroupNames::try_from(vec!["a;b".to_owned(), " c".to_owned()]).unwrap());
        assert_eq!(
            KeyGroupNames::parse("").unwrap_err().to_string(),
            "is empty; remove the key or name a key group"
        );
        assert_eq!(
            KeyGroupNames::parse(r"k\q").unwrap_err().to_string(),
            r"invalid escape '\q'"
        );
        assert_eq!(
            KeyGroupNames::try_from(Vec::new()).unwrap_err().to_string(),
            "is empty; remove the key or name a key group"
        );
    }

    #[test]
    fn collection_id_lists_are_checked() {
        assert_eq!(
            CollectionIdList::parse("org.ex.B;org.ex.A;org.ex.B;").map(CollectionIdList::into_ids),
            Ok(vec!["org.ex.B".to_owned(), "org.ex.A".to_owned()])
        );
        assert_eq!(
            CollectionIdList::parse("").unwrap_err().to_string(),
            "holds no collection id"
        );
        for (raw, id) in [(";", ""), ("org.ex.A;;org.ex.B", ""), ("org/ex", "org/ex")] {
            assert_eq!(
                CollectionIdList::parse(raw).unwrap_err().to_string(),
                format!("holds the invalid collection id '{id}'"),
                "{raw:?}"
            );
        }
        assert!(CollectionIdList::parse(r"org.ex.A\q").is_err());
        round_trips(CollectionIdList::parse("org.ex.A;org.ex.B").unwrap());
    }

    #[test]
    fn auth_items_drop_a_repeated_item() {
        let items =
            AuthItems::parse("ssh:a;anonymous;ssh:a;net:2001:db8::/56;net:2001:0db8::/56").unwrap();
        let texts: Vec<String> = items.items().iter().map(AuthItem::to_string).collect();
        assert_eq!(texts, ["ssh:a", "anonymous", "net:2001:db8::/56"]);
        assert_eq!(items.format(), "ssh:a;anonymous;net:2001:db8::/56;");
        round_trips(items);
        let items = AuthItems::parse("").unwrap();
        assert!(items.items().is_empty());
        round_trips(items);
        round_trips(AuthItems::parse(r"ssh:a\;b;tls:x\sy").unwrap());
        let forms = "the item is anonymous, tls:*, tls:NAME, tls-sha256:HEX, \
                     token-sha256:HEX, basic-sha256:USER:HEX, ssh:NAME, or net:CIDR";
        for (raw, text) in [("bogus", "bogus"), (";", ""), ("anonymous;;ssh:a", "")] {
            assert_eq!(
                AuthItems::parse(raw).unwrap_err().to_string(),
                format!("malformed item '{text}': {forms}"),
                "{raw:?}"
            );
        }
        assert_eq!(
            AuthItems::parse("ssh: b").unwrap_err().to_string(),
            "malformed item 'ssh: b': the NAME of ssh:NAME is not empty, holds no control \
             character, and does not start or end with white space"
        );
        assert_eq!(
            AuthItems::parse(r"a\q").unwrap_err().to_string(),
            r"invalid escape '\q'"
        );
    }

    #[test]
    fn allow_items_keep_each_entry_and_its_collection() {
        let items = AllowItems::parse("os/**;rw:os/x;@a.b:y;wd:@a.b:z;os/**").unwrap();
        let entries: Vec<(Option<&str>, String)> = items
            .entries()
            .map(|(id, item)| (id, item.to_string()))
            .collect();
        assert_eq!(
            entries,
            [
                (None, "r:os/**".to_owned()),
                (None, "rw:os/x".to_owned()),
                (Some("a.b"), "r:y".to_owned()),
                (Some("a.b"), "wd:z".to_owned()),
                (None, "r:os/**".to_owned()),
            ]
        );
        assert_eq!(
            items.format(),
            "r:os/**;rw:os/x;r:@a.b:y;wd:@a.b:z;r:os/**;"
        );
        round_trips(items);
        round_trips(AllowItems::default());
        assert_eq!(AllowItems::default().format(), "");
        assert_eq!(AllowItems::parse("").unwrap(), AllowItems::default());
        for (raw, why) in [
            ("R:a", "the modes are one or more of r, w, c, t, and d"),
            ("rr:a", "each mode occurs at most one time"),
            ("@a.b", "a collection id is @ID: before the pattern"),
            ("@fresh:a", "the collection id fails the collection-id rule"),
        ] {
            assert_eq!(
                AllowItems::parse(raw).unwrap_err().to_string(),
                format!("malformed item '{raw}': {why}"),
                "{raw:?}"
            );
        }
        assert_eq!(
            AllowItems::parse(r"a\").unwrap_err().to_string(),
            "value ends with a lone backslash"
        );
    }

    #[test]
    fn deny_items_keep_each_entry_and_its_collection() {
        let items = DenyItems::parse("os/secret/**;@a.b:x;y;y").unwrap();
        let entries: Vec<(Option<&str>, &str)> = items
            .entries()
            .map(|(id, pattern)| (id, pattern.as_str()))
            .collect();
        assert_eq!(
            entries,
            [
                (None, "os/secret/**"),
                (Some("a.b"), "x"),
                (None, "y"),
                (None, "y")
            ]
        );
        assert_eq!(items.format(), "os/secret/**;@a.b:x;y;y;");
        round_trips(items);
        round_trips(DenyItems::default());
        for (raw, why) in [
            ("@a.b", "a collection id is @ID: before the pattern"),
            ("@1a.b:a", "the collection id fails the collection-id rule"),
        ] {
            assert_eq!(
                DenyItems::parse(raw).unwrap_err().to_string(),
                format!("malformed item '{raw}': {why}"),
                "{raw:?}"
            );
        }
        assert!(
            DenyItems::parse("r:a")
                .unwrap_err()
                .to_string()
                .starts_with("malformed item 'r:a': ")
        );
        assert_eq!(
            DenyItems::parse(r"a\q").unwrap_err().to_string(),
            r"invalid escape '\q'"
        );
    }

    #[test]
    fn a_trust_ref_takes_trust_name_alone() {
        let verify = TrustRef::parse("trust:ci").unwrap();
        assert_eq!(verify.group().name(), "ci");
        round_trips(verify);
        let verify = TrustRef::parse(r"trust:a\sb").unwrap();
        assert_eq!(verify.group().name(), "a b");
        assert_eq!(verify.format(), "trust:a b");
        round_trips(verify);
        round_trips(TrustRef::from(GroupRef::new(" a;b").unwrap()));
        let other = "the value is trust:NAME; leave out the key for no verification";
        for (raw, text) in [
            ("off", "off"),
            ("", ""),
            ("trust:", "trust:"),
            ("t", "t"),
            ("Trust:t", "Trust:t"),
            (r"of\sf", "of f"),
        ] {
            assert_eq!(
                TrustRef::parse(raw).unwrap_err().to_string(),
                format!("malformed value '{text}': {other}"),
                "{raw:?}"
            );
        }
        assert_eq!(
            TrustRef::parse("remote:origin").unwrap_err().to_string(),
            "malformed value 'remote:origin': the remote:NAME form is removed; name a trust \
             group with trust:NAME"
        );
        assert_eq!(
            TrustRef::parse(r"trust:\q").unwrap_err().to_string(),
            r"invalid escape '\q'"
        );
    }
}