rustango 0.43.1

Django-shaped batteries-included web framework for Rust: ORM + migrations + auto-admin + multi-tenancy + audit log + auth (sessions, JWT, OAuth2/OIDC, HMAC) + APIs (ViewSet, OpenAPI auto-derive, JSON:API) + jobs (in-mem + Postgres) + email + media (S3 / R2 / B2 / MinIO + presigned uploads + collections + tags) + production middleware (CSRF, CSP, rate-limiting, compression, idempotency, etc.).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
//! Django-shape standalone validators. Issue #54.
//!
//! Lightweight check functions that mirror Django's
//! `django.core.validators` module. Each returns `Result<(),
//! ValidationError>` so they compose with `?` inside `Form::clean()`
//! or any other input-validation flow.
//!
//! ```ignore
//! use rustango::validators::{validate_email, validate_url, validate_slug};
//!
//! pub fn clean_contact(email: &str, website: &str, handle: &str) -> Result<(), ValidationError> {
//!     validate_email(email)?;
//!     validate_url(website)?;
//!     validate_slug(handle)?;
//!     Ok(())
//! }
//! ```
//!
//! ## Scope
//!
//! Hand-rolled checks (no `regex` crate dependency) — fast, allocation-free,
//! and cover the 99% case. The character-class checks here match
//! Django's defaults for the typical web form:
//!
//! - `validate_email` — basic shape check (local-part `@` domain `.` tld).
//!   NOT RFC 5322. Catches typos like missing `@` or empty parts.
//! - `validate_url` — accepts `http://` / `https://` schemes with a
//!   non-empty host. Optional port + path + query.
//! - `validate_slug` — `[a-zA-Z0-9_-]+`. Django's `slug_re`.
//! - `validate_unicode_slug` — letters of any script + digits + `_` + `-`.
//!   Django's unicode-aware `UnicodeSlugValidator`.
//! - `validate_prohibit_null_characters` — reject strings containing
//!   NUL (`\0`). Mirrors Django's `ProhibitNullCharactersValidator`,
//!   used at form-input boundaries to block null-byte injection.
//! - `validate_min_length` / `validate_max_length` — string char count.
//! - `validate_min_value` / `validate_max_value` — i64 numeric bounds.
//! - `validate_min_value_f64` / `validate_max_value_f64` — float
//!   bounds, for prices / measurements / scientific values that
//!   don't fit `i64`.
//! - `validate_integer` — parses as `i64`.
//! - `validate_decimal` — `max_digits` + `decimal_places` bounds
//!   (Django's `DecimalValidator`).
//! - `validate_file_size_max` / `validate_file_mime_type` —
//!   Django-shape file-upload size + MIME allowlist checks.
//! - `validate_step_value` — Django's `StepValueValidator` —
//!   `n == offset + k*step` for non-negative integer `k`.
//! - `validate_ipv4_address` / `validate_ipv6_address` — dotted-quad /
//!   colon-hex address shape via `std::net::Ipv4Addr` / `Ipv6Addr`.
//! - `validate_comma_separated_integer_list` — `"1,2,3"`. Django's
//!   `validate_comma_separated_integer_list`.
//! - `validate_email_list` — comma-separated list of email addresses,
//!   one per "CC" field entry.
//! - `validate_phone_e164` — E.164 international phone format
//!   (`+` followed by 1–15 digits). Not a Django built-in but
//!   widely needed in the same role.
//! - `validate_hex_color` — `#rgb` / `#rrggbb` / `#rrggbbaa` /
//!   `#rgba` web-color hex codes. For color-picker form fields.
//! - `validate_uuid` — RFC 4122 UUID string format. Useful for
//!   handler argument validation when a path/query carries a UUID
//!   you want to validate before hitting the DB.
//! - `validate_iso_date` — ISO 8601 `YYYY-MM-DD` date.
//! - `validate_iso_time` — ISO 8601 `HH:MM:SS` time (optional
//!   fractional seconds).
//! - `validate_iso_datetime` — RFC 3339 / ISO 8601 datetime with
//!   timezone offset (`...Z` or `+HH:MM`).
//! - `validate_alphanumeric` — `[a-zA-Z0-9]+` ASCII only.
//! - `validate_numeric` — `[0-9]+` ASCII digits only.
//! - `validate_alpha` — `[a-zA-Z]+` ASCII letters only.
//! - `validate_creditcard_luhn` — Luhn checksum on a credit card
//!   PAN string. Catches typos before hitting the PCI processor;
//!   does NOT verify the card is real / not expired / has funds.
//! - `validate_isbn` — ISBN-10 or ISBN-13 checksum (auto-detects
//!   which form by digit count).
//! - `validate_hostname` — RFC 1123 hostname format. Each
//!   dot-separated label 1–63 chars, letters/digits/hyphens, no
//!   leading or trailing hyphen, total length ≤ 253.
//! - `validate_iban` — ISO 13616 IBAN mod-97 checksum (catches typos
//!   in bank account fields).
//! - `validate_mac_address` — EUI-48 MAC address (6 hex pairs
//!   separated by `:` or `-`).
//! - `validate_base64` — standard base64 (`[A-Za-z0-9+/]` +
//!   optional `=` padding).
//! - `validate_base64_urlsafe` — URL-safe base64 (`[A-Za-z0-9_-]`).
//! - `validate_jwt_shape` — three dot-separated URL-safe base64
//!   segments. Shape check only, NO signature verification.
//! - `validate_semver` — semantic version 2.0.0 (`MAJOR.MINOR.PATCH`
//!   with optional `-pre.release` and `+build` suffixes).
//! - `validate_country_code` — ISO 3166-1 alpha-2 country code
//!   (2 uppercase letters). Format-only; doesn't check the code
//!   exists.
//! - `validate_currency_code` — ISO 4217 currency code (3 uppercase
//!   letters). Format-only.
//! - `validate_language_tag` — BCP 47 light: `lang[-region]`
//!   (e.g. `en`, `en-US`, `fr-CA`, `zh-Hans`).
//! - `validate_postal_code_us` — US ZIP code in `12345` or
//!   `12345-6789` (ZIP+4) form.
//! - `validate_postal_code_ca` — Canadian postal code in `A1A 1A1`
//!   form (uppercase, single space).
//! - `validate_postal_code_uk` — UK postcode (`SW1A 1AA` shape;
//!   loose check on the well-formed cases).
//!
//! What's NOT here (yet):
//! - Locale-sensitive numeric formats.
//! - IDN / punycode email + URL support (the basic check accepts
//!   ASCII; non-ASCII domains are valid per RFC but the basic
//!   shape rejects them — file a follow-up if you actually need
//!   IDN forms).

/// One validation failure.
///
/// Carries a stable `code` (machine-readable, used to map to UI
/// localized strings) and a `message` (human-readable English
/// default). Forms typically forward both into a `FormErrors` entry.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidationError {
    /// Stable machine-readable code, e.g. `"invalid_email"`,
    /// `"min_length"`. Use to look up localized messages.
    pub code: &'static str,
    /// Default English message. Replace via the localization layer
    /// when surfacing to end users.
    pub message: String,
}

impl ValidationError {
    /// Construct a validation error with a code + message.
    #[must_use]
    pub fn new(code: &'static str, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
        }
    }
}

impl std::fmt::Display for ValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.message)
    }
}

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

// ------------------------------------------------------------------ email

/// Validate that `s` looks like an email address.
///
/// Basic shape check: a non-empty local part, exactly one `@`, a
/// non-empty domain containing at least one `.`, and a non-empty
/// TLD. **Not** RFC 5322 — catches typos (missing `@`, double dots)
/// but doesn't enforce the full grammar. For production-grade email
/// verification, send a confirmation email anyway.
///
/// # Errors
/// `ValidationError { code: "invalid_email", ... }` on shape mismatch.
pub fn validate_email(s: &str) -> Result<(), ValidationError> {
    let trimmed = s.trim();
    if trimmed.is_empty() {
        return Err(ValidationError::new(
            "invalid_email",
            "Enter a valid email address.",
        ));
    }
    let (local, domain) = match trimmed.split_once('@') {
        Some(parts) => parts,
        None => {
            return Err(ValidationError::new(
                "invalid_email",
                "Enter a valid email address.",
            ))
        }
    };
    if local.is_empty() || domain.is_empty() {
        return Err(ValidationError::new(
            "invalid_email",
            "Enter a valid email address.",
        ));
    }
    // Reject a SECOND @ — split_once gave us first occurrence;
    // any remaining @ in the domain is invalid.
    if domain.contains('@') {
        return Err(ValidationError::new(
            "invalid_email",
            "Enter a valid email address.",
        ));
    }
    // Domain must have a dot, and that dot can't be at either end
    // (".com" / "example." both invalid).
    if !domain.contains('.') || domain.starts_with('.') || domain.ends_with('.') {
        return Err(ValidationError::new(
            "invalid_email",
            "Enter a valid email address.",
        ));
    }
    // Reject consecutive dots in domain or local — common typo.
    if domain.contains("..") || local.contains("..") {
        return Err(ValidationError::new(
            "invalid_email",
            "Enter a valid email address.",
        ));
    }
    Ok(())
}

/// Boolean form of [`validate_email`]. Useful in `if` guards where
/// the caller doesn't need the error message.
#[must_use]
pub fn is_email(s: &str) -> bool {
    validate_email(s).is_ok()
}

/// Django-parity `validate_email_with_name(value)` — accepts both
/// a bare email (`user@host.tld`) and the RFC 5322 display-name form
/// (`"Display Name" <user@host.tld>` or `Display Name <user@host.tld>`).
///
/// Useful for `From:` / `To:` / `Cc:` header values where operators
/// may type the human-friendly form. Internally splits via
/// [`crate::email::parseaddr`] and forwards the address portion to
/// [`validate_email`].
///
/// ```ignore
/// use rustango::validators::validate_email_with_name;
/// assert!(validate_email_with_name("alice@example.com").is_ok());
/// assert!(validate_email_with_name("Alice <alice@example.com>").is_ok());
/// assert!(validate_email_with_name("\"Alice C.\" <alice@example.com>").is_ok());
/// assert!(validate_email_with_name("not an email").is_err());
/// ```
///
/// # Errors
/// `ValidationError { code: "invalid_email", ... }` if the email
/// portion (after stripping the optional display name) doesn't
/// pass [`validate_email`].
///
/// Gated on the `email` feature since the implementation routes
/// through `crate::email::parseaddr`. Operators on a non-`email`
/// build can still parse + validate manually by hand-rolling
/// the `Name <addr>` split themselves and passing the address
/// through [`validate_email`].
#[cfg(feature = "email")]
pub fn validate_email_with_name(s: &str) -> Result<(), ValidationError> {
    let (_name, address) = crate::email::parseaddr(s);
    validate_email(&address)
}

/// `true` when `s` would pass [`validate_email_with_name`].
#[cfg(feature = "email")]
#[must_use]
pub fn is_email_with_name(s: &str) -> bool {
    validate_email_with_name(s).is_ok()
}

// ------------------------------------------------------------------ url

/// Validate that `s` looks like an `http://` / `https://` URL.
///
/// Checks scheme + non-empty host. Doesn't validate path / query /
/// fragment beyond requiring well-formed UTF-8 (which is implicit
/// in `&str`).
///
/// # Errors
/// `ValidationError { code: "invalid_url", ... }`.
pub fn validate_url(s: &str) -> Result<(), ValidationError> {
    let trimmed = s.trim();
    if trimmed.is_empty() {
        return Err(ValidationError::new("invalid_url", "Enter a valid URL."));
    }
    let rest = if let Some(r) = trimmed.strip_prefix("https://") {
        r
    } else if let Some(r) = trimmed.strip_prefix("http://") {
        r
    } else {
        return Err(ValidationError::new("invalid_url", "Enter a valid URL."));
    };
    // Host portion: everything up to the first '/', '?', or '#'.
    let host_end = rest
        .find(|c: char| c == '/' || c == '?' || c == '#')
        .unwrap_or(rest.len());
    let host = &rest[..host_end];
    if host.is_empty() || host.starts_with(':') {
        return Err(ValidationError::new("invalid_url", "Enter a valid URL."));
    }
    // Strip optional :port off the host and require a hostname part.
    let hostname = host.split(':').next().unwrap_or(host);
    if hostname.is_empty() {
        return Err(ValidationError::new("invalid_url", "Enter a valid URL."));
    }
    Ok(())
}

/// Boolean form of [`validate_url`].
#[must_use]
pub fn is_url(s: &str) -> bool {
    validate_url(s).is_ok()
}

// ------------------------------------------------------------------ slug

/// Validate that `s` is a Django-shape slug: `[a-zA-Z0-9_-]+`, no
/// other characters, must be non-empty.
///
/// # Errors
/// `ValidationError { code: "invalid_slug", ... }`.
pub fn validate_slug(s: &str) -> Result<(), ValidationError> {
    if s.is_empty() {
        return Err(ValidationError::new(
            "invalid_slug",
            "Enter a valid slug consisting of letters, numbers, underscores or hyphens.",
        ));
    }
    for ch in s.chars() {
        let ok = ch.is_ascii_alphanumeric() || ch == '_' || ch == '-';
        if !ok {
            return Err(ValidationError::new(
                "invalid_slug",
                "Enter a valid slug consisting of letters, numbers, underscores or hyphens.",
            ));
        }
    }
    Ok(())
}

/// Boolean form of [`validate_slug`].
#[must_use]
pub fn is_slug(s: &str) -> bool {
    validate_slug(s).is_ok()
}

/// Validate a unicode-aware slug. Allows any Unicode alphanumeric
/// character plus `_` and `-`. Mirrors Django's
/// `validate_unicode_slug`, which is the variant Django falls back
/// to under `SLUG_VALIDATOR = UnicodeSlugValidator` (set via the
/// `Field(allow_unicode=True)` shape).
///
/// # Errors
/// `ValidationError { code: "invalid_unicode_slug", ... }`.
pub fn validate_unicode_slug(s: &str) -> Result<(), ValidationError> {
    if s.is_empty() {
        return Err(ValidationError::new(
            "invalid_unicode_slug",
            "Enter a valid slug consisting of Unicode letters, numbers, underscores or hyphens.",
        ));
    }
    for ch in s.chars() {
        let ok = ch.is_alphanumeric() || ch == '_' || ch == '-';
        if !ok {
            return Err(ValidationError::new(
                "invalid_unicode_slug",
                "Enter a valid slug consisting of Unicode letters, numbers, underscores or hyphens.",
            ));
        }
    }
    Ok(())
}

/// Boolean form of [`validate_unicode_slug`].
#[must_use]
pub fn is_unicode_slug(s: &str) -> bool {
    validate_unicode_slug(s).is_ok()
}

// ------------------------------------------------------------------ null-character guard

/// Reject strings containing NUL (`\0`). Mirrors Django's
/// `ProhibitNullCharactersValidator`. Null bytes inside user input
/// are a known injection vector against C-string-aware downstream
/// systems (database drivers, file paths, syscalls) and almost
/// never represent legitimate user intent — Django runs this
/// validator on every CharField by default.
///
/// # Errors
/// `ValidationError { code: "null_characters_not_allowed", ... }`.
pub fn validate_prohibit_null_characters(s: &str) -> Result<(), ValidationError> {
    if s.contains('\0') {
        return Err(ValidationError::new(
            "null_characters_not_allowed",
            "Null characters are not allowed.",
        ));
    }
    Ok(())
}

// ------------------------------------------------------------------ phone (E.164)

/// Validate an [E.164](https://en.wikipedia.org/wiki/E.164)
/// international phone number: a `+` followed by 1 to 15 ASCII
/// digits, no other characters. This is the format every modern
/// phone API (Twilio, AWS SNS, Vonage) expects.
///
/// Not a Django built-in — Django delegates phone validation to
/// the `django-phonenumber-field` package which depends on
/// `phonenumbers` (the Google libphonenumber port). E.164 is a
/// reasonable lowest-common-denominator that doesn't require a
/// 20MB country-codes database. For full national-format /
/// region-aware parsing, plug a `phonenumbers`-backed validator
/// alongside this one.
///
/// Examples:
/// - `validate_phone_e164("+14155552671")` → `Ok(())`
/// - `validate_phone_e164("+442012345678")` → `Ok(())`
/// - `validate_phone_e164("415-555-2671")` → `Err(invalid_phone)` (no `+`)
/// - `validate_phone_e164("+1")` → `Ok(())` (1 digit is the minimum)
/// - `validate_phone_e164("+0123456789012345")` → `Err(invalid_phone)` (16 digits)
///
/// # Errors
/// `ValidationError { code: "invalid_phone", ... }`.
pub fn validate_phone_e164(s: &str) -> Result<(), ValidationError> {
    let rest = match s.strip_prefix('+') {
        Some(r) => r,
        None => {
            return Err(ValidationError::new(
                "invalid_phone",
                "Enter a phone number in E.164 format (e.g. +14155552671).",
            ));
        }
    };
    let len = rest.len();
    if !(1..=15).contains(&len) {
        return Err(ValidationError::new(
            "invalid_phone",
            "Enter a phone number in E.164 format (e.g. +14155552671).",
        ));
    }
    if !rest.chars().all(|c| c.is_ascii_digit()) {
        return Err(ValidationError::new(
            "invalid_phone",
            "Enter a phone number in E.164 format (e.g. +14155552671).",
        ));
    }
    Ok(())
}

/// Boolean form of [`validate_phone_e164`].
#[must_use]
pub fn is_phone_e164(s: &str) -> bool {
    validate_phone_e164(s).is_ok()
}

// ------------------------------------------------------------------ hex color

/// Validate a web-color hex code: `#rgb`, `#rrggbb`, `#rgba`, or
/// `#rrggbbaa`. The `#` prefix is required; hex digits are
/// case-insensitive. Anything else (named colors, `rgb()` /
/// `hsl()` functions, hex without `#`) is rejected.
///
/// Useful for color-picker form fields in admin / theme-config
/// surfaces. Pair with [`validate_max_length`] to bound the input
/// to 9 characters total.
///
/// Examples:
/// - `validate_hex_color("#fff")` → `Ok(())`
/// - `validate_hex_color("#ffaabb")` → `Ok(())`
/// - `validate_hex_color("#FFAA00CC")` → `Ok(())` (8 = with alpha)
/// - `validate_hex_color("fff")` → `Err` (missing `#`)
/// - `validate_hex_color("#ffffg")` → `Err` (`g` not hex)
/// - `validate_hex_color("#ffff")` → `Err` (4 chars: only valid
///   shorthand is 3 / 6 / 4 / 8)
///
/// # Errors
/// `ValidationError { code: "invalid_hex_color", ... }`.
pub fn validate_hex_color(s: &str) -> Result<(), ValidationError> {
    let rest = match s.strip_prefix('#') {
        Some(r) => r,
        None => {
            return Err(ValidationError::new(
                "invalid_hex_color",
                "Enter a hex color like `#fff` or `#ffaa00`.",
            ));
        }
    };
    if !matches!(rest.len(), 3 | 4 | 6 | 8) {
        return Err(ValidationError::new(
            "invalid_hex_color",
            "Enter a hex color like `#fff` or `#ffaa00`.",
        ));
    }
    if !rest.chars().all(|c| c.is_ascii_hexdigit()) {
        return Err(ValidationError::new(
            "invalid_hex_color",
            "Enter a hex color like `#fff` or `#ffaa00`.",
        ));
    }
    Ok(())
}

/// Boolean form of [`validate_hex_color`].
#[must_use]
pub fn is_hex_color(s: &str) -> bool {
    validate_hex_color(s).is_ok()
}

