delaunay 0.8.0

D-dimensional Delaunay triangulations and convex hulls in Rust, with exact predicates, deterministic degeneracy handling, explicit topology validation, and bistellar flips for finite point sets.
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
//! Hilbert space-filling curve ordering utilities.
//!
//! This module provides stateless, pure functions for mapping D-dimensional coordinates
//! to 1D Hilbert curve indices and for sorting arbitrary items by that ordering.
//!
//! ## Scope
//! - No triangulation types (no `Vertex`, no keys, no TDS access)
//! - Pure ordering primitives suitable for reuse across the crate

#![forbid(unsafe_code)]

use crate::geometry::coordinate_range::{
    CoordinateRange, CoordinateRangeError, CoordinateRangeOrdering,
};
use core::fmt;
use num_traits::ToPrimitive;
use std::num::NonZeroU32;

/// Maximum supported Hilbert bit depth per coordinate accepted by [`HilbertBitDepth`].
pub const MAX_HILBERT_BITS: u32 = 31;

/// Errors that can occur during Hilbert curve operations.
#[derive(Clone, Debug, thiserror::Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum HilbertError {
    /// The `bits` parameter is out of valid range [1, 31].
    #[error("bits parameter {bits} is out of valid range [1, 31]")]
    InvalidBitsParameter {
        /// The invalid bits value provided.
        bits: u32,
    },

    /// The combination of dimension and bits would cause index overflow.
    #[error(
        "Hilbert index would overflow u128: dimension {dimension} * bits {bits} = {total_bits} > 128"
    )]
    IndexOverflow {
        /// The dimension of the coordinate space.
        dimension: usize,
        /// The bits parameter.
        bits: u32,
        /// The total number of bits required (dimension * bits).
        total_bits: u128,
    },

    /// The dimension is too large to represent.
    #[error("dimension {dimension} is too large (exceeds u32::MAX)")]
    DimensionTooLarge {
        /// The dimension that exceeded representable limits.
        dimension: usize,
    },

    /// A Hilbert quantization bound was non-finite.
    #[error(
        "Hilbert quantization bounds must be finite: lower bound finite = {lower_bound_finite}, upper bound finite = {upper_bound_finite}"
    )]
    NonFiniteBounds {
        /// Whether the lower quantization bound is finite.
        lower_bound_finite: bool,
        /// Whether the upper quantization bound is finite.
        upper_bound_finite: bool,
    },

    /// Finite Hilbert quantization bounds were equal or decreasing.
    #[error("Hilbert quantization bounds must satisfy min < max ({ordering})")]
    NonIncreasingBounds {
        /// Whether the bounds were equal or decreasing.
        ordering: CoordinateRangeOrdering,
    },

    /// Finite bounds produced a non-finite quantization extent.
    #[error("Hilbert quantization bounds produced a non-finite extent")]
    NonFiniteBoundsExtent {},

    /// A coordinate to quantize was non-finite.
    #[error("Hilbert coordinate at index {coordinate_index} must be finite")]
    NonFiniteCoordinate {
        /// The coordinate index whose value was non-finite.
        coordinate_index: usize,
    },

    /// A finite coordinate and finite bounds produced a non-finite normalized value.
    #[error(
        "Hilbert coordinate at index {coordinate_index} produced a non-finite normalized value"
    )]
    NonFiniteNormalizedCoordinate {
        /// The coordinate index whose normalized value was non-finite.
        coordinate_index: usize,
    },

    /// A rounded, scaled coordinate could not be represented as a `u32`.
    #[error(
        "Hilbert quantized coordinate at index {coordinate_index} for {bits} bits and grid maximum {max_grid_value} cannot be represented as u32"
    )]
    QuantizedCoordinateConversionFailed {
        /// The requested number of Hilbert bits per coordinate.
        bits: u32,
        /// The computed grid maximum, `2^bits - 1`.
        max_grid_value: u32,
        /// The coordinate index whose rounded scaled value could not be converted.
        coordinate_index: usize,
    },

    /// A pre-quantized coordinate exceeded the grid range implied by the bit depth.
    #[error(
        "pre-quantized Hilbert coordinate at point {point_index}, coordinate {coordinate_index} has value {coordinate}, which exceeds the maximum {max_grid_value} for {bits} bits"
    )]
    PrequantizedCoordinateOutOfRange {
        /// The requested number of Hilbert bits per coordinate.
        bits: u32,
        /// The computed grid maximum, `2^bits - 1`.
        max_grid_value: u32,
        /// The point index whose pre-quantized coordinate was out of range.
        point_index: usize,
        /// The coordinate index whose value was out of range.
        coordinate_index: usize,
        /// The out-of-range pre-quantized coordinate value.
        coordinate: u32,
    },

    /// An internally constructed Hilbert sort permutation had the wrong length.
    #[error(
        "Hilbert sort permutation length mismatch: item count {item_count}, permutation count {permutation_count}"
    )]
    InvalidSortPermutationLength {
        /// Number of items being sorted.
        item_count: usize,
        /// Number of indices in the permutation.
        permutation_count: usize,
    },

    /// An internally constructed Hilbert sort permutation referenced an invalid item index.
    #[error(
        "Hilbert sort permutation index {permutation_index} has value {item_index}, which is outside item count {item_count}"
    )]
    InvalidSortPermutationIndex {
        /// Position in the permutation whose value was invalid.
        permutation_index: usize,
        /// Invalid source item index.
        item_index: usize,
        /// Number of items being sorted.
        item_count: usize,
    },

    /// An internally constructed Hilbert sort permutation referenced the same item twice.
    #[error("Hilbert sort permutation index {permutation_index} repeats item index {item_index}")]
    InvalidSortPermutationDuplicate {
        /// Position in the permutation whose value repeated an earlier item.
        permutation_index: usize,
        /// Repeated source item index.
        item_index: usize,
    },
}

/// Validated Hilbert bit depth per coordinate.
///
/// Values are constrained to the inclusive range from `1` through
/// [`MAX_HILBERT_BITS`], matching the `u32` quantization grid used by the
/// Hilbert ordering implementation. Public Hilbert APIs accept this type so raw
/// bit-depth validation happens once at the boundary instead of being repeated
/// during sorting or index computation.
///
/// # Examples
///
/// ```rust
/// use delaunay::prelude::ordering::{HilbertBitDepth, HilbertError, MAX_HILBERT_BITS};
///
/// let bits = HilbertBitDepth::try_new(8)?;
/// assert_eq!(bits.get(), 8);
/// assert!(HilbertBitDepth::try_new(MAX_HILBERT_BITS).is_ok());
///
/// std::assert_matches!(
///     HilbertBitDepth::try_new(0),
///     Err(HilbertError::InvalidBitsParameter { bits: 0 })
/// );
/// # Ok::<(), HilbertError>(())
/// ```
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
#[must_use]
pub struct HilbertBitDepth(NonZeroU32);

impl HilbertBitDepth {
    /// Parses a raw bit depth into a validated Hilbert bit depth.
    ///
    /// # Errors
    ///
    /// Returns [`HilbertError::InvalidBitsParameter`] if `bits` is outside
    /// the supported `1..=31` range.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use delaunay::prelude::ordering::{HilbertBitDepth, HilbertError};
    ///
    /// let bits = HilbertBitDepth::try_new(12)?;
    /// assert_eq!(bits.get(), 12);
    ///
    /// std::assert_matches!(
    ///     HilbertBitDepth::try_new(32),
    ///     Err(HilbertError::InvalidBitsParameter { bits: 32 })
    /// );
    /// # Ok::<(), HilbertError>(())
    /// ```
    pub const fn try_new(bits: u32) -> Result<Self, HilbertError> {
        let Some(bits) = NonZeroU32::new(bits) else {
            return Err(HilbertError::InvalidBitsParameter { bits: 0 });
        };
        if bits.get() > MAX_HILBERT_BITS {
            return Err(HilbertError::InvalidBitsParameter { bits: bits.get() });
        }
        Ok(Self(bits))
    }

    /// Returns the validated bit depth as a raw integer.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use delaunay::prelude::ordering::{HilbertBitDepth, HilbertError};
    ///
    /// let bits = HilbertBitDepth::try_new(16)?;
    /// assert_eq!(bits.get(), 16);
    /// # Ok::<(), HilbertError>(())
    /// ```
    #[must_use]
    pub const fn get(self) -> u32 {
        self.0.get()
    }
}

impl TryFrom<u32> for HilbertBitDepth {
    type Error = HilbertError;

    fn try_from(bits: u32) -> Result<Self, Self::Error> {
        Self::try_new(bits)
    }
}

impl fmt::Display for HilbertBitDepth {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.get().fmt(f)
    }
}

/// Pre-quantized Hilbert coordinates proven to fit a selected bit-depth grid.
///
/// This borrowed wrapper carries the validation evidence for a batch of
/// caller-supplied quantized coordinates. Use [`Self::try_new`] at the boundary,
/// then call [`Self::indices`] or [`hilbert_indices_for_quantized_batch`] for an
/// infallible mapping to Hilbert indices.
///
/// # Examples
///
/// ```rust
/// use delaunay::prelude::ordering::{
///     HilbertBitDepth, HilbertError, HilbertQuantizedBatch,
/// };
///
/// let quantized = [[0_u32, 0], [3, 3]];
/// let bits = HilbertBitDepth::try_new(2)?;
/// let batch = HilbertQuantizedBatch::try_new(&quantized, bits)?;
///
/// let indices = batch.indices();
/// assert_eq!(indices.len(), quantized.len());
/// # Ok::<(), HilbertError>(())
/// ```
#[derive(Clone, Copy, Debug)]
#[must_use]
pub struct HilbertQuantizedBatch<'a, const D: usize> {
    quantized: &'a [[u32; D]],
    index_mode: HilbertIndexMode<D>,
}

impl<'a, const D: usize> HilbertQuantizedBatch<'a, D> {
    /// Parses pre-quantized coordinates into a validated Hilbert batch.
    ///
    /// # Errors
    ///
    /// Returns [`HilbertError::IndexOverflow`] if `D * bits > 128` (index would not fit in `u128`).
    /// Returns [`HilbertError::DimensionTooLarge`] if the dimension `D` exceeds `u32::MAX`.
    /// Returns [`HilbertError::PrequantizedCoordinateOutOfRange`] if any pre-quantized
    /// coordinate exceeds `2^bits - 1`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use delaunay::prelude::ordering::{
    ///     HilbertBitDepth, HilbertError, HilbertQuantizedBatch,
    /// };
    ///
    /// let quantized = [[0_u32, 0], [1, 2], [3, 3]];
    /// let bits = HilbertBitDepth::try_new(2)?;
    ///
    /// let batch = HilbertQuantizedBatch::try_new(&quantized, bits)?;
    /// assert_eq!(batch.coordinates(), quantized.as_slice());
    /// # Ok::<(), HilbertError>(())
    /// ```
    pub fn try_new(quantized: &'a [[u32; D]], bits: HilbertBitDepth) -> Result<Self, HilbertError> {
        let index_mode = HilbertIndexMode::try_new(bits)?;

        if D != 0 {
            validate_prequantized_coordinates(quantized, bits)?;
        }

        Ok(Self {
            quantized,
            index_mode,
        })
    }

    /// Returns the validated pre-quantized coordinates.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use delaunay::prelude::ordering::{
    ///     HilbertBitDepth, HilbertError, HilbertQuantizedBatch,
    /// };
    ///
    /// let quantized = [[0_u32, 0], [3, 3]];
    /// let bits = HilbertBitDepth::try_new(2)?;
    /// let batch = HilbertQuantizedBatch::try_new(&quantized, bits)?;
    ///
    /// assert_eq!(batch.coordinates(), quantized.as_slice());
    /// # Ok::<(), HilbertError>(())
    /// ```
    #[must_use]
    pub const fn coordinates(self) -> &'a [[u32; D]] {
        self.quantized
    }

    /// Returns the bit depth whose grid bounds were checked.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use delaunay::prelude::ordering::{
    ///     HilbertBitDepth, HilbertError, HilbertQuantizedBatch,
    /// };
    ///
    /// let quantized = [[0_u32, 0], [3, 3]];
    /// let bits = HilbertBitDepth::try_new(2)?;
    /// let batch = HilbertQuantizedBatch::try_new(&quantized, bits)?;
    ///
    /// assert_eq!(batch.bits(), bits);
    /// # Ok::<(), HilbertError>(())
    /// ```
    pub const fn bits(self) -> HilbertBitDepth {
        self.index_mode.bits()
    }

    /// Computes Hilbert indices without revalidating the batch.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use delaunay::prelude::ordering::{
    ///     HilbertBitDepth, HilbertError, HilbertQuantizedBatch,
    /// };
    ///
    /// let quantized = [[0_u32, 0], [3, 3]];
    /// let bits = HilbertBitDepth::try_new(2)?;
    /// let batch = HilbertQuantizedBatch::try_new(&quantized, bits)?;
    ///
    /// let indices = batch.indices();
    /// assert_eq!(indices.len(), quantized.len());
    /// # Ok::<(), HilbertError>(())
    /// ```
    #[must_use]
    pub fn indices(self) -> Vec<u128> {
        hilbert_indices_for_quantized_batch(self)
    }
}

/// Owned, pre-quantized Hilbert coordinates proven in-grid by the quantizer
/// that produced them.
///
/// Unlike [`HilbertQuantizedBatch`], which borrows caller-supplied coordinates
/// and revalidates them at the boundary, this type is only constructed by
/// [`hilbert_quantize_batch_in_range`]. That constructor clamps every
/// coordinate into the selected bit-depth grid, so the in-grid invariant is
/// carried structurally by the stored, validated index mode and
/// [`Self::indices`] is infallible — no second per-coordinate scan is needed.
///
/// # Examples
///
/// ```rust
/// use delaunay::prelude::geometry::CoordinateRange;
/// use delaunay::prelude::ordering::{
///     HilbertBitDepth, HilbertError, hilbert_quantize_batch_in_range,
/// };
///
/// # fn main() -> Result<(), HilbertError> {
/// let points = [[0.1_f64, 0.2], [0.9, 0.8], [0.5, 0.5]];
/// # let Ok(bounds) = CoordinateRange::try_new(0.0_f64, 1.0) else {
/// #     return Ok(());
/// # };
/// let bits = HilbertBitDepth::try_new(8)?;
///
/// let batch = hilbert_quantize_batch_in_range(&points, bounds, bits, |p| *p)?;
/// assert_eq!(batch.indices().len(), points.len());
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
#[must_use]
pub struct HilbertQuantizedVec<const D: usize> {
    quantized: Vec<[u32; D]>,
    index_mode: HilbertIndexMode<D>,
}

impl<const D: usize> HilbertQuantizedVec<D> {
    /// Returns the validated pre-quantized coordinates.
    #[must_use]
    pub fn coordinates(&self) -> &[[u32; D]] {
        &self.quantized
    }

    /// Returns the bit depth whose grid the coordinates were quantized to.
    pub const fn bits(&self) -> HilbertBitDepth {
        self.index_mode.bits()
    }

    /// Returns the number of quantized points in the batch.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.quantized.len()
    }

    /// Returns `true` when the batch contains no points.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.quantized.is_empty()
    }

    /// Computes Hilbert indices without revalidating the batch.
    ///
    /// This is infallible: the constructor already validated the index width
    /// and clamped every coordinate into the selected bit-depth grid.
    #[must_use]
    pub fn indices(&self) -> Vec<u128> {
        indices_for_mode(&self.quantized, self.index_mode)
    }

    /// Consumes the batch, returning its Hilbert indices alongside the owned
    /// quantized coordinates.
    ///
    /// This fuses the two products batch callers usually need — the per-point
    /// Hilbert index and the quantized cell used as a sort tie-break — without
    /// an extra allocation or a per-coordinate revalidation pass.
    #[must_use]
    pub fn into_indices_and_coordinates(self) -> (Vec<u128>, Vec<[u32; D]>) {
        let indices = self.indices();
        (indices, self.quantized)
    }

    /// Consumes the batch, returning only the owned quantized coordinates.
    #[must_use]
    pub fn into_coordinates(self) -> Vec<[u32; D]> {
        self.quantized
    }
}

/// Quantizes a batch of items into an owned, proof-bearing Hilbert batch.
///
/// Coordinates are extracted with `coords_of`, normalized against `bounds`
/// (already parsed at an upstream boundary), and clamped into the
/// `0..=2^bits - 1` grid. The index width and quantization scale are validated
/// once for the whole batch, after which [`HilbertQuantizedVec::indices`] is
/// infallible.
///
/// This is the single-pass bulk entry point preferred by construction
/// preprocessing: it avoids both the per-item bound parsing of
/// [`try_hilbert_quantize`] and the per-coordinate revalidation that
/// [`hilbert_indices_prequantized`] performs on caller-supplied grids.
///
/// # Errors
///
/// Returns [`HilbertError::IndexOverflow`] if `D * bits > 128` (index would not fit in `u128`).
/// Returns [`HilbertError::DimensionTooLarge`] if the dimension `D` exceeds `u32::MAX`.
/// Returns [`HilbertError::NonFiniteBoundsExtent`], [`HilbertError::NonFiniteCoordinate`],
/// [`HilbertError::NonFiniteNormalizedCoordinate`], or
/// [`HilbertError::QuantizedCoordinateConversionFailed`] if coordinate
/// quantization fails.
///
/// # Examples
///
/// ```rust
/// use delaunay::prelude::geometry::CoordinateRange;
/// use delaunay::prelude::ordering::{
///     HilbertBitDepth, HilbertError, hilbert_quantize_batch_in_range,
/// };
///
/// # fn main() -> Result<(), HilbertError> {
/// let points = [[0.0_f64, 0.0], [1.0, 1.0]];
/// # let Ok(bounds) = CoordinateRange::try_new(0.0_f64, 1.0) else {
/// #     return Ok(());
/// # };
/// let batch =
///     hilbert_quantize_batch_in_range(&points, bounds, HilbertBitDepth::try_new(4)?, |p| *p)?;
///
/// let (indices, quantized) = batch.into_indices_and_coordinates();
/// assert_eq!(indices.len(), 2);
/// assert_eq!(quantized.len(), 2);
/// # Ok(())
/// # }
/// ```
pub fn hilbert_quantize_batch_in_range<Item, const D: usize>(
    items: &[Item],
    bounds: CoordinateRange<f64>,
    bits: HilbertBitDepth,
    mut coords_of: impl FnMut(&Item) -> [f64; D],
) -> Result<HilbertQuantizedVec<D>, HilbertError> {
    let index_mode = HilbertIndexMode::try_new(bits)?;

    if D == 0 {
        return Ok(HilbertQuantizedVec {
            quantized: vec![[0_u32; D]; items.len()],
            index_mode,
        });
    }

    let (max_val_u32, max_val_t) = quantization_scale(bits);

    let quantized = items
        .iter()
        .map(|item| {
            let coords = coords_of(item);
            quantize_with_scale(&coords, bounds, bits, max_val_u32, max_val_t)
        })
        .collect::<Result<Vec<[u32; D]>, HilbertError>>()?;

    Ok(HilbertQuantizedVec {
        quantized,
        index_mode,
    })
}

/// Converts a validated bit depth into the exact f64 grid maximum.
fn quantization_scale(bits: HilbertBitDepth) -> (u32, f64) {
    let max_grid_value = max_quantized_coordinate(bits);
    (max_grid_value, f64::from(max_grid_value))
}

/// Returns the largest coordinate accepted by Hilbert APIs for the selected grid.
///
/// Keeping this calculation shared prevents the quantization and pre-quantized
/// validation paths from drifting on the inclusive `0..=2^bits - 1` contract.
const fn max_quantized_coordinate(bits: HilbertBitDepth) -> u32 {
    (1_u32 << bits.get()) - 1
}

/// Computes encoded index width once so overflow errors report consistent context.
fn total_bits<const D: usize>(bits: HilbertBitDepth) -> Result<u128, HilbertError> {
    let d_u32 = u32::try_from(D).map_err(|_| HilbertError::DimensionTooLarge { dimension: D })?;
    Ok(u128::from(d_u32) * u128::from(bits.get()))
}

/// Positive-dimensional Hilbert index parameters after width validation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct HilbertIndexParams<const D: usize> {
    bits: HilbertBitDepth,
}

impl<const D: usize> HilbertIndexParams<D> {
    const fn bits(self) -> u32 {
        self.bits.get()
    }
}

/// Validated Hilbert indexing mode, including the zero-dimensional special case.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum HilbertIndexMode<const D: usize> {
    ZeroDimensional { bits: HilbertBitDepth },
    Positive(HilbertIndexParams<D>),
}

impl<const D: usize> HilbertIndexMode<D> {
    fn try_new(bits: HilbertBitDepth) -> Result<Self, HilbertError> {
        validate_index_width::<D>(bits)?;
        if D == 0 {
            Ok(Self::ZeroDimensional { bits })
        } else {
            Ok(Self::Positive(HilbertIndexParams { bits }))
        }
    }

    const fn bits(self) -> HilbertBitDepth {
        match self {
            Self::ZeroDimensional { bits } => bits,
            Self::Positive(params) => params.bits,
        }
    }
}

/// Centralizes index-width validation shared by indexing and ordering APIs.
fn validate_index_width<const D: usize>(bits: HilbertBitDepth) -> Result<(), HilbertError> {
    let total_bits = total_bits::<D>(bits)?;
    if total_bits > 128 {
        return Err(HilbertError::IndexOverflow {
            dimension: D,
            bits: bits.get(),
            total_bits,
        });
    }
    Ok(())
}

fn parse_hilbert_bounds(bounds: (f64, f64)) -> Result<CoordinateRange<f64>, HilbertError> {
    let lower_bound_finite = bounds.0.is_finite();
    let upper_bound_finite = bounds.1.is_finite();

    CoordinateRange::try_from(bounds).map_err(|error| match error {
        CoordinateRangeError::NonFiniteBound { .. } => HilbertError::NonFiniteBounds {
            lower_bound_finite,
            upper_bound_finite,
        },
        CoordinateRangeError::NonIncreasing { ordering, .. } => {
            HilbertError::NonIncreasingBounds { ordering }
        }
    })
}