// ------------------------------------------------------------------ uuid

/// Validate a UUID string in any of the formats `uuid::Uuid::parse_str`
/// accepts (hyphenated, simple, URN, or braced). Backs onto the
/// `uuid` crate so the accepted shapes match the rest of rustango.
///
/// Useful for handler argument validation when a path / query
/// parameter carries a UUID you want to validate before hitting the
/// DB — gives a clean `ValidationError` with a stable code instead
/// of a "no rows matched" 500 deeper in the stack.
///
/// Examples:
/// - `validate_uuid("550e8400-e29b-41d4-a716-446655440000")` → Ok
/// - `validate_uuid("550e8400e29b41d4a716446655440000")` → Ok (simple)
/// - `validate_uuid("urn:uuid:550e8400-e29b-41d4-a716-446655440000")` → Ok
/// - `validate_uuid("not-a-uuid")` → Err
///
/// # Errors
/// `ValidationError { code: "invalid_uuid", ... }`.
pub fn validate_uuid(s: &str) -> Result<(), ValidationError> {
    uuid::Uuid::parse_str(s)
        .map(|_| ())
        .map_err(|_| ValidationError::new("invalid_uuid", "Enter a valid UUID."))
}

/// Boolean form of [`validate_uuid`].
#[must_use]
pub fn is_uuid(s: &str) -> bool {
    validate_uuid(s).is_ok()
}

// ------------------------------------------------------------------ ISO 8601 date / time / datetime

/// Validate an ISO 8601 calendar date in `YYYY-MM-DD` format. Rejects
/// shorter / longer strings and out-of-range months / days (`Feb 30`,
/// month 13, day 0 etc.) via chrono's `NaiveDate::parse_from_str`.
///
/// # Errors
/// `ValidationError { code: "invalid_iso_date", ... }`.
pub fn validate_iso_date(s: &str) -> Result<(), ValidationError> {
    chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d")
        .map(|_| ())
        .map_err(|_| ValidationError::new("invalid_iso_date", "Enter a date in YYYY-MM-DD format."))
}

/// Validate an ISO 8601 wall-clock time in `HH:MM:SS` format,
/// optionally with fractional seconds (`HH:MM:SS.sss`). Rejects
/// out-of-range hours / minutes / seconds.
///
/// # Errors
/// `ValidationError { code: "invalid_iso_time", ... }`.
pub fn validate_iso_time(s: &str) -> Result<(), ValidationError> {
    // Accept "HH:MM:SS" and "HH:MM:SS.sss" — chrono parses both with
    // the %.f optional-fraction specifier.
    chrono::NaiveTime::parse_from_str(s, "%H:%M:%S%.f")
        .map(|_| ())
        .map_err(|_| ValidationError::new("invalid_iso_time", "Enter a time in HH:MM:SS format."))
}

/// Validate an RFC 3339 / ISO 8601 datetime with timezone offset
/// (`2026-01-15T14:30:00Z` or `2026-01-15T14:30:00+02:00`). The
/// timezone is REQUIRED — naive datetimes (no offset) are rejected
/// because mixing local-time and UTC values without a marker is a
/// classic data-corruption vector.
///
/// # Errors
/// `ValidationError { code: "invalid_iso_datetime", ... }`.
pub fn validate_iso_datetime(s: &str) -> Result<(), ValidationError> {
    chrono::DateTime::parse_from_rfc3339(s)
        .map(|_| ())
        .map_err(|_| {
            ValidationError::new(
                "invalid_iso_datetime",
                "Enter a datetime in RFC 3339 format (e.g. 2026-01-15T14:30:00Z).",
            )
        })
}

// ------------------------------------------------------------------ character-class predicates

/// Reject any input that contains characters outside
/// `[a-zA-Z0-9]`. Non-empty input required. ASCII only — for the
/// Unicode-aware variant use [`validate_unicode_slug`] (which adds
/// `_` / `-` to letters/digits).
///
/// # Errors
/// `ValidationError { code: "not_alphanumeric", ... }`.
pub fn validate_alphanumeric(s: &str) -> Result<(), ValidationError> {
    if s.is_empty() {
        return Err(ValidationError::new(
            "not_alphanumeric",
            "Enter only letters and digits.",
        ));
    }
    if !s.chars().all(|c| c.is_ascii_alphanumeric()) {
        return Err(ValidationError::new(
            "not_alphanumeric",
            "Enter only letters and digits.",
        ));
    }
    Ok(())
}

/// Reject any input that contains characters outside `[0-9]`.
/// Non-empty input required. No sign, no decimal point, no
/// underscores — use [`validate_integer`] for those.
///
/// # Errors
/// `ValidationError { code: "not_numeric", ... }`.
pub fn validate_numeric(s: &str) -> Result<(), ValidationError> {
    if s.is_empty() {
        return Err(ValidationError::new("not_numeric", "Enter only digits."));
    }
    if !s.chars().all(|c| c.is_ascii_digit()) {
        return Err(ValidationError::new("not_numeric", "Enter only digits."));
    }
    Ok(())
}

/// Reject any input that contains characters outside `[a-zA-Z]`.
/// Non-empty input required. ASCII only.
///
/// # Errors
/// `ValidationError { code: "not_alpha", ... }`.
pub fn validate_alpha(s: &str) -> Result<(), ValidationError> {
    if s.is_empty() {
        return Err(ValidationError::new("not_alpha", "Enter only letters."));
    }
    if !s.chars().all(|c| c.is_ascii_alphabetic()) {
        return Err(ValidationError::new("not_alpha", "Enter only letters."));
    }
    Ok(())
}

// ------------------------------------------------------------------ credit card (Luhn)

/// Verify the Luhn checksum on a credit-card-shape Primary Account
/// Number (PAN). Strips spaces and hyphens (the typical
/// human-typed shape), then checks that:
///
/// 1. Every remaining character is a digit.
/// 2. The total length is between 12 and 19 (current PAN range).
/// 3. The Luhn algorithm reports a valid trailing check digit.
///
/// **Scope**: catches typos before hitting the PCI processor. This
/// does NOT verify the card is real / unexpired / has funds — only
/// the upstream payment-gateway authorization can do that. Use as
/// a client-side sanity check, never as the only line of defence.
///
/// # Errors
/// `ValidationError { code: "invalid_card_number", ... }`.
pub fn validate_creditcard_luhn(s: &str) -> Result<(), ValidationError> {
    let cleaned: String = s
        .chars()
        .filter(|c| !c.is_whitespace() && *c != '-')
        .collect();
    if !cleaned.chars().all(|c| c.is_ascii_digit()) {
        return Err(ValidationError::new(
            "invalid_card_number",
            "Enter a valid credit card number.",
        ));
    }
    if !(12..=19).contains(&cleaned.len()) {
        return Err(ValidationError::new(
            "invalid_card_number",
            "Enter a valid credit card number.",
        ));
    }
    // Luhn: walk digits right-to-left. Every second digit (starting
    // at the second from the right) is doubled; if the doubled value
    // is >= 10, sum its digits (which is equivalent to subtracting 9).
    // Total must be divisible by 10.
    let mut sum = 0u32;
    let mut double = false;
    for ch in cleaned.chars().rev() {
        let mut d = ch.to_digit(10).expect("digit-only by check above");
        if double {
            d *= 2;
            if d >= 10 {
                d -= 9;
            }
        }
        sum += d;
        double = !double;
    }
    if sum % 10 != 0 {
        return Err(ValidationError::new(
            "invalid_card_number",
            "Enter a valid credit card number.",
        ));
    }
    Ok(())
}

// ------------------------------------------------------------------ ISBN

/// Verify the checksum on an ISBN-10 or ISBN-13 string. Strips
/// spaces and hyphens (the typical printed shape), then dispatches
/// on digit count:
///
/// - **10 chars**: ISBN-10 form. First 9 must be digits; 10th may
///   be `0`–`9` or `X` (representing 10). Checksum:
///   `sum(i * d_i) mod 11 == 0` for i = 1..10.
/// - **13 chars**: ISBN-13 form. All digits. Checksum:
///   `sum(d_i * w_i) mod 10 == 0` where weights alternate
///   `1, 3, 1, 3, …`.
///
/// Anything else is rejected. Used by Library / catalog admin
/// pages to catch typoed ISBNs at form-input time before the row
/// hits the DB.
///
/// # Errors
/// `ValidationError { code: "invalid_isbn", ... }`.
pub fn validate_isbn(s: &str) -> Result<(), ValidationError> {
    let cleaned: String = s
        .chars()
        .filter(|c| !c.is_whitespace() && *c != '-')
        .collect();
    match cleaned.len() {
        10 => validate_isbn_10(&cleaned),
        13 => validate_isbn_13(&cleaned),
        _ => Err(ValidationError::new(
            "invalid_isbn",
            "Enter a valid ISBN-10 or ISBN-13.",
        )),
    }
}

fn validate_isbn_10(s: &str) -> Result<(), ValidationError> {
    // First 9 chars must be digits; last may be `X` for 10.
    let chars: Vec<char> = s.chars().collect();
    let mut sum = 0u32;
    for (i, &ch) in chars.iter().enumerate() {
        let digit = if i == 9 && (ch == 'X' || ch == 'x') {
            10
        } else if let Some(d) = ch.to_digit(10) {
            d
        } else {
            return Err(ValidationError::new(
                "invalid_isbn",
                "Enter a valid ISBN-10 or ISBN-13.",
            ));
        };
        // Weight = (i + 1) per the ISBN-10 spec.
        sum += digit * (u32::try_from(i).unwrap_or(0) + 1);
    }
    if sum % 11 != 0 {
        return Err(ValidationError::new(
            "invalid_isbn",
            "Enter a valid ISBN-10 or ISBN-13.",
        ));
    }
    Ok(())
}

fn validate_isbn_13(s: &str) -> Result<(), ValidationError> {
    if !s.chars().all(|c| c.is_ascii_digit()) {
        return Err(ValidationError::new(
            "invalid_isbn",
            "Enter a valid ISBN-10 or ISBN-13.",
        ));
    }
    let mut sum = 0u32;
    for (i, ch) in s.chars().enumerate() {
        let d = ch.to_digit(10).expect("digit-only by check above");
        // Alternating weights: 1, 3, 1, 3, ...
        let weight = if i.is_multiple_of(2) { 1 } else { 3 };
        sum += d * weight;
    }
    if sum % 10 != 0 {
        return Err(ValidationError::new(
            "invalid_isbn",
            "Enter a valid ISBN-10 or ISBN-13.",
        ));
    }
    Ok(())
}

// ------------------------------------------------------------------ hostname

/// Validate an RFC 1123 hostname: dot-separated labels, each label
/// 1–63 chars containing only ASCII letters / digits / hyphens, no
/// leading or trailing hyphen on any label, total length ≤ 253.
/// Empty string is rejected.
///
/// Suited for admin form fields that take a server hostname /
/// DNS name. Distinct from `validate_url` (which expects a scheme)
/// and `validate_ipv4_address` (which is for literal IPs).
///
/// Examples:
/// - `validate_hostname("example.com")` → Ok
/// - `validate_hostname("sub.example.co.uk")` → Ok
/// - `validate_hostname("localhost")` → Ok (single-label allowed)
/// - `validate_hostname("-bad.example.com")` → Err (leading `-`)
/// - `validate_hostname("very-long-label-that-exceeds-the-sixty-three-character-limit-XX.com")` → Err
/// - `validate_hostname("")` → Err
///
/// # Errors
/// `ValidationError { code: "invalid_hostname", ... }`.
pub fn validate_hostname(s: &str) -> Result<(), ValidationError> {
    if s.is_empty() || s.len() > 253 {
        return Err(ValidationError::new(
            "invalid_hostname",
            "Enter a valid hostname.",
        ));
    }
    // Reject leading/trailing dot at the whole-name level.
    if s.starts_with('.') || s.ends_with('.') {
        return Err(ValidationError::new(
            "invalid_hostname",
            "Enter a valid hostname.",
        ));
    }
    for label in s.split('.') {
        if label.is_empty() || label.len() > 63 {
            return Err(ValidationError::new(
                "invalid_hostname",
                "Enter a valid hostname.",
            ));
        }
        if label.starts_with('-') || label.ends_with('-') {
            return Err(ValidationError::new(
                "invalid_hostname",
                "Enter a valid hostname.",
            ));
        }
        if !label.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') {
            return Err(ValidationError::new(
                "invalid_hostname",
                "Enter a valid hostname.",
            ));
        }
    }
    Ok(())
}

// ------------------------------------------------------------------ IBAN

/// Validate an ISO 13616 IBAN (International Bank Account Number)
/// via the mod-97 check. Strips spaces (the typical printed
/// "GB82 WEST 1234 5698 7654 32" shape) before validating.
///
/// Format requirements:
/// - 2-letter ISO country code (uppercase).
/// - 2-digit check digits.
/// - 1–30 additional ASCII alphanumeric chars.
/// - Total length 5–34.
///
/// Algorithm:
/// 1. Move the first 4 chars to the end.
/// 2. Replace each letter with two digits: A=10, B=11, ..., Z=35.
/// 3. Treat the result as a single integer; mod 97 must equal 1.
///
/// This catches typos before hitting the bank-rails verification
/// API. Does NOT verify the account exists / has funds — only the
/// payment provider can do that.
///
/// # Errors
/// `ValidationError { code: "invalid_iban", ... }`.
pub fn validate_iban(s: &str) -> Result<(), ValidationError> {
    let cleaned: String = s.chars().filter(|c| !c.is_whitespace()).collect();
    if !(5..=34).contains(&cleaned.len()) {
        return Err(ValidationError::new("invalid_iban", "Enter a valid IBAN."));
    }
    let bytes = cleaned.as_bytes();
    // First 2 must be uppercase letters (country code), next 2 digits.
    if !bytes[0].is_ascii_uppercase()
        || !bytes[1].is_ascii_uppercase()
        || !bytes[2].is_ascii_digit()
        || !bytes[3].is_ascii_digit()
    {
        return Err(ValidationError::new("invalid_iban", "Enter a valid IBAN."));
    }
    // Remaining chars must be uppercase alphanumeric.
    if !bytes[4..]
        .iter()
        .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit())
    {
        return Err(ValidationError::new("invalid_iban", "Enter a valid IBAN."));
    }
    // Rearrange: move first 4 to end. Then convert letters → digits.
    let rearranged: String = cleaned[4..]
        .chars()
        .chain(cleaned[..4].chars())
        .flat_map(|c| {
            if c.is_ascii_digit() {
                vec![c]
            } else {
                let n = c as u32 - 'A' as u32 + 10;
                n.to_string().chars().collect()
            }
        })
        .collect();
    // mod-97 on a string of digits — fold from the left to avoid
    // overflowing u64 on the full 30+-digit number.
    let mut remainder: u64 = 0;
    for ch in rearranged.chars() {
        let d = ch.to_digit(10).expect("digit-only after letter map");
        remainder = (remainder * 10 + u64::from(d)) % 97;
    }
    if remainder != 1 {
        return Err(ValidationError::new("invalid_iban", "Enter a valid IBAN."));
    }
    Ok(())
}

// ------------------------------------------------------------------ MAC address

/// Validate an EUI-48 MAC address: six pairs of hex digits
/// separated by `:` or `-`. Case-insensitive. The separator must
/// be consistent across the string (no mix-and-match between `:`
/// and `-`).
///
/// Examples:
/// - `validate_mac_address("00:1A:2B:3C:4D:5E")` → Ok
/// - `validate_mac_address("00-1a-2b-3c-4d-5e")` → Ok (case-insensitive)
/// - `validate_mac_address("001A2B3C4D5E")` → Err (separators required)
/// - `validate_mac_address("00:1A:2B-3C:4D:5E")` → Err (mixed separators)
///
/// # Errors
/// `ValidationError { code: "invalid_mac_address", ... }`.
pub fn validate_mac_address(s: &str) -> Result<(), ValidationError> {
    // 6 pairs of hex digits + 5 separators = 17 chars exactly.
    if s.len() != 17 {
        return Err(ValidationError::new(
            "invalid_mac_address",
            "Enter a valid MAC address (e.g. 00:1A:2B:3C:4D:5E).",
        ));
    }
    // Detect the separator from position 2.
    let sep = s.as_bytes()[2] as char;
    if sep != ':' && sep != '-' {
        return Err(ValidationError::new(
            "invalid_mac_address",
            "Enter a valid MAC address (e.g. 00:1A:2B:3C:4D:5E).",
        ));
    }
    let parts: Vec<&str> = s.split(sep).collect();
    if parts.len() != 6 {
        return Err(ValidationError::new(
            "invalid_mac_address",
            "Enter a valid MAC address (e.g. 00:1A:2B:3C:4D:5E).",
        ));
    }
    for part in parts {
        if part.len() != 2 || !part.chars().all(|c| c.is_ascii_hexdigit()) {
            return Err(ValidationError::new(
                "invalid_mac_address",
                "Enter a valid MAC address (e.g. 00:1A:2B:3C:4D:5E).",
            ));
        }
    }
    Ok(())
}

// ------------------------------------------------------------------ base64

/// Validate that `s` is a well-formed standard base64 string:
/// characters from `[A-Za-z0-9+/]`, length a multiple of 4 after
/// optional `=` padding (at most two trailing `=`).
///
/// Doesn't decode the bytes — just checks the shape. Useful for
/// admin form fields capturing encoded secrets / tokens / blobs
/// where the caller will decode separately.
///
/// # Errors
/// `ValidationError { code: "invalid_base64", ... }`.
pub fn validate_base64(s: &str) -> Result<(), ValidationError> {
    validate_base64_impl(s, false)
}

/// Validate that `s` is a well-formed URL-safe base64 string:
/// characters from `[A-Za-z0-9_-]`, length a multiple of 4 after
/// optional `=` padding (or, by RFC 4648 convention, padding may
/// be omitted in URL-safe encoding — we accept either).
///
/// # Errors
/// `ValidationError { code: "invalid_base64", ... }`.
pub fn validate_base64_urlsafe(s: &str) -> Result<(), ValidationError> {
    validate_base64_impl(s, true)
}

fn validate_base64_impl(s: &str, urlsafe: bool) -> Result<(), ValidationError> {
    if s.is_empty() {
        return Err(ValidationError::new(
            "invalid_base64",
            "Enter a valid base64 string.",
        ));
    }
    // Trailing padding count.
    let pad = s.bytes().rev().take_while(|b| *b == b'=').count();
    if pad > 2 {
        return Err(ValidationError::new(
            "invalid_base64",
            "Enter a valid base64 string.",
        ));
    }
    let body = &s[..s.len() - pad];
    // Body must contain no `=`. Body chars must be in the right
    // alphabet.
    for ch in body.chars() {
        let ok = ch.is_ascii_alphanumeric()
            || (if urlsafe {
                ch == '-' || ch == '_'
            } else {
                ch == '+' || ch == '/'
            });
        if !ok {
            return Err(ValidationError::new(
                "invalid_base64",
                "Enter a valid base64 string.",
            ));
        }
    }
    // Standard base64 with padding: total length multiple of 4.
    // URL-safe base64 without padding: any length is fine PROVIDED
    // there's no padding present. URL-safe WITH padding follows the
    // standard rule.
    if (pad > 0 || !urlsafe) && !s.len().is_multiple_of(4) {
        return Err(ValidationError::new(
            "invalid_base64",
            "Enter a valid base64 string.",
        ));
    }
    Ok(())
}

// ------------------------------------------------------------------ JWT shape