/// Quantize D-dimensional coordinates into integer grid coordinates in `[0, 2^bits)`.
///
/// The coordinates are normalized using a scalar `(min, max)` bound applied to every
/// dimension and then clamped to `[0, 1]` before quantization.
///
/// # Errors
///
/// Returns [`HilbertError::NonFiniteBounds`],
/// [`HilbertError::NonIncreasingBounds`],
/// [`HilbertError::NonFiniteBoundsExtent`],
/// [`HilbertError::NonFiniteCoordinate`], or
/// [`HilbertError::NonFiniteNormalizedCoordinate`] if quantization input or
/// normalization arithmetic is non-finite.
///
/// Returns [`HilbertError::QuantizedCoordinateConversionFailed`] if a rounded
/// scaled coordinate cannot be represented as `u32`.
///
/// # Examples
///
/// ```rust
/// use delaunay::prelude::ordering::{HilbertBitDepth, HilbertError, try_hilbert_quantize};
///
/// let coords = [0.5_f64, 0.25];
/// let q = try_hilbert_quantize(&coords, (0.0, 1.0), HilbertBitDepth::try_new(2)?)?;
/// assert!(q[0] <= 3 && q[1] <= 3);
/// # Ok::<(), HilbertError>(())
/// ```
pub fn try_hilbert_quantize<const D: usize>(
    coords: &[f64; D],
    bounds: (f64, f64),
    bits: HilbertBitDepth,
) -> Result<[u32; D], HilbertError> {
    let bounds = parse_hilbert_bounds(bounds)?;

    if D == 0 {
        return Ok([0_u32; D]);
    }

    let (max_val_u32, max_val_t) = quantization_scale(bits);

    quantize_with_scale(coords, bounds, bits, max_val_u32, max_val_t)
}

/// Quantizes coordinates against bounds already parsed by an upstream boundary.
///
/// # Errors
///
/// Returns [`HilbertError::NonFiniteBoundsExtent`] if the validated bounds
/// produce a non-finite extent. Returns [`HilbertError::NonFiniteCoordinate`] or
/// [`HilbertError::NonFiniteNormalizedCoordinate`] if a coordinate or its
/// normalized value is non-finite. Returns
/// [`HilbertError::QuantizedCoordinateConversionFailed`] if a rounded scaled
/// coordinate cannot be represented as `u32`.
///
/// # Examples
///
/// ```rust
/// use delaunay::prelude::geometry::CoordinateRange;
/// use delaunay::prelude::ordering::{
///     HilbertBitDepth, HilbertError, hilbert_quantize_in_range,
/// };
///
/// # fn main() -> Result<(), HilbertError> {
/// # let Ok(bounds) = CoordinateRange::try_new(0.0_f64, 1.0) else {
/// #     return Ok(());
/// # };
/// let q = hilbert_quantize_in_range(&[0.5_f64, 0.25], bounds, HilbertBitDepth::try_new(2)?)?;
/// assert!(q[0] <= 3 && q[1] <= 3);
/// # Ok(())
/// # }
/// ```
pub fn hilbert_quantize_in_range<const D: usize>(
    coords: &[f64; D],
    bounds: CoordinateRange<f64>,
    bits: HilbertBitDepth,
) -> Result<[u32; D], HilbertError> {
    if D == 0 {
        return Ok([0_u32; D]);
    }

    let (max_val_u32, max_val_t) = quantization_scale(bits);
    quantize_with_scale(coords, bounds, bits, max_val_u32, max_val_t)
}

/// Quantizes coordinates with a precomputed scalar grid maximum so hot callers
/// can validate conversion once before sorting or batch index generation.
#[inline]
fn quantize_with_scale<const D: usize>(
    coords: &[f64; D],
    bounds: CoordinateRange<f64>,
    bits: HilbertBitDepth,
    max_val_u32: u32,
    max_val_t: f64,
) -> Result<[u32; D], HilbertError> {
    let min = bounds.min();
    let max = bounds.max();
    let extent = max - min;
    if !extent.is_finite() {
        return Err(HilbertError::NonFiniteBoundsExtent {});
    }

    let mut quantized = [0_u32; D];
    for (i, &coord) in coords.iter().enumerate() {
        if !coord.is_finite() {
            return Err(HilbertError::NonFiniteCoordinate {
                coordinate_index: i,
            });
        }

        let t = (coord - min) / extent;
        let normalized = if t.is_finite() {
            t.clamp(0.0, 1.0)
        } else {
            return Err(HilbertError::NonFiniteNormalizedCoordinate {
                coordinate_index: i,
            });
        };

        let scaled = normalized * max_val_t;
        // Round to nearest grid cell (instead of truncating) for fairer distribution.
        let Some(value) = scaled.round().to_u32() else {
            return Err(HilbertError::QuantizedCoordinateConversionFailed {
                bits: bits.get(),
                max_grid_value: max_val_u32,
                coordinate_index: i,
            });
        };
        let q = value.min(max_val_u32);
        quantized[i] = q;
    }

    Ok(quantized)
}

/// Applies a prevalidated permutation after key construction succeeds so sort
/// helpers never partially reorder items before returning a Hilbert error.
fn apply_order<Item>(
    items: &mut [Item],
    order: impl ExactSizeIterator<Item = usize>,
) -> Result<(), HilbertError> {
    let item_len = items.len();
    let permutation_count = order.len();
    if item_len != permutation_count {
        return Err(HilbertError::InvalidSortPermutationLength {
            item_count: item_len,
            permutation_count,
        });
    }

    let mut ranks = vec![usize::MAX; item_len];
    let mut observed_count = 0_usize;
    for (new_index, old_index) in order.into_iter().enumerate() {
        observed_count = new_index + 1;
        if new_index >= item_len {
            return Err(HilbertError::InvalidSortPermutationLength {
                item_count: item_len,
                permutation_count: observed_count,
            });
        }
        if old_index >= item_len {
            return Err(HilbertError::InvalidSortPermutationIndex {
                permutation_index: new_index,
                item_index: old_index,
                item_count: item_len,
            });
        }
        if ranks[old_index] != usize::MAX {
            return Err(HilbertError::InvalidSortPermutationDuplicate {
                permutation_index: new_index,
                item_index: old_index,
            });
        }
        ranks[old_index] = new_index;
    }
    if observed_count != item_len {
        return Err(HilbertError::InvalidSortPermutationLength {
            item_count: item_len,
            permutation_count: observed_count,
        });
    }

    for index in 0..item_len {
        while ranks[index] != index {
            let target = ranks[index];
            items.swap(index, target);
            ranks.swap(index, target);
        }
    }

    Ok(())
}

/// Compute the Hilbert curve index for a point in D-dimensional space.
///
/// Internally, coordinates are quantized to an integer grid and then mapped to a
/// single index using an iterative Gray-code based algorithm.
///
/// # Errors
///
/// Returns [`HilbertError::IndexOverflow`] if `D * bits > 128` (index would not fit in `u128`).
///
/// Returns [`HilbertError::DimensionTooLarge`] if the dimension `D` exceeds `u32::MAX`
/// (extremely unlikely in practice).
///
/// Returns [`HilbertError::NonFiniteBounds`],
/// [`HilbertError::NonIncreasingBounds`],
/// [`HilbertError::NonFiniteBoundsExtent`],
/// [`HilbertError::NonFiniteCoordinate`], or
/// [`HilbertError::NonFiniteNormalizedCoordinate`] if quantization input or
/// normalization arithmetic is non-finite.
///
/// Returns [`HilbertError::QuantizedCoordinateConversionFailed`] if a rounded
/// scaled coordinate cannot be represented as `u32`.
///
/// # Examples
///
/// ```rust
/// use delaunay::prelude::ordering::{HilbertBitDepth, HilbertError, try_hilbert_index};
///
/// let idx = try_hilbert_index(&[0.0_f64, 0.0], (0.0, 1.0), HilbertBitDepth::try_new(4)?)?;
/// assert_eq!(idx, 0);
/// # Ok::<(), HilbertError>(())
/// ```
pub fn try_hilbert_index<const D: usize>(
    coords: &[f64; D],
    bounds: (f64, f64),
    bits: HilbertBitDepth,
) -> Result<u128, HilbertError> {
    let bounds = parse_hilbert_bounds(bounds)?;
    hilbert_index_in_range(coords, bounds, bits)
}

/// Computes a Hilbert index against bounds already parsed by an upstream boundary.
///
/// # Errors
///
/// Returns [`HilbertError::IndexOverflow`] if `D * bits > 128` (index would not fit in `u128`).
/// Returns [`HilbertError::DimensionTooLarge`] if the dimension `D` exceeds `u32::MAX`.
/// Returns [`HilbertError::NonFiniteBoundsExtent`], [`HilbertError::NonFiniteCoordinate`],
/// [`HilbertError::NonFiniteNormalizedCoordinate`], or
/// [`HilbertError::QuantizedCoordinateConversionFailed`] if coordinate
/// quantization fails.
///
/// # Examples
///
/// ```rust
/// use delaunay::prelude::geometry::CoordinateRange;
/// use delaunay::prelude::ordering::{HilbertBitDepth, HilbertError, hilbert_index_in_range};
///
/// # fn main() -> Result<(), HilbertError> {
/// # let Ok(bounds) = CoordinateRange::try_new(0.0_f64, 1.0) else {
/// #     return Ok(());
/// # };
/// let idx = hilbert_index_in_range(&[0.0_f64, 0.0], bounds, HilbertBitDepth::try_new(4)?)?;
/// assert_eq!(idx, 0);
/// # Ok(())
/// # }
/// ```
pub fn hilbert_index_in_range<const D: usize>(
    coords: &[f64; D],
    bounds: CoordinateRange<f64>,
    bits: HilbertBitDepth,
) -> Result<u128, HilbertError> {
    let index_mode = HilbertIndexMode::try_new(bits)?;
    let HilbertIndexMode::Positive(index_params) = index_mode else {
        return Ok(0);
    };

    let q = hilbert_quantize_in_range(coords, bounds, bits)?;
    Ok(index_from_quantized(&q, index_params))
}

/// Compute Hilbert index from pre-quantized integer coordinates.
///
/// This uses the Skilling (2004) algorithm ("Programming the Hilbert curve") to map
/// `D` integer coordinates (each `bits` bits wide) to a single Hilbert index.
///
/// The resulting ordering is continuous on the integer grid (successive indices move to
/// adjacent cells).
#[must_use]
fn index_from_quantized<const D: usize>(coords: &[u32; D], params: HilbertIndexParams<D>) -> u128 {
    let bits = params.bits();

    // Work on a local copy in "transposed" form.
    let mut transposed = *coords;

    // See: J. Skilling, "Programming the Hilbert curve", AIP Conference Proceedings 707 (2004).
    // Step 1: transform axes to 'transpose' form.
    let highest_bit_mask = max_quantized_coordinate(params.bits).isolate_highest_one();
    let mut bit_mask: u32 = highest_bit_mask;
    while bit_mask > 1 {
        let mask_minus_one = bit_mask - 1;

        // i = 0 case (special-cased to avoid borrow conflicts in the iterator loop below).
        if (transposed[0] & bit_mask) != 0 {
            transposed[0] ^= mask_minus_one;
        }

        let (first, rest) = transposed.split_at_mut(1);
        let first_coord = &mut first[0];

        for coord in rest {
            if (*coord & bit_mask) != 0 {
                *first_coord ^= mask_minus_one;
            } else {
                let toggle = (*first_coord ^ *coord) & mask_minus_one;
                *first_coord ^= toggle;
                *coord ^= toggle;
            }
        }

        bit_mask >>= 1;
    }

    // Step 2: Gray encode.
    let mut prev = transposed[0];
    for coord in transposed.iter_mut().skip(1) {
        *coord ^= prev;
        prev = *coord;
    }

    let mut gray_mask: u32 = 0;
    bit_mask = highest_bit_mask;
    while bit_mask > 1 {
        if (transposed[D - 1] & bit_mask) != 0 {
            gray_mask ^= bit_mask - 1;
        }
        bit_mask >>= 1;
    }

    for coord in &mut transposed {
        *coord ^= gray_mask;
    }

    // Step 3: interleave the transposed bits into the final index.
    let mut index: u128 = 0;
    for bit_pos in (0..bits).rev() {
        for &coord in &transposed {
            let bit_value = (coord >> bit_pos) & 1;
            index = (index << 1) | u128::from(bit_value);
        }
    }

    index
}

/// Stable sort helper: sort items by Hilbert index + quantized-coordinate tie-break.
///
/// This is a generic helper that does not depend on triangulation types.
///
/// When `D == 0`, all items are considered equivalent (index 0) and the sort is stable
/// based on original order.
///
/// # Errors
///
/// Returns [`HilbertError::IndexOverflow`] if `D * bits > 128` (index would not fit in `u128`).
///
/// Returns [`HilbertError::DimensionTooLarge`] if the dimension `D` exceeds `u32::MAX`
/// (extremely unlikely in practice).
///
/// Returns [`HilbertError::NonFiniteBounds`],
/// [`HilbertError::NonIncreasingBounds`],
/// [`HilbertError::NonFiniteBoundsExtent`],
/// [`HilbertError::NonFiniteCoordinate`], or
/// [`HilbertError::NonFiniteNormalizedCoordinate`] if quantization input or
/// normalization arithmetic is non-finite.
///
/// Returns [`HilbertError::QuantizedCoordinateConversionFailed`] if a rounded
/// scaled coordinate cannot be represented as `u32`.
///
/// Returns [`HilbertError::InvalidSortPermutationLength`],
/// [`HilbertError::InvalidSortPermutationIndex`], or
/// [`HilbertError::InvalidSortPermutationDuplicate`] if an internally
/// constructed permutation is inconsistent.
///
/// # Examples
///
/// ```rust
/// use delaunay::prelude::ordering::{HilbertBitDepth, HilbertError, try_hilbert_sort_by_stable};
///
/// let mut points = vec![[0.9_f64, 0.9], [0.1, 0.1], [0.5, 0.5]];
/// try_hilbert_sort_by_stable(&mut points, (0.0, 1.0), HilbertBitDepth::try_new(8)?, |p| *p)?;
/// assert_eq!(points[0], [0.1, 0.1]);
/// # Ok::<(), HilbertError>(())
/// ```
pub fn try_hilbert_sort_by_stable<Item, const D: usize>(
    items: &mut [Item],
    bounds: (f64, f64),
    bits: HilbertBitDepth,
    coords_of: impl FnMut(&Item) -> [f64; D],
) -> Result<(), HilbertError> {
    let bounds = parse_hilbert_bounds(bounds)?;
    hilbert_sort_by_stable_in_range(items, bounds, bits, coords_of)
}

/// Stable sort helper using bounds already parsed by an upstream boundary.
///
/// This is equivalent to [`try_hilbert_sort_by_stable`], but accepts a
/// [`CoordinateRange`] so callers can carry range validation evidence inward.
///
/// # Errors
///
/// Returns [`HilbertError::IndexOverflow`] if `D * bits > 128` (index would not fit in `u128`).
/// Returns [`HilbertError::DimensionTooLarge`] if the dimension `D` exceeds `u32::MAX`.
/// Returns [`HilbertError::NonFiniteBoundsExtent`], [`HilbertError::NonFiniteCoordinate`],
/// [`HilbertError::NonFiniteNormalizedCoordinate`], or
/// [`HilbertError::QuantizedCoordinateConversionFailed`] if coordinate
/// quantization fails.
///
/// Returns [`HilbertError::InvalidSortPermutationLength`],
/// [`HilbertError::InvalidSortPermutationIndex`], or
/// [`HilbertError::InvalidSortPermutationDuplicate`] if an internally
/// constructed permutation is inconsistent.
///
/// # Examples
///
/// ```rust
/// use delaunay::prelude::geometry::CoordinateRange;
/// use delaunay::prelude::ordering::{
///     HilbertBitDepth, HilbertError, hilbert_sort_by_stable_in_range,
/// };
///
/// # fn main() -> Result<(), HilbertError> {
/// let mut points = vec![[0.9_f64, 0.9], [0.1, 0.1], [0.5, 0.5]];
/// # let Ok(bounds) = CoordinateRange::try_new(0.0_f64, 1.0) else {
/// #     return Ok(());
/// # };
/// hilbert_sort_by_stable_in_range(&mut points, bounds, HilbertBitDepth::try_new(8)?, |p| *p)?;
/// assert_eq!(points[0], [0.1, 0.1]);
/// # Ok(())
/// # }
/// ```
pub fn hilbert_sort_by_stable_in_range<Item, const D: usize>(
    items: &mut [Item],
    bounds: CoordinateRange<f64>,
    bits: HilbertBitDepth,
    mut coords_of: impl FnMut(&Item) -> [f64; D],
) -> Result<(), HilbertError> {
    let index_mode = HilbertIndexMode::try_new(bits)?;
    let HilbertIndexMode::Positive(index_params) = index_mode else {
        return Ok(());
    };

    let (max_val_u32, max_val_t) = quantization_scale(bits);

    let mut keyed: Vec<((u128, [u32; D]), usize)> = items
        .iter()
        .enumerate()
        .map(|(i, item)| {
            let c = coords_of(item);
            let q = quantize_with_scale(&c, bounds, bits, max_val_u32, max_val_t)?;
            let idx = index_from_quantized(&q, index_params);
            Ok(((idx, q), i))
        })
        .collect::<Result<_, HilbertError>>()?;

    keyed.sort_by_key(|(key, _)| *key);
    apply_order(items, keyed.into_iter().map(|(_, i)| i))?;

    Ok(())
}

/// Unstable sort helper: sort items by Hilbert index + quantized-coordinate tie-break.
///
/// This precomputes fallible Hilbert keys once, then applies an unstable ordering.
/// Prefer [`try_hilbert_sort_by_stable`] when equal-key items must preserve their
/// original relative order.
///
/// When `D == 0`, all items are considered equivalent (index 0) and the sort order is
/// implementation-defined.
///
/// # Errors
///
/// Returns [`HilbertError::IndexOverflow`] if `D * bits > 128` (index would not fit in `u128`).
///
/// Returns [`HilbertError::DimensionTooLarge`] if the dimension `D` exceeds `u32::MAX`
/// (extremely unlikely in practice).
///
/// Returns [`HilbertError::NonFiniteBounds`],
/// [`HilbertError::NonIncreasingBounds`],
/// [`HilbertError::NonFiniteBoundsExtent`],
/// [`HilbertError::NonFiniteCoordinate`], or
/// [`HilbertError::NonFiniteNormalizedCoordinate`] if quantization input or
/// normalization arithmetic is non-finite.
///
/// Returns [`HilbertError::QuantizedCoordinateConversionFailed`] if a rounded
/// scaled coordinate cannot be represented as `u32`.
///
/// Returns [`HilbertError::InvalidSortPermutationLength`],
/// [`HilbertError::InvalidSortPermutationIndex`], or
/// [`HilbertError::InvalidSortPermutationDuplicate`] if an internally
/// constructed permutation is inconsistent.
///
/// # Examples
///
/// ```rust
/// use delaunay::prelude::ordering::{HilbertBitDepth, HilbertError, try_hilbert_sort_by_unstable};
///
/// let mut points = vec![[0.9_f64, 0.9], [0.1, 0.1], [0.5, 0.5]];
/// try_hilbert_sort_by_unstable(&mut points, (0.0, 1.0), HilbertBitDepth::try_new(8)?, |p| *p)?;
/// assert_eq!(points[0], [0.1, 0.1]);
/// # Ok::<(), HilbertError>(())
/// ```
pub fn try_hilbert_sort_by_unstable<Item, const D: usize>(
    items: &mut [Item],
    bounds: (f64, f64),
    bits: HilbertBitDepth,
    coords_of: impl FnMut(&Item) -> [f64; D],
) -> Result<(), HilbertError> {
    let bounds = parse_hilbert_bounds(bounds)?;
    hilbert_sort_by_unstable_in_range(items, bounds, bits, coords_of)
}

/// Unstable sort helper using bounds already parsed by an upstream boundary.
///
/// This is equivalent to [`try_hilbert_sort_by_unstable`], but accepts a
/// [`CoordinateRange`] so callers can carry range validation evidence inward.
///
/// # Errors
///
/// Returns [`HilbertError::IndexOverflow`] if `D * bits > 128` (index would not fit in `u128`).
/// Returns [`HilbertError::DimensionTooLarge`] if the dimension `D` exceeds `u32::MAX`.
/// Returns [`HilbertError::NonFiniteBoundsExtent`], [`HilbertError::NonFiniteCoordinate`],
/// [`HilbertError::NonFiniteNormalizedCoordinate`], or
/// [`HilbertError::QuantizedCoordinateConversionFailed`] if coordinate
/// quantization fails.
///
/// Returns [`HilbertError::InvalidSortPermutationLength`],
/// [`HilbertError::InvalidSortPermutationIndex`], or
/// [`HilbertError::InvalidSortPermutationDuplicate`] if an internally
/// constructed permutation is inconsistent.
///
/// # Examples
///
/// ```rust
/// use delaunay::prelude::geometry::CoordinateRange;
/// use delaunay::prelude::ordering::{
///     HilbertBitDepth, HilbertError, hilbert_sort_by_unstable_in_range,
/// };
///
/// # fn main() -> Result<(), HilbertError> {
/// let mut points = vec![[0.9_f64, 0.9], [0.1, 0.1], [0.5, 0.5]];
/// # let Ok(bounds) = CoordinateRange::try_new(0.0_f64, 1.0) else {
/// #     return Ok(());
/// # };
/// hilbert_sort_by_unstable_in_range(&mut points, bounds, HilbertBitDepth::try_new(8)?, |p| *p)?;
/// assert_eq!(points[0], [0.1, 0.1]);
/// # Ok(())
/// # }
/// ```
pub fn hilbert_sort_by_unstable_in_range<Item, const D: usize>(
    items: &mut [Item],
    bounds: CoordinateRange<f64>,
    bits: HilbertBitDepth,
    mut coords_of: impl FnMut(&Item) -> [f64; D],
) -> Result<(), HilbertError> {
    let index_mode = HilbertIndexMode::try_new(bits)?;
    let HilbertIndexMode::Positive(index_params) = index_mode else {
        return Ok(());
    };

    let (max_val_u32, max_val_t) = quantization_scale(bits);

    let mut keyed: Vec<((u128, [u32; D]), usize)> = items
        .iter()
        .enumerate()
        .map(|(i, item)| {
            let c = coords_of(item);
            let q = quantize_with_scale(&c, bounds, bits, max_val_u32, max_val_t)?;
            let idx = index_from_quantized(&q, index_params);
            Ok(((idx, q), i))
        })
        .collect::<Result<_, HilbertError>>()?;

    keyed.sort_unstable_by_key(|(key, _)| *key);
    apply_order(items, keyed.into_iter().map(|(_, i)| i))?;

    Ok(())
}

/// Validates that caller-supplied pre-quantized coordinates fit the selected grid.
///
/// This protects [`hilbert_indices_prequantized`] from passing high-bit values
/// into [`index_from_quantized`], where bits above the selected depth are
/// intentionally ignored by the Hilbert interleaving loop.
fn validate_prequantized_coordinates<const D: usize>(
    quantized: &[[u32; D]],
    bits: HilbertBitDepth,
) -> Result<(), HilbertError> {
    let max_grid_value = max_quantized_coordinate(bits);
    for (point_index, point) in quantized.iter().enumerate() {
        for (coordinate_index, &coordinate) in point.iter().enumerate() {
            if coordinate > max_grid_value {
                return Err(HilbertError::PrequantizedCoordinateOutOfRange {
                    bits: bits.get(),
                    max_grid_value,
                    point_index,
                    coordinate_index,
                    coordinate,
                });
            }
        }
    }

    Ok(())
}