/// Validate that `s` looks like a JWT: three URL-safe base64 segments
/// separated by `.`, each non-empty.
///
/// **Shape check only — does NOT verify the signature.** The whole
/// point of this validator is to catch a typoed / truncated JWT at
/// form-input time before the real JWT library returns a less clear
/// error. Use [`crate::auth`] / `jsonwebtoken` to actually verify
/// the signature and claims.
///
/// # Errors
/// `ValidationError { code: "invalid_jwt", ... }`.
pub fn validate_jwt_shape(s: &str) -> Result<(), ValidationError> {
    let parts: Vec<&str> = s.split('.').collect();
    if parts.len() != 3 {
        return Err(ValidationError::new(
            "invalid_jwt",
            "Enter a valid JWT (header.payload.signature).",
        ));
    }
    for part in &parts {
        if part.is_empty() {
            return Err(ValidationError::new(
                "invalid_jwt",
                "Enter a valid JWT (header.payload.signature).",
            ));
        }
        // Each part is unpadded URL-safe base64.
        validate_base64_urlsafe(part).map_err(|_| {
            ValidationError::new(
                "invalid_jwt",
                "Enter a valid JWT (header.payload.signature).",
            )
        })?;
    }
    Ok(())
}

// ------------------------------------------------------------------ semver

/// Validate a [Semantic Versioning 2.0.0](https://semver.org/spec/v2.0.0.html)
/// version string: `MAJOR.MINOR.PATCH` with optional `-pre.release`
/// and `+build.metadata` suffixes.
///
/// Rules:
/// - MAJOR / MINOR / PATCH are non-negative integers. Leading zeros
///   are forbidden except the bare `0` itself.
/// - Pre-release: dot-separated identifiers, each non-empty,
///   `[0-9A-Za-z-]`. Numeric identifiers must not have leading
///   zeros (except `0`).
/// - Build metadata: dot-separated identifiers, each non-empty,
///   `[0-9A-Za-z-]`. Numeric leading zeros ARE allowed (per spec).
///
/// Examples:
/// - `validate_semver("1.0.0")` → Ok
/// - `validate_semver("1.0.0-alpha.1")` → Ok
/// - `validate_semver("1.0.0+20240101")` → Ok
/// - `validate_semver("1.0.0-rc.1+build.42")` → Ok
/// - `validate_semver("1.0")` → Err (missing patch)
/// - `validate_semver("01.0.0")` → Err (leading zero in major)
/// - `validate_semver("1.0.0-")` → Err (empty pre-release)
///
/// # Errors
/// `ValidationError { code: "invalid_semver", ... }`.
pub fn validate_semver(s: &str) -> Result<(), ValidationError> {
    let bad = || ValidationError::new("invalid_semver", "Enter a valid semver (e.g. 1.2.3).");
    // Split off build metadata (after first `+`).
    let (core_pre, build) = match s.split_once('+') {
        Some((cp, b)) => (cp, Some(b)),
        None => (s, None),
    };
    // Split off pre-release (after first `-`).
    let (core, pre) = match core_pre.split_once('-') {
        Some((c, p)) => (c, Some(p)),
        None => (core_pre, None),
    };
    // Core: exactly three dot-separated non-negative-integer
    // identifiers with no leading zeros.
    let core_parts: Vec<&str> = core.split('.').collect();
    if core_parts.len() != 3 {
        return Err(bad());
    }
    for part in core_parts {
        if !is_valid_numeric_id(part) {
            return Err(bad());
        }
    }
    if let Some(p) = pre {
        if !is_valid_semver_id_list(p, /* allow_numeric_leading_zero = */ false) {
            return Err(bad());
        }
    }
    if let Some(b) = build {
        // Build metadata identifiers may have leading zeros.
        if !is_valid_semver_id_list(b, /* allow_numeric_leading_zero = */ true) {
            return Err(bad());
        }
    }
    Ok(())
}

fn is_valid_numeric_id(s: &str) -> bool {
    if s.is_empty() {
        return false;
    }
    if !s.chars().all(|c| c.is_ascii_digit()) {
        return false;
    }
    // No leading zero unless the value IS "0".
    !(s.len() > 1 && s.starts_with('0'))
}

fn is_valid_semver_id_list(s: &str, allow_numeric_leading_zero: bool) -> bool {
    if s.is_empty() {
        return false;
    }
    for part in s.split('.') {
        if part.is_empty() {
            return false;
        }
        if !part.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') {
            return false;
        }
        // Numeric-only identifier without leading-zero permission?
        if !allow_numeric_leading_zero
            && part.chars().all(|c| c.is_ascii_digit())
            && part.len() > 1
            && part.starts_with('0')
        {
            return false;
        }
    }
    true
}

// ------------------------------------------------------------------ ISO country / currency codes

/// Validate an ISO 3166-1 alpha-2 country code: exactly 2 uppercase
/// ASCII letters (`US`, `GB`, `DE`, `JP`, ...). Format-only — does
/// NOT check that the code corresponds to a real country (that
/// would need an embedded list of 249 codes maintained against
/// every ISO update).
///
/// # Errors
/// `ValidationError { code: "invalid_country_code", ... }`.
pub fn validate_country_code(s: &str) -> Result<(), ValidationError> {
    if s.len() != 2 || !s.chars().all(|c| c.is_ascii_uppercase()) {
        return Err(ValidationError::new(
            "invalid_country_code",
            "Enter a 2-letter ISO 3166-1 country code (e.g. US, GB).",
        ));
    }
    Ok(())
}

/// Validate an ISO 4217 currency code: exactly 3 uppercase ASCII
/// letters (`USD`, `EUR`, `GBP`, `JPY`, ...). Format-only — does
/// NOT check that the code corresponds to a circulating currency.
///
/// # Errors
/// `ValidationError { code: "invalid_currency_code", ... }`.
pub fn validate_currency_code(s: &str) -> Result<(), ValidationError> {
    if s.len() != 3 || !s.chars().all(|c| c.is_ascii_uppercase()) {
        return Err(ValidationError::new(
            "invalid_currency_code",
            "Enter a 3-letter ISO 4217 currency code (e.g. USD, EUR).",
        ));
    }
    Ok(())
}

/// Validate a [BCP 47](https://tools.ietf.org/html/bcp47)-shape
/// language tag in its most common forms:
/// - `lang` — 2 or 3 lowercase letters (ISO 639-1 / 639-2).
/// - `lang-REGION` — 2-letter region (`en-US`, `fr-CA`).
/// - `lang-Script` — 4-letter Title-case script subtag
///   (`zh-Hans`, `sr-Cyrl`).
/// - `lang-Script-REGION` — both (`zh-Hans-CN`).
/// - Numeric 3-digit UN region code in place of the 2-letter
///   region (`es-419` for Latin America).
///
/// **Subset only** — doesn't cover the full BCP 47 grammar (no
/// extensions, no private use, no variants beyond Script).
/// Doesn't validate that the language / region codes correspond
/// to real entries in the IANA registry — that needs an embedded
/// list.
///
/// Examples:
/// - `validate_language_tag("en")` → Ok
/// - `validate_language_tag("en-US")` → Ok
/// - `validate_language_tag("fr-CA")` → Ok
/// - `validate_language_tag("zh-Hans-CN")` → Ok
/// - `validate_language_tag("es-419")` → Ok
/// - `validate_language_tag("EN")` → Err (uppercase lang)
/// - `validate_language_tag("en-us")` → Err (lowercase region)
/// - `validate_language_tag("english")` → Err (too long)
///
/// # Errors
/// `ValidationError { code: "invalid_language_tag", ... }`.
pub fn validate_language_tag(s: &str) -> Result<(), ValidationError> {
    let bad = || {
        ValidationError::new(
            "invalid_language_tag",
            "Enter a valid language tag (e.g. en, en-US, zh-Hans-CN).",
        )
    };
    let parts: Vec<&str> = s.split('-').collect();
    if parts.is_empty() || parts.len() > 3 {
        return Err(bad());
    }
    // Part 0: language subtag — 2 or 3 lowercase letters.
    let lang = parts[0];
    if !(2..=3).contains(&lang.len()) || !lang.chars().all(|c| c.is_ascii_lowercase()) {
        return Err(bad());
    }
    let mut idx = 1;
    // Optional script subtag — 4 letters, Title-case (Xxxx).
    if idx < parts.len() {
        let p = parts[idx];
        if p.len() == 4 && is_script_subtag(p) {
            idx += 1;
        }
    }
    // Optional region subtag — 2 uppercase letters OR 3 digits.
    if idx < parts.len() {
        let p = parts[idx];
        let is_alpha2 = p.len() == 2 && p.chars().all(|c| c.is_ascii_uppercase());
        let is_num3 = p.len() == 3 && p.chars().all(|c| c.is_ascii_digit());
        if !is_alpha2 && !is_num3 {
            return Err(bad());
        }
        idx += 1;
    }
    if idx != parts.len() {
        return Err(bad());
    }
    Ok(())
}

fn is_script_subtag(s: &str) -> bool {
    if s.len() != 4 {
        return false;
    }
    let mut chars = s.chars();
    let first = chars.next().unwrap();
    if !first.is_ascii_uppercase() {
        return false;
    }
    chars.all(|c| c.is_ascii_lowercase())
}

// ------------------------------------------------------------------ postal code (US)

/// Validate a US ZIP code: either 5 digits (`94110`) or the
/// ZIP+4 form `12345-6789`. No other separators or formats are
/// accepted.
///
/// Examples:
/// - `validate_postal_code_us("94110")` → Ok
/// - `validate_postal_code_us("12345-6789")` → Ok
/// - `validate_postal_code_us("123456789")` → Err (need hyphen for +4)
/// - `validate_postal_code_us("9411")` → Err (too short)
/// - `validate_postal_code_us("94110-")` → Err (incomplete +4)
///
/// # Errors
/// `ValidationError { code: "invalid_postal_code", ... }`.
pub fn validate_postal_code_us(s: &str) -> Result<(), ValidationError> {
    let bad = || {
        ValidationError::new(
            "invalid_postal_code",
            "Enter a valid US ZIP code (12345 or 12345-6789).",
        )
    };
    match s.split_once('-') {
        Some((first, second)) => {
            if first.len() != 5 || second.len() != 4 {
                return Err(bad());
            }
            if !first.chars().all(|c| c.is_ascii_digit())
                || !second.chars().all(|c| c.is_ascii_digit())
            {
                return Err(bad());
            }
            Ok(())
        }
        None => {
            if s.len() != 5 || !s.chars().all(|c| c.is_ascii_digit()) {
                return Err(bad());
            }
            Ok(())
        }
    }
}

/// Validate a Canadian postal code: 6 characters in the
/// alternating letter-digit-letter-space-digit-letter-digit
/// pattern (`A1A 1A1`). Letters must be uppercase ASCII.
///
/// Per Canada Post, the letters D, F, I, O, Q, U are NOT used in
/// the first position; and W, Z are not used as the first letter.
/// This validator does the format check only — it doesn't reject
/// codes with those letters (they'd just never be issued; making
/// a typo here is worth catching, but a strict version is a
/// follow-up).
///
/// # Errors
/// `ValidationError { code: "invalid_postal_code", ... }`.
pub fn validate_postal_code_ca(s: &str) -> Result<(), ValidationError> {
    let bad = || {
        ValidationError::new(
            "invalid_postal_code",
            "Enter a valid Canadian postal code (A1A 1A1).",
        )
    };
    if s.len() != 7 {
        return Err(bad());
    }
    let bytes = s.as_bytes();
    let is_uppercase_letter = |b: u8| b.is_ascii_uppercase();
    let is_digit = |b: u8| b.is_ascii_digit();
    if !is_uppercase_letter(bytes[0])
        || !is_digit(bytes[1])
        || !is_uppercase_letter(bytes[2])
        || bytes[3] != b' '
        || !is_digit(bytes[4])
        || !is_uppercase_letter(bytes[5])
        || !is_digit(bytes[6])
    {
        return Err(bad());
    }
    Ok(())
}

/// Validate a UK postcode in the canonical `OUTWARD INWARD` shape:
/// 1-2 outward characters + space + 3 inward characters.
///
/// The detailed UK postcode rules (Royal Mail BS7666) have several
/// allowed patterns; this validator covers the common shapes:
/// - `A9 9AA` (e.g. `M1 1AA`)
/// - `A99 9AA` (`B33 8TH`)
/// - `AA9 9AA` (`CR2 6XH`)
/// - `AA99 9AA` (`DN55 1PT`)
/// - `A9A 9AA` (`W1A 1AA`)
/// - `AA9A 9AA` (`EC1A 1BB`)
///
/// The inward part is always digit-letter-letter; outward is 2-4
/// characters mixing letters and digits per the patterns above.
/// Single mandatory space; letters must be uppercase.
///
/// # Errors
/// `ValidationError { code: "invalid_postal_code", ... }`.
pub fn validate_postal_code_uk(s: &str) -> Result<(), ValidationError> {
    let bad = || {
        ValidationError::new(
            "invalid_postal_code",
            "Enter a valid UK postcode (e.g. SW1A 1AA).",
        )
    };
    let (outward, inward) = s.split_once(' ').ok_or_else(bad)?;
    // Inward must be exactly 3: digit, letter, letter.
    if inward.len() != 3 {
        return Err(bad());
    }
    let inward_bytes = inward.as_bytes();
    if !inward_bytes[0].is_ascii_digit()
        || !inward_bytes[1].is_ascii_uppercase()
        || !inward_bytes[2].is_ascii_uppercase()
    {
        return Err(bad());
    }
    // Outward: 2-4 chars. First is letter. Last is digit OR letter
    // (`W1A`, `EC1A`). Middle chars follow specific patterns; for
    // a loose check we just require: first is letter, all chars
    // are uppercase-letter-or-digit, last position covers the
    // valid `Letter/Digit` set.
    if !(2..=4).contains(&outward.len()) {
        return Err(bad());
    }
    let outward_bytes = outward.as_bytes();
    if !outward_bytes[0].is_ascii_uppercase() {
        return Err(bad());
    }
    if !outward
        .chars()
        .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit())
    {
        return Err(bad());
    }
    Ok(())
}

// ------------------------------------------------------------------ length / value bounds

/// Reject strings shorter than `min` characters (Unicode code points,
/// not bytes — matches Django's `MinLengthValidator`).
///
/// # Errors
/// `ValidationError { code: "min_length", ... }` if the string is too short.
pub fn validate_min_length(s: &str, min: usize) -> Result<(), ValidationError> {
    let len = s.chars().count();
    if len < min {
        return Err(ValidationError::new(
            "min_length",
            format!("Ensure this value has at least {min} characters (it has {len})."),
        ));
    }
    Ok(())
}

/// Reject strings longer than `max` characters.
///
/// # Errors
/// `ValidationError { code: "max_length", ... }` if the string is too long.
pub fn validate_max_length(s: &str, max: usize) -> Result<(), ValidationError> {
    let len = s.chars().count();
    if len > max {
        return Err(ValidationError::new(
            "max_length",
            format!("Ensure this value has at most {max} characters (it has {len})."),
        ));
    }
    Ok(())
}

/// Reject integers below `min`.
///
/// # Errors
/// `ValidationError { code: "min_value", ... }`.
pub fn validate_min_value(n: i64, min: i64) -> Result<(), ValidationError> {
    if n < min {
        return Err(ValidationError::new(
            "min_value",
            format!("Ensure this value is greater than or equal to {min}."),
        ));
    }
    Ok(())
}

/// Reject integers above `max`.
///
/// # Errors
/// `ValidationError { code: "max_value", ... }`.
pub fn validate_max_value(n: i64, max: i64) -> Result<(), ValidationError> {
    if n > max {
        return Err(ValidationError::new(
            "max_value",
            format!("Ensure this value is less than or equal to {max}."),
        ));
    }
    Ok(())
}

/// Reject floats below `min`. Float variant of [`validate_min_value`]
/// for prices, measurements, scientific values that don't fit `i64`.
/// NaN is rejected.
///
/// # Errors
/// `ValidationError { code: "min_value", ... }`.
pub fn validate_min_value_f64(n: f64, min: f64) -> Result<(), ValidationError> {
    if n.is_nan() || n < min {
        return Err(ValidationError::new(
            "min_value",
            format!("Ensure this value is greater than or equal to {min}."),
        ));
    }
    Ok(())
}

/// Reject floats above `max`. Float variant of [`validate_max_value`].
/// NaN is rejected.
///
/// # Errors
/// `ValidationError { code: "max_value", ... }`.
pub fn validate_max_value_f64(n: f64, max: f64) -> Result<(), ValidationError> {
    if n.is_nan() || n > max {
        return Err(ValidationError::new(
            "max_value",
            format!("Ensure this value is less than or equal to {max}."),
        ));
    }
    Ok(())
}

/// Django-parity `StepValueValidator(limit_value, offset=0)` —
/// validate that `n` equals `offset + k * step` for some non-negative
/// integer `k`. Used to enforce HTML5 `<input type=number step="…">`
/// semantics from the server side.
///
/// `step` must be positive; passing zero or negative returns a
/// `ValidationError` with code `"invalid_step"` (Django raises
/// `ValueError` at validator construction; we surface it as a
/// validation failure for ergonomics).
///
/// Tolerance for floating-point round-off: the value is considered
/// "on-step" if the absolute residue from `(n - offset) / step` to
/// the nearest integer is below `1e-9 * step`.
///
/// # Errors
/// `ValidationError { code: "step_size", ... }` when `n` isn't on the
/// step grid; `code: "invalid_step"` when `step <= 0`.
///
/// ```ignore
/// use rustango::validators::validate_step_value;
/// // step=0.5 from offset=0 → 0.0, 0.5, 1.0, 1.5, ... all valid
/// assert!(validate_step_value(1.5, 0.5, 0.0).is_ok());
/// assert!(validate_step_value(1.3, 0.5, 0.0).is_err());
/// // step=10 from offset=5 → 5, 15, 25, ... valid
/// assert!(validate_step_value(25.0, 10.0, 5.0).is_ok());
/// ```
pub fn validate_step_value(n: f64, step: f64, offset: f64) -> Result<(), ValidationError> {
    if !(step > 0.0) {
        return Err(ValidationError::new(
            "invalid_step",
            "Step value must be strictly positive.",
        ));
    }
    if n.is_nan() {
        return Err(ValidationError::new(
            "step_size",
            format!("Ensure this value is a multiple of {step}."),
        ));
    }
    let residue = (n - offset) / step;
    let nearest = residue.round();
    // 1e-9 * step is tighter than f64::EPSILON for typical inputs but
    // still tolerates the round-off you'd see from doing e.g.
    // (1.0 + 0.5) and asking "is that a multiple of 0.5".
    if (residue - nearest).abs() > 1e-9 {
        return Err(ValidationError::new(
            "step_size",
            if offset == 0.0 {
                format!("Ensure this value is a multiple of {step}.")
            } else {
                format!("Ensure this value is a multiple of {step}, starting from {offset}.")
            },
        ));
    }
    Ok(())
}

// ------------------------------------------------------------------ integer / decimal

/// Validate that `s` parses as a signed 64-bit integer. Django's
/// `validate_integer`. Leading/trailing whitespace is rejected
/// (Django's implementation calls `int()` which is strict about
/// surrounding whitespace).
///
/// # Errors
/// `ValidationError { code: "invalid_integer", ... }`.
pub fn validate_integer(s: &str) -> Result<(), ValidationError> {
    if s != s.trim() || s.is_empty() {
        return Err(ValidationError::new(
            "invalid_integer",
            "Enter a valid integer.",
        ));
    }
    s.parse::<i64>()
        .map(|_| ())
        .map_err(|_| ValidationError::new("invalid_integer", "Enter a valid integer."))
}

/// Validate a decimal-number string under Django's
/// `DecimalValidator` shape: at most `max_digits` total digits
/// (excluding sign + decimal point), and at most `decimal_places`
/// digits after the point.
///
/// `max_digits` is the **total** digit count — pre- and
/// post-decimal combined. So `12.34` is 4 digits, 2 decimal_places.
/// Pass `None` for either bound to disable that check.
///
/// # Errors
/// `ValidationError { code: "invalid_decimal", ... }` for non-numeric
/// input. `code: "max_digits"` / `"max_decimal_places"` for bound
/// violations.
pub fn validate_decimal(
    s: &str,
    max_digits: Option<usize>,
    decimal_places: Option<usize>,
) -> Result<(), ValidationError> {
    let trimmed = s.trim();
    if trimmed.is_empty() {
        return Err(ValidationError::new("invalid_decimal", "Enter a number."));
    }
    let unsigned = trimmed.strip_prefix(['+', '-']).unwrap_or(trimmed);
    let (int_part, frac_part) = match unsigned.split_once('.') {
        Some((a, b)) => (a, b),
        None => (unsigned, ""),
    };
    // Either side may be empty individually (".5" or "5."), but
    // not both (a bare "." or empty string).
    if int_part.is_empty() && frac_part.is_empty() {
        return Err(ValidationError::new("invalid_decimal", "Enter a number."));
    }
    if !int_part.chars().all(|c| c.is_ascii_digit())
        || !frac_part.chars().all(|c| c.is_ascii_digit())
    {
        return Err(ValidationError::new("invalid_decimal", "Enter a number."));
    }
    // Drop leading zeros from int_part when counting, so "007.5"
    // has 2 digits not 4 — matches Django's Decimal coercion.
    let int_digits = int_part.trim_start_matches('0').len();
    let frac_digits = frac_part.len();
    if let Some(places) = decimal_places {
        if frac_digits > places {
            return Err(ValidationError::new(
                "max_decimal_places",
                format!(
                    "Ensure there are no more than {places} decimal places (got {frac_digits})."
                ),
            ));
        }
    }
    if let Some(total) = max_digits {
        let total_digits = int_digits + frac_digits;
        if total_digits > total {
            return Err(ValidationError::new(
                "max_digits",
                format!(
                    "Ensure there are no more than {total} digits in total (got {total_digits})."
                ),
            ));
        }
    }
    Ok(())
}

// ------------------------------------------------------------------ IPv4 / IPv6

/// Validate that `s` parses as an IPv4 address (dotted-quad). Uses
/// `std::net::Ipv4Addr::from_str` so the parse rules match the rest
/// of the standard library.
///
/// # Errors
/// `ValidationError { code: "invalid_ipv4_address", ... }`.
pub fn validate_ipv4_address(s: &str) -> Result<(), ValidationError> {
    use std::str::FromStr as _;
    std::net::Ipv4Addr::from_str(s)
        .map(|_| ())
        .map_err(|_| ValidationError::new("invalid_ipv4_address", "Enter a valid IPv4 address."))
}

/// Validate that `s` parses as an IPv6 address. Uses
/// `std::net::Ipv6Addr::from_str`.
///
/// # Errors
/// `ValidationError { code: "invalid_ipv6_address", ... }`.
pub fn validate_ipv6_address(s: &str) -> Result<(), ValidationError> {
    use std::str::FromStr as _;
    std::net::Ipv6Addr::from_str(s)
        .map(|_| ())
        .map_err(|_| ValidationError::new("invalid_ipv6_address", "Enter a valid IPv6 address."))
}

/// Django-parity `validate_ipv46_address(value)` — accept EITHER
/// an IPv4 or an IPv6 address. Used by Django's `GenericIPAddressField`
/// when the protocol is set to "both" (the default).
///
/// # Errors
/// `ValidationError { code: "invalid_ip_address", ... }` when `s`
/// parses as neither IPv4 nor IPv6.
///
/// ```ignore
/// use rustango::validators::validate_ipv46_address;
/// assert!(validate_ipv46_address("192.0.2.1").is_ok());
/// assert!(validate_ipv46_address("2001:db8::1").is_ok());
/// assert!(validate_ipv46_address("not an ip").is_err());
/// ```
pub fn validate_ipv46_address(s: &str) -> Result<(), ValidationError> {
    if validate_ipv4_address(s).is_ok() || validate_ipv6_address(s).is_ok() {
        return Ok(());
    }
    Err(ValidationError::new(
        "invalid_ip_address",
        "Enter a valid IPv4 or IPv6 address.",
    ))
}

/// Django-parity
/// [`django.utils.ipv6.clean_ipv6_address(ip, unpack_ipv4=False)`](https://docs.djangoproject.com/en/6.0/ref/utils/#django.utils.ipv6.clean_ipv6_address) —
/// normalize an IPv6 address into the canonical RFC 5952 compressed
/// form (lowercase hex, longest zero-run replaced with `::`, leading
/// zeros dropped per group).
///
/// Use when storing or comparing IPv6 addresses so different textual
/// representations of the same address fold to one canonical string.
/// Returns `None` if `ip` doesn't parse as IPv6 — Django raises
/// `ValidationError`; rustango surfaces the gap as `Option::None`
/// for ergonomic `?` propagation.
///
/// `unpack_ipv4 = true` mirrors Django's flag: when the address is
/// IPv4-mapped (`::ffff:192.0.2.1`), return the dotted-quad IPv4 form
/// instead. When `false`, the IPv4-mapped form is preserved.
///
/// ```ignore
/// use rustango::validators::clean_ipv6_address;
/// assert_eq!(
///     clean_ipv6_address("2001:0db8:0000:0000:0000:0000:0000:0001", false),
///     Some("2001:db8::1".to_owned())
/// );
/// assert_eq!(
///     clean_ipv6_address("::ffff:192.0.2.1", true),
///     Some("192.0.2.1".to_owned())
/// );
/// assert!(clean_ipv6_address("not an ip", false).is_none());
/// ```
#[must_use]
pub fn clean_ipv6_address(ip: &str, unpack_ipv4: bool) -> Option<String> {
    let parsed: std::net::Ipv6Addr = ip.parse().ok()?;
    if unpack_ipv4 {
        if let Some(v4) = parsed.to_ipv4_mapped() {
            return Some(v4.to_string());
        }
    }
    // Rust's `Ipv6Addr::to_string` emits RFC 5952 canonical form.
    Some(parsed.to_string())
}

/// Validate that `s` parses as either an IPv4 or IPv6 address.
/// Mirrors Django's `GenericIPAddressField(protocol="both")` (the
/// default). Issue #337 / Django-parity.
///
/// # Errors
/// `ValidationError { code: "invalid_ip_address", ... }` when the
/// value doesn't parse as either family.
pub fn validate_ip_address(s: &str) -> Result<(), ValidationError> {
    use std::str::FromStr as _;
    if std::net::Ipv4Addr::from_str(s).is_ok() || std::net::Ipv6Addr::from_str(s).is_ok() {
        return Ok(());
    }
    Err(ValidationError::new(
        "invalid_ip_address",
        "Enter a valid IPv4 or IPv6 address.",
    ))
}

/// Validate that `s` looks like a safe filesystem path string. Mirrors
/// the *structural* half of Django's `FilePathField` validation:
/// non-empty, no NUL bytes, no `..` parent-directory segments (path
/// traversal). Does NOT touch the filesystem — caller's responsibility
/// to verify existence + readability + sandbox membership when that
/// matters. Issue #338.
///
/// Accepted shapes:
/// - Relative: `docs/intro.md`, `assets/logo.png`
/// - Absolute (any platform): `/var/uploads/x.txt`, `C:\Users\me\f.txt`
/// - Trailing slash on directories
///
/// Rejected shapes:
/// - Empty string
/// - Strings containing `\0` (also caught by `validate_prohibit_null_characters`)
/// - Strings with a `..` segment between separators
///   (`docs/../etc/passwd`, `../secret`, `a/../b`)
///
/// # Errors
/// `ValidationError { code: "invalid_filepath", ... }` on any of the
/// rejected shapes above.
pub fn validate_filepath(s: &str) -> Result<(), ValidationError> {
    if s.is_empty() {
        return Err(ValidationError::new(
            "invalid_filepath",
            "Enter a non-empty file path.",
        ));
    }
    if s.contains('\0') {
        return Err(ValidationError::new(
            "invalid_filepath",
            "File path must not contain NUL characters.",
        ));
    }
    // Reject `..` segments between separators. Split on both `/` and
    // `\` so Windows-style paths get the same defense.
    for segment in s.split(['/', '\\']) {
        if segment == ".." {
            return Err(ValidationError::new(
                "invalid_filepath",
                "File path must not contain `..` parent-directory segments.",
            ));
        }
    }
    Ok(())
}

// ------------------------------------------------------------------ comma-separated integer list

/// Validate a comma-separated list of email addresses (e.g. a
/// "CC" field that takes multiple recipients). Each entry must
/// pass [`validate_email`]; surrounding whitespace per entry is
/// tolerated.
///
/// Empty list and empty entries (`"a@b.com,,c@d.com"`) are
/// rejected — they're almost certainly a typo, not intent.
///
/// # Errors
/// Returns the FIRST invalid entry's error, with the same code
/// (`"invalid_email"`) so handlers can surface a single "fix this"
/// message to the user.
pub fn validate_email_list(s: &str) -> Result<(), ValidationError> {
    if s.trim().is_empty() {
        return Err(ValidationError::new(
            "invalid_email",
            "Enter at least one email address.",
        ));
    }
    for part in s.split(',') {
        let entry = part.trim();
        if entry.is_empty() {
            return Err(ValidationError::new(
                "invalid_email",
                "Enter a valid email address.",
            ));
        }
        validate_email(entry)?;
    }
    Ok(())
}

/// Validate that `s` is a comma-separated list of integers
/// (`"1,2,3"`). Empty string is rejected (Django returns an error
/// — use `Option<String>` upstream if the field is optional).
///
/// Whitespace around individual entries is tolerated (`"1, 2, 3"`
/// passes) since this is how operators typically type lists into
/// forms — Django accepts it too.
///
/// # Errors
/// `ValidationError { code: "invalid_comma_separated_integer_list", ... }`.
pub fn validate_comma_separated_integer_list(s: &str) -> Result<(), ValidationError> {
    if s.trim().is_empty() {
        return Err(ValidationError::new(
            "invalid_comma_separated_integer_list",
            "Enter only digits separated by commas.",
        ));
    }
    for part in s.split(',') {
        let part = part.trim();
        if part.is_empty() || part.parse::<i64>().is_err() {
            return Err(ValidationError::new(
                "invalid_comma_separated_integer_list",
                "Enter only digits separated by commas.",
            ));
        }
    }
    Ok(())
}

/// Django-parity
/// [`int_list_validator(sep, allow_negative)`](https://docs.djangoproject.com/en/6.0/ref/validators/#django.core.validators.int_list_validator) —
/// parameterized variant of [`validate_comma_separated_integer_list`].
///
/// Accepts a list of integers separated by `sep`. When
/// `allow_negative` is false (Django default), a leading `-` on
/// any list element rejects the entire input. Whitespace around
/// each element is allowed and trimmed.
///
/// Use `validate_comma_separated_integer_list(s)` for the
/// canonical `sep=","`, `allow_negative=false` shape; this
/// function exists for callers that need:
/// * A different separator (`":"`, `";"`, `"|"`, `" "`)
/// * Negative integers permitted (`-1,2,-3`)
///
/// ```
/// use rustango::validators::int_list_validator;
/// assert!(int_list_validator("1,2,3",     ",", false).is_ok());
/// assert!(int_list_validator("1 2 3",     " ", false).is_ok());
/// assert!(int_list_validator("1|-2|3",    "|", true).is_ok());
/// assert!(int_list_validator("1|-2|3",    "|", false).is_err());
/// assert!(int_list_validator("1,abc,3",   ",", false).is_err());
/// assert!(int_list_validator("",          ",", false).is_err());
/// ```
///
/// # Errors
/// `ValidationError { code: "invalid", ... }` if any element
/// isn't a valid integer, or if the input is empty, or if a
/// negative value is found and `allow_negative` is false.
pub fn int_list_validator(s: &str, sep: &str, allow_negative: bool) -> Result<(), ValidationError> {
    if s.trim().is_empty() {
        return Err(ValidationError::new(
            "invalid",
            "Enter only digits separated by the configured separator.",
        ));
    }
    if sep.is_empty() {
        // Without a separator the function would split-by-empty into
        // chars — meaningless. Reject loudly.
        return Err(ValidationError::new(
            "invalid",
            "int_list_validator: separator must be non-empty.",
        ));
    }
    for part in s.split(sep) {
        let part = part.trim();
        if part.is_empty() {
            return Err(ValidationError::new(
                "invalid",
                "Enter only digits separated by the configured separator.",
            ));
        }
        let parsed: Result<i64, _> = part.parse();
        match parsed {
            Ok(n) => {
                if !allow_negative && n < 0 {
                    return Err(ValidationError::new(
                        "invalid",
                        "Negative integers are not allowed.",
                    ));
                }
            }
            Err(_) => {
                return Err(ValidationError::new(
                    "invalid",
                    "Enter only digits separated by the configured separator.",
                ));
            }
        }
    }
    Ok(())
}

/// Django-parity `FileExtensionValidator(allowed_extensions=[...])` —
/// reject filenames whose extension (case-insensitive) isn't on the
/// allowlist. The extension is everything after the LAST `.` in the
/// filename — `archive.tar.gz` has extension `gz`, matching Django.
/// `allowed_extensions` entries are compared lowercase; pass them
/// without the leading dot (`["jpg", "png"]`, not `[".jpg"]`).
///
/// Files with no extension at all are rejected — calling code that
/// wants to allow extensionless uploads should branch before calling
/// the validator.
///
/// # Errors
/// `ValidationError { code: "invalid_extension", ... }` when the
/// extension isn't in `allowed_extensions`.
pub fn validate_file_extension(
    filename: &str,
    allowed_extensions: &[&str],
) -> Result<(), ValidationError> {
    let ext = filename
        .rsplit_once('.')
        .map(|(_, e)| e.to_ascii_lowercase());
    let Some(ext) = ext else {
        return Err(ValidationError::new(
            "invalid_extension",
            format!(
                "File extension is required. Allowed extensions are: {}.",
                allowed_extensions.join(", ")
            ),
        ));
    };
    let allowed_lc: Vec<String> = allowed_extensions
        .iter()
        .map(|s| s.trim_start_matches('.').to_ascii_lowercase())
        .collect();
    if !allowed_lc.iter().any(|a| a == &ext) {
        return Err(ValidationError::new(
            "invalid_extension",
            format!(
                "File extension '{ext}' is not allowed. Allowed extensions are: {}.",
                allowed_extensions.join(", ")
            ),
        ));
    }
    Ok(())
}

/// Django-parity `validate_image_file_extension` — convenience around
/// [`validate_file_extension`] that allows the same defaults Django
/// uses: `bmp / dib / gif / tif / tiff / jfif / jpe / jpg / jpeg /
/// pbm / pgm / ppm / pnm / png / apng / blp / bufr / cur / pcx /
/// dcx / dds / ps / eps / fit / fits / fli / flc / ftc / ftu / gbr /
/// gif / grib / h5 / hdf / jp2 / j2k / jpc / jpf / jpx / j2c / icns /
/// ico / im / iim / mic / mpo / msp / palm / pcd / pdf / pxr / psd /
/// bw / rgb / rgba / sgi / ras / tga / icb / vda / vst / webp / wmf /
/// emf / xbm / xpm`. Matches Pillow's `Image.registered_extensions`
/// snapshot Django ships.
///
/// # Errors
/// Forwarded from [`validate_file_extension`].
pub fn validate_image_file_extension(filename: &str) -> Result<(), ValidationError> {
    // Pillow's registered image extensions as of Django 6.0 — the
    // exact list Django's `validate_image_file_extension` walks.
    const IMAGE_EXTENSIONS: &[&str] = &[
        "apng", "bmp", "blp", "bufr", "bw", "cur", "dcx", "dds", "dib", "emf", "eps", "fit",
        "fits", "flc", "fli", "ftc", "ftu", "gbr", "gif", "grib", "h5", "hdf", "icb", "icns",
        "ico", "iim", "im", "j2c", "j2k", "jfif", "jp2", "jpc", "jpe", "jpeg", "jpf", "jpg", "jpx",
        "mic", "mpo", "msp", "palm", "pbm", "pcd", "pcx", "pdf", "pgm", "png", "pnm", "ppm", "ps",
        "psd", "pxr", "ras", "rgb", "rgba", "sgi", "tga", "tif", "tiff", "vda", "vst", "webp",
        "wmf", "xbm", "xpm",
    ];
    validate_file_extension(filename, IMAGE_EXTENSIONS)
}

/// Django-shape file-size cap — reject uploads whose byte length
/// exceeds `max_bytes`. Pair with `uploads::save_uploads` (which
/// streams + caps at the transport layer) when the form-level check
/// needs to produce a Django-compatible `FormErrors` entry instead
/// of a 413 response.
///
/// Message-shape mirrors Django's `FILE_UPLOAD_MAX_MEMORY_SIZE`
/// rejection: `"File size {actual} exceeds {max} bytes."`.
///
/// # Errors
/// `ValidationError { code: "file_too_large", ... }` when `actual_bytes
/// > max_bytes`.
pub fn validate_file_size_max(actual_bytes: u64, max_bytes: u64) -> Result<(), ValidationError> {
    if actual_bytes > max_bytes {
        return Err(ValidationError::new(
            "file_too_large",
            format!("File size {actual_bytes} exceeds {max_bytes} bytes."),
        ));
    }
    Ok(())
}

/// Bounded width/height check for an image already decoded by the
/// caller. Each bound is optional — pass `None` to skip that
/// side.
///
/// Django ships dimension validation via PIL inside `ImageField`;
/// rustango doesn't pull in image processing, so the caller is
/// expected to extract `(width, height)` from the file using
/// whichever image lib they choose (`image`, `imageinfo`,
/// `kamadak-exif`, etc.) then feed them through this validator.
///
/// Bounds are pixel counts. All four bounds default to "no check"
/// when `None`; the function returns `Ok(())` when every supplied
/// bound is satisfied.
///
/// ```
/// use rustango::validators::validate_image_dimensions;
/// // Avatar must be square-ish and at most 2000×2000.
/// assert!(validate_image_dimensions(1024, 1024, Some(2000), Some(2000), None, None).is_ok());
/// // Reject too wide.
/// assert!(validate_image_dimensions(3000, 1024, Some(2000), Some(2000), None, None).is_err());
/// // Enforce minimum.
/// assert!(validate_image_dimensions(50, 50, None, None, Some(100), Some(100)).is_err());
/// // Skip both bounds → always ok.
/// assert!(validate_image_dimensions(1, 1, None, None, None, None).is_ok());
/// ```
///
/// # Errors
/// `ValidationError { code: "image_too_wide" | "image_too_tall" |
/// "image_too_narrow" | "image_too_short", ... }` — distinct codes
/// so error rendering can pick the right human message per axis.
pub fn validate_image_dimensions(
    width: u32,
    height: u32,
    max_width: Option<u32>,
    max_height: Option<u32>,
    min_width: Option<u32>,
    min_height: Option<u32>,
) -> Result<(), ValidationError> {
    if let Some(max_w) = max_width {
        if width > max_w {
            return Err(ValidationError::new(
                "image_too_wide",
                format!("Image width {width}px exceeds {max_w}px."),
            ));
        }
    }
    if let Some(max_h) = max_height {
        if height > max_h {
            return Err(ValidationError::new(
                "image_too_tall",
                format!("Image height {height}px exceeds {max_h}px."),
            ));
        }
    }
    if let Some(min_w) = min_width {
        if width < min_w {
            return Err(ValidationError::new(
                "image_too_narrow",
                format!("Image width {width}px is below the {min_w}px minimum."),
            ));
        }
    }
    if let Some(min_h) = min_height {
        if height < min_h {
            return Err(ValidationError::new(
                "image_too_short",
                format!("Image height {height}px is below the {min_h}px minimum."),
            ));
        }
    }
    Ok(())
}