/// Compute Hilbert indices for a batch of pre-quantized coordinates.
///
/// This is a bulk API that avoids recomputing quantization parameters for large
/// insertion batches. When inserting many points, quantize them once using
/// [`try_hilbert_quantize`] and then call this function to compute all indices in bulk.
/// Pre-quantized coordinates must be in the inclusive range `0..=2^bits - 1`;
/// values outside that grid are rejected instead of being truncated.
///
/// # Performance
///
/// This function validates index width and pre-quantized coordinate ranges, then
/// maps each quantized coordinate through the internal Hilbert index computation.
/// For large batches, this is significantly faster than calling [`try_hilbert_index`]
/// individually for each point.
/// If the same pre-quantized batch is reused, construct a [`HilbertQuantizedBatch`]
/// once and call [`HilbertQuantizedBatch::indices`] to avoid repeated validation.
///
/// # Errors
///
/// Returns [`HilbertError::IndexOverflow`] if `D * bits > 128` (index would not fit in `u128`).
///
/// Returns [`HilbertError::DimensionTooLarge`] if the dimension `D` exceeds `u32::MAX`
/// (extremely unlikely in practice).
///
/// Returns [`HilbertError::PrequantizedCoordinateOutOfRange`] if any pre-quantized
/// coordinate exceeds `2^bits - 1`.
///
/// # Examples
///
/// ```rust
/// use delaunay::prelude::ordering::{
///     HilbertBitDepth, HilbertError, hilbert_indices_prequantized, try_hilbert_quantize,
/// };
///
/// let coords = vec![[0.1_f64, 0.2], [0.5, 0.5], [0.9, 0.8]];
/// let bounds = (0.0, 1.0);
/// let bits = HilbertBitDepth::try_new(8)?;
///
/// // Quantize once
/// let quantized: Vec<[u32; 2]> = coords
///     .iter()
///     .map(|c| try_hilbert_quantize(c, bounds, bits))
///     .collect::<Result<_, _>>()?;
///
/// // Compute all indices in bulk
/// let indices = hilbert_indices_prequantized(&quantized, bits)?;
/// assert_eq!(indices.len(), coords.len());
/// # Ok::<(), HilbertError>(())
/// ```
///
/// Error handling:
///
/// ```rust
/// use delaunay::prelude::ordering::{
///     HilbertBitDepth, HilbertError, hilbert_indices_prequantized,
/// };
///
/// # fn main() -> Result<(), HilbertError> {
/// let quantized = vec![[1_u32, 2]];
///
/// // Zero cannot cross the typed API boundary.
/// std::assert_matches!(
///     HilbertBitDepth::try_new(0),
///     Err(HilbertError::InvalidBitsParameter { bits: 0 })
/// );
///
/// // Overflow (D=5, bits=26 => 130 > 128)
/// let quantized_5d = vec![[1_u32, 2, 3, 4, 5]];
/// let result = hilbert_indices_prequantized(&quantized_5d, HilbertBitDepth::try_new(26)?);
/// std::assert_matches!(result, Err(HilbertError::IndexOverflow { .. }));
///
/// // Pre-quantized coordinates must fit the selected grid.
/// let out_of_range = vec![[4_u32, 1]];
/// let result = hilbert_indices_prequantized(&out_of_range, HilbertBitDepth::try_new(2)?);
/// std::assert_matches!(
///     result,
///     Err(HilbertError::PrequantizedCoordinateOutOfRange { .. })
/// );
/// # Ok(())
/// # }
/// ```
pub fn hilbert_indices_prequantized<const D: usize>(
    quantized: &[[u32; D]],
    bits: HilbertBitDepth,
) -> Result<Vec<u128>, HilbertError> {
    Ok(HilbertQuantizedBatch::try_new(quantized, bits)?.indices())
}

/// Computes Hilbert indices from a validated pre-quantized batch.
///
/// This is the infallible companion to [`hilbert_indices_prequantized`]. The
/// [`HilbertQuantizedBatch`] constructor has already checked both the Hilbert
/// index width and every coordinate against the selected bit-depth grid.
///
/// # Examples
///
/// ```rust
/// use delaunay::prelude::ordering::{
///     HilbertBitDepth, HilbertError, HilbertQuantizedBatch,
///     hilbert_indices_for_quantized_batch,
/// };
///
/// let quantized = [[0_u32, 0], [3, 3]];
/// let bits = HilbertBitDepth::try_new(2)?;
/// let batch = HilbertQuantizedBatch::try_new(&quantized, bits)?;
///
/// let indices = hilbert_indices_for_quantized_batch(batch);
/// assert_eq!(indices.len(), quantized.len());
/// # Ok::<(), HilbertError>(())
/// ```
#[must_use]
pub fn hilbert_indices_for_quantized_batch<const D: usize>(
    batch: HilbertQuantizedBatch<'_, D>,
) -> Vec<u128> {
    indices_for_mode(batch.quantized, batch.index_mode)
}

/// Maps validated quantized coordinates to Hilbert indices for a known index
/// mode.
///
/// Both [`HilbertQuantizedBatch`] and [`HilbertQuantizedVec`] carry a validated
/// [`HilbertIndexMode`], so neither revalidates coordinates before computing
/// indices.
fn indices_for_mode<const D: usize>(
    quantized: &[[u32; D]],
    index_mode: HilbertIndexMode<D>,
) -> Vec<u128> {
    match index_mode {
        HilbertIndexMode::ZeroDimensional { .. } => vec![0_u128; quantized.len()],
        HilbertIndexMode::Positive(index_params) => quantized
            .iter()
            .map(|q| index_from_quantized(q, index_params))
            .collect(),
    }
}

/// Return the indices that would sort `coords` by Hilbert order.
///
/// When `D == 0`, all coordinates are considered equivalent (index 0) and the returned
/// indices preserve the original order.
///
/// # Errors
///
/// Returns [`HilbertError::IndexOverflow`] if `D * bits > 128` (index would not fit in `u128`).
///
/// Returns [`HilbertError::DimensionTooLarge`] if the dimension `D` exceeds `u32::MAX`
/// (extremely unlikely in practice).
///
/// Returns [`HilbertError::NonFiniteBounds`],
/// [`HilbertError::NonIncreasingBounds`],
/// [`HilbertError::NonFiniteBoundsExtent`],
/// [`HilbertError::NonFiniteCoordinate`], or
/// [`HilbertError::NonFiniteNormalizedCoordinate`] if quantization input or
/// normalization arithmetic is non-finite.
///
/// Returns [`HilbertError::QuantizedCoordinateConversionFailed`] if a rounded
/// scaled coordinate cannot be represented as `u32`.
///
/// # Examples
///
/// ```rust
/// use delaunay::prelude::ordering::{HilbertBitDepth, HilbertError, try_hilbert_sorted_indices};
///
/// let coords = vec![[0.9_f64, 0.9], [0.1, 0.1], [0.5, 0.5]];
/// let order = try_hilbert_sorted_indices(&coords, (0.0, 1.0), HilbertBitDepth::try_new(8)?)?;
/// assert_eq!(order.len(), coords.len());
/// # Ok::<(), HilbertError>(())
/// ```
pub fn try_hilbert_sorted_indices<const D: usize>(
    coords: &[[f64; D]],
    bounds: (f64, f64),
    bits: HilbertBitDepth,
) -> Result<Vec<usize>, HilbertError> {
    let bounds = parse_hilbert_bounds(bounds)?;
    hilbert_sorted_indices_in_range(coords, bounds, bits)
}