/// Django-shape MIME-type allowlist — reject uploads whose
/// `Content-Type` (or per-part media-type for multipart forms) isn't
/// in `allowed_mimetypes`. Comparison is case-insensitive on the
/// `type/subtype` portion and ignores any trailing `; charset=...`
/// parameters.
///
/// Wildcard subtypes work: `"image/*"` allows `image/png`,
/// `image/jpeg`, etc. — matches the HTML `<input accept>` shape.
///
/// # Errors
/// `ValidationError { code: "invalid_mime_type", ... }` when none of
/// `allowed_mimetypes` matches.
///
/// ```ignore
/// use rustango::validators::validate_file_mime_type;
///
/// // Strict allowlist.
/// assert!(validate_file_mime_type("image/png", &["image/png", "image/jpeg"]).is_ok());
/// // Wildcard subtype.
/// assert!(validate_file_mime_type("image/webp", &["image/*"]).is_ok());
/// // Charset parameter ignored.
/// assert!(validate_file_mime_type("text/html; charset=utf-8", &["text/html"]).is_ok());
/// // Wrong type rejected.
/// assert!(validate_file_mime_type("application/x-msdownload", &["image/*"]).is_err());
/// ```
pub fn validate_file_mime_type(
    mimetype: &str,
    allowed_mimetypes: &[&str],
) -> Result<(), ValidationError> {
    let core = mimetype
        .split(';')
        .next()
        .unwrap_or("")
        .trim()
        .to_ascii_lowercase();
    let (ty, subty) = core.split_once('/').unwrap_or((core.as_str(), ""));
    let matches_any = allowed_mimetypes.iter().any(|a| {
        let a_core = a
            .split(';')
            .next()
            .unwrap_or("")
            .trim()
            .to_ascii_lowercase();
        let (a_ty, a_subty) = a_core.split_once('/').unwrap_or((a_core.as_str(), ""));
        a_ty == ty && (a_subty == "*" || a_subty == subty)
    });
    if !matches_any {
        return Err(ValidationError::new(
            "invalid_mime_type",
            format!(
                "MIME type '{mimetype}' is not allowed. Allowed: {}.",
                allowed_mimetypes.join(", ")
            ),
        ));
    }
    Ok(())
}

// ============================================================
// `is_*` boolean companions
//
// Mirror `is_email` / `is_url` / etc. style for the rest of the
// `validate_*` family. Useful for filter-iterators and pattern-
// matching call sites that only need "is this valid?" without
// consuming the Result. Each delegates to the matching
// `validate_*` (single source of truth — change the validator,
// the predicate follows).
// ============================================================

/// `true` when `s` would pass [`validate_alpha`].
#[must_use]
pub fn is_alpha(s: &str) -> bool {
    validate_alpha(s).is_ok()
}

/// `true` when `s` would pass [`validate_alphanumeric`].
#[must_use]
pub fn is_alphanumeric(s: &str) -> bool {
    validate_alphanumeric(s).is_ok()
}

/// `true` when `s` would pass [`validate_numeric`].
#[must_use]
pub fn is_numeric(s: &str) -> bool {
    validate_numeric(s).is_ok()
}

/// `true` when `s` would pass [`validate_creditcard_luhn`].
#[must_use]
pub fn is_creditcard_luhn(s: &str) -> bool {
    validate_creditcard_luhn(s).is_ok()
}

/// `true` when `s` would pass [`validate_hostname`].
#[must_use]
pub fn is_hostname(s: &str) -> bool {
    validate_hostname(s).is_ok()
}

/// `true` when `s` would pass [`validate_iban`].
#[must_use]
pub fn is_iban(s: &str) -> bool {
    validate_iban(s).is_ok()
}

/// `true` when `s` would pass [`validate_mac_address`].
#[must_use]
pub fn is_mac_address(s: &str) -> bool {
    validate_mac_address(s).is_ok()
}

/// `true` when `s` would pass [`validate_semver`].
#[must_use]
pub fn is_semver(s: &str) -> bool {
    validate_semver(s).is_ok()
}

/// `true` when `s` would pass [`validate_isbn`].
#[must_use]
pub fn is_isbn(s: &str) -> bool {
    validate_isbn(s).is_ok()
}

/// `true` when `s` would pass [`validate_iso_date`].
#[must_use]
pub fn is_iso_date(s: &str) -> bool {
    validate_iso_date(s).is_ok()
}

/// `true` when `s` would pass [`validate_iso_time`].
#[must_use]
pub fn is_iso_time(s: &str) -> bool {
    validate_iso_time(s).is_ok()
}

/// `true` when `s` would pass [`validate_iso_datetime`].
#[must_use]
pub fn is_iso_datetime(s: &str) -> bool {
    validate_iso_datetime(s).is_ok()
}

/// `true` when `s` would pass [`validate_base64`].
#[must_use]
pub fn is_base64(s: &str) -> bool {
    validate_base64(s).is_ok()
}

/// `true` when `s` would pass [`validate_base64_urlsafe`].
#[must_use]
pub fn is_base64_urlsafe(s: &str) -> bool {
    validate_base64_urlsafe(s).is_ok()
}

/// `true` when `s` would pass [`validate_jwt_shape`].
#[must_use]
pub fn is_jwt_shape(s: &str) -> bool {
    validate_jwt_shape(s).is_ok()
}

/// `true` when `s` would pass [`validate_country_code`] (ISO 3166-1
/// alpha-2). Boolean form for filter chains; the `Result` form
/// remains the right call when the message matters.
#[must_use]
pub fn is_country_code(s: &str) -> bool {
    validate_country_code(s).is_ok()
}

/// `true` when `s` would pass [`validate_currency_code`] (ISO 4217
/// alpha-3). Boolean form for filter chains.
#[must_use]
pub fn is_currency_code(s: &str) -> bool {
    validate_currency_code(s).is_ok()
}

/// `true` when `s` would pass [`validate_language_tag`] (BCP 47
/// language tag). Boolean form for filter chains.
#[must_use]
pub fn is_language_tag(s: &str) -> bool {
    validate_language_tag(s).is_ok()
}

/// `true` when `s` would pass [`validate_postal_code_us`]
/// (5-digit or 9-digit ZIP). Boolean form for filter chains.
#[must_use]
pub fn is_postal_code_us(s: &str) -> bool {
    validate_postal_code_us(s).is_ok()
}

/// `true` when `s` would pass [`validate_postal_code_ca`]
/// (`A1A 1A1` / `A1A1A1`). Boolean form for filter chains.
#[must_use]
pub fn is_postal_code_ca(s: &str) -> bool {
    validate_postal_code_ca(s).is_ok()
}

/// `true` when `s` would pass [`validate_postal_code_uk`]
/// (UK postcode shape). Boolean form for filter chains.
#[must_use]
pub fn is_postal_code_uk(s: &str) -> bool {
    validate_postal_code_uk(s).is_ok()
}

/// `true` when `s` would pass [`validate_ipv4_address`]
/// (dotted-quad IPv4). Boolean form for filter chains.
#[must_use]
pub fn is_ipv4_address(s: &str) -> bool {
    validate_ipv4_address(s).is_ok()
}

/// `true` when `s` would pass [`validate_ipv6_address`]
/// (RFC 4291 IPv6, condensed or full). Boolean form for filter chains.
#[must_use]
pub fn is_ipv6_address(s: &str) -> bool {
    validate_ipv6_address(s).is_ok()
}

/// `true` when `s` would pass [`validate_ipv46_address`]
/// (accepts either IPv4 or IPv6). Boolean form for filter chains.
#[must_use]
pub fn is_ipv46_address(s: &str) -> bool {
    validate_ipv46_address(s).is_ok()
}

/// `true` when `s` would pass [`validate_ip_address`] — alias of
/// [`is_ipv46_address`] for symmetry with Django's
/// `validate_ip_address`. Boolean form for filter chains.
#[must_use]
pub fn is_ip_address(s: &str) -> bool {
    validate_ip_address(s).is_ok()
}

/// `true` when `s` would pass [`validate_filepath`] — POSIX-shape
/// path with no embedded NUL / control chars. Boolean form for
/// filter chains.
#[must_use]
pub fn is_filepath(s: &str) -> bool {
    validate_filepath(s).is_ok()
}

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

    // -------- validate_email --------

    #[test]
    fn email_accepts_common_shapes() {
        assert!(validate_email("alice@example.com").is_ok());
        assert!(validate_email("a.b+tag@example.co.uk").is_ok());
        assert!(validate_email("nested.dots+plus_underscore-hyphen@sub.example.org").is_ok());
    }

    #[test]
    fn email_rejects_missing_at() {
        let e = validate_email("alice.example.com").unwrap_err();
        assert_eq!(e.code, "invalid_email");
    }

    #[test]
    fn email_rejects_empty_local_or_domain() {
        assert!(validate_email("@example.com").is_err());
        assert!(validate_email("alice@").is_err());
    }

    #[test]
    fn email_rejects_no_dot_in_domain() {
        assert!(validate_email("alice@localhost").is_err());
    }

    #[test]
    fn email_rejects_two_at_signs() {
        assert!(validate_email("a@b@c.com").is_err());
    }

    #[test]
    fn email_rejects_consecutive_dots() {
        assert!(validate_email("a..b@example.com").is_err());
        assert!(validate_email("a@example..com").is_err());
    }

    #[test]
    fn email_rejects_empty_and_whitespace_only() {
        assert!(validate_email("").is_err());
        assert!(validate_email("   ").is_err());
    }

    #[test]
    fn is_email_is_a_thin_boolean_wrapper() {
        assert!(is_email("a@b.com"));
        assert!(!is_email("not an email"));
    }

    // -------- validate_url --------

    #[test]
    fn url_accepts_http_and_https() {
        assert!(validate_url("http://example.com").is_ok());
        assert!(validate_url("https://example.com").is_ok());
    }

    #[test]
    fn url_accepts_paths_query_fragment() {
        assert!(validate_url("https://example.com/path?q=1#frag").is_ok());
    }

    #[test]
    fn url_accepts_port() {
        assert!(validate_url("http://example.com:8080/api").is_ok());
    }

    #[test]
    fn url_rejects_no_scheme() {
        assert!(validate_url("example.com").is_err());
    }

    #[test]
    fn url_rejects_unknown_scheme() {
        assert!(validate_url("ftp://example.com").is_err());
    }

    #[test]
    fn url_rejects_empty_host() {
        assert!(validate_url("https://").is_err());
        assert!(validate_url("https:///path").is_err());
    }

    #[test]
    fn url_rejects_empty_string() {
        assert!(validate_url("").is_err());
    }

    // -------- validate_slug --------

    #[test]
    fn slug_accepts_alnum_underscore_hyphen() {
        assert!(validate_slug("hello-world_42").is_ok());
        assert!(validate_slug("just-letters").is_ok());
        assert!(validate_slug("123").is_ok());
    }

    #[test]
    fn slug_rejects_spaces_and_punctuation() {
        assert!(validate_slug("hello world").is_err());
        assert!(validate_slug("hello!").is_err());
        assert!(validate_slug("a.b").is_err());
    }

    #[test]
    fn slug_rejects_empty() {
        assert!(validate_slug("").is_err());
    }

    #[test]
    fn slug_rejects_non_ascii_letters() {
        // Django's default slug_re is ASCII-only; the unicode-aware
        // form is opt-in. Match that.
        assert!(validate_slug("café").is_err());
    }

    // -------- length / value bounds --------

    #[test]
    fn min_length_uses_char_count_not_byte_count() {
        // "éé" is 2 chars but 4 bytes — the validator counts chars.
        assert!(validate_min_length("éé", 2).is_ok());
        assert!(validate_min_length("é", 2).is_err());
    }

    #[test]
    fn max_length_uses_char_count_not_byte_count() {
        assert!(validate_max_length("éé", 2).is_ok());
        assert!(validate_max_length("ééé", 2).is_err());
    }

    #[test]
    fn min_length_at_boundary_is_ok() {
        assert!(validate_min_length("abc", 3).is_ok());
        assert!(validate_min_length("ab", 3).is_err());
    }

    #[test]
    fn min_and_max_value_bounds_are_inclusive() {
        assert!(validate_min_value(5, 5).is_ok());
        assert!(validate_max_value(5, 5).is_ok());
        assert!(validate_min_value(4, 5).is_err());
        assert!(validate_max_value(6, 5).is_err());
    }

    #[test]
    fn min_and_max_value_f64_bounds_are_inclusive() {
        assert!(validate_min_value_f64(5.0, 5.0).is_ok());
        assert!(validate_max_value_f64(5.0, 5.0).is_ok());
        assert!(validate_min_value_f64(4.999, 5.0).is_err());
        assert!(validate_max_value_f64(5.001, 5.0).is_err());
    }

    #[test]
    fn min_and_max_value_f64_reject_nan() {
        // NaN compares false against any value, so the bare `<`/`>`
        // check would silently accept it. We explicitly reject it.
        assert!(validate_min_value_f64(f64::NAN, 0.0).is_err());
        assert!(validate_max_value_f64(f64::NAN, 100.0).is_err());
    }

    #[test]
    fn min_and_max_value_f64_handle_infinities() {
        // +Inf passes min check, fails max check (and vice versa).
        assert!(validate_min_value_f64(f64::INFINITY, 5.0).is_ok());
        assert!(validate_max_value_f64(f64::INFINITY, 5.0).is_err());
        assert!(validate_min_value_f64(f64::NEG_INFINITY, 5.0).is_err());
        assert!(validate_max_value_f64(f64::NEG_INFINITY, 5.0).is_ok());
    }

    // -------- ValidationError --------

    #[test]
    fn validation_error_display_renders_message() {
        let e = ValidationError::new("invalid_email", "Bad email.");
        assert_eq!(format!("{e}"), "Bad email.");
        assert_eq!(e.code, "invalid_email");
    }

    // -------- validate_integer --------

    #[test]
    fn integer_accepts_positive_negative_zero() {
        assert!(validate_integer("0").is_ok());
        assert!(validate_integer("42").is_ok());
        assert!(validate_integer("-7").is_ok());
        assert!(validate_integer("+1").is_ok());
    }

    #[test]
    fn integer_rejects_decimals_and_letters() {
        assert!(validate_integer("3.14").is_err());
        assert!(validate_integer("abc").is_err());
        assert!(validate_integer("12abc").is_err());
    }

    #[test]
    fn integer_rejects_surrounding_whitespace() {
        // Django's `int()` rejects whitespace — we match.
        assert!(validate_integer(" 42").is_err());
        assert!(validate_integer("42 ").is_err());
        assert!(validate_integer("").is_err());
    }

    // -------- validate_decimal --------

    #[test]
    fn decimal_accepts_well_formed_numbers() {
        assert!(validate_decimal("12.34", None, None).is_ok());
        assert!(validate_decimal("-12.34", None, None).is_ok());
        assert!(validate_decimal("+0.5", None, None).is_ok());
        assert!(validate_decimal(".5", None, None).is_ok());
        assert!(validate_decimal("5.", None, None).is_ok());
        assert!(validate_decimal("100", None, None).is_ok());
    }

    #[test]
    fn decimal_rejects_non_numeric() {
        assert!(validate_decimal("abc", None, None).is_err());
        assert!(validate_decimal("12.3.4", None, None).is_err());
        assert!(validate_decimal(".", None, None).is_err());
        assert!(validate_decimal("", None, None).is_err());
    }

    #[test]
    fn decimal_enforces_max_decimal_places() {
        // 2 places allowed; "12.345" has 3 → error.
        let e = validate_decimal("12.345", None, Some(2)).unwrap_err();
        assert_eq!(e.code, "max_decimal_places");
        // Equal-to-limit passes.
        assert!(validate_decimal("12.34", None, Some(2)).is_ok());
    }

    #[test]
    fn decimal_enforces_max_total_digits() {
        // 5 total digits allowed; "12345.6" has 6 → error.
        let e = validate_decimal("12345.6", Some(5), None).unwrap_err();
        assert_eq!(e.code, "max_digits");
        assert!(validate_decimal("1234.5", Some(5), None).is_ok());
    }

    #[test]
    fn decimal_max_digits_ignores_leading_zeros() {
        // "007.5" should count as 2 digits (7 + 5) not 4.
        assert!(validate_decimal("007.5", Some(2), None).is_ok());
    }

    // -------- validate_ipv4_address --------

    #[test]
    fn ipv4_accepts_dotted_quad() {
        assert!(validate_ipv4_address("127.0.0.1").is_ok());
        assert!(validate_ipv4_address("0.0.0.0").is_ok());
        assert!(validate_ipv4_address("255.255.255.255").is_ok());
    }

    #[test]
    fn ipv4_rejects_malformed_or_out_of_range() {
        assert!(validate_ipv4_address("256.0.0.1").is_err());
        assert!(validate_ipv4_address("not.an.ip.addr").is_err());
        assert!(validate_ipv4_address("1.2.3").is_err());
        assert!(validate_ipv4_address("").is_err());
    }

    // -------- validate_ipv6_address --------

    #[test]
    fn ipv6_accepts_full_and_shorthand() {
        assert!(validate_ipv6_address("2001:db8::1").is_ok());
        assert!(validate_ipv6_address("::1").is_ok());
        assert!(validate_ipv6_address("fe80::1234:5678:9abc:def0").is_ok());
    }

    #[test]
    fn ipv6_rejects_v4_addresses_and_garbage() {
        assert!(validate_ipv6_address("127.0.0.1").is_err());
        assert!(validate_ipv6_address("zzz").is_err());
        assert!(validate_ipv6_address("").is_err());
    }

    // -------- validate_comma_separated_integer_list --------

    #[test]
    fn comma_list_accepts_clean_form() {
        assert!(validate_comma_separated_integer_list("1,2,3").is_ok());
        assert!(validate_comma_separated_integer_list("42").is_ok());
        assert!(validate_comma_separated_integer_list("-1,0,1").is_ok());
    }

    #[test]
    fn comma_list_tolerates_inner_whitespace() {
        assert!(validate_comma_separated_integer_list("1, 2, 3").is_ok());
    }

    #[test]
    fn comma_list_rejects_empty_and_non_integers() {
        assert!(validate_comma_separated_integer_list("").is_err());
        assert!(validate_comma_separated_integer_list("1,abc,3").is_err());
        assert!(validate_comma_separated_integer_list("1,,3").is_err());
    }

    // -------- validate_unicode_slug --------

    #[test]
    fn unicode_slug_accepts_non_ascii_letters() {
        // The whole point — café / 日本語 / Привет all valid.
        assert!(validate_unicode_slug("café-au-lait").is_ok());
        assert!(validate_unicode_slug("日本語").is_ok());
        assert!(validate_unicode_slug("Привет_мир").is_ok());
    }

    #[test]
    fn unicode_slug_still_rejects_punctuation_and_spaces() {
        // The "unicode" part is just about which letters count; the
        // slug shape (no spaces / punctuation) still applies.
        assert!(validate_unicode_slug("hello world").is_err());
        assert!(validate_unicode_slug("hello!").is_err());
        assert!(validate_unicode_slug("a.b").is_err());
    }

    #[test]
    fn unicode_slug_rejects_empty() {
        assert!(validate_unicode_slug("").is_err());
    }

    // -------- validate_prohibit_null_characters --------

    #[test]
    fn prohibit_null_accepts_strings_without_nul() {
        assert!(validate_prohibit_null_characters("hello").is_ok());
        assert!(validate_prohibit_null_characters("").is_ok());
        assert!(validate_prohibit_null_characters("non-printable\x01ok").is_ok());
    }

    #[test]
    fn prohibit_null_rejects_strings_containing_nul() {
        let e = validate_prohibit_null_characters("hello\0world").unwrap_err();
        assert_eq!(e.code, "null_characters_not_allowed");
    }

    // -------- validate_email_list --------

    #[test]
    fn email_list_accepts_single_email() {
        assert!(validate_email_list("alice@example.com").is_ok());
    }

    #[test]
    fn email_list_accepts_multiple_with_whitespace() {
        assert!(validate_email_list("a@b.com, c@d.com,e@f.com").is_ok());
    }

    #[test]
    fn email_list_rejects_empty_string() {
        assert!(validate_email_list("").is_err());
        assert!(validate_email_list("   ").is_err());
    }

    #[test]
    fn email_list_rejects_empty_entries() {
        assert!(validate_email_list("a@b.com,,c@d.com").is_err());
        assert!(validate_email_list("a@b.com, ,c@d.com").is_err());
    }

    #[test]
    fn email_list_rejects_invalid_entry() {
        let e = validate_email_list("a@b.com,not-an-email,c@d.com").unwrap_err();
        assert_eq!(e.code, "invalid_email");
    }

    // -------- validate_phone_e164 --------

    #[test]
    fn phone_e164_accepts_typical_examples() {
        assert!(validate_phone_e164("+14155552671").is_ok());
        assert!(validate_phone_e164("+442012345678").is_ok());
        assert!(validate_phone_e164("+919876543210").is_ok());
    }

    #[test]
    fn phone_e164_accepts_minimum_length_of_one_digit() {
        assert!(validate_phone_e164("+1").is_ok());
    }

    #[test]
    fn phone_e164_accepts_maximum_length_of_fifteen_digits() {
        assert!(validate_phone_e164("+123456789012345").is_ok());
    }

    #[test]
    fn phone_e164_rejects_missing_plus() {
        let e = validate_phone_e164("14155552671").unwrap_err();
        assert_eq!(e.code, "invalid_phone");
    }

    #[test]
    fn phone_e164_rejects_too_many_digits() {
        // 16 digits — one too many.
        assert!(validate_phone_e164("+1234567890123456").is_err());
    }

    #[test]
    fn phone_e164_rejects_zero_digits_after_plus() {
        assert!(validate_phone_e164("+").is_err());
    }

    #[test]
    fn phone_e164_rejects_separators_and_letters() {
        assert!(validate_phone_e164("+1-415-555-2671").is_err());
        assert!(validate_phone_e164("+1 (415) 555-2671").is_err());
        assert!(validate_phone_e164("+1abc4155552671").is_err());
    }

    #[test]
    fn phone_e164_rejects_empty() {
        assert!(validate_phone_e164("").is_err());
    }

    #[test]
    fn is_phone_e164_is_thin_boolean_wrapper() {
        assert!(is_phone_e164("+14155552671"));
        assert!(!is_phone_e164("14155552671"));
    }

    // -------- validate_hex_color --------

    #[test]
    fn hex_color_accepts_rgb_shorthand() {
        assert!(validate_hex_color("#fff").is_ok());
        assert!(validate_hex_color("#000").is_ok());
        assert!(validate_hex_color("#fA0").is_ok());
    }

    #[test]
    fn hex_color_accepts_full_rrggbb() {
        assert!(validate_hex_color("#ffffff").is_ok());
        assert!(validate_hex_color("#FFAA00").is_ok());
    }

    #[test]
    fn hex_color_accepts_alpha_variants() {
        // 4 = rgba shorthand, 8 = rrggbbaa.
        assert!(validate_hex_color("#fff8").is_ok());
        assert!(validate_hex_color("#FFAA00CC").is_ok());
    }

    #[test]
    fn hex_color_rejects_missing_hash() {
        assert!(validate_hex_color("fff").is_err());
    }

    #[test]
    fn hex_color_rejects_non_hex_chars() {
        let e = validate_hex_color("#ffffg0").unwrap_err();
        assert_eq!(e.code, "invalid_hex_color");
    }

    #[test]
    fn hex_color_rejects_wrong_length() {
        // 1, 2, 5, 7 are all rejected — only 3/4/6/8 are valid.
        assert!(validate_hex_color("#f").is_err());
        assert!(validate_hex_color("#ff").is_err());
        assert!(validate_hex_color("#fffff").is_err());
        assert!(validate_hex_color("#fffffff").is_err());
    }

    #[test]
    fn hex_color_rejects_empty_and_hash_only() {
        assert!(validate_hex_color("").is_err());
        assert!(validate_hex_color("#").is_err());
    }

    #[test]
    fn is_hex_color_is_thin_boolean_wrapper() {
        assert!(is_hex_color("#fff"));
        assert!(!is_hex_color("fff"));
    }

    // -------- validate_uuid --------

    #[test]
    fn uuid_accepts_hyphenated_form() {
        assert!(validate_uuid("550e8400-e29b-41d4-a716-446655440000").is_ok());
    }

    #[test]
    fn uuid_accepts_simple_form_no_hyphens() {
        assert!(validate_uuid("550e8400e29b41d4a716446655440000").is_ok());
    }

    #[test]
    fn uuid_accepts_urn_prefix() {
        assert!(validate_uuid("urn:uuid:550e8400-e29b-41d4-a716-446655440000").is_ok());
    }

    #[test]
    fn uuid_accepts_braced_form() {
        assert!(validate_uuid("{550e8400-e29b-41d4-a716-446655440000}").is_ok());
    }

    #[test]
    fn uuid_rejects_garbage() {
        let e = validate_uuid("not-a-uuid").unwrap_err();
        assert_eq!(e.code, "invalid_uuid");
    }

    #[test]
    fn uuid_rejects_wrong_length() {
        // 31 hex chars instead of 32.
        assert!(validate_uuid("550e8400e29b41d4a71644665544000").is_err());
    }

    #[test]
    fn uuid_rejects_non_hex() {
        assert!(validate_uuid("550e8400-e29b-41d4-a716-44665544000g").is_err());
    }

    #[test]
    fn is_uuid_is_thin_boolean_wrapper() {
        assert!(is_uuid("550e8400-e29b-41d4-a716-446655440000"));
        assert!(!is_uuid("nope"));
    }

    // -------- validate_iso_date --------

    #[test]
    fn iso_date_accepts_well_formed() {
        assert!(validate_iso_date("2026-01-15").is_ok());
        assert!(validate_iso_date("1970-01-01").is_ok());
        assert!(validate_iso_date("9999-12-31").is_ok());
    }

    #[test]
    fn iso_date_rejects_out_of_range() {
        assert!(validate_iso_date("2026-02-30").is_err()); // Feb has no 30
        assert!(validate_iso_date("2026-13-01").is_err()); // month 13
        assert!(validate_iso_date("2026-00-01").is_err()); // month 0
        assert!(validate_iso_date("2026-01-32").is_err()); // day 32
    }

    #[test]
    fn iso_date_rejects_wrong_format() {
        // chrono's `%m` is lenient about padding — `2026-1-15` parses
        // OK. We only reject formats that are unambiguously not a
        // calendar date (US format, datetime-with-time, empty).
        assert!(validate_iso_date("01/15/2026").is_err()); // US format
        assert!(validate_iso_date("2026-01-15T00:00:00").is_err()); // datetime, not date
        assert!(validate_iso_date("").is_err());
    }

    // -------- validate_iso_time --------

    #[test]
    fn iso_time_accepts_well_formed() {
        assert!(validate_iso_time("14:30:00").is_ok());
        assert!(validate_iso_time("00:00:00").is_ok());
        assert!(validate_iso_time("23:59:59").is_ok());
    }

    #[test]
    fn iso_time_accepts_fractional_seconds() {
        assert!(validate_iso_time("14:30:00.123").is_ok());
        assert!(validate_iso_time("14:30:00.123456").is_ok());
    }

    #[test]
    fn iso_time_rejects_out_of_range() {
        assert!(validate_iso_time("24:00:00").is_err()); // hour 24
        assert!(validate_iso_time("14:60:00").is_err()); // minute 60
                                                         // Note: chrono accepts second=60 as a leap-second marker
                                                         // — that's intentional IETF/ISO behaviour, so we don't
                                                         // assert against it here.
    }

    #[test]
    fn iso_time_rejects_wrong_format() {
        assert!(validate_iso_time("2:30 PM").is_err());
        assert!(validate_iso_time("14:30").is_err()); // missing seconds
        assert!(validate_iso_time("").is_err());
    }

    // -------- validate_iso_datetime --------

    #[test]
    fn iso_datetime_accepts_z_offset() {
        assert!(validate_iso_datetime("2026-01-15T14:30:00Z").is_ok());
        assert!(validate_iso_datetime("2026-01-15T14:30:00.123Z").is_ok());
    }

    #[test]
    fn iso_datetime_accepts_explicit_offset() {
        assert!(validate_iso_datetime("2026-01-15T14:30:00+02:00").is_ok());
        assert!(validate_iso_datetime("2026-01-15T14:30:00-05:00").is_ok());
    }

    #[test]
    fn iso_datetime_rejects_naive_datetime() {
        // No timezone marker → rejected. Mixing naive + tz-aware
        // datetimes is a data-corruption vector.
        assert!(validate_iso_datetime("2026-01-15T14:30:00").is_err());
    }

    #[test]
    fn iso_datetime_rejects_garbage() {
        let e = validate_iso_datetime("not a date").unwrap_err();
        assert_eq!(e.code, "invalid_iso_datetime");
    }

    // -------- validate_alphanumeric / numeric / alpha --------

    #[test]
    fn alphanumeric_accepts_letters_and_digits() {
        assert!(validate_alphanumeric("abc123").is_ok());
        assert!(validate_alphanumeric("ABC").is_ok());
        assert!(validate_alphanumeric("9").is_ok());
    }

    #[test]
    fn alphanumeric_rejects_punctuation_spaces_and_empty() {
        assert!(validate_alphanumeric("abc 123").is_err());
        assert!(validate_alphanumeric("abc-123").is_err());
        assert!(validate_alphanumeric("abc!").is_err());
        assert!(validate_alphanumeric("").is_err());
    }

    #[test]
    fn alphanumeric_rejects_non_ascii_letters() {
        // ASCII-only — use unicode_slug for the broader variant.
        assert!(validate_alphanumeric("café").is_err());
    }

    #[test]
    fn numeric_accepts_digits_only() {
        assert!(validate_numeric("123").is_ok());
        assert!(validate_numeric("0").is_ok());
    }

    #[test]
    fn numeric_rejects_signs_decimal_letters_empty() {
        assert!(validate_numeric("-1").is_err());
        assert!(validate_numeric("3.14").is_err());
        assert!(validate_numeric("12a").is_err());
        assert!(validate_numeric("").is_err());
    }

    #[test]
    fn alpha_accepts_letters_only() {
        assert!(validate_alpha("Alice").is_ok());
        assert!(validate_alpha("Z").is_ok());
    }

    #[test]
    fn alpha_rejects_digits_punctuation_empty() {
        assert!(validate_alpha("abc1").is_err());
        assert!(validate_alpha("a b").is_err());
        assert!(validate_alpha("a-b").is_err());
        assert!(validate_alpha("").is_err());
    }

    // -------- validate_creditcard_luhn --------

    #[test]
    fn luhn_accepts_known_valid_pans() {
        // Standard test PANs from the major card networks.
        // Visa
        assert!(validate_creditcard_luhn("4111111111111111").is_ok());
        // Mastercard
        assert!(validate_creditcard_luhn("5555555555554444").is_ok());
        // Amex (15 digits — within 12-19 range)
        assert!(validate_creditcard_luhn("378282246310005").is_ok());
        // Discover
        assert!(validate_creditcard_luhn("6011111111111117").is_ok());
    }

    #[test]
    fn luhn_strips_spaces_and_hyphens() {
        // Typical human-typed shapes.
        assert!(validate_creditcard_luhn("4111 1111 1111 1111").is_ok());
        assert!(validate_creditcard_luhn("4111-1111-1111-1111").is_ok());
        assert!(validate_creditcard_luhn(" 4111-1111 1111-1111 ").is_ok());
    }

    #[test]
    fn luhn_rejects_wrong_checksum() {
        // Off-by-one on the last digit: Luhn catches it.
        let e = validate_creditcard_luhn("4111111111111112").unwrap_err();
        assert_eq!(e.code, "invalid_card_number");
    }

    #[test]
    fn luhn_rejects_non_digit_chars() {
        assert!(validate_creditcard_luhn("4111-1111-1111-abcd").is_err());
    }

    #[test]
    fn luhn_rejects_too_short_or_too_long() {
        // 11 digits: too short. 20 digits: too long.
        assert!(validate_creditcard_luhn("41111111111").is_err());
        assert!(validate_creditcard_luhn("41111111111111111111").is_err());
    }

    #[test]
    fn luhn_rejects_empty_and_whitespace_only() {
        assert!(validate_creditcard_luhn("").is_err());
        assert!(validate_creditcard_luhn("   ").is_err());
    }

    // -------- validate_isbn --------

    #[test]
    fn isbn10_accepts_real_books() {
        // "The C Programming Language" — ISBN-10 0131103628.
        assert!(validate_isbn("0131103628").is_ok());
        // ISBN-10 ending in X (check digit = 10).
        assert!(validate_isbn("080442957X").is_ok());
        // Lower-case x also accepted.
        assert!(validate_isbn("080442957x").is_ok());
    }

    #[test]
    fn isbn13_accepts_real_books() {
        // "The C Programming Language" 2nd ed — ISBN-13 9780131103627.
        assert!(validate_isbn("9780131103627").is_ok());
    }

    #[test]
    fn isbn_strips_spaces_and_hyphens() {
        assert!(validate_isbn("0-13-110362-8").is_ok());
        assert!(validate_isbn("978-0-13-110362-7").is_ok());
        assert!(validate_isbn(" 978 0 13 110362 7 ").is_ok());
    }

    #[test]
    fn isbn_rejects_wrong_checksum() {
        // Flip the last digit of a known good ISBN.
        let e = validate_isbn("0131103627").unwrap_err();
        assert_eq!(e.code, "invalid_isbn");
        assert!(validate_isbn("9780131103620").is_err());
    }

    #[test]
    fn isbn_rejects_wrong_length() {
        // 11 / 14 digits — neither valid ISBN length.
        assert!(validate_isbn("01311036280").is_err());
        assert!(validate_isbn("97801311036270").is_err());
        assert!(validate_isbn("").is_err());
    }

    #[test]
    fn isbn_rejects_non_digit_chars() {
        // Letters in the middle are never valid.
        assert!(validate_isbn("01311a3628").is_err());
        // X only valid as the 10th digit of ISBN-10.
        assert!(validate_isbn("9780131103X27").is_err());
        assert!(validate_isbn("X131103628").is_err());
    }

    // -------- validate_hostname --------

    #[test]
    fn hostname_accepts_common_shapes() {
        assert!(validate_hostname("example.com").is_ok());
        assert!(validate_hostname("sub.example.co.uk").is_ok());
        assert!(validate_hostname("localhost").is_ok()); // single label
        assert!(validate_hostname("api-v1.example.com").is_ok()); // hyphen in middle
        assert!(validate_hostname("123.example.com").is_ok()); // numeric leading label
    }

    #[test]
    fn hostname_rejects_leading_or_trailing_hyphen() {
        assert!(validate_hostname("-bad.example.com").is_err());
        assert!(validate_hostname("example-.com").is_err());
        assert!(validate_hostname("sub.-bad.com").is_err());
    }

    #[test]
    fn hostname_rejects_leading_or_trailing_dot() {
        assert!(validate_hostname(".example.com").is_err());
        assert!(validate_hostname("example.com.").is_err());
    }

    #[test]
    fn hostname_rejects_empty_label_between_dots() {
        assert!(validate_hostname("example..com").is_err());
    }

    #[test]
    fn hostname_rejects_invalid_chars() {
        assert!(validate_hostname("example.com/path").is_err());
        assert!(validate_hostname("ex_ample.com").is_err()); // underscore not allowed
        assert!(validate_hostname("ex ample.com").is_err());
        assert!(validate_hostname("café.com").is_err()); // ASCII only
    }

    #[test]
    fn hostname_rejects_oversize_label() {
        // 64-char label — 1 too long.
        let long_label: String = "a".repeat(64);
        assert!(validate_hostname(&format!("{long_label}.com")).is_err());
        // 63 chars is the max allowed.
        let max_label: String = "a".repeat(63);
        assert!(validate_hostname(&format!("{max_label}.com")).is_ok());
    }

    #[test]
    fn hostname_rejects_oversize_total() {
        // 254 chars total — 1 over the 253 cap.
        let label = "a".repeat(63);
        let too_long = format!("{label}.{label}.{label}.{label}xx"); // 63*4 + 3 dots + 2 = 257
        assert!(validate_hostname(&too_long).is_err());
    }

    #[test]
    fn hostname_rejects_empty() {
        assert!(validate_hostname("").is_err());
    }

    // -------- validate_iban --------

    #[test]
    fn iban_accepts_known_valid_examples() {
        // Standard test IBANs from various countries (ISO 13616).
        // UK
        assert!(validate_iban("GB82WEST12345698765432").is_ok());
        // Germany
        assert!(validate_iban("DE89370400440532013000").is_ok());
        // France
        assert!(validate_iban("FR1420041010050500013M02606").is_ok());
        // Norway (shortest standard IBAN — 15 chars)
        assert!(validate_iban("NO9386011117947").is_ok());
    }

    #[test]
    fn iban_strips_spaces() {
        // Printed form is space-grouped.
        assert!(validate_iban("GB82 WEST 1234 5698 7654 32").is_ok());
    }

    #[test]
    fn iban_rejects_wrong_checksum() {
        // Flip a digit in the check region.
        let e = validate_iban("GB82WEST12345698765431").unwrap_err();
        assert_eq!(e.code, "invalid_iban");
    }

    #[test]
    fn iban_rejects_wrong_format() {
        // Lowercase country code rejected (must be uppercase).
        assert!(validate_iban("gb82WEST12345698765432").is_err());
        // First 2 must be letters, next 2 digits.
        assert!(validate_iban("1B82WEST12345698765432").is_err());
        assert!(validate_iban("GBAB12345678901234567890").is_err());
        // Non-alphanumeric chars after the prefix rejected.
        assert!(validate_iban("GB82WEST!2345698765432").is_err());
    }

    #[test]
    fn iban_rejects_out_of_range_length() {
        // 4 chars total — below the 5-char floor.
        assert!(validate_iban("GB82").is_err());
        // 35 chars total — above the 34-char ceiling.
        let too_long = format!("GB82{}", "X".repeat(31));
        assert!(validate_iban(&too_long).is_err());
    }

    #[test]
    fn iban_rejects_empty_and_whitespace_only() {
        assert!(validate_iban("").is_err());
        assert!(validate_iban("   ").is_err());
    }

    // -------- validate_mac_address --------

    #[test]
    fn mac_accepts_colon_separated() {
        assert!(validate_mac_address("00:1A:2B:3C:4D:5E").is_ok());
        assert!(validate_mac_address("FF:FF:FF:FF:FF:FF").is_ok());
        assert!(validate_mac_address("00:00:00:00:00:00").is_ok());
    }

    #[test]
    fn mac_accepts_hyphen_separated() {
        assert!(validate_mac_address("00-1A-2B-3C-4D-5E").is_ok());
    }

    #[test]
    fn mac_accepts_lowercase_hex() {
        assert!(validate_mac_address("00:1a:2b:3c:4d:5e").is_ok());
        assert!(validate_mac_address("ff:ff:ff:ff:ff:ff").is_ok());
    }

    #[test]
    fn mac_rejects_no_separators() {
        // Bare 12-hex form (Cisco style) intentionally NOT supported
        // here — operators typing into a form expect : or - to
        // separate octets, and accepting both with-and-without
        // makes UX murky.
        assert!(validate_mac_address("001A2B3C4D5E").is_err());
    }

    #[test]
    fn mac_rejects_mixed_separators() {
        assert!(validate_mac_address("00:1A:2B-3C:4D:5E").is_err());
        assert!(validate_mac_address("00-1A:2B:3C:4D:5E").is_err());
    }

    #[test]
    fn mac_rejects_non_hex_chars() {
        assert!(validate_mac_address("00:1A:2B:3C:4D:5Z").is_err());
        assert!(validate_mac_address("00:1G:2B:3C:4D:5E").is_err());
    }

    #[test]
    fn mac_rejects_wrong_octet_length() {
        // Single-digit octets rejected (operators should zero-pad).
        assert!(validate_mac_address("0:1A:2B:3C:4D:5E").is_err());
        // Triple-digit octets rejected.
        assert!(validate_mac_address("000:1A:2B:3C:4D:5E").is_err());
    }

    #[test]
    fn mac_rejects_wrong_total_length() {
        assert!(validate_mac_address("").is_err());
        assert!(validate_mac_address("00:1A:2B:3C:4D").is_err()); // 5 octets
        assert!(validate_mac_address("00:1A:2B:3C:4D:5E:6F").is_err()); // 7 octets
    }

    // -------- validate_base64 --------

    #[test]
    fn base64_accepts_standard_alphabet() {
        // "Hello" → "SGVsbG8="
        assert!(validate_base64("SGVsbG8=").is_ok());
        // "Many hands" → "TWFueSBoYW5kcw=="
        assert!(validate_base64("TWFueSBoYW5kcw==").is_ok());
        // No padding needed when len % 3 == 0.
        assert!(validate_base64("abcd").is_ok());
    }

    #[test]
    fn base64_accepts_plus_and_slash() {
        // "?>>>" → "Pz4+Pg==" (uses + character).
        // Build a likely-valid string with + and /.
        assert!(validate_base64("AB+/").is_ok());
    }

    #[test]
    fn base64_rejects_urlsafe_chars() {
        // - and _ are URL-safe, not standard.
        assert!(validate_base64("AB-_").is_err());
    }

    #[test]
    fn base64_rejects_bad_padding_count() {
        // Three trailing = is never valid.
        assert!(validate_base64("AB===").is_err());
    }

    #[test]
    fn base64_rejects_non_multiple_of_4() {
        // Standard base64 with any padding must be a multiple of 4.
        assert!(validate_base64("ABCDE=").is_err()); // 6 chars, not 4n
    }

    #[test]
    fn base64_rejects_empty() {
        assert!(validate_base64("").is_err());
        assert!(validate_base64_urlsafe("").is_err());
    }

    // -------- validate_base64_urlsafe --------

    #[test]
    fn base64_urlsafe_accepts_dash_and_underscore() {
        assert!(validate_base64_urlsafe("AB-_").is_ok());
        assert!(validate_base64_urlsafe("SGVsbG8=").is_ok()); // standard chars also fine
    }

    #[test]
    fn base64_urlsafe_rejects_plus_and_slash() {
        assert!(validate_base64_urlsafe("AB+/").is_err());
    }

    #[test]
    fn base64_urlsafe_accepts_unpadded() {
        // URL-safe base64 commonly omits padding (JWT, etc.).
        // 5 chars, no padding — allowed for url-safe.
        assert!(validate_base64_urlsafe("ABCDE").is_ok());
    }

    // -------- validate_jwt_shape --------

    #[test]
    fn jwt_shape_accepts_valid_three_segments() {
        // Canonical JWT example: header.payload.signature
        // (3 URL-safe base64 segments, each non-empty).
        let jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.\
                   eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIn0.\
                   SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";
        assert!(validate_jwt_shape(jwt).is_ok());
    }

    #[test]
    fn jwt_shape_rejects_wrong_segment_count() {
        assert!(validate_jwt_shape("abc.def").is_err()); // 2 segments
        assert!(validate_jwt_shape("a.b.c.d").is_err()); // 4 segments
        assert!(validate_jwt_shape("no-dots").is_err());
    }

    #[test]
    fn jwt_shape_rejects_empty_segments() {
        assert!(validate_jwt_shape(".payload.sig").is_err());
        assert!(validate_jwt_shape("header..sig").is_err());
        assert!(validate_jwt_shape("header.payload.").is_err());
    }

    #[test]
    fn jwt_shape_rejects_non_urlsafe_chars_in_segment() {
        // `+` and `/` are standard-base64, not URL-safe — JWT spec
        // uses URL-safe alphabet.
        assert!(validate_jwt_shape("abc.de+f.ghi").is_err());
        assert!(validate_jwt_shape("abc.def.gh/i").is_err());
    }

    #[test]
    fn jwt_shape_rejects_empty() {
        assert!(validate_jwt_shape("").is_err());
    }

    // -------- validate_semver --------

    #[test]
    fn semver_accepts_canonical_form() {
        assert!(validate_semver("1.0.0").is_ok());
        assert!(validate_semver("0.0.1").is_ok());
        assert!(validate_semver("10.20.30").is_ok());
    }

    #[test]
    fn semver_accepts_pre_release() {
        assert!(validate_semver("1.0.0-alpha").is_ok());
        assert!(validate_semver("1.0.0-alpha.1").is_ok());
        assert!(validate_semver("1.0.0-0.3.7").is_ok());
        assert!(validate_semver("1.0.0-x-y-z.--").is_ok());
    }

    #[test]
    fn semver_accepts_build_metadata() {
        assert!(validate_semver("1.0.0+20130313144700").is_ok());
        assert!(validate_semver("1.0.0+exp.sha.5114f85").is_ok());
        // Build metadata IS allowed to have leading-zero numeric ids.
        assert!(validate_semver("1.0.0+007").is_ok());
    }

    #[test]
    fn semver_accepts_full_form() {
        assert!(validate_semver("1.0.0-rc.1+build.42").is_ok());
    }

    #[test]
    fn semver_rejects_missing_core_parts() {
        assert!(validate_semver("1").is_err());
        assert!(validate_semver("1.0").is_err());
        assert!(validate_semver("1.0.0.0").is_err());
        assert!(validate_semver("").is_err());
    }

    #[test]
    fn semver_rejects_leading_zero_in_core() {
        assert!(validate_semver("01.0.0").is_err());
        assert!(validate_semver("1.02.0").is_err());
        assert!(validate_semver("1.0.03").is_err());
        // But "0" itself is fine.
        assert!(validate_semver("0.0.0").is_ok());
    }

    #[test]
    fn semver_rejects_leading_zero_in_numeric_prerelease_id() {
        // Numeric pre-release IDs may NOT have leading zeros.
        assert!(validate_semver("1.0.0-01").is_err());
        assert!(validate_semver("1.0.0-alpha.01").is_err());
    }

    #[test]
    fn semver_rejects_empty_prerelease_or_build() {
        assert!(validate_semver("1.0.0-").is_err());
        assert!(validate_semver("1.0.0+").is_err());
        assert!(validate_semver("1.0.0-alpha..1").is_err());
    }

    #[test]
    fn semver_rejects_invalid_chars() {
        assert!(validate_semver("1.0.0-alpha_1").is_err()); // underscore not allowed
        assert!(validate_semver("1.0.0-alpha 1").is_err()); // space
        assert!(validate_semver("v1.0.0").is_err()); // leading v
    }

    // -------- validate_country_code --------

    #[test]
    fn country_code_accepts_two_uppercase_letters() {
        assert!(validate_country_code("US").is_ok());
        assert!(validate_country_code("GB").is_ok());
        assert!(validate_country_code("DE").is_ok());
        assert!(validate_country_code("JP").is_ok());
        // The format check accepts ANY 2 uppercase letters — `ZZ`
        // isn't a real country, but full validation against ISO
        // 3166-1 needs a maintained list (documented).
        assert!(validate_country_code("ZZ").is_ok());
    }

    #[test]
    fn country_code_rejects_wrong_length() {
        assert!(validate_country_code("U").is_err());
        assert!(validate_country_code("USA").is_err()); // alpha-3, not alpha-2
        assert!(validate_country_code("").is_err());
    }

    #[test]
    fn country_code_rejects_lowercase_or_non_letters() {
        assert!(validate_country_code("us").is_err());
        assert!(validate_country_code("Us").is_err());
        assert!(validate_country_code("U1").is_err());
        assert!(validate_country_code("U-").is_err());
    }

    // -------- validate_currency_code --------

    #[test]
    fn currency_code_accepts_three_uppercase_letters() {
        assert!(validate_currency_code("USD").is_ok());
        assert!(validate_currency_code("EUR").is_ok());
        assert!(validate_currency_code("GBP").is_ok());
        assert!(validate_currency_code("JPY").is_ok());
        assert!(validate_currency_code("XXX").is_ok()); // ZZZ-style
    }

    #[test]
    fn currency_code_rejects_wrong_length() {
        assert!(validate_currency_code("US").is_err());
        assert!(validate_currency_code("USDD").is_err());
        assert!(validate_currency_code("").is_err());
    }

    #[test]
    fn currency_code_rejects_lowercase_or_non_letters() {
        assert!(validate_currency_code("usd").is_err());
        assert!(validate_currency_code("UsD").is_err());
        assert!(validate_currency_code("U5D").is_err());
    }

    // -------- validate_language_tag --------

    #[test]
    fn language_tag_accepts_bare_lang() {
        assert!(validate_language_tag("en").is_ok());
        assert!(validate_language_tag("fr").is_ok());
        assert!(validate_language_tag("zh").is_ok());
        // 3-letter language (ISO 639-2/3).
        assert!(validate_language_tag("eng").is_ok());
    }

    #[test]
    fn language_tag_accepts_lang_with_region() {
        assert!(validate_language_tag("en-US").is_ok());
        assert!(validate_language_tag("fr-CA").is_ok());
        assert!(validate_language_tag("pt-BR").is_ok());
        // Numeric UN region code (es-419 = Latin American Spanish).
        assert!(validate_language_tag("es-419").is_ok());
    }

    #[test]
    fn language_tag_accepts_lang_with_script() {
        assert!(validate_language_tag("zh-Hans").is_ok());
        assert!(validate_language_tag("sr-Cyrl").is_ok());
        // Script + region.
        assert!(validate_language_tag("zh-Hans-CN").is_ok());
    }

    #[test]
    fn language_tag_rejects_uppercase_lang() {
        assert!(validate_language_tag("EN").is_err());
        assert!(validate_language_tag("En").is_err());
    }

    #[test]
    fn language_tag_rejects_wrong_region_case() {
        assert!(validate_language_tag("en-us").is_err());
        assert!(validate_language_tag("en-Us").is_err());
    }

    #[test]
    fn language_tag_rejects_wrong_lang_length() {
        assert!(validate_language_tag("e").is_err());
        assert!(validate_language_tag("english").is_err());
    }

    #[test]
    fn language_tag_rejects_too_many_parts() {
        // Variants / extensions / private-use not supported here.
        assert!(validate_language_tag("en-US-x-something").is_err());
    }

    #[test]
    fn language_tag_rejects_empty_or_garbage() {
        assert!(validate_language_tag("").is_err());
        assert!(validate_language_tag("not a tag").is_err());
        assert!(validate_language_tag("en_US").is_err()); // wrong separator
    }

    // -------- validate_postal_code_us --------

    #[test]
    fn postal_code_us_accepts_five_digit_zip() {
        assert!(validate_postal_code_us("94110").is_ok());
        assert!(validate_postal_code_us("00501").is_ok()); // valid northeast ZIP
        assert!(validate_postal_code_us("99950").is_ok());
    }

    #[test]
    fn postal_code_us_accepts_zip_plus_four() {
        assert!(validate_postal_code_us("12345-6789").is_ok());
        assert!(validate_postal_code_us("94110-0001").is_ok());
    }

    #[test]
    fn postal_code_us_rejects_wrong_length() {
        assert!(validate_postal_code_us("1234").is_err()); // 4 digits
        assert!(validate_postal_code_us("123456").is_err()); // 6 digits
        assert!(validate_postal_code_us("123456789").is_err()); // 9 digits without hyphen
    }

    #[test]
    fn postal_code_us_rejects_bad_plus_four_shape() {
        assert!(validate_postal_code_us("94110-").is_err()); // missing +4
        assert!(validate_postal_code_us("9411-12345").is_err()); // wrong prefix length
        assert!(validate_postal_code_us("94110-12").is_err()); // wrong suffix length
        assert!(validate_postal_code_us("94110-123A").is_err()); // non-digit in +4
    }

    #[test]
    fn postal_code_us_rejects_non_digit_in_base() {
        assert!(validate_postal_code_us("9411A").is_err());
        assert!(validate_postal_code_us("").is_err());
    }

    // -------- validate_postal_code_ca --------

    #[test]
    fn postal_code_ca_accepts_canonical_shape() {
        assert!(validate_postal_code_ca("K1A 0B1").is_ok()); // Parliament Hill
        assert!(validate_postal_code_ca("M5W 1E6").is_ok()); // Toronto
        assert!(validate_postal_code_ca("V6B 4Y8").is_ok()); // Vancouver
    }

    #[test]
    fn postal_code_ca_rejects_lowercase_letters() {
        assert!(validate_postal_code_ca("k1a 0b1").is_err());
        assert!(validate_postal_code_ca("K1a 0B1").is_err());
    }

    #[test]
    fn postal_code_ca_rejects_missing_space_or_wrong_separator() {
        assert!(validate_postal_code_ca("K1A0B1").is_err()); // no space
        assert!(validate_postal_code_ca("K1A-0B1").is_err()); // hyphen
        assert!(validate_postal_code_ca("K1A  0B1").is_err()); // double space
    }

    #[test]
    fn postal_code_ca_rejects_wrong_pattern() {
        assert!(validate_postal_code_ca("1AB 0B1").is_err()); // starts with digit
        assert!(validate_postal_code_ca("AAA 0B1").is_err()); // all letters
        assert!(validate_postal_code_ca("K1A 000").is_err()); // all digits
        assert!(validate_postal_code_ca("").is_err());
    }

    // -------- validate_postal_code_uk --------

    #[test]
    fn postal_code_uk_accepts_canonical_shapes() {
        // All the patterns from the docstring.
        assert!(validate_postal_code_uk("M1 1AA").is_ok()); // A9 9AA
        assert!(validate_postal_code_uk("B33 8TH").is_ok()); // A99 9AA
        assert!(validate_postal_code_uk("CR2 6XH").is_ok()); // AA9 9AA
        assert!(validate_postal_code_uk("DN55 1PT").is_ok()); // AA99 9AA
        assert!(validate_postal_code_uk("W1A 1AA").is_ok()); // A9A 9AA
        assert!(validate_postal_code_uk("EC1A 1BB").is_ok()); // AA9A 9AA
        assert!(validate_postal_code_uk("SW1A 1AA").is_ok()); // Downing Street
    }

    #[test]
    fn postal_code_uk_rejects_missing_space() {
        assert!(validate_postal_code_uk("SW1A1AA").is_err());
    }

    #[test]
    fn postal_code_uk_rejects_lowercase() {
        assert!(validate_postal_code_uk("sw1a 1aa").is_err());
    }

    #[test]
    fn postal_code_uk_rejects_wrong_inward_length() {
        assert!(validate_postal_code_uk("M1 1A").is_err());
        assert!(validate_postal_code_uk("M1 1AAA").is_err());
    }

    #[test]
    fn postal_code_uk_rejects_wrong_inward_pattern() {
        // Inward must be digit-letter-letter.
        assert!(validate_postal_code_uk("M1 AAA").is_err()); // letter-letter-letter
        assert!(validate_postal_code_uk("M1 123").is_err()); // all digits
    }

    #[test]
    fn postal_code_uk_rejects_outward_starting_with_digit() {
        assert!(validate_postal_code_uk("1A 1AA").is_err());
    }

    #[test]
    fn postal_code_uk_rejects_empty() {
        assert!(validate_postal_code_uk("").is_err());
    }

    // -------- validate_file_extension (Django parity) --------

    #[test]
    fn file_extension_accepts_allowed() {
        assert!(validate_file_extension("photo.jpg", &["jpg", "png"]).is_ok());
        assert!(validate_file_extension("photo.png", &["jpg", "png"]).is_ok());
    }

    #[test]
    fn file_extension_case_insensitive() {
        // Django parity: uppercase extension still matches lowercase allowlist.
        assert!(validate_file_extension("PHOTO.JPG", &["jpg"]).is_ok());
        assert!(validate_file_extension("photo.Jpeg", &["jpeg"]).is_ok());
    }

    #[test]
    fn file_extension_strips_leading_dot_on_allowlist() {
        // Convenience: callers can pass `.jpg` or `jpg` — either works.
        assert!(validate_file_extension("photo.jpg", &[".jpg"]).is_ok());
    }

    #[test]
    fn file_extension_rejects_disallowed() {
        let err = validate_file_extension("malware.exe", &["jpg", "png"]).unwrap_err();
        assert_eq!(err.code, "invalid_extension");
        assert!(err.message.contains("'exe'"));
    }

    #[test]
    fn file_extension_uses_last_dot_only() {
        // Django parity: archive.tar.gz has extension "gz", not "tar.gz".
        assert!(validate_file_extension("archive.tar.gz", &["gz"]).is_ok());
        assert!(validate_file_extension("archive.tar.gz", &["tar.gz"]).is_err());
    }

    #[test]
    fn file_extension_rejects_no_extension() {
        let err = validate_file_extension("README", &["txt", "md"]).unwrap_err();
        assert_eq!(err.code, "invalid_extension");
    }

    // -------- validate_image_file_extension --------

    #[test]
    fn image_file_extension_accepts_common_formats() {
        assert!(validate_image_file_extension("photo.jpg").is_ok());
        assert!(validate_image_file_extension("photo.jpeg").is_ok());
        assert!(validate_image_file_extension("logo.png").is_ok());
        assert!(validate_image_file_extension("animation.gif").is_ok());
        assert!(validate_image_file_extension("modern.webp").is_ok());
        assert!(validate_image_file_extension("vector.svg").is_err()); // SVG NOT in Pillow's list
    }

    #[test]
    fn image_file_extension_rejects_documents() {
        // Common non-image extensions Django would reject.
        assert!(validate_image_file_extension("doc.txt").is_err());
        assert!(validate_image_file_extension("script.js").is_err());
        assert!(validate_image_file_extension("malware.exe").is_err());
    }

    #[test]
    fn image_file_extension_case_insensitive() {
        assert!(validate_image_file_extension("PHOTO.JPG").is_ok());
        assert!(validate_image_file_extension("Photo.PNG").is_ok());
    }

    // -------- validate_file_size_max (Django parity) --------

    #[test]
    fn file_size_max_accepts_under_limit() {
        assert!(validate_file_size_max(0, 1024).is_ok());
        assert!(validate_file_size_max(500, 1024).is_ok());
        assert!(validate_file_size_max(1024, 1024).is_ok()); // exact match passes
    }

    #[test]
    fn file_size_max_rejects_over_limit() {
        let err = validate_file_size_max(1025, 1024).unwrap_err();
        assert_eq!(err.code, "file_too_large");
        assert!(err.message.contains("1025"));
        assert!(err.message.contains("1024"));
    }

    #[test]
    fn file_size_max_handles_zero_limit() {
        // Pathological but well-defined: max=0 means anything fails.
        assert!(validate_file_size_max(0, 0).is_ok()); // 0 <= 0
        assert!(validate_file_size_max(1, 0).is_err());
    }

    // -------- validate_file_mime_type (Django parity) --------

    #[test]
    fn file_mime_type_accepts_exact_match() {
        assert!(validate_file_mime_type("image/png", &["image/png"]).is_ok());
        assert!(validate_file_mime_type("image/png", &["image/png", "image/jpeg"]).is_ok());
    }

    #[test]
    fn file_mime_type_accepts_wildcard_subtype() {
        // HTML <input accept="image/*"> shape.
        assert!(validate_file_mime_type("image/png", &["image/*"]).is_ok());
        assert!(validate_file_mime_type("image/webp", &["image/*"]).is_ok());
        assert!(validate_file_mime_type("text/plain", &["image/*"]).is_err());
    }

    #[test]
    fn file_mime_type_ignores_charset_parameter() {
        assert!(validate_file_mime_type("text/html; charset=utf-8", &["text/html"]).is_ok());
        assert!(validate_file_mime_type("text/html;charset=utf-8", &["text/html"]).is_ok());
    }

    #[test]
    fn file_mime_type_case_insensitive() {
        assert!(validate_file_mime_type("Image/PNG", &["image/png"]).is_ok());
        assert!(validate_file_mime_type("IMAGE/JPEG", &["image/jpeg"]).is_ok());
    }

    #[test]
    fn file_mime_type_rejects_unknown() {
        let err = validate_file_mime_type("application/x-msdownload", &["image/png", "image/jpeg"])
            .unwrap_err();
        assert_eq!(err.code, "invalid_mime_type");
        assert!(err.message.contains("application/x-msdownload"));
    }

    #[test]
    fn file_mime_type_wildcard_does_not_cross_top_level_type() {
        // image/* must NOT match application/json
        assert!(validate_file_mime_type("application/json", &["image/*"]).is_err());
    }

    // -------- validate_step_value (Django parity) --------

    #[test]
    fn step_value_accepts_multiples_of_step() {
        // step=0.5 from offset=0 → 0, 0.5, 1, 1.5 ... all valid.
        assert!(validate_step_value(0.0, 0.5, 0.0).is_ok());
        assert!(validate_step_value(0.5, 0.5, 0.0).is_ok());
        assert!(validate_step_value(1.0, 0.5, 0.0).is_ok());
        assert!(validate_step_value(1.5, 0.5, 0.0).is_ok());
        assert!(validate_step_value(-1.5, 0.5, 0.0).is_ok());
    }

    #[test]
    fn step_value_rejects_off_grid_values() {
        let err = validate_step_value(1.3, 0.5, 0.0).unwrap_err();
        assert_eq!(err.code, "step_size");
        assert!(err.message.contains("0.5"));
    }

    #[test]
    fn step_value_honors_offset() {
        // step=10 with offset=5 → 5, 15, 25, ... valid; 0, 10, 20, ... invalid.
        assert!(validate_step_value(5.0, 10.0, 5.0).is_ok());
        assert!(validate_step_value(15.0, 10.0, 5.0).is_ok());
        assert!(validate_step_value(25.0, 10.0, 5.0).is_ok());
        let err = validate_step_value(10.0, 10.0, 5.0).unwrap_err();
        assert_eq!(err.code, "step_size");
        assert!(err.message.contains("5"));
    }

    #[test]
    fn step_value_tolerates_floating_point_round_off() {
        // 0.1 + 0.2 != 0.3 in f64, but 0.3 should still be a multiple of 0.1.
        assert!(validate_step_value(0.1 + 0.2, 0.1, 0.0).is_ok());
        // 1.5 / 0.5 = 3.0 exactly — guard against accidentally tight tolerance.
        assert!(validate_step_value(1.5, 0.5, 0.0).is_ok());
    }

    #[test]
    fn step_value_rejects_zero_or_negative_step() {
        let err = validate_step_value(1.0, 0.0, 0.0).unwrap_err();
        assert_eq!(err.code, "invalid_step");
        let err = validate_step_value(1.0, -0.5, 0.0).unwrap_err();
        assert_eq!(err.code, "invalid_step");
    }

    #[test]
    fn step_value_rejects_nan() {
        let err = validate_step_value(f64::NAN, 0.5, 0.0).unwrap_err();
        assert_eq!(err.code, "step_size");
    }

    #[test]
    fn step_value_integer_step_works() {
        // step=5 from offset=0 → 0, 5, 10, 15, ... — common HTML5 form
        // case: step="5" attribute on a number input.
        assert!(validate_step_value(0.0, 5.0, 0.0).is_ok());
        assert!(validate_step_value(25.0, 5.0, 0.0).is_ok());
        assert!(validate_step_value(7.0, 5.0, 0.0).is_err());
    }

    // -------- clean_ipv6_address (Django parity) --------

    #[test]
    fn clean_ipv6_compresses_zero_run() {
        // Long form → canonical compressed form.
        assert_eq!(
            clean_ipv6_address("2001:0db8:0000:0000:0000:0000:0000:0001", false),
            Some("2001:db8::1".to_owned())
        );
    }

    #[test]
    fn clean_ipv6_already_compressed_passes_through() {
        assert_eq!(
            clean_ipv6_address("2001:db8::1", false),
            Some("2001:db8::1".to_owned())
        );
    }

    #[test]
    fn clean_ipv6_lowercases_hex_digits() {
        // Uppercase hex input gets folded to lowercase per RFC 5952.
        assert_eq!(
            clean_ipv6_address("2001:DB8::ABCD", false),
            Some("2001:db8::abcd".to_owned())
        );
    }

    #[test]
    fn clean_ipv6_unpack_ipv4_mapped_to_dotted_quad() {
        // ::ffff:192.0.2.1 unpacks to 192.0.2.1 when flag set.
        assert_eq!(
            clean_ipv6_address("::ffff:192.0.2.1", true),
            Some("192.0.2.1".to_owned())
        );
    }

    #[test]
    fn clean_ipv6_unpack_off_preserves_mapped_form() {
        // unpack_ipv4=false → keep IPv6 textual form.
        let out = clean_ipv6_address("::ffff:192.0.2.1", false).unwrap();
        assert!(out.contains("ffff"));
    }

    #[test]
    fn clean_ipv6_loopback() {
        assert_eq!(
            clean_ipv6_address("0:0:0:0:0:0:0:1", false),
            Some("::1".to_owned())
        );
    }

    #[test]
    fn clean_ipv6_rejects_garbage() {
        assert!(clean_ipv6_address("not an ip", false).is_none());
        assert!(clean_ipv6_address("", false).is_none());
        // IPv4 is NOT IPv6.
        assert!(clean_ipv6_address("192.0.2.1", false).is_none());
    }

    // -------- validate_ipv46_address (Django parity) --------

    #[test]
    fn ipv46_accepts_ipv4() {
        assert!(validate_ipv46_address("192.0.2.1").is_ok());
        assert!(validate_ipv46_address("127.0.0.1").is_ok());
        assert!(validate_ipv46_address("255.255.255.255").is_ok());
    }

    #[test]
    fn ipv46_accepts_ipv6() {
        assert!(validate_ipv46_address("2001:db8::1").is_ok());
        assert!(validate_ipv46_address("::1").is_ok());
        assert!(validate_ipv46_address("::").is_ok());
    }

    #[test]
    fn ipv46_rejects_neither() {
        let err = validate_ipv46_address("not an ip").unwrap_err();
        assert_eq!(err.code, "invalid_ip_address");
        assert!(err.message.contains("IPv4"));
        assert!(err.message.contains("IPv6"));
    }

    #[test]
    fn ipv46_rejects_empty() {
        assert!(validate_ipv46_address("").is_err());
    }

    #[test]
    fn ipv46_rejects_ipv4_out_of_range() {
        // 256.0.0.1 isn't a valid IPv4 — should also fail as IPv6.
        assert!(validate_ipv46_address("256.0.0.1").is_err());
    }

    // -------- int_list_validator --------

    #[test]
    fn int_list_comma_basic() {
        assert!(int_list_validator("1,2,3", ",", false).is_ok());
        assert!(int_list_validator("100,200,300", ",", false).is_ok());
        assert!(int_list_validator("42", ",", false).is_ok()); // single int
    }

    #[test]
    fn int_list_custom_separator() {
        assert!(int_list_validator("1 2 3", " ", false).is_ok());
        assert!(int_list_validator("1|2|3", "|", false).is_ok());
        assert!(int_list_validator("1:2:3", ":", false).is_ok());
        assert!(int_list_validator("1;2;3", ";", false).is_ok());
    }

    #[test]
    fn int_list_allows_negative_when_flagged() {
        assert!(int_list_validator("1,-2,3", ",", true).is_ok());
        assert!(int_list_validator("-1,-2,-3", ",", true).is_ok());
        // Same input rejected when allow_negative=false.
        assert!(int_list_validator("1,-2,3", ",", false).is_err());
    }

    #[test]
    fn int_list_rejects_non_integer() {
        assert!(int_list_validator("1,abc,3", ",", false).is_err());
        assert!(int_list_validator("1,2.5,3", ",", false).is_err()); // float
        assert!(int_list_validator("1, ,3", ",", false).is_err()); // empty element
    }

    #[test]
    fn int_list_rejects_empty_input() {
        assert!(int_list_validator("", ",", false).is_err());
        assert!(int_list_validator("   ", ",", false).is_err());
    }

    #[test]
    fn int_list_rejects_empty_separator() {
        assert!(int_list_validator("1,2,3", "", false).is_err());
    }

    #[test]
    fn int_list_trims_whitespace_around_elements() {
        // Django shape: whitespace around each element is tolerated.
        assert!(int_list_validator("1, 2, 3", ",", false).is_ok());
        assert!(int_list_validator("  10 ,  20 ,  30  ", ",", false).is_ok());
    }

    // -------- is_* boolean companions --------

    #[test]
    fn is_alpha_companion() {
        assert!(is_alpha("hello"));
        assert!(!is_alpha("hello1"));
    }

    #[test]
    fn is_alphanumeric_companion() {
        assert!(is_alphanumeric("abc123"));
        assert!(!is_alphanumeric("abc 123"));
    }

    #[test]
    fn is_numeric_companion() {
        assert!(is_numeric("12345"));
        assert!(!is_numeric("12a"));
    }

    #[test]
    fn is_creditcard_luhn_companion() {
        // 4111-1111-1111-1111 is the canonical Visa test card.
        assert!(is_creditcard_luhn("4111111111111111"));
        assert!(!is_creditcard_luhn("1234567890123456"));
    }

    #[test]
    fn is_hostname_companion() {
        assert!(is_hostname("example.com"));
        assert!(!is_hostname("not a hostname"));
    }

    #[test]
    fn is_iban_companion() {
        // Valid German IBAN test value (publicly known).
        assert!(is_iban("DE89370400440532013000"));
        assert!(!is_iban("XX00garbage"));
    }

    #[test]
    fn is_mac_address_companion() {
        assert!(is_mac_address("00:1A:2B:3C:4D:5E"));
        assert!(!is_mac_address("not-a-mac"));
    }

    #[test]
    fn is_semver_companion() {
        assert!(is_semver("1.2.3"));
        assert!(is_semver("1.2.3-alpha+build"));
        assert!(!is_semver("1.2"));
    }

    #[test]
    fn is_isbn_companion() {
        // Valid ISBN-13.
        assert!(is_isbn("9780132350884"));
        assert!(!is_isbn("not-an-isbn"));
    }

    #[test]
    fn is_iso_date_companion() {
        assert!(is_iso_date("2026-06-05"));
        assert!(!is_iso_date("06/05/2026"));
    }

    #[test]
    fn is_iso_time_companion() {
        assert!(is_iso_time("12:30:00"));
        assert!(!is_iso_time("12 30"));
    }

    #[test]
    fn is_iso_datetime_companion() {
        assert!(is_iso_datetime("2026-06-05T12:30:00Z"));
        assert!(!is_iso_datetime("2026-06-05"));
    }

    #[test]
    fn is_base64_companion() {
        assert!(is_base64("SGVsbG8="));
        assert!(!is_base64("not base 64!"));
    }

    #[test]
    fn is_base64_urlsafe_companion() {
        assert!(is_base64_urlsafe("SGVsbG8"));
        assert!(!is_base64_urlsafe("not+base/64"));
    }

    #[test]
    fn is_jwt_shape_companion() {
        // Three dot-separated base64url segments.
        assert!(is_jwt_shape("eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.sig"));
        assert!(!is_jwt_shape("not.a.jwt.shape.four.dots"));
    }

    #[test]
    fn is_country_code_companion() {
        assert!(is_country_code("US"));
        assert!(is_country_code("DE"));
        assert!(!is_country_code("USA"));
        assert!(!is_country_code("us"));
    }

    #[test]
    fn is_currency_code_companion() {
        assert!(is_currency_code("USD"));
        assert!(is_currency_code("EUR"));
        assert!(!is_currency_code("US"));
        assert!(!is_currency_code("usd"));
    }

    #[test]
    fn is_language_tag_companion() {
        assert!(is_language_tag("en"));
        assert!(is_language_tag("en-US"));
        assert!(is_language_tag("zh-Hant-TW"));
        assert!(!is_language_tag(""));
        assert!(!is_language_tag("not a tag"));
    }

    #[test]
    fn is_postal_code_us_companion() {
        assert!(is_postal_code_us("90210"));
        assert!(is_postal_code_us("90210-1234"));
        assert!(!is_postal_code_us("9021"));
        assert!(!is_postal_code_us("ABCDE"));
    }

    #[test]
    fn is_postal_code_ca_companion() {
        assert!(is_postal_code_ca("K1A 0B1"));
        // CA validator enforces the mandatory single space — no-space
        // form rejects.
        assert!(!is_postal_code_ca("K1A0B1"));
        assert!(!is_postal_code_ca("90210"));
    }

    #[test]
    fn is_postal_code_uk_companion() {
        assert!(is_postal_code_uk("SW1A 1AA"));
        assert!(!is_postal_code_uk("90210"));
    }

    #[test]
    fn is_ipv4_address_companion() {
        assert!(is_ipv4_address("127.0.0.1"));
        assert!(is_ipv4_address("255.255.255.255"));
        assert!(!is_ipv4_address("::1"));
        assert!(!is_ipv4_address("not.an.ip"));
    }

    #[test]
    fn is_ipv6_address_companion() {
        assert!(is_ipv6_address("::1"));
        assert!(is_ipv6_address("2001:db8::1"));
        assert!(!is_ipv6_address("127.0.0.1"));
    }

    #[test]
    fn is_ipv46_address_accepts_both_families() {
        assert!(is_ipv46_address("127.0.0.1"));
        assert!(is_ipv46_address("::1"));
        assert!(!is_ipv46_address("not.an.ip"));
        // Symmetric is_ip_address alias.
        assert!(is_ip_address("127.0.0.1"));
        assert!(is_ip_address("::1"));
    }

    #[test]
    fn is_filepath_companion() {
        assert!(is_filepath("/var/lib/data.json"));
        assert!(is_filepath("./relative/path"));
        // NUL byte in input → reject.
        assert!(!is_filepath("/etc/passwd\0"));
    }

    // -------- validate_email_with_name (gated on `email` feature) --------

    #[cfg(feature = "email")]
    #[test]
    fn email_with_name_accepts_bare_email() {
        assert!(validate_email_with_name("alice@example.com").is_ok());
    }

    #[cfg(feature = "email")]
    #[test]
    fn email_with_name_accepts_display_name_form() {
        assert!(validate_email_with_name("Alice <alice@example.com>").is_ok());
        assert!(validate_email_with_name("\"Alice C.\" <alice@example.com>").is_ok());
    }

    #[cfg(feature = "email")]
    #[test]
    fn email_with_name_rejects_invalid_email_portion() {
        assert!(validate_email_with_name("not an email").is_err());
        assert!(validate_email_with_name("Display <not.an.email>").is_err());
        assert!(validate_email_with_name("").is_err());
    }

    #[cfg(feature = "email")]
    #[test]
    fn is_email_with_name_companion() {
        assert!(is_email_with_name("alice@example.com"));
        assert!(is_email_with_name("Alice <alice@example.com>"));
        assert!(!is_email_with_name("garbage"));
    }

    // -------- validate_image_dimensions --------

    #[test]
    fn image_dimensions_max_only_accepts_within_bounds() {
        assert!(validate_image_dimensions(1024, 1024, Some(2000), Some(2000), None, None).is_ok());
        assert!(validate_image_dimensions(2000, 2000, Some(2000), Some(2000), None, None).is_ok());
    }

    #[test]
    fn image_dimensions_max_rejects_too_wide() {
        let err =
            validate_image_dimensions(3000, 1024, Some(2000), Some(2000), None, None).unwrap_err();
        assert_eq!(err.code, "image_too_wide");
        assert!(err.message.contains("3000"));
        assert!(err.message.contains("2000"));
    }

    #[test]
    fn image_dimensions_max_rejects_too_tall() {
        let err =
            validate_image_dimensions(1024, 3000, Some(2000), Some(2000), None, None).unwrap_err();
        assert_eq!(err.code, "image_too_tall");
    }

    #[test]
    fn image_dimensions_min_rejects_too_narrow() {
        let err = validate_image_dimensions(50, 200, None, None, Some(100), Some(100)).unwrap_err();
        assert_eq!(err.code, "image_too_narrow");
    }

    #[test]
    fn image_dimensions_min_rejects_too_short() {
        let err = validate_image_dimensions(200, 50, None, None, Some(100), Some(100)).unwrap_err();
        assert_eq!(err.code, "image_too_short");
    }

    #[test]
    fn image_dimensions_no_bounds_always_ok() {
        assert!(validate_image_dimensions(1, 1, None, None, None, None).is_ok());
        assert!(validate_image_dimensions(99999, 99999, None, None, None, None).is_ok());
    }

    #[test]
    fn image_dimensions_combined_bounds() {
        // Must be at least 100×100 and at most 2000×2000.
        assert!(
            validate_image_dimensions(500, 500, Some(2000), Some(2000), Some(100), Some(100))
                .is_ok()
        );
        // Above max width fails first.
        let err =
            validate_image_dimensions(2500, 500, Some(2000), Some(2000), Some(100), Some(100))
                .unwrap_err();
        assert_eq!(err.code, "image_too_wide");
        // Below min height fails (after maxes pass).
        let err = validate_image_dimensions(1500, 50, Some(2000), Some(2000), Some(100), Some(100))
            .unwrap_err();
        assert_eq!(err.code, "image_too_short");
    }
}