/// Return the indices that would sort `coords` by Hilbert order using validated bounds.
///
/// This is equivalent to [`try_hilbert_sorted_indices`], but accepts a
/// [`CoordinateRange`] so callers can carry range validation evidence inward.
///
/// # Errors
///
/// Returns [`HilbertError::IndexOverflow`] if `D * bits > 128` (index would not fit in `u128`).
/// Returns [`HilbertError::DimensionTooLarge`] if the dimension `D` exceeds `u32::MAX`.
/// Returns [`HilbertError::NonFiniteBoundsExtent`], [`HilbertError::NonFiniteCoordinate`],
/// [`HilbertError::NonFiniteNormalizedCoordinate`], or
/// [`HilbertError::QuantizedCoordinateConversionFailed`] if coordinate
/// quantization fails.
///
/// # Examples
///
/// ```rust
/// use delaunay::prelude::geometry::CoordinateRange;
/// use delaunay::prelude::ordering::{
///     HilbertBitDepth, HilbertError, hilbert_sorted_indices_in_range,
/// };
///
/// # fn main() -> Result<(), HilbertError> {
/// let coords = vec![[0.9_f64, 0.9], [0.1, 0.1], [0.5, 0.5]];
/// # let Ok(bounds) = CoordinateRange::try_new(0.0_f64, 1.0) else {
/// #     return Ok(());
/// # };
/// let order = hilbert_sorted_indices_in_range(&coords, bounds, HilbertBitDepth::try_new(8)?)?;
/// assert_eq!(order.len(), coords.len());
/// # Ok(())
/// # }
/// ```
pub fn hilbert_sorted_indices_in_range<const D: usize>(
    coords: &[[f64; D]],
    bounds: CoordinateRange<f64>,
    bits: HilbertBitDepth,
) -> Result<Vec<usize>, HilbertError> {
    let index_mode = HilbertIndexMode::try_new(bits)?;
    let HilbertIndexMode::Positive(index_params) = index_mode else {
        return Ok((0..coords.len()).collect());
    };

    let (max_val_u32, max_val_t) = quantization_scale(bits);

    let mut keyed: Vec<((u128, [u32; D]), usize)> = coords
        .iter()
        .enumerate()
        .map(|(i, c)| {
            let q = quantize_with_scale(c, bounds, bits, max_val_u32, max_val_t)?;
            let idx = index_from_quantized(&q, index_params);
            Ok(((idx, q), i))
        })
        .collect::<Result<_, HilbertError>>()?;

    keyed.sort_by(|(ka, ia), (kb, ib)| ka.cmp(kb).then_with(|| ia.cmp(ib)));
    Ok(keyed.into_iter().map(|(_, i)| i).collect())
}

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

    use crate::geometry::point::Point;

    fn bit_depth(value: u32) -> HilbertBitDepth {
        HilbertBitDepth::try_new(value).expect("test bit depth must be valid")
    }

    fn positive_index_params<const D: usize>(bits: HilbertBitDepth) -> HilbertIndexParams<D> {
        let HilbertIndexMode::Positive(params) =
            HilbertIndexMode::<D>::try_new(bits).expect("test index parameters must be valid")
        else {
            panic!("test index parameters must be positive-dimensional");
        };
        params
    }

    struct LyingOrder {
        values: std::vec::IntoIter<usize>,
        reported_len: usize,
    }

    impl LyingOrder {
        fn new(values: Vec<usize>, reported_len: usize) -> Self {
            Self {
                values: values.into_iter(),
                reported_len,
            }
        }
    }

    impl Iterator for LyingOrder {
        type Item = usize;

        fn next(&mut self) -> Option<Self::Item> {
            self.values.next()
        }
    }

    impl ExactSizeIterator for LyingOrder {
        fn len(&self) -> usize {
            self.reported_len
        }
    }

    /// Asserts that the bulk pre-quantized API matches per-point Hilbert indexing.
    fn assert_prequantized_matches_hilbert_index<const D: usize>(
        coords: &[[f64; D]],
        bounds: (f64, f64),
        bits: HilbertBitDepth,
    ) {
        let quantized: Vec<[u32; D]> = coords
            .iter()
            .map(|c| try_hilbert_quantize(c, bounds, bits).unwrap())
            .collect();
        let indices_bulk =
            hilbert_indices_prequantized(&quantized, bits).expect("valid quantized points");
        let indices_individual: Vec<u128> = coords
            .iter()
            .map(|c| try_hilbert_index(c, bounds, bits).unwrap())
            .collect();

        assert_eq!(indices_bulk, indices_individual);
    }

    #[test]
    fn test_hilbert_bit_depth_boundaries_and_traits() {
        let min_bits = HilbertBitDepth::try_new(1).expect("minimum bit depth should be valid");
        let max_bits =
            HilbertBitDepth::try_new(MAX_HILBERT_BITS).expect("maximum bit depth should be valid");

        assert_eq!(min_bits.get(), 1);
        assert_eq!(max_bits.get(), MAX_HILBERT_BITS);
        assert_eq!(max_bits.to_string(), MAX_HILBERT_BITS.to_string());
        assert_eq!(HilbertBitDepth::try_from(8), HilbertBitDepth::try_new(8));
        assert_matches!(
            HilbertBitDepth::try_new(0),
            Err(HilbertError::InvalidBitsParameter { bits: 0 })
        );
        assert_matches!(
            HilbertBitDepth::try_new(32),
            Err(HilbertError::InvalidBitsParameter { bits: 32 })
        );
        assert_matches!(
            HilbertBitDepth::try_from(0),
            Err(HilbertError::InvalidBitsParameter { bits: 0 })
        );
        assert_matches!(
            HilbertBitDepth::try_from(MAX_HILBERT_BITS + 1),
            Err(HilbertError::InvalidBitsParameter { bits }) if bits == MAX_HILBERT_BITS + 1
        );
    }

    #[test]
    fn test_hilbert_index_2d() {
        let bits = bit_depth(4);
        let origin = try_hilbert_index(&[0.0_f64, 0.0], (0.0, 1.0), bits).unwrap();
        let corner = try_hilbert_index(&[1.0_f64, 1.0], (0.0, 1.0), bits).unwrap();
        let center = try_hilbert_index(&[0.5_f64, 0.5], (0.0, 1.0), bits).unwrap();

        assert_eq!(origin, 0);
        assert_ne!(origin, center);
        assert_ne!(center, corner);
    }

    #[test]
    fn test_hilbert_index_3d() {
        let bits = bit_depth(8);
        let origin = try_hilbert_index(&[0.0_f64, 0.0, 0.0], (-1.0, 1.0), bits).unwrap();
        let corner = try_hilbert_index(&[1.0_f64, 1.0, 1.0], (-1.0, 1.0), bits).unwrap();
        assert_ne!(origin, corner);
    }

    macro_rules! gen_prequantized_matches_hilbert_index_tests {
        ($dim:literal, $coords:expr, $bounds:expr, $bits:expr) => {
            pastey::paste! {
                #[test]
                fn [<test_hilbert_indices_prequantized_matches_hilbert_index_ $dim d>]() {
                    let coords: [[f64; $dim]; 4] = $coords;
                    assert_prequantized_matches_hilbert_index(
                        &coords,
                        $bounds,
                        bit_depth($bits),
                    );
                }
            }
        };
    }

    gen_prequantized_matches_hilbert_index_tests!(
        2,
        [[-2.0, -1.0], [-1.5, 0.25], [0.1, -0.7], [3.0, 3.0]],
        (-2.0_f64, 3.0_f64),
        8
    );
    gen_prequantized_matches_hilbert_index_tests!(
        3,
        [
            [-2.0, -1.0, 0.0],
            [-1.5, 0.25, 1.75],
            [0.1, -0.7, 2.2],
            [3.0, 3.0, -2.0],
        ],
        (-2.0_f64, 3.0_f64),
        8
    );
    gen_prequantized_matches_hilbert_index_tests!(
        4,
        [
            [-2.0, -1.0, 0.0, 1.0],
            [-1.5, 0.25, 1.75, 2.5],
            [0.1, -0.7, 2.2, -1.8],
            [3.0, 3.0, -2.0, -2.0],
        ],
        (-2.0_f64, 3.0_f64),
        8
    );
    gen_prequantized_matches_hilbert_index_tests!(
        5,
        [
            [-2.0, -1.0, 0.0, 1.0, 2.0],
            [-1.5, 0.25, 1.75, 2.5, -0.5],
            [0.1, -0.7, 2.2, -1.8, 1.4],
            [3.0, 3.0, -2.0, -2.0, 0.5],
        ],
        (-2.0_f64, 3.0_f64),
        8
    );

    #[test]
    fn test_hilbert_sorted_indices_and_sort_helpers() {
        let coords: Vec<[f64; 2]> =
            vec![[0.9, 0.9], [0.1, 0.1], [0.5, 0.5], [0.1, 0.9], [0.9, 0.1]];
        let bits = bit_depth(16);
        let order = try_hilbert_sorted_indices(&coords, (0.0, 1.0), bits).unwrap();
        assert_eq!(order.len(), coords.len());

        // Apply the ordering to a parallel payload.
        let mut payload: Vec<usize> = (0..coords.len()).collect();
        try_hilbert_sort_by_stable(&mut payload, (0.0_f64, 1.0), bits, |&i| coords[i]).unwrap();

        // Sorting by stable helper should be deterministic.
        let mut payload2: Vec<usize> = (0..coords.len()).collect();
        try_hilbert_sort_by_stable(&mut payload2, (0.0_f64, 1.0), bits, |&i| coords[i]).unwrap();
        assert_eq!(payload, order);
        assert_eq!(payload, payload2);
    }

    #[test]
    fn test_sort_helpers_accept_stateful_coordinate_closures() {
        let coords: Vec<[f64; 2]> = vec![[0.9, 0.9], [0.1, 0.1], [0.5, 0.5]];
        let bits = bit_depth(8);
        let expected_order = try_hilbert_sorted_indices(&coords, (0.0, 1.0), bits).unwrap();

        let mut stable_calls = 0_usize;
        let mut stable_payload: Vec<usize> = (0..coords.len()).collect();
        try_hilbert_sort_by_stable(&mut stable_payload, (0.0_f64, 1.0), bits, |&i| {
            stable_calls += 1;
            coords[i]
        })
        .unwrap();
        assert_eq!(stable_payload, expected_order);
        assert_eq!(stable_calls, coords.len());

        let mut unstable_calls = 0_usize;
        let mut unstable_payload: Vec<usize> = (0..coords.len()).collect();
        try_hilbert_sort_by_unstable(&mut unstable_payload, (0.0_f64, 1.0), bits, |&i| {
            unstable_calls += 1;
            coords[i]
        })
        .unwrap();
        assert_eq!(unstable_payload, expected_order);
        assert_eq!(unstable_calls, coords.len());
    }

    #[test]
    fn test_unstable_sort_orders_by_key() {
        let coords: Vec<[f64; 2]> =
            vec![[0.9, 0.9], [0.1, 0.1], [0.5, 0.5], [0.1, 0.9], [0.9, 0.1]];
        let bits = bit_depth(16);
        let expected_order = try_hilbert_sorted_indices(&coords, (0.0, 1.0), bits).unwrap();

        let mut payload: Vec<usize> = (0..coords.len()).collect();
        try_hilbert_sort_by_unstable(&mut payload, (0.0_f64, 1.0), bits, |&i| coords[i]).unwrap();

        assert_eq!(payload, expected_order);
    }

    #[test]
    fn test_zero_dim_sort_helpers_noop() {
        let coords: Vec<[f64; 0]> = vec![[], [], []];
        let bits = bit_depth(8);
        let order = try_hilbert_sorted_indices(&coords, (0.0, 1.0), bits).unwrap();
        assert_eq!(order, vec![0, 1, 2]);

        let mut stable_payload = vec![3, 2, 1];
        try_hilbert_sort_by_stable(&mut stable_payload, (0.0_f64, 1.0), bits, |_| []).unwrap();
        assert_eq!(stable_payload, vec![3, 2, 1]);

        let mut unstable_payload = vec![3, 2, 1];
        try_hilbert_sort_by_unstable(&mut unstable_payload, (0.0_f64, 1.0), bits, |_| []).unwrap();
        assert_eq!(unstable_payload, vec![3, 2, 1]);
    }

    #[test]
    fn test_zero_dim_raw_bound_apis_reject_invalid_bounds() {
        let bits = bit_depth(8);
        let coords = [0.0_f64; 0];
        let coordinate_batch = vec![coords; 3];
        let mut payload = vec![3, 2, 1];

        assert_matches!(
            try_hilbert_quantize(&coords, (f64::NAN, 1.0), bits),
            Err(HilbertError::NonFiniteBounds {
                lower_bound_finite: false,
                upper_bound_finite: true
            })
        );
        assert_matches!(
            try_hilbert_index(&coords, (1.0, 1.0), bits),
            Err(HilbertError::NonIncreasingBounds {
                ordering: CoordinateRangeOrdering::Equal
            })
        );
        assert_matches!(
            try_hilbert_sorted_indices(&coordinate_batch, (1.0, 0.0), bits),
            Err(HilbertError::NonIncreasingBounds {
                ordering: CoordinateRangeOrdering::Decreasing
            })
        );
        assert_matches!(
            try_hilbert_sort_by_stable(&mut payload, (f64::NEG_INFINITY, 1.0), bits, |_| coords),
            Err(HilbertError::NonFiniteBounds {
                lower_bound_finite: false,
                upper_bound_finite: true
            })
        );
    }

    #[test]
    fn test_scaled_quantize_reports_conversion_error() {
        let result = quantize_with_scale(
            &[1.0_f64],
            CoordinateRange::try_new(0.0, 1.0).unwrap(),
            bit_depth(31),
            u32::MAX,
            f64::INFINITY,
        );

        assert_matches!(
            result,
            Err(HilbertError::QuantizedCoordinateConversionFailed {
                bits: 31,
                max_grid_value: u32::MAX,
                coordinate_index: 0
            })
        );
    }

    macro_rules! gen_in_range_quantization_tests {
        ($dim:literal, $points:expr, $sample:expr) => {
            pastey::paste! {
                #[test]
                fn [<test_quantize_in_range_matches_tuple_boundary_ $dim d>]() {
                    let bits = bit_depth(8);
                    let range = CoordinateRange::try_new(-2.0_f64, 3.0).unwrap();
                    let coords: [f64; $dim] = $sample;

                    let parsed = try_hilbert_quantize(&coords, range.bounds(), bits).unwrap();
                    let prevalidated = hilbert_quantize_in_range(&coords, range, bits).unwrap();

                    assert_eq!(prevalidated, parsed);
                }

                #[test]
                fn [<test_quantized_batch_carries_prequantized_validation_ $dim d>]() {
                    let bits = bit_depth(8);
                    let range = CoordinateRange::try_new(-2.0_f64, 3.0).unwrap();
                    let points: [[f64; $dim]; 4] = $points;
                    let quantized: Vec<[u32; $dim]> = points
                        .iter()
                        .map(|point| hilbert_quantize_in_range(point, range, bits).unwrap())
                        .collect();
                    let batch = HilbertQuantizedBatch::try_new(&quantized, bits).unwrap();

                    assert_eq!(batch.coordinates(), quantized.as_slice());
                    assert_eq!(batch.bits(), bits);

                    let checked = hilbert_indices_prequantized(&quantized, bits).unwrap();
                    assert_eq!(batch.indices(), checked);
                    assert_eq!(hilbert_indices_for_quantized_batch(batch), checked);
                }

                #[test]
                fn [<test_quantize_batch_in_range_matches_two_step_path_ $dim d>]() {
                    let bits = bit_depth(8);
                    let bounds = CoordinateRange::try_new(-2.0_f64, 3.0).unwrap();
                    let points: [[f64; $dim]; 4] = $points;

                    let two_step: Vec<[u32; $dim]> = points
                        .iter()
                        .map(|point| hilbert_quantize_in_range(point, bounds, bits).unwrap())
                        .collect();
                    let two_step_indices = hilbert_indices_prequantized(&two_step, bits).unwrap();

                    let batch = hilbert_quantize_batch_in_range(&points, bounds, bits, |point| *point)
                        .unwrap();
                    assert_eq!(batch.coordinates(), two_step.as_slice());
                    assert_eq!(batch.bits(), bits);
                    assert_eq!(batch.len(), points.len());
                    assert!(!batch.is_empty());

                    let (indices, quantized) = batch.into_indices_and_coordinates();
                    assert_eq!(quantized, two_step);
                    assert_eq!(indices, two_step_indices);
                }
            }
        };
    }

    gen_in_range_quantization_tests!(
        2,
        [[-2.0_f64, -1.0], [-1.5, 0.25], [0.1, -0.7], [3.0, 3.0]],
        [0.25_f64, 0.75]
    );
    gen_in_range_quantization_tests!(
        3,
        [
            [-2.0_f64, -1.0, 0.0],
            [-1.5, 0.25, 1.75],
            [0.1, -0.7, 2.2],
            [3.0, 3.0, -2.0]
        ],
        [0.25_f64, 0.75, -1.0]
    );
    gen_in_range_quantization_tests!(
        4,
        [
            [-2.0_f64, -1.0, 0.0, 1.0],
            [-1.5, 0.25, 1.75, 2.5],
            [0.1, -0.7, 2.2, -1.8],
            [3.0, 3.0, -2.0, -2.0],
        ],
        [0.25_f64, 0.75, -1.0, 2.5]
    );
    gen_in_range_quantization_tests!(
        5,
        [
            [-2.0_f64, -1.0, 0.0, 1.0, 2.0],
            [-1.5, 0.25, 1.75, 2.5, -0.5],
            [0.1, -0.7, 2.2, -1.8, 1.4],
            [3.0, 3.0, -2.0, -2.0, 0.5],
        ],
        [0.25_f64, 0.75, -1.0, 2.5, 0.0]
    );

    #[test]
    fn test_quantized_batch_rejects_out_of_range_coordinate() {
        let bits = bit_depth(2);
        let quantized = [[0_u32, 0], [4, 1]];
        let result = HilbertQuantizedBatch::try_new(&quantized, bits);

        assert_matches!(
            result,
            Err(HilbertError::PrequantizedCoordinateOutOfRange {
                bits: 2,
                max_grid_value: 3,
                point_index: 1,
                coordinate_index: 0,
                coordinate: 4
            })
        );
    }

    #[test]
    fn test_quantized_batch_rejects_index_overflow() {
        let quantized = [[1_u32, 2, 3, 4, 5]];
        let result = HilbertQuantizedBatch::try_new(&quantized, bit_depth(26));

        assert_matches!(
            result,
            Err(HilbertError::IndexOverflow {
                dimension: 5,
                bits: 26,
                total_bits: 130
            })
        );
    }

    #[test]
    fn test_quantized_batch_handles_zero_dimension() {
        let bits = bit_depth(8);
        let quantized = [[], [], []];
        let batch = HilbertQuantizedBatch::try_new(&quantized, bits).unwrap();

        assert_eq!(batch.coordinates(), quantized.as_slice());
        assert_eq!(batch.bits(), bits);
        assert_eq!(batch.indices(), vec![0_u128, 0_u128, 0_u128]);
        assert_eq!(
            hilbert_indices_for_quantized_batch(batch),
            vec![0_u128, 0_u128, 0_u128]
        );
    }

    #[test]
    fn test_quantize_batch_in_range_handles_zero_dimension() {
        let bits = bit_depth(8);
        let bounds = CoordinateRange::try_new(0.0_f64, 1.0).unwrap();
        let items = [(), (), ()];

        let batch =
            hilbert_quantize_batch_in_range(&items, bounds, bits, |()| [0.0_f64; 0]).unwrap();
        assert_eq!(batch.len(), 3);
        assert!(!batch.is_empty());
        assert_eq!(batch.indices(), vec![0_u128, 0_u128, 0_u128]);
        assert_eq!(batch.into_coordinates(), vec![[0_u32; 0]; 3]);
    }

    #[test]
    fn test_quantize_in_range_handles_zero_dimension() {
        let bits = bit_depth(8);
        let bounds = CoordinateRange::try_new(0.0_f64, 1.0).unwrap();
        let coords = [0.0_f64; 0];

        assert_eq!(
            hilbert_quantize_in_range(&coords, bounds, bits).unwrap(),
            [0_u32; 0]
        );
    }

    #[test]
    fn test_quantize_batch_in_range_rejects_index_overflow() {
        let bits = bit_depth(26);
        let bounds = CoordinateRange::try_new(0.0_f64, 1.0).unwrap();
        let items = [[0.0_f64; 5]];

        assert_matches!(
            hilbert_quantize_batch_in_range(&items, bounds, bits, |p| *p),
            Err(HilbertError::IndexOverflow {
                dimension: 5,
                bits: 26,
                total_bits: 130
            })
        );
    }

    #[test]
    fn test_quantize_rejects_nonfinite_bounds() {
        let result = try_hilbert_quantize(&[0.5_f64], (f64::NAN, 1.0), bit_depth(8));

        assert_eq!(
            result,
            Err(HilbertError::NonFiniteBounds {
                lower_bound_finite: false,
                upper_bound_finite: true
            })
        );

        let both_non_finite =
            try_hilbert_quantize(&[0.5_f64], (f64::NAN, f64::INFINITY), bit_depth(8));
        assert_eq!(
            both_non_finite,
            Err(HilbertError::NonFiniteBounds {
                lower_bound_finite: false,
                upper_bound_finite: false
            })
        );
    }

    #[test]
    fn test_quantize_rejects_nonfinite_extent() {
        let result = try_hilbert_quantize(&[0.0_f64], (-f64::MAX, f64::MAX), bit_depth(8));

        assert_eq!(result, Err(HilbertError::NonFiniteBoundsExtent {}));
    }

    #[test]
    fn test_quantize_rejects_nonfinite_coordinate() {
        let result = try_hilbert_quantize(&[0.25_f64, f64::INFINITY], (0.0, 1.0), bit_depth(8));

        assert_eq!(
            result,
            Err(HilbertError::NonFiniteCoordinate {
                coordinate_index: 1
            })
        );
    }

    #[test]
    fn test_quantize_rejects_nonfinite_normalized() {
        let result =
            try_hilbert_quantize(&[f64::MAX], (-f64::MAX / 2.0, f64::MAX / 2.0), bit_depth(8));

        assert_eq!(
            result,
            Err(HilbertError::NonFiniteNormalizedCoordinate {
                coordinate_index: 0
            })
        );
    }

    #[test]
    fn test_sort_error_keeps_order() {
        let coords = [[0.5_f64], [f64::NAN], [0.25]];
        let mut payload = vec![0_usize, 1, 2];

        let result =
            try_hilbert_sort_by_stable(&mut payload, (0.0, 1.0), bit_depth(8), |&i| coords[i]);

        assert_eq!(
            result,
            Err(HilbertError::NonFiniteCoordinate {
                coordinate_index: 0
            })
        );
        assert_eq!(payload, vec![0, 1, 2]);
    }

    #[test]
    fn test_apply_order_rejects_length_mismatch_without_reordering() {
        let mut payload = vec![10, 20, 30];
        let result = apply_order(&mut payload, [0_usize, 1].into_iter());

        assert_eq!(payload, vec![10, 20, 30]);
        assert_matches!(
            result,
            Err(HilbertError::InvalidSortPermutationLength {
                item_count: 3,
                permutation_count: 2
            })
        );
    }

    #[test]
    fn test_apply_order_rejects_out_of_range_index_without_reordering() {
        let mut payload = vec![10, 20, 30];
        let result = apply_order(&mut payload, [0_usize, 3, 1].into_iter());

        assert_eq!(payload, vec![10, 20, 30]);
        assert_matches!(
            result,
            Err(HilbertError::InvalidSortPermutationIndex {
                permutation_index: 1,
                item_index: 3,
                item_count: 3
            })
        );
    }

    #[test]
    fn test_apply_order_rejects_duplicate_index_without_reordering() {
        let mut payload = vec![10, 20, 30];
        let result = apply_order(&mut payload, [0_usize, 1, 1].into_iter());

        assert_eq!(payload, vec![10, 20, 30]);
        assert_matches!(
            result,
            Err(HilbertError::InvalidSortPermutationDuplicate {
                permutation_index: 2,
                item_index: 1
            })
        );
    }

    #[test]
    fn test_apply_order_rejects_short_iterator_length_lie_without_reordering() {
        let mut payload = vec![10, 20, 30];
        let result = apply_order(&mut payload, LyingOrder::new(vec![0, 1], 3));

        assert_eq!(payload, vec![10, 20, 30]);
        assert_matches!(
            result,
            Err(HilbertError::InvalidSortPermutationLength {
                item_count: 3,
                permutation_count: 2
            })
        );
    }

    #[test]
    fn test_apply_order_rejects_long_iterator_length_lie_without_reordering() {
        let mut payload = vec![10, 20, 30];
        let result = apply_order(&mut payload, LyingOrder::new(vec![0, 1, 2, 0], 3));

        assert_eq!(payload, vec![10, 20, 30]);
        assert_matches!(
            result,
            Err(HilbertError::InvalidSortPermutationLength {
                item_count: 3,
                permutation_count: 4
            })
        );
    }

    #[test]
    fn test_quantize_clamps_f64_endpoint() {
        let q = try_hilbert_quantize(&[1.0], (0.0, 1.0), bit_depth(31)).unwrap();

        assert_eq!(q, [(1_u32 << 31) - 1]);
    }

    #[test]
    fn test_hilbert_curve_is_continuous_on_2d_grid() {
        // A defining property of the (discrete) Hilbert curve is continuity:
        // successive indices correspond to adjacent grid cells.
        let bits: u32 = 4;
        let n: u32 = 1_u32 << bits;

        let mut points: Vec<([u32; 2], u128)> = Vec::with_capacity((n * n) as usize);
        let params = positive_index_params::<2>(bit_depth(bits));
        for x in 0..n {
            for y in 0..n {
                let q = [x, y];
                let idx = index_from_quantized(&q, params);
                points.push((q, idx));
            }
        }

        points.sort_by_key(|(_, idx)| *idx);

        // Indices should form a permutation of 0..n^2.
        for (i, (_, idx)) in points.iter().enumerate() {
            let i_u128 = u128::from(u32::try_from(i).expect("grid size should fit in u32"));
            assert_eq!(*idx, i_u128);
        }

        // Continuity: successive points differ by Manhattan distance exactly 1.
        for window in points.windows(2) {
            let a = window[0].0;
            let b = window[1].0;
            let dx = a[0].abs_diff(b[0]);
            let dy = a[1].abs_diff(b[1]);
            assert_eq!(dx + dy, 1, "Non-adjacent step: a={a:?}, b={b:?}");
        }
    }

    #[test]
    fn test_hilbert_curve_is_continuous_on_4d_grid() {
        // A defining property of the (discrete) Hilbert curve is continuity:
        // successive indices correspond to adjacent grid cells.
        let bits: u32 = 2;
        let n: u32 = 1_u32 << bits;

        let mut points: Vec<([u32; 4], u128)> = Vec::with_capacity((n * n * n * n) as usize);
        let params = positive_index_params::<4>(bit_depth(bits));
        for x in 0..n {
            for y in 0..n {
                for z in 0..n {
                    for w in 0..n {
                        let q = [x, y, z, w];
                        let idx = index_from_quantized(&q, params);
                        points.push((q, idx));
                    }
                }
            }
        }

        points.sort_by_key(|(_, idx)| *idx);

        // Indices should form a permutation of 0..n^4.
        for (i, (_, idx)) in points.iter().enumerate() {
            let i_u128 = u128::from(u32::try_from(i).expect("grid size should fit in u32"));
            assert_eq!(*idx, i_u128);
        }

        // Continuity: successive points differ by Manhattan distance exactly 1.
        for window in points.windows(2) {
            let a = window[0].0;
            let b = window[1].0;
            let dx = a[0].abs_diff(b[0]);
            let dy = a[1].abs_diff(b[1]);
            let dz = a[2].abs_diff(b[2]);
            let dw = a[3].abs_diff(b[3]);
            assert_eq!(dx + dy + dz + dw, 1, "Non-adjacent step: a={a:?}, b={b:?}");
        }
    }

    #[test]
    fn test_point_coords_work_with_hilbert() {
        let p: Point<2> = Point::try_new([0.25, 0.75]).expect("finite point coordinates");
        let idx = try_hilbert_index(p.coords(), (0.0, 1.0), bit_depth(16)).unwrap();
        assert!(idx > 0);
    }

    #[test]
    fn test_hilbert_bits_boundaries() {
        let coarsest_bits = bit_depth(1);
        let origin = try_hilbert_index(&[0.0_f64, 0.0], (0.0, 1.0), coarsest_bits).unwrap();
        let corner = try_hilbert_index(&[1.0_f64, 1.0], (0.0, 1.0), coarsest_bits).unwrap();
        tracing::debug!(origin, corner, "bits=1 boundaries");
        assert_eq!(origin, 0, "bits=1 origin should map to 0");
        assert_ne!(origin, corner, "bits=1 should distinguish corners");

        let finest_bits = bit_depth(31);
        let origin_31 = try_hilbert_index(&[0.0_f64, 0.0], (0.0, 1.0), finest_bits).unwrap();
        let corner_31 = try_hilbert_index(&[1.0_f64, 1.0], (0.0, 1.0), finest_bits).unwrap();
        tracing::debug!(origin_31, corner_31, "bits=31 boundaries");
        assert_eq!(origin_31, 0, "bits=31 origin should map to 0");
        assert_ne!(origin_31, corner_31, "bits=31 should distinguish corners");
    }

    #[test]
    fn test_hilbert_index_1d_monotonic() {
        let bounds = (0.0_f64, 1.0_f64);
        let bits = bit_depth(8);
        let a = try_hilbert_index(&[0.0_f64], bounds, bits).unwrap();
        let b = try_hilbert_index(&[0.25_f64], bounds, bits).unwrap();
        let c = try_hilbert_index(&[0.5_f64], bounds, bits).unwrap();
        let d = try_hilbert_index(&[1.0_f64], bounds, bits).unwrap();
        tracing::debug!(a, b, c, d, "1d indices");
        assert!(
            a < b && b < c && c < d,
            "1D Hilbert indices should be monotonic"
        );
    }

    #[test]
    fn test_hilbert_rejects_degenerate_bounds() {
        let bounds = (1.0_f64, 1.0_f64);
        let coords = [2.0_f64, -2.0_f64];
        let bits = bit_depth(8);

        assert_matches!(
            try_hilbert_quantize(&coords, bounds, bits),
            Err(HilbertError::NonIncreasingBounds {
                ordering: CoordinateRangeOrdering::Equal
            })
        );
        assert_matches!(
            try_hilbert_index(&coords, bounds, bits),
            Err(HilbertError::NonIncreasingBounds {
                ordering: CoordinateRangeOrdering::Equal
            })
        );
    }

    #[test]
    fn test_hilbert_rejects_decreasing_bounds() {
        let bounds = (1.0_f64, 0.0_f64);
        let coords = [0.5_f64, 0.25_f64];
        let bits = bit_depth(8);

        assert_matches!(
            try_hilbert_quantize(&coords, bounds, bits),
            Err(HilbertError::NonIncreasingBounds {
                ordering: CoordinateRangeOrdering::Decreasing
            })
        );
    }

    #[test]
    fn test_hilbert_quantize_clamps_out_of_range() {
        let bounds = (0.0_f64, 1.0_f64);
        let bits = bit_depth(4);
        let coords = [-1.0_f64, 2.0_f64];
        let q = try_hilbert_quantize(&coords, bounds, bits).unwrap();
        let max_val = (1_u32 << bits.get()) - 1;
        tracing::debug!(?q, max_val, "clamp quantize");
        assert_eq!(
            q,
            [0, max_val],
            "out-of-range coords should clamp to bounds"
        );

        let idx = try_hilbert_index(&coords, bounds, bits).unwrap();
        let idx_clamped = try_hilbert_index(&[0.0_f64, 1.0_f64], bounds, bits).unwrap();
        tracing::debug!(idx, idx_clamped, "clamp index");
        assert_eq!(
            idx, idx_clamped,
            "clamped coords should match clamped index"
        );
    }

    #[test]
    fn test_hilbert_indices_prequantized_matches_individual_calls() {
        let coords = [
            [0.1_f64, 0.2, 0.3],
            [0.5, 0.5, 0.5],
            [0.9, 0.8, 0.7],
            [0.0, 0.0, 0.0],
            [1.0, 1.0, 1.0],
        ];
        let bounds = (0.0_f64, 1.0_f64);
        let bits = bit_depth(8);

        // Quantize all coordinates
        let quantized: Vec<[u32; 3]> = coords
            .iter()
            .map(|c| try_hilbert_quantize(c, bounds, bits).unwrap())
            .collect();

        // Compute indices via bulk API
        let indices_bulk = hilbert_indices_prequantized(&quantized, bits)
            .expect("valid parameters should succeed");

        // Compute indices individually
        let indices_individual: Vec<u128> = coords
            .iter()
            .map(|c| try_hilbert_index(c, bounds, bits).unwrap())
            .collect();

        assert_eq!(indices_bulk.len(), coords.len());
        assert_eq!(indices_bulk, indices_individual);
    }

    #[test]
    fn test_hilbert_indices_prequantized_empty_input() {
        let empty: Vec<[u32; 2]> = vec![];
        let bits = bit_depth(4);

        let indices =
            hilbert_indices_prequantized(&empty, bits).expect("valid parameters should succeed");
        assert_eq!(indices.len(), 0);
    }

    #[test]
    fn test_hilbert_indices_prequantized_validates_overflow() {
        // With D=5 and bits=26, total_bits = 130 > 128
        let quantized = vec![[1_u32, 2, 3, 4, 5]];
        let result = hilbert_indices_prequantized(&quantized, bit_depth(26));
        assert_matches!(
            result,
            Err(HilbertError::IndexOverflow {
                dimension: 5,
                bits: 26,
                total_bits: 130
            })
        );
    }

    #[test]
    fn test_hilbert_indices_prequantized_validates_coordinate_range() {
        let bits = bit_depth(2);
        let quantized = vec![[0_u32, 3], [4, 1]];
        let result = hilbert_indices_prequantized(&quantized, bits);

        assert_matches!(
            result,
            Err(HilbertError::PrequantizedCoordinateOutOfRange {
                bits: 2,
                max_grid_value: 3,
                point_index: 1,
                coordinate_index: 0,
                coordinate: 4
            })
        );
    }

    #[test]
    fn test_hilbert_indices_prequantized_handles_zero_dimension() {
        // Zero-dimensional space has only one point, all map to index 0
        let quantized: Vec<[u32; 0]> = vec![[], [], []];
        let bits = bit_depth(8);

        let indices = hilbert_indices_prequantized(&quantized, bits).expect("D=0 should succeed");

        assert_eq!(indices.len(), 3);
        assert_eq!(indices, vec![0_u128, 0_u128, 0_u128]);
    }

    #[test]
    fn test_hilbert_quantize_uses_rounding_not_truncation() {
        let bounds = (0.0_f64, 1.0_f64);
        let bits = bit_depth(2); // Grid has 4 cells: 0, 1, 2, 3

        // With bits=2, max_val = 3, so we scale by 3.0.
        // coord * 3.0 is then rounded to nearest integer.
        // Cell boundaries (where rounding changes) are at:
        // 0.5/3 ≈ 0.167 (rounds from 0 to 1)
        // 1.5/3 = 0.5 (rounds from 1 to 2)
        // 2.5/3 ≈ 0.833 (rounds from 2 to 3)

        // Test points that should round to different cells
        let test_cases = [
            (0.0, 0),  // 0.0 * 3 = 0.0, rounds to 0
            (0.1, 0),  // 0.1 * 3 = 0.3, rounds to 0
            (0.17, 1), // 0.17 * 3 = 0.51, rounds to 1
            (0.3, 1),  // 0.3 * 3 = 0.9, rounds to 1
            (0.5, 2),  // 0.5 * 3 = 1.5, rounds to 2
            (0.7, 2),  // 0.7 * 3 = 2.1, rounds to 2
            (0.85, 3), // 0.85 * 3 = 2.55, rounds to 3
            (1.0, 3),  // exactly 1.0 -> cell 3 (clamped)
        ];

        for (coord, expected_cell) in test_cases {
            let q = try_hilbert_quantize(&[coord], bounds, bits).unwrap();
            assert_eq!(
                q[0], expected_cell,
                "coordinate {coord} should quantize to cell {expected_cell}, got {}",
                q[0]
            );
        }

        // Verify rounding distribution:
        // With rounding and bits=2 (max_val=3), cell boundaries are at:
        // - Cell 0: coord * 3 < 0.5 → coord < 0.167 (width 0.167)
        // - Cell 1: 0.5 <= coord * 3 < 1.5 → 0.167 <= coord < 0.5 (width 0.333)
        // - Cell 2: 1.5 <= coord * 3 < 2.5 → 0.5 <= coord < 0.833 (width 0.333)
        // - Cell 3: 2.5 <= coord * 3 <= 3.0 → 0.833 <= coord <= 1.0 (width 0.167)
        // So cells 1 and 2 should get roughly twice as many samples as cells 0 and 3.
        let samples = 1000;
        let mut cell_counts = [0_usize; 4];
        for i in 0..samples {
            let coord = f64::from(i) / f64::from(samples);
            let q = try_hilbert_quantize(&[coord], bounds, bits).unwrap();
            cell_counts[q[0] as usize] += 1;
        }

        tracing::debug!(?cell_counts, "cell distribution for {samples} samples");

        // Expected distribution: ~167 samples in cells 0 and 3, ~333 in cells 1 and 2.
        // Allow ±50 tolerance for discrete sampling effects.
        assert!(
            cell_counts[0] >= 100 && cell_counts[0] <= 217,
            "cell 0 should have ~167 samples with rounding, got {}",
            cell_counts[0]
        );
        assert!(
            cell_counts[1] >= 283 && cell_counts[1] <= 383,
            "cell 1 should have ~333 samples with rounding, got {}",
            cell_counts[1]
        );
        assert!(
            cell_counts[2] >= 283 && cell_counts[2] <= 383,
            "cell 2 should have ~333 samples with rounding, got {}",
            cell_counts[2]
        );
        assert!(
            cell_counts[3] >= 100 && cell_counts[3] <= 217,
            "cell 3 should have ~167 samples with rounding, got {}",
            cell_counts[3]
        );
    }
}