libasdf-rs 0.1.1

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

use crate::file_ffi::file_document_mut;
use std::ffi::{CStr, CString, c_char, c_int, c_void};

use asdf_core::compression::Compression;
use asdf_core::core::datatype::{Datatype, ScalarType};
use asdf_core::core::elements::{Element, decode_all};
use asdf_core::core::ndarray::{Ndarray, Source};

use crate::ffi::{CMallocBuf, write_out};
use crate::panic::guard;
use crate::types::AsdfArrayStorage;

/// Error codes matching `asdf_ndarray_err_t`.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[repr(i32)]
pub enum NdarrayErr {
    /// Read successfully.
    Ok = 0,
    /// Read beyond the bounds of the array.
    OutOfBounds,
    /// Allocation failure.
    Oom,
    /// An argument was invalid.
    Inval,
    /// A value did not fit the requested type.
    Overflow,
    /// An element could not be converted to the requested type.
    Conversion,
}

/// Mirror of `asdf_datatype_t`.
///
/// Field order and widths must match `include/asdf/core/datatype.h`.
#[repr(C)]
#[derive(Debug)]
pub struct asdf_datatype_t {
    /// The scalar type, or `STRUCTURED` for a compound type.
    pub type_: ScalarTypeAbi,
    /// Element size in bytes. May be left 0 for numeric types.
    pub size: u64,
    /// Optional field name, for a compound type's member.
    pub name: *const c_char,
    /// Byte order of the elements.
    pub byteorder: ByteOrderAbi,
    /// Number of sub-array dimensions, 0 for a scalar.
    pub ndim: u32,
    /// The sub-array shape, `ndim` entries.
    pub shape: *const u64,
    /// Number of fields, for a compound type.
    pub nfields: u32,
    /// The fields, `nfields` entries.
    pub fields: *const asdf_datatype_t,
}

/// `asdf_scalar_datatype_t` as it crosses the boundary.
pub type ScalarTypeAbi = i32;
/// `asdf_byteorder_t` as it crosses the boundary.
pub type ByteOrderAbi = i32;

/// Mirror of `asdf_ndarray_t`.
///
/// The header notes that these fields are public "for now" and may not stay
/// ABI-stable; reproducing them exactly is what makes this a drop-in today.
#[repr(C)]
#[derive(Debug)]
pub struct asdf_ndarray_t {
    /// Index of the block holding the data.
    pub source: usize,
    /// Number of dimensions.
    pub ndim: u32,
    /// The shape, `ndim` entries.
    pub shape: *const u64,
    /// The element type.
    pub datatype: asdf_datatype_t,
    /// Byte order of the array data.
    pub byteorder: ByteOrderAbi,
    /// Offset into the block where the data starts.
    pub offset: u64,
    /// Strides in bytes, `ndim` entries, or null for C-contiguous.
    pub strides: *const i64,
    /// Reserved for the implementation. This is where our state lives.
    pub _reserved: *mut c_void,
}

/// Sixteen bytes, aligned to sixteen. See [`AlignedBuf`].
///
/// The field is never named again: it exists to give the allocation its size
/// and its alignment, and the bytes are reached through the buffer's slice
/// accessors. `#[repr(align)]` rather than `u128` because `u128`'s alignment
/// is 16 only on some targets.
#[repr(align(16))]
#[derive(Clone, Copy, Debug)]
struct Chunk(#[allow(dead_code)] [u8; 16]);

/// A byte buffer aligned the way `malloc` aligns.
///
/// `asdf_ndarray_data` returns its pointer straight to C, and every caller
/// casts it before dereferencing:
///
/// ```c
/// int32_t *values = asdf_ndarray_data(array, &size);
/// printf("%d\n", values[0]);
/// ```
///
/// A `Vec<u8>` is aligned to 1, so that cast is undefined behaviour, and on a
/// strict-alignment target it is a bus error rather than a theoretical one.
/// Upstream libasdf gets this right without trying, because `malloc` is
/// specified to return storage aligned for any fundamental type; we had
/// quietly given up that guarantee by holding the bytes in a `Vec<u8>`.
///
/// Backing the storage with a 16-byte-aligned element restores it in safe
/// code: `Vec<T>` is always aligned to `align_of::<T>()`. Sixteen covers
/// every ASDF datatype -- the widest is `complex128`, a pair of doubles --
/// and matches `max_align_t` on the platforms libasdf targets.
#[derive(Clone, Debug)]
pub(crate) struct AlignedBuf {
    chunks: Vec<Chunk>,
    /// The requested length. The backing store rounds up to a whole chunk.
    len: usize,
}

impl AlignedBuf {
    /// A zeroed buffer of `len` bytes.
    fn zeroed(len: usize) -> Self {
        Self { chunks: vec![Chunk([0; 16]); len.div_ceil(16)], len }
    }

    /// A buffer holding a copy of `bytes`.
    fn from_slice(bytes: &[u8]) -> Self {
        let mut buf = Self::zeroed(bytes.len());
        buf.as_mut_slice()[..bytes.len()].copy_from_slice(bytes);
        buf
    }

    fn as_slice(&self) -> &[u8] {
        // Reading a `[Chunk]` as bytes is always valid: `Chunk` is a byte
        // array under a stricter alignment, so it has no padding and no
        // invalid bit patterns.
        let bytes: &[u8] = unsafe {
            std::slice::from_raw_parts(self.chunks.as_ptr().cast::<u8>(), self.chunks.len() * 16)
        };
        &bytes[..self.len]
    }

    fn as_mut_slice(&mut self) -> &mut [u8] {
        // SAFETY: as `as_slice`, and the borrow is exclusive.
        let bytes: &mut [u8] = unsafe {
            std::slice::from_raw_parts_mut(
                self.chunks.as_mut_ptr().cast::<u8>(),
                self.chunks.len() * 16,
            )
        };
        &mut bytes[..self.len]
    }

    /// The aligned pointer handed to C.
    fn as_mut_ptr(&mut self) -> *mut u8 {
        self.chunks.as_mut_ptr().cast::<u8>()
    }
}

impl std::ops::Deref for AlignedBuf {
    type Target = [u8];

    fn deref(&self) -> &[u8] {
        self.as_slice()
    }
}

/// The state hanging off `_reserved`.
///
/// It owns every buffer the public struct points at, so the pointers stay
/// valid for as long as the array does and are freed exactly once.
struct NdarrayState {
    shape: Vec<u64>,
    strides: Option<Vec<i64>>,
    /// Field descriptors for a compound datatype, kept alive for `fields`.
    fields: Vec<asdf_datatype_t>,
    /// Field names, kept alive for each field's `name`.
    field_names: Vec<CString>,
    /// Per-field sub-array shapes.
    field_shapes: Vec<Vec<u64>>,
    /// The engine's own view of the array.
    parsed: Ndarray,
    /// Data read from the file, cached for `asdf_ndarray_data`.
    data: Option<AlignedBuf>,
    /// A buffer from `asdf_ndarray_data_alloc`, owned until dealloc.
    allocated: Option<AlignedBuf>,
    /// Compression to use when the array is written.
    compression: Compression,
    /// Where the data will be written.
    storage: AsdfArrayStorage,
    /// The file the array was read from, for `asdf_ndarray_block`.
    file: *mut crate::file_ffi::AsdfFile,
    /// The index of the block holding the data, when it is not inline.
    block_index: Option<usize>,
    /// The block view handed out by `asdf_ndarray_block`, owned here.
    block: *mut crate::block_ffi::AsdfBlock,
}

fn scalar_abi(t: ScalarType) -> ScalarTypeAbi {
    t as i32
}

/// The scalar type for an ABI discriminant, for other modules.
pub(crate) fn scalar_from_abi_public(v: ScalarTypeAbi) -> ScalarType {
    scalar_from_abi(v)
}

fn scalar_from_abi(v: ScalarTypeAbi) -> ScalarType {
    match v {
        1 => ScalarType::Int8,
        2 => ScalarType::Uint8,
        3 => ScalarType::Int16,
        4 => ScalarType::Uint16,
        5 => ScalarType::Int32,
        6 => ScalarType::Uint32,
        7 => ScalarType::Int64,
        8 => ScalarType::Uint64,
        9 => ScalarType::Float16,
        10 => ScalarType::Float32,
        11 => ScalarType::Float64,
        12 => ScalarType::Complex64,
        13 => ScalarType::Complex128,
        14 => ScalarType::Bool8,
        15 => ScalarType::Ascii,
        16 => ScalarType::Ucs4,
        17 => ScalarType::Structured,
        _ => ScalarType::Unknown,
    }
}

/// Build the C datatype view for `datatype`, parking owned storage in `state`.
fn build_datatype(
    datatype: &Datatype,
    array_order: asdf_core::core::datatype::ByteOrder,
    state: &mut NdarrayState,
) -> asdf_datatype_t {
    use asdf_core::core::datatype::ByteOrder;

    // A datatype states its own byte order only inside a compound field; a
    // plain one takes the array's, which is where the schema puts it.
    let effective = |own: ByteOrder| if own == ByteOrder::Default { array_order } else { own };

    for field in &datatype.fields {
        let name = field.name.as_deref().and_then(|n| CString::new(n).ok()).unwrap_or_default();
        state.field_names.push(name);
        state.field_shapes.push(field.datatype.shape.clone());
    }

    let base = state.fields.len();
    for (index, field) in datatype.fields.iter().enumerate() {
        let name_ptr = state.field_names[base + index].as_ptr();
        let shape = &state.field_shapes[base + index];
        state.fields.push(asdf_datatype_t {
            type_: scalar_abi(field.datatype.scalar),
            size: field.datatype.item_size(),
            name: name_ptr,
            byteorder: effective(field.datatype.byteorder) as i32,
            ndim: u32::try_from(shape.len()).unwrap_or(0),
            shape: if shape.is_empty() { std::ptr::null() } else { shape.as_ptr() },
            nfields: 0,
            fields: std::ptr::null(),
        });
    }

    asdf_datatype_t {
        type_: scalar_abi(datatype.scalar),
        size: datatype.item_size(),
        name: std::ptr::null(),
        byteorder: effective(datatype.byteorder) as i32,
        ndim: 0,
        shape: std::ptr::null(),
        nfields: u32::try_from(datatype.fields.len()).unwrap_or(0),
        fields: if state.fields.is_empty() {
            std::ptr::null()
        } else {
            state.fields[base..].as_ptr()
        },
    }
}

/// Build a public ndarray handle from the engine's parsed form.
pub(crate) fn make_ndarray(parsed: Ndarray, shape: Vec<u64>) -> *mut asdf_ndarray_t {
    let mut state = Box::new(NdarrayState {
        shape,
        strides: parsed.strides.clone(),
        fields: Vec::new(),
        field_names: Vec::new(),
        field_shapes: Vec::new(),
        parsed: parsed.clone(),
        data: None,
        allocated: None,
        compression: Compression::None,
        // Where the data was found is where it will go back, unless the
        // caller says otherwise with `asdf_ndarray_storage_set`.
        storage: match parsed.source {
            Source::Inline(_) => AsdfArrayStorage::Inline,
            Source::External(_) => AsdfArrayStorage::External,
            _ => AsdfArrayStorage::Internal,
        },
        file: std::ptr::null_mut(),
        block_index: None,
        block: std::ptr::null_mut(),
    });

    // The compound-field storage must be sized before any pointer into it is
    // taken, or a later push would reallocate and dangle it.
    state.fields.reserve(parsed.datatype.fields.len());
    state.field_names.reserve(parsed.datatype.fields.len());
    state.field_shapes.reserve(parsed.datatype.fields.len());
    let datatype = build_datatype(&parsed.datatype, parsed.byteorder, &mut state);

    let source = match parsed.source {
        Source::Block(index) => index,
        _ => 0,
    };

    let shape_ptr = if state.shape.is_empty() { std::ptr::null() } else { state.shape.as_ptr() };
    let strides_ptr = state.strides.as_ref().map_or(std::ptr::null(), |s| s.as_ptr());

    let array = Box::new(asdf_ndarray_t {
        source,
        ndim: u32::try_from(state.shape.len()).unwrap_or(0),
        shape: shape_ptr,
        datatype,
        byteorder: parsed.byteorder as i32,
        offset: parsed.offset,
        strides: strides_ptr,
        _reserved: Box::into_raw(state).cast::<c_void>(),
    });
    Box::into_raw(array)
}

fn state_of<'a>(array: *mut asdf_ndarray_t) -> Option<&'a mut NdarrayState> {
    if array.is_null() {
        return None;
    }
    let reserved = unsafe { &*array }._reserved;
    unsafe { crate::ffi::as_mut(reserved.cast::<NdarrayState>()) }
}

/// The state behind an array, creating it from the public fields if absent.
///
/// A caller may build an `asdf_ndarray_t` as a stack literal with
/// `_reserved` left zero -- libasdf's own README write example does exactly
/// that, then calls `asdf_ndarray_data_alloc` on it. So anything needing
/// state has to bring it into being rather than assume it is already there.
///
/// The caller then owns that allocation, and releases it with
/// `asdf_ndarray_deinit` or `asdf_ndarray_destroy`.
fn ensure_state<'a>(array: *mut asdf_ndarray_t) -> Option<&'a mut NdarrayState> {
    if array.is_null() {
        return None;
    }
    if state_of(array).is_some() {
        return state_of(array);
    }

    let view = unsafe { &*array };
    let shape: Vec<u64> = if view.shape.is_null() || view.ndim == 0 {
        Vec::new()
    } else {
        unsafe { std::slice::from_raw_parts(view.shape, view.ndim as usize) }.to_vec()
    };
    let strides: Option<Vec<i64>> = (!view.strides.is_null() && view.ndim > 0)
        .then(|| unsafe { std::slice::from_raw_parts(view.strides, view.ndim as usize) }.to_vec());

    // Rebuild the engine's view from what the caller filled in.
    let scalar = scalar_from_abi(view.datatype.type_);
    let mut datatype = Datatype::scalar(scalar);
    if view.datatype.size != 0 {
        datatype.size = view.datatype.size;
    }
    let parsed = Ndarray {
        source: Source::Block(view.source),
        shape: shape.iter().map(|d| Some(*d)).collect(),
        datatype,
        byteorder: match view.byteorder {
            62 => asdf_core::core::datatype::ByteOrder::Big,
            60 => asdf_core::core::datatype::ByteOrder::Little,
            _ => asdf_core::core::datatype::ByteOrder::native(),
        },
        offset: view.offset,
        strides: strides.clone(),
        mask: None,
    };

    let state = Box::new(NdarrayState {
        shape,
        strides,
        fields: Vec::new(),
        field_names: Vec::new(),
        field_shapes: Vec::new(),
        parsed,
        data: None,
        allocated: None,
        compression: Compression::None,
        storage: AsdfArrayStorage::Internal,
        file: std::ptr::null_mut(),
        block_index: None,
        block: std::ptr::null_mut(),
    });
    unsafe { (*array)._reserved = Box::into_raw(state).cast::<c_void>() };
    state_of(array)
}

/// The number of elements.
///
/// # Safety
/// `ndarray` must be null or a valid `asdf_ndarray_t`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn asdf_ndarray_size(ndarray: *const asdf_ndarray_t) -> u64 {
    guard("asdf_ndarray_size", 0, || ndarray_size(ndarray))
}

/// Safe internal form of [`asdf_ndarray_size`].
///
/// The exported entry point is `unsafe extern "C"`, so calling it from
/// inside the crate would need an `unsafe` block at every site to assert a
/// contract the crate itself is upholding. Callers use this instead.
pub(crate) fn ndarray_size(ndarray: *const asdf_ndarray_t) -> u64 {
    if ndarray.is_null() {
        return 0;
    }
    let array = unsafe { &*ndarray };
    if array.shape.is_null() || array.ndim == 0 {
        return 0;
    }
    let shape = unsafe { std::slice::from_raw_parts(array.shape, array.ndim as usize) };
    shape.iter().product()
}

/// The number of bytes the elements occupy.
///
/// # Safety
/// `ndarray` must be null or a valid `asdf_ndarray_t`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn asdf_ndarray_nbytes(ndarray: *const asdf_ndarray_t) -> u64 {
    guard("asdf_ndarray_nbytes", 0, || ndarray_nbytes(ndarray))
}

/// Safe internal form of [`asdf_ndarray_nbytes`].
///
/// The exported entry point is `unsafe extern "C"`, so calling it from
/// inside the crate would need an `unsafe` block at every site to assert a
/// contract the crate itself is upholding. Callers use this instead.
pub(crate) fn ndarray_nbytes(ndarray: *const asdf_ndarray_t) -> u64 {
    if ndarray.is_null() {
        return 0;
    }
    let count = ndarray_size(ndarray);
    // Only the field projection needs the unsafe; the size call does not.
    let datatype = unsafe { &raw const (*ndarray).datatype };
    count * datatype_size(datatype.cast_mut())
}

/// The size of one element of a datatype, computing it when left at zero.
///
/// # Safety
/// `datatype` must be null or a valid `asdf_datatype_t`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn asdf_datatype_size(datatype: *mut asdf_datatype_t) -> u64 {
    guard("asdf_datatype_size", 0, || datatype_size(datatype))
}

/// Safe internal form of [`asdf_datatype_size`].
///
/// The exported entry point is `unsafe extern "C"`, so calling it from
/// inside the crate would need an `unsafe` block at every site to assert a
/// contract the crate itself is upholding. Callers use this instead.
pub(crate) fn datatype_size(datatype: *mut asdf_datatype_t) -> u64 {
    if datatype.is_null() {
        return 0;
    }
    let dt = unsafe { &mut *datatype };
    if dt.size != 0 {
        return dt.size;
    }
    // A string type must carry its own size; zero there means an empty
    // string, as the header documents. Numeric types are computed and
    // written back.
    let scalar = scalar_from_abi(dt.type_);
    let computed = scalar.size();
    dt.size = computed;
    computed
}

/// The scalar type named by a string, or `UNKNOWN`.
///
/// # Safety
/// `name` must be a valid NUL-terminated string or null.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn asdf_scalar_datatype_from_string(name: *const c_char) -> ScalarTypeAbi {
    guard("asdf_scalar_datatype_from_string", 0, || {
        if name.is_null() {
            return 0;
        }
        let text = unsafe { CStr::from_ptr(name) }.to_string_lossy().into_owned();
        scalar_abi(ScalarType::from_name(&text))
    })
}

/// The string naming a scalar type.
///
/// # Safety
/// The returned pointer refers to a `'static` string.
#[unsafe(no_mangle)]
pub extern "C" fn asdf_scalar_datatype_to_string(datatype: ScalarTypeAbi) -> *const c_char {
    // Static names, so no allocation and no lifetime question.
    let name: &'static CStr = match scalar_from_abi(datatype) {
        ScalarType::Int8 => c"int8",
        ScalarType::Uint8 => c"uint8",
        ScalarType::Int16 => c"int16",
        ScalarType::Uint16 => c"uint16",
        ScalarType::Int32 => c"int32",
        ScalarType::Uint32 => c"uint32",
        ScalarType::Int64 => c"int64",
        ScalarType::Uint64 => c"uint64",
        ScalarType::Float16 => c"float16",
        ScalarType::Float32 => c"float32",
        ScalarType::Float64 => c"float64",
        ScalarType::Complex64 => c"complex64",
        ScalarType::Complex128 => c"complex128",
        ScalarType::Bool8 => c"bool8",
        ScalarType::Ascii => c"ascii",
        ScalarType::Ucs4 => c"ucs4",
        ScalarType::Structured => c"structured",
        ScalarType::Unknown => c"unknown",
    };
    name.as_ptr()
}

/// Allocate a data buffer sized for the array.
///
/// Repeated calls return the same buffer. It is released by
/// [`asdf_ndarray_data_dealloc`], not automatically.
///
/// # Safety
/// `ndarray` must be null or a valid `asdf_ndarray_t`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn asdf_ndarray_data_alloc(ndarray: *mut asdf_ndarray_t) -> *mut c_void {
    guard("asdf_ndarray_data_alloc", std::ptr::null_mut(), || ndarray_data_alloc(ndarray))
}

/// Safe internal form of [`asdf_ndarray_data_alloc`].
///
/// The exported entry point is `unsafe extern "C"`, so calling it from
/// inside the crate would need an `unsafe` block at every site to assert a
/// contract the crate itself is upholding. Callers use this instead.
pub(crate) fn ndarray_data_alloc(ndarray: *mut asdf_ndarray_t) -> *mut c_void {
    let nbytes = ndarray_nbytes(ndarray);
    let Some(state) = ensure_state(ndarray) else {
        return std::ptr::null_mut();
    };
    let Ok(len) = usize::try_from(nbytes) else {
        return std::ptr::null_mut();
    };
    if state.allocated.is_none() {
        state.allocated = Some(AlignedBuf::zeroed(len));
    }
    state.allocated.as_mut().map_or(std::ptr::null_mut(), |b| b.as_mut_ptr().cast::<c_void>())
}

/// Free a buffer from [`asdf_ndarray_data_alloc`].
///
/// Calling this without a prior allocation is a no-op.
///
/// # Safety
/// `ndarray` must be null or a valid `asdf_ndarray_t`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn asdf_ndarray_data_dealloc(ndarray: *mut asdf_ndarray_t) {
    guard("asdf_ndarray_data_dealloc", (), || {
        if let Some(state) = state_of(ndarray) {
            state.allocated = None;
        }
    })
}

/// Allocate the array's buffer and copy `src` into it.
///
/// # Safety
/// `src` must point to at least `asdf_ndarray_nbytes` readable bytes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn asdf_ndarray_data_copy(
    ndarray: *mut asdf_ndarray_t,
    src: *const c_void,
) -> NdarrayErr {
    guard("asdf_ndarray_data_copy", NdarrayErr::Inval, || {
        if ndarray.is_null() || src.is_null() {
            return NdarrayErr::Inval;
        }
        let nbytes = ndarray_nbytes(ndarray);
        let Ok(len) = usize::try_from(nbytes) else {
            return NdarrayErr::Inval;
        };
        let destination = ndarray_data_alloc(ndarray);
        if destination.is_null() {
            return NdarrayErr::Oom;
        }
        unsafe {
            std::ptr::copy_nonoverlapping(src.cast::<u8>(), destination.cast::<u8>(), len);
        }
        NdarrayErr::Ok
    })
}

/// The array's data, decompressed if needed.
///
/// # Safety
/// `ndarray` must be null or a valid `asdf_ndarray_t`; `size` writable or
/// null. The pointer is owned by the array.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn asdf_ndarray_data(
    ndarray: *mut asdf_ndarray_t,
    size: *mut usize,
) -> *const c_void {
    guard("asdf_ndarray_data", std::ptr::null(), || ndarray_data(ndarray, size))
}

/// Safe internal form of [`asdf_ndarray_data`].
///
/// The exported entry point is `unsafe extern "C"`, so calling it from
/// inside the crate would need an `unsafe` block at every site to assert a
/// contract the crate itself is upholding. Callers use this instead.
pub(crate) fn ndarray_data(ndarray: *mut asdf_ndarray_t, size: *mut usize) -> *const c_void {
    let Some(state) = state_of(ndarray) else {
        if !size.is_null() {
            unsafe { write_out(size, 0) };
        }
        return std::ptr::null();
    };
    // A buffer the caller built takes precedence: it is the array's data.
    let bytes = match (&state.allocated, &state.data) {
        (Some(buffer), _) => buffer,
        (None, Some(data)) => data,
        (None, None) => {
            if !size.is_null() {
                unsafe { write_out(size, 0) };
            }
            return std::ptr::null();
        }
    };
    if !size.is_null() {
        unsafe { write_out(size, bytes.len()) };
    }
    bytes.as_ptr().cast::<c_void>()
}

/// The array's data as stored, without decompressing.
///
/// # Safety
/// See [`asdf_ndarray_data`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn asdf_ndarray_data_raw(
    ndarray: *mut asdf_ndarray_t,
    size: *mut usize,
) -> *const c_void {
    // The engine decompresses on read, so the two coincide for arrays we
    // hand out; a caller wanting the stored form uses the block API.
    ndarray_data(ndarray, size)
}

/// Set the compression used when the array is written.
///
/// # Safety
/// `compression` must be a valid NUL-terminated string or null.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn asdf_ndarray_compression_set(
    ndarray: *mut asdf_ndarray_t,
    compression: *const c_char,
) -> c_int {
    guard("asdf_ndarray_compression_set", -1, || {
        let Some(state) = ensure_state(ndarray) else { return -1 };
        let name = if compression.is_null() {
            String::new()
        } else {
            unsafe { CStr::from_ptr(compression) }.to_string_lossy().into_owned()
        };
        let Ok(method) = Compression::from_name(&name) else {
            return -1;
        };
        if !method.is_available() {
            return -1;
        }
        state.compression = method;
        0
    })
}

/// Where the array's data will be written.
///
/// # Safety
/// `ndarray` must be null or a valid `asdf_ndarray_t`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn asdf_ndarray_storage(ndarray: *mut asdf_ndarray_t) -> AsdfArrayStorage {
    guard("asdf_ndarray_storage", AsdfArrayStorage::Default, || {
        state_of(ndarray).map_or(AsdfArrayStorage::Default, |s| s.storage)
    })
}

/// Set where the array's data will be written.
///
/// `External` is not yet supported and leaves the setting unchanged, as
/// upstream does.
///
/// # Safety
/// `ndarray` must be null or a valid `asdf_ndarray_t`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn asdf_ndarray_storage_set(
    ndarray: *mut asdf_ndarray_t,
    storage: AsdfArrayStorage,
) {
    guard("asdf_ndarray_storage_set", (), || {
        if storage == AsdfArrayStorage::External {
            return;
        }
        if let Some(state) = ensure_state(ndarray) {
            state.storage = storage;
        }
    })
}

/// Convert one element to a destination scalar type, writing it into `out`.
///
/// A value outside the destination's range **saturates** rather than
/// wrapping or being refused: to the destination's minimum or maximum for an
/// integer, and to an infinity for a float. The call still reports
/// [`NdarrayErr::Overflow`], and the caller is expected to keep the
/// converted buffer -- that is what upstream does, and what a reader
/// converting a whole array needs, since one bad element should not cost the
/// rest.
///
/// Losing *precision* is not overflow: `int32::MAX` as an `f32` rounds, and
/// that is an ordinary conversion. Only leaving the representable range is.
fn write_converted(element: &Element, target: ScalarType, out: &mut [u8]) -> NdarrayErr {
    /// Write a value's native-endian bytes, if they fit.
    macro_rules! emit {
        ($bytes:expr) => {{
            let bytes = $bytes;
            if out.len() < bytes.len() {
                return NdarrayErr::Inval;
            }
            out[..bytes.len()].copy_from_slice(&bytes);
        }};
    }

    macro_rules! put_int {
        ($ty:ty) => {{
            let (wide, saturated): (i128, bool) = match element {
                Element::Int(v) => (i128::from(*v), false),
                Element::Uint(v) => (i128::from(*v), false),
                Element::Bool(v) => (i128::from(*v), false),
                Element::Float(v) => {
                    if v.is_nan() {
                        // Converting a NaN to an integer has no defined
                        // answer; zero is as good as any, and upstream
                        // makes no promise either.
                        (0, false)
                    } else if v.is_infinite() {
                        (
                            if *v > 0.0 { i128::from(<$ty>::MAX) } else { i128::from(<$ty>::MIN) },
                            true,
                        )
                    } else {
                        // Truncates toward zero, as a C cast does.
                        (v.trunc() as i128, false)
                    }
                }
                _ => return NdarrayErr::Conversion,
            };

            let clamped = wide.clamp(i128::from(<$ty>::MIN), i128::from(<$ty>::MAX));
            emit!((clamped as $ty).to_ne_bytes());
            if saturated || clamped != wide { NdarrayErr::Overflow } else { NdarrayErr::Ok }
        }};
    }

    /// Convert to a float type, reporting only a finite value turning
    /// infinite.
    macro_rules! put_float {
        ($convert:expr, $bytes:expr) => {{
            let source: f64 = match element {
                Element::Float(v) => *v,
                Element::Int(v) => *v as f64,
                Element::Uint(v) => *v as f64,
                Element::Bool(v) => f64::from(*v),
                _ => return NdarrayErr::Conversion,
            };
            #[allow(clippy::redundant_closure_call)]
            let value = ($convert)(source);
            #[allow(clippy::redundant_closure_call)]
            let bytes = ($bytes)(value);
            emit!(bytes);
            if source.is_finite() && !is_finite_result(value.into()) {
                NdarrayErr::Overflow
            } else {
                NdarrayErr::Ok
            }
        }};
    }

    match target {
        ScalarType::Int8 => put_int!(i8),
        ScalarType::Int16 => put_int!(i16),
        ScalarType::Int32 => put_int!(i32),
        ScalarType::Int64 => put_int!(i64),
        ScalarType::Uint8 => put_int!(u8),
        ScalarType::Uint16 => put_int!(u16),
        ScalarType::Uint32 => put_int!(u32),
        ScalarType::Uint64 => put_int!(u64),
        ScalarType::Bool8 => {
            let value = match element {
                Element::Bool(v) => u8::from(*v),
                Element::Int(v) => u8::from(*v != 0),
                Element::Uint(v) => u8::from(*v != 0),
                _ => return NdarrayErr::Conversion,
            };
            emit!(value.to_ne_bytes());
            NdarrayErr::Ok
        }
        ScalarType::Float32 => put_float!(|v: f64| v as f32, |v: f32| v.to_ne_bytes()),
        ScalarType::Float64 => put_float!(|v: f64| v, |v: f64| v.to_ne_bytes()),
        ScalarType::Float16 => {
            put_float!(half::f16::from_f64, |v: half::f16| v.to_bits().to_ne_bytes())
        }
        _ => NdarrayErr::Conversion,
    }
}

/// Whether a converted float stayed finite.
fn is_finite_result(value: f64) -> bool {
    value.is_finite()
}

/// Decode the array's elements, using the cached data.
fn elements_of(state: &NdarrayState) -> Option<Vec<Element>> {
    let data = state.allocated.as_ref().or(state.data.as_ref())?;
    decode_all(&state.parsed, &state.shape, data).ok()
}

/// Read the whole array, converting to `dst_t`.
///
/// With `dst` pointing at a null pointer, a buffer is allocated and the
/// caller frees it with `free`. Passing `ASDF_DATATYPE_SOURCE` (which is
/// `UNKNOWN`) keeps the array's own type.
///
/// # Safety
/// `ndarray` must be a valid `asdf_ndarray_t`; `dst` must be writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn asdf_ndarray_read_all(
    ndarray: *mut asdf_ndarray_t,
    dst_t: ScalarTypeAbi,
    dst: *mut *mut c_void,
) -> NdarrayErr {
    guard("asdf_ndarray_read_all", NdarrayErr::Inval, || {
        let Some(state) = state_of(ndarray) else {
            return NdarrayErr::Inval;
        };
        let Some(elements) = elements_of(state) else {
            return NdarrayErr::Inval;
        };

        let target = match scalar_from_abi(dst_t) {
            // ASDF_DATATYPE_SOURCE is an alias for UNKNOWN and means
            // "keep the source type".
            ScalarType::Unknown => state.parsed.datatype.scalar,
            other => other,
        };
        let width = target.size();
        if width == 0 {
            return NdarrayErr::Conversion;
        }
        let Ok(width) = usize::try_from(width) else {
            return NdarrayErr::Inval;
        };

        let total = elements.len() * width;
        let mut buffer = vec![0u8; total];
        // An overflowing element saturates and the read continues: the
        // caller gets the whole converted array *and* the report that
        // something did not fit. Anything else is a hard failure.
        let mut overflowed = false;
        for (index, element) in elements.iter().enumerate() {
            let slot = &mut buffer[index * width..(index + 1) * width];
            match write_converted(element, target, slot) {
                NdarrayErr::Ok => {}
                NdarrayErr::Overflow => overflowed = true,
                err => return err,
            }
        }

        let delivered = deliver(&buffer, dst);
        if delivered != NdarrayErr::Ok {
            return delivered;
        }
        if overflowed { NdarrayErr::Overflow } else { NdarrayErr::Ok }
    })
}

/// The flat offset of an element, or `None` if the indices are out of range.
fn flat_index(shape: &[u64], indices: &[u64]) -> Option<usize> {
    if shape.len() != indices.len() {
        return None;
    }
    let mut flat = 0u64;
    for (dim, index) in shape.iter().zip(indices.iter()) {
        if index >= dim {
            return None;
        }
        flat = flat.checked_mul(*dim)?.checked_add(*index)?;
    }
    usize::try_from(flat).ok()
}

/// Generate a typed single-element accessor.
macro_rules! read_at {
    ($name:ident, $ty:ty, $convert:expr) => {
        /// Read one element, converted to this type.
        ///
        /// # Safety
        /// `ndarray` must be a valid `asdf_ndarray_t`; `indices` must point
        /// to `ndim` values; `err` writable or null.
        #[unsafe(no_mangle)]
        pub unsafe extern "C" fn $name(
            ndarray: *mut asdf_ndarray_t,
            indices: *const u64,
            err: *mut c_int,
        ) -> $ty {
            guard(stringify!($name), <$ty>::default(), || {
                let set = |code: NdarrayErr| {
                    if !err.is_null() {
                        unsafe { write_out(err, code as c_int) };
                    }
                };
                let Some(state) = state_of(ndarray) else {
                    set(NdarrayErr::Inval);
                    return <$ty>::default();
                };
                if indices.is_null() {
                    set(NdarrayErr::Inval);
                    return <$ty>::default();
                }
                let idx = unsafe { std::slice::from_raw_parts(indices, state.shape.len()) };
                let Some(flat) = flat_index(&state.shape, idx) else {
                    set(NdarrayErr::OutOfBounds);
                    return <$ty>::default();
                };
                let Some(elements) = elements_of(state) else {
                    set(NdarrayErr::Inval);
                    return <$ty>::default();
                };
                let Some(element) = elements.get(flat) else {
                    set(NdarrayErr::OutOfBounds);
                    return <$ty>::default();
                };
                #[allow(clippy::redundant_closure_call)]
                match ($convert)(element) {
                    Some(v) => {
                        set(NdarrayErr::Ok);
                        v
                    }
                    None => {
                        set(NdarrayErr::Conversion);
                        <$ty>::default()
                    }
                }
            })
        }
    };
}

/// Convert an element to an integer type, or `None`.
macro_rules! to_int {
    ($ty:ty) => {
        |element: &Element| -> Option<$ty> {
            let wide: i128 = match element {
                Element::Int(v) => i128::from(*v),
                Element::Uint(v) => i128::from(*v),
                Element::Bool(v) => i128::from(*v),
                Element::Float(v) if v.fract() == 0.0 => *v as i128,
                _ => return None,
            };
            <$ty>::try_from(wide).ok()
        }
    };
}

read_at!(asdf_ndarray_read_int8_at, i8, to_int!(i8));
read_at!(asdf_ndarray_read_int16_at, i16, to_int!(i16));
read_at!(asdf_ndarray_read_int32_at, i32, to_int!(i32));
read_at!(asdf_ndarray_read_int64_at, i64, to_int!(i64));
read_at!(asdf_ndarray_read_uint8_at, u8, to_int!(u8));
read_at!(asdf_ndarray_read_uint16_at, u16, to_int!(u16));
read_at!(asdf_ndarray_read_uint32_at, u32, to_int!(u32));
read_at!(asdf_ndarray_read_uint64_at, u64, to_int!(u64));

read_at!(asdf_ndarray_read_float32_at, f32, |element: &Element| {
    match element {
        Element::Float(v) => Some(*v as f32),
        Element::Int(v) => Some(*v as f32),
        Element::Uint(v) => Some(*v as f32),
        _ => None,
    }
});
read_at!(asdf_ndarray_read_float64_at, f64, |element: &Element| {
    match element {
        Element::Float(v) => Some(*v),
        Element::Int(v) => Some(*v as f64),
        Element::Uint(v) => Some(*v as f64),
        _ => None,
    }
});

/// Read one `float16` element, returning its raw bit pattern.
///
/// Called only by `shim.c`, which reinterprets the bits as `_Float16`. The
/// conversion has to happen on the C side: `_Float16` and `uint16_t` do not
/// share a return ABI -- on x86-64 SysV one returns in `xmm0`, the other in
/// `rax` -- so returning bits from Rust and reinterpreting in C is the only
/// way to place the value correctly without unstable Rust.
///
/// # Safety
/// See the other `read_*_at` accessors.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn asdf_shim_ndarray_read_float16_bits_at(
    ndarray: *mut c_void,
    indices: *const u64,
    err: *mut c_int,
) -> u16 {
    guard("asdf_shim_ndarray_read_float16_bits_at", 0u16, || {
        let value =
            unsafe { asdf_ndarray_read_float64_at(ndarray.cast::<asdf_ndarray_t>(), indices, err) };
        half::f16::from_f64(value).to_bits()
    })
}

/// Free an ndarray handle and everything it owns.
///
/// # Safety
/// `ndarray` must be null or have come from the library, and must not be used
/// afterwards.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn asdf_ndarray_destroy(ndarray: *mut asdf_ndarray_t) {
    guard("asdf_ndarray_destroy", (), || ndarray_destroy(ndarray))
}

/// Safe internal form of [`asdf_ndarray_destroy`].
///
/// The exported entry point is `unsafe extern "C"`, so calling it from
/// inside the crate would need an `unsafe` block at every site to assert a
/// contract the crate itself is upholding. Callers use this instead.
pub(crate) fn ndarray_destroy(ndarray: *mut asdf_ndarray_t) {
    if ndarray.is_null() {
        return;
    }
    let boxed = unsafe { Box::from_raw(ndarray) };
    if !boxed._reserved.is_null() {
        drop(unsafe { Box::from_raw(boxed._reserved.cast::<NdarrayState>()) });
    }
}

/// Attach data read from a file to an array handle.
pub(crate) fn set_data(array: *mut asdf_ndarray_t, data: &[u8]) {
    if let Some(state) = state_of(array) {
        state.data = Some(AlignedBuf::from_slice(data));
    }
}

/// Build an ndarray handle for a value, reading its block data.
fn ndarray_from_value(value: *mut crate::file_ffi::AsdfValue) -> *mut asdf_ndarray_t {
    use crate::file_ffi::{file_reader, value_document, value_file, value_node};

    let (Some(doc), Some(node)) = (value_document(value), value_node(value)) else {
        return std::ptr::null_mut();
    };
    let Ok(parsed) = Ndarray::parse(doc, node) else {
        return std::ptr::null_mut();
    };

    // Read the block up front, as libasdf does, so the array's data pointer
    // is usable for as long as the handle is.
    let mut data: Option<Vec<u8>> = None;
    let mut block_len = None;
    let mut block_index = None;
    if let Some(file) = value_file(value)
        && let Some(reader) = file_reader(file)
    {
        let index = match parsed.source {
            Source::Block(index) => Some(index),
            Source::LastBlock => reader.block_count().checked_sub(1),
            // An external `source` names another file. `asdf_core` resolves
            // those, but upstream libasdf does not -- it logs a warning and
            // hands back nothing -- so the C surface does not either. The
            // idiomatic API is where exploded form is available.
            _ => None,
        };
        block_index = index;
        if let Some(index) = index
            && let Ok(bytes) = reader.block_data(index)
        {
            block_len = Some(bytes.len() as u64);
            data = Some(bytes.into_owned());
        }
    }

    let Ok(shape) = parsed.resolved_shape(block_len) else {
        return std::ptr::null_mut();
    };

    // An inline array's elements are already in the tree. `asdf_ndarray_data`
    // still hands out bytes, so they are encoded into the array's own scalar
    // type in this machine's order -- there is no stored layout to preserve.
    if data.is_none() && matches!(parsed.source, Source::Inline(_)) {
        data = encode_inline(doc, &parsed, &shape);
    }

    let array = make_ndarray(parsed, shape);
    if let Some(bytes) = &data {
        set_data(array, bytes);
    }
    // Remember where the data came from so `asdf_ndarray_block` can hand
    // back a view of the underlying block.
    if let Some(state) = state_of(array) {
        state.file = value_file(value).unwrap_or(std::ptr::null_mut());
        state.block_index = block_index;
    }
    array
}

/// Encode an inline array's elements as bytes of its own scalar type.
///
/// Returns `None` for a compound datatype, whose record layout is not a
/// simple sequence of scalars; such an array is still described correctly,
/// it just has no flat buffer to hand out.
fn encode_inline(
    doc: &asdf_core::yaml::Document,
    parsed: &Ndarray,
    shape: &[u64],
) -> Option<Vec<u8>> {
    let scalar = parsed.datatype.scalar;
    if !parsed.datatype.fields.is_empty() {
        return None;
    }
    let width = usize::try_from(scalar.size()).ok()?;
    if width == 0 {
        return None;
    }

    let elements = asdf_core::core::decode_inline(doc, parsed, shape).ok()?;
    let mut out = vec![0u8; elements.len() * width];
    for (index, element) in elements.iter().enumerate() {
        let slot = &mut out[index * width..(index + 1) * width];
        if write_converted(element, scalar, slot) != NdarrayErr::Ok {
            return None;
        }
    }
    Some(out)
}

/// Read the array at `path`.
///
/// # Safety
/// `file` must be a valid file handle, `path` a valid NUL-terminated string
/// or null, and `out` writable. The result must be released with
/// [`asdf_ndarray_destroy`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn asdf_get_ndarray(
    file: *mut crate::file_ffi::AsdfFile,
    path: *const c_char,
    out: *mut *mut asdf_ndarray_t,
) -> crate::types::AsdfValueErr {
    use crate::types::AsdfValueErr;

    guard("asdf_get_ndarray", AsdfValueErr::Unknown, || {
        let value = unsafe { crate::file_ffi::asdf_get_value(file, path) };
        if value.is_null() {
            return AsdfValueErr::NotFound;
        }
        let array = ndarray_from_value(value);
        unsafe { crate::file_ffi::asdf_value_destroy(value) };

        if array.is_null() {
            return AsdfValueErr::TypeMismatch;
        }
        if !out.is_null() {
            unsafe { write_out(out, array) };
        } else {
            ndarray_destroy(array);
        }
        AsdfValueErr::Ok
    })
}

/// Interpret a value as an array.
///
/// # Safety
/// `value` must be a valid value handle and `out` writable. The result must
/// be released with [`asdf_ndarray_destroy`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn asdf_value_as_ndarray(
    value: *mut crate::file_ffi::AsdfValue,
    out: *mut *mut asdf_ndarray_t,
) -> crate::types::AsdfValueErr {
    use crate::types::AsdfValueErr;

    guard("asdf_value_as_ndarray", AsdfValueErr::Unknown, || {
        let array = ndarray_from_value(value);
        if array.is_null() {
            return AsdfValueErr::TypeMismatch;
        }
        if !out.is_null() {
            unsafe { write_out(out, array) };
        } else {
            ndarray_destroy(array);
        }
        AsdfValueErr::Ok
    })
}

/// Whether the value at `path` is an ndarray.
///
/// # Safety
/// `file` must be a valid file handle and `path` a valid string or null.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn asdf_is_ndarray(
    file: *mut crate::file_ffi::AsdfFile,
    path: *const c_char,
) -> bool {
    guard("asdf_is_ndarray", false, || {
        let value = unsafe { crate::file_ffi::asdf_get_value(file, path) };
        if value.is_null() {
            return false;
        }
        let is_array = value_is_ndarray(value);
        unsafe { crate::file_ffi::asdf_value_destroy(value) };
        is_array
    })
}

/// Whether a value is an ndarray, by its tag.
///
/// # Safety
/// `value` must be null or a valid value handle.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn asdf_value_is_ndarray(value: *mut crate::file_ffi::AsdfValue) -> bool {
    guard("asdf_value_is_ndarray", false, || value_is_ndarray(value))
}

/// Safe internal form of [`asdf_value_is_ndarray`].
///
/// The exported entry point is `unsafe extern "C"`, so calling it from
/// inside the crate would need an `unsafe` block at every site to assert a
/// contract the crate itself is upholding. Callers use this instead.
pub(crate) fn value_is_ndarray(value: *mut crate::file_ffi::AsdfValue) -> bool {
    use crate::file_ffi::{value_document, value_node};
    let (Some(doc), Some(node)) = (value_document(value), value_node(value)) else {
        return false;
    };
    doc.tag_of(node).is_some_and(|t| t.split_version().0 == "core/ndarray")
}

// ---- The rest of the generated extension family ----------------------

/// Free an ndarray's fields without freeing the struct.
///
/// # Safety
/// `ndarray` must be null or a valid `asdf_ndarray_t`; safe on a zeroed one.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn asdf_ndarray_deinit(ndarray: *mut asdf_ndarray_t) {
    guard("asdf_ndarray_deinit", (), || ndarray_deinit(ndarray))
}

/// Safe internal form of [`asdf_ndarray_deinit`].
///
/// The exported entry point is `unsafe extern "C"`, so calling it from
/// inside the crate would need an `unsafe` block at every site to assert a
/// contract the crate itself is upholding. Callers use this instead.
pub(crate) fn ndarray_deinit(ndarray: *mut asdf_ndarray_t) {
    if ndarray.is_null() {
        return;
    }
    let array = unsafe { &mut *ndarray };
    if !array._reserved.is_null() {
        let state = unsafe { Box::from_raw(array._reserved.cast::<NdarrayState>()) };
        if !state.block.is_null() {
            unsafe { crate::block_ffi::asdf_block_close(state.block) };
        }
        drop(state);
        array._reserved = std::ptr::null_mut();
    }
    // The public pointers all borrowed from the state that just went.
    array.shape = std::ptr::null();
    array.strides = std::ptr::null();
    array.datatype.fields = std::ptr::null();
    array.datatype.nfields = 0;
    array.ndim = 0;
}

/// Deep-copy an ndarray into caller-provided storage.
///
/// The copy owns its own data, so it may outlive the original and be written
/// to a different file.
///
/// # Safety
/// `src` and `dst` must be valid `asdf_ndarray_t` values.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn asdf_ndarray_copy_into(
    file: *mut crate::file_ffi::AsdfFile,
    src: *const asdf_ndarray_t,
    dst: *mut asdf_ndarray_t,
) -> bool {
    guard("asdf_ndarray_copy_into", false, || ndarray_copy_into(file, src, dst))
}

/// Safe internal form of [`asdf_ndarray_copy_into`].
///
/// The exported entry point is `unsafe extern "C"`, so calling it from
/// inside the crate would need an `unsafe` block at every site to assert a
/// contract the crate itself is upholding. Callers use this instead.
pub(crate) fn ndarray_copy_into(
    file: *mut crate::file_ffi::AsdfFile,
    src: *const asdf_ndarray_t,
    dst: *mut asdf_ndarray_t,
) -> bool {
    let _ = file;
    if src.is_null() || dst.is_null() {
        return false;
    }
    let Some(state) = state_of(src.cast_mut()) else {
        return false;
    };

    // Rebuild from the engine's own view, so every buffer is fresh.
    let rebuilt = make_ndarray(state.parsed.clone(), state.shape.clone());
    if rebuilt.is_null() {
        return false;
    }
    if let Some(data) = state.allocated.as_ref().or(state.data.as_ref()) {
        set_data(rebuilt, data);
    }
    if let Some(fresh) = state_of(rebuilt) {
        fresh.compression = state.compression;
        fresh.storage = state.storage;
    }

    // Move the rebuilt value into the caller's storage.
    let boxed = unsafe { Box::from_raw(rebuilt) };
    unsafe { std::ptr::write(dst, *boxed) };
    true
}

/// Deep-copy an ndarray into fresh storage.
///
/// # Safety
/// `src` must be a valid `asdf_ndarray_t`. The result must be released with
/// [`asdf_ndarray_destroy`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn asdf_ndarray_copy(
    file: *mut crate::file_ffi::AsdfFile,
    src: *const asdf_ndarray_t,
) -> *mut asdf_ndarray_t {
    guard("asdf_ndarray_copy", std::ptr::null_mut(), || ndarray_copy(file, src))
}

/// Safe internal form of [`asdf_ndarray_copy`].
///
/// The exported entry point is `unsafe extern "C"`, so calling it from
/// inside the crate would need an `unsafe` block at every site to assert a
/// contract the crate itself is upholding. Callers use this instead.
pub(crate) fn ndarray_copy(
    file: *mut crate::file_ffi::AsdfFile,
    src: *const asdf_ndarray_t,
) -> *mut asdf_ndarray_t {
    if src.is_null() {
        return std::ptr::null_mut();
    }
    let raw = Box::into_raw(Box::new(asdf_ndarray_t {
        source: 0,
        ndim: 0,
        shape: std::ptr::null(),
        datatype: asdf_datatype_t {
            type_: 0,
            size: 0,
            name: std::ptr::null(),
            byteorder: 0,
            ndim: 0,
            shape: std::ptr::null(),
            nfields: 0,
            fields: std::ptr::null(),
        },
        byteorder: 0,
        offset: 0,
        strides: std::ptr::null(),
        _reserved: std::ptr::null_mut(),
    }));
    if ndarray_copy_into(file, src, raw) {
        raw
    } else {
        drop(unsafe { Box::from_raw(raw) });
        std::ptr::null_mut()
    }
}

/// Deep-copy a null-terminated array of ndarrays.
///
/// # Safety
/// `src` must be a null-terminated array of valid `asdf_ndarray_t` pointers.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn asdf_ndarray_array_copy(
    file: *mut crate::file_ffi::AsdfFile,
    src: *mut *const asdf_ndarray_t,
) -> *mut *mut asdf_ndarray_t {
    guard("asdf_ndarray_array_copy", std::ptr::null_mut(), || {
        if src.is_null() {
            return std::ptr::null_mut();
        }
        let mut count = 0isize;
        while !unsafe { *src.offset(count) }.is_null() {
            count += 1;
        }

        let mut copies: Vec<*mut asdf_ndarray_t> = Vec::with_capacity(count as usize + 1);
        for index in 0..count {
            // Reading the caller's NULL-terminated list is the unsafe part.
            let entry = unsafe { *src.offset(index) };
            let copy = ndarray_copy(file, entry);
            if copy.is_null() {
                // Unwind rather than leak the copies already made.
                for made in copies {
                    ndarray_destroy(made);
                }
                return std::ptr::null_mut();
            }
            copies.push(copy);
        }
        copies.push(std::ptr::null_mut());
        Box::into_raw(copies.into_boxed_slice()).cast::<*mut asdf_ndarray_t>()
    })
}

/// Build a value for an ndarray, writing its data into a new block.
///
/// The array's `source` in the tree is the index of the block appended to
/// `file`, so the value is only meaningful once written with that file.
///
/// # Safety
/// `file` must be a file handle open for writing and `obj` a valid
/// `asdf_ndarray_t`. The result must be released with `asdf_value_destroy`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn asdf_value_of_ndarray(
    file: *mut crate::file_ffi::AsdfFile,
    obj: *const asdf_ndarray_t,
) -> *mut crate::file_ffi::AsdfValue {
    use asdf_core::yaml::{CollectionStyle, NodeData, Tag};

    guard("asdf_value_of_ndarray", std::ptr::null_mut(), || {
        if file.is_null() || obj.is_null() {
            return std::ptr::null_mut();
        }
        let array = unsafe { &*obj };

        // The shape and datatype come from the public fields, so an array
        // built as a C stack literal works -- which is what libasdf's own
        // write example does.
        let shape: Vec<u64> = if array.shape.is_null() || array.ndim == 0 {
            Vec::new()
        } else {
            unsafe { std::slice::from_raw_parts(array.shape, array.ndim as usize) }.to_vec()
        };
        let scalar = scalar_from_abi(array.datatype.type_);
        let item_size = if array.datatype.size != 0 { array.datatype.size } else { scalar.size() };
        if item_size == 0 {
            return std::ptr::null_mut();
        }

        // The data is whatever the caller allocated or we read.
        let element_count: u64 = shape.iter().product::<u64>().max(1);
        let expected = (element_count * item_size) as usize;
        let payload: Vec<u8> = match ensure_state(obj.cast_mut()) {
            Some(state) => state
                .allocated
                .as_ref()
                .or(state.data.as_ref())
                .map(|b| b.as_slice().to_vec())
                .unwrap_or_else(|| vec![0u8; expected]),
            None => vec![0u8; expected],
        };
        let (compression, array_storage) = state_of(obj.cast_mut())
            .map(|s| (s.compression, s.storage))
            .unwrap_or((Compression::None, AsdfArrayStorage::Default));

        // The file's own `emitter.array_storage` decides for every array it
        // holds; each array's setting applies only where the file has none.
        let config = crate::file_ffi::file_config(file).unwrap_or_default();
        let storage = if config.array_storage == AsdfArrayStorage::Default {
            array_storage
        } else {
            config.array_storage
        };

        // Inline storage writes the values into the tree instead of a block,
        // which is what `asdf_ndarray_storage_set(.., INLINE)` asks for.
        if storage == AsdfArrayStorage::Inline {
            let count: u64 = shape.iter().product::<u64>().max(1);
            warn_if_inline_is_large(file, count, config.inline_ndarray_warning_thresh);
            return inline_value_of_ndarray(file, array, &shape, &payload);
        }

        // Append the block, then reference it by index.
        let Some(blocks) = crate::file_ffi::file_blocks_mut(file) else {
            return std::ptr::null_mut();
        };
        blocks.push(asdf_core::PendingBlock::compressed(payload, compression));
        let index = blocks.len() - 1;

        let Some(doc) = file_document_mut(file) else {
            return std::ptr::null_mut();
        };

        let source = doc.add_scalar(index.to_string());
        let datatype = doc.add_scalar(scalar.name());
        let order = match array.byteorder {
            62 => "big",
            60 => "little",
            // An unspecified order means this machine's.
            _ => ByteOrderNative,
        };
        let byteorder = doc.add_scalar(order);

        let dims: Vec<_> = shape.iter().map(|d| doc.add_scalar(d.to_string())).collect();
        let shape_node = doc.add_sequence(dims);
        if let NodeData::Sequence { style, .. } = &mut doc.node_mut(shape_node).data {
            *style = CollectionStyle::Flow;
        }

        let keys: Vec<_> = ["source", "datatype", "byteorder", "shape"]
            .iter()
            .map(|k| doc.add_scalar(*k))
            .collect();
        let mut pairs = vec![
            (keys[0], source),
            (keys[1], datatype),
            (keys[2], byteorder),
            (keys[3], shape_node),
        ];

        // `offset` and `strides` say where the elements sit inside the
        // block, so an array that has them is unreadable without them. Both
        // are omitted at their defaults, as every other writer omits them.
        if array.offset != 0 {
            let key = doc.add_scalar("offset");
            let value = doc.add_scalar(array.offset.to_string());
            pairs.push((key, value));
        }
        if !array.strides.is_null() && array.ndim > 0 {
            let strides = unsafe { std::slice::from_raw_parts(array.strides, array.ndim as usize) };
            let items: Vec<_> = strides.iter().map(|s| doc.add_scalar(s.to_string())).collect();
            let node = doc.add_sequence(items);
            if let NodeData::Sequence { style, .. } = &mut doc.node_mut(node).data {
                *style = CollectionStyle::Flow;
            }
            let key = doc.add_scalar("strides");
            pairs.push((key, node));
        }

        let node = doc.add_mapping(pairs);
        doc.node_mut(node).tag = Some(Tag::parse("tag:stsci.edu:asdf/core/ndarray-1.1.0"));

        Box::into_raw(Box::new(crate::file_ffi::AsdfValue::new(file, node)))
    })
}

/// Warn when an inline array is larger than the file's threshold.
///
/// Inline data is text, so a large array bloats the tree and slows every
/// reader that parses it. A threshold of zero means the caller set none.
fn warn_if_inline_is_large(file: *mut crate::file_ffi::AsdfFile, elements: u64, threshold: usize) {
    if threshold == 0 || elements <= threshold as u64 {
        return;
    }
    crate::error_ffi::log_to_file(
        file,
        crate::error_ffi::LogLevel::Warn,
        &format!(
            "inline ndarray has {elements} elements, exceeding the threshold of {threshold}; \
             consider using binary block storage instead"
        ),
    );
}

/// Build the tree value for an array whose data goes inline.
///
/// The elements are decoded from the caller's buffer and nested to the
/// array's shape, so the file carries `data: [[..], ..]` and no block at
/// all. `byteorder` is left out: it describes bytes in a block, and there
/// are none.
fn inline_value_of_ndarray(
    file: *mut crate::file_ffi::AsdfFile,
    array: &asdf_ndarray_t,
    shape: &[u64],
    payload: &[u8],
) -> *mut crate::file_ffi::AsdfValue {
    use asdf_core::core::datatype::Datatype;
    use asdf_core::core::ndarray::Ndarray;
    use asdf_core::yaml::{CollectionStyle, NodeData, Tag};

    let scalar = scalar_from_abi(array.datatype.type_);
    let mut datatype = Datatype::scalar(scalar);
    if array.datatype.size != 0 {
        datatype.size = array.datatype.size;
    }
    let parsed = Ndarray {
        source: Source::Block(0),
        shape: shape.iter().map(|d| Some(*d)).collect(),
        datatype,
        byteorder: match array.byteorder {
            62 => asdf_core::core::datatype::ByteOrder::Big,
            60 => asdf_core::core::datatype::ByteOrder::Little,
            _ => asdf_core::core::datatype::ByteOrder::native(),
        },
        offset: array.offset,
        strides: None,
        mask: None,
    };

    // A zero-dimensional array holds nothing -- `asdf_ndarray_size` says so
    // and `asdf_ndarray_data_alloc` allocates nothing -- so there is no data
    // to decode, and `data: []` is what goes in the tree.
    let elements = if shape.is_empty() {
        Vec::new()
    } else {
        match asdf_core::core::decode_all(&parsed, shape, payload) {
            Ok(elements) => elements,
            Err(_) => return std::ptr::null_mut(),
        }
    };

    let Some(doc) = file_document_mut(file) else {
        return std::ptr::null_mut();
    };

    let data = if elements.is_empty() {
        let node = doc.add_sequence(Vec::new());
        if let NodeData::Sequence { style, .. } = &mut doc.node_mut(node).data {
            *style = CollectionStyle::Flow;
        }
        node
    } else {
        asdf_core::core::elements::nest(doc, &elements, shape)
    };
    let datatype_node = doc.add_scalar(scalar.name());

    let dims: Vec<_> = shape.iter().map(|d| doc.add_scalar(d.to_string())).collect();
    let shape_node = doc.add_sequence(dims);
    if let NodeData::Sequence { style, .. } = &mut doc.node_mut(shape_node).data {
        *style = CollectionStyle::Flow;
    }

    let keys: Vec<_> = ["datatype", "data", "shape"].iter().map(|k| doc.add_scalar(*k)).collect();
    let node =
        doc.add_mapping(vec![(keys[0], datatype_node), (keys[1], data), (keys[2], shape_node)]);
    doc.node_mut(node).tag = Some(Tag::parse("tag:stsci.edu:asdf/core/ndarray-1.1.0"));

    Box::into_raw(Box::new(crate::file_ffi::AsdfValue::new(file, node)))
}

/// This machine's byte order, as the schema spells it.
#[allow(non_upper_case_globals)]
const ByteOrderNative: &str = if cfg!(target_endian = "big") { "big" } else { "little" };

/// Write an ndarray at `path`, appending its data as a new block.
///
/// # Safety
/// See [`asdf_value_of_ndarray`]; `path` must be a valid string or null.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn asdf_set_ndarray(
    file: *mut crate::file_ffi::AsdfFile,
    path: *const c_char,
    obj: *const asdf_ndarray_t,
) -> crate::types::AsdfValueErr {
    use crate::types::AsdfValueErr;

    guard("asdf_set_ndarray", AsdfValueErr::Unknown, || {
        let value = unsafe { asdf_value_of_ndarray(file, obj) };
        if value.is_null() {
            return AsdfValueErr::EmitFailure;
        }
        let result = unsafe { crate::file_ffi::set_value_at(file, path, value) };
        unsafe { crate::file_ffi::asdf_value_destroy(value) };
        result
    })
}

// ---- Blocks and tiles ------------------------------------------------

/// The block underlying an array, or null when its data is inline.
///
/// The view is opened on first use and owned by the array, so it must not be
/// closed by the caller; it is released with the array.
///
/// # Safety
/// `ndarray` must be null or a valid `asdf_ndarray_t`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn asdf_ndarray_block(
    ndarray: *mut asdf_ndarray_t,
) -> *mut crate::block_ffi::AsdfBlock {
    guard("asdf_ndarray_block", std::ptr::null_mut(), || {
        let Some(state) = state_of(ndarray) else {
            return std::ptr::null_mut();
        };
        if !state.block.is_null() {
            return state.block;
        }
        let (Some(index), false) = (state.block_index, state.file.is_null()) else {
            return std::ptr::null_mut();
        };
        state.block = unsafe { crate::block_ffi::asdf_block_open(state.file, index) };
        state.block
    })
}

/// Copy `count` elements starting at `flat` into `dst`, converting to `target`.
fn write_elements(
    elements: &[Element],
    flat: usize,
    count: usize,
    target: ScalarType,
    width: usize,
    dst: &mut [u8],
) -> NdarrayErr {
    let mut overflowed = false;
    for step in 0..count {
        let Some(element) = elements.get(flat + step) else {
            return NdarrayErr::OutOfBounds;
        };
        let slot = &mut dst[step * width..(step + 1) * width];
        match write_converted(element, target, slot) {
            NdarrayErr::Ok => {}
            // Saturating is reported but does not stop the copy; see
            // `write_converted`.
            NdarrayErr::Overflow => overflowed = true,
            err => return err,
        }
    }
    if overflowed { NdarrayErr::Overflow } else { NdarrayErr::Ok }
}

/// Hand a buffer back through `dst`, allocating with `malloc` if asked.
///
/// libasdf lets the caller either supply storage or take a fresh allocation
/// by pointing `dst` at a null pointer, in which case the caller frees it
/// with `free` -- so `malloc` rather than Rust's allocator.
fn deliver(buffer: &[u8], dst: *mut *mut c_void) -> NdarrayErr {
    if dst.is_null() {
        return NdarrayErr::Inval;
    }
    let existing = unsafe { *dst };
    if existing.is_null() {
        // A null destination means "allocate one for me, I will `free` it",
        // so this must come from `malloc` and not Rust's allocator.
        let Some(allocation) = CMallocBuf::copy_from(buffer) else {
            return NdarrayErr::Oom;
        };
        unsafe { write_out(dst, allocation.into_raw()) };
    } else {
        unsafe {
            std::ptr::copy_nonoverlapping(buffer.as_ptr(), existing.cast::<u8>(), buffer.len());
        }
    }
    NdarrayErr::Ok
}

/// Read one element, converting to `dst_t`.
///
/// # Safety
/// `ndarray` must be a valid `asdf_ndarray_t`; `indices` must point to `ndim`
/// values; `dst` must have room for one value of `dst_t`. `dst` need not be
/// aligned.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn asdf_ndarray_read_at(
    ndarray: *mut asdf_ndarray_t,
    indices: *const u64,
    dst_t: ScalarTypeAbi,
    dst: *mut c_void,
) -> NdarrayErr {
    guard("asdf_ndarray_read_at", NdarrayErr::Inval, || {
        let Some(state) = state_of(ndarray) else {
            return NdarrayErr::Inval;
        };
        if indices.is_null() || dst.is_null() {
            return NdarrayErr::Inval;
        }
        let idx = unsafe { std::slice::from_raw_parts(indices, state.shape.len()) };
        let Some(flat) = flat_index(&state.shape, idx) else {
            return NdarrayErr::OutOfBounds;
        };
        let Some(elements) = elements_of(state) else {
            return NdarrayErr::Inval;
        };
        let Some(element) = elements.get(flat) else {
            return NdarrayErr::OutOfBounds;
        };

        let target = match scalar_from_abi(dst_t) {
            ScalarType::Unknown => state.parsed.datatype.scalar,
            other => other,
        };
        let Ok(width) = usize::try_from(target.size()) else {
            return NdarrayErr::Inval;
        };
        if width == 0 {
            return NdarrayErr::Conversion;
        }
        // Written into a local first because `dst` carries no alignment
        // guarantee, then copied out byte by byte.
        let mut scratch = vec![0u8; width];
        let err = write_converted(element, target, &mut scratch);
        if err != NdarrayErr::Ok {
            return err;
        }
        unsafe { std::ptr::copy_nonoverlapping(scratch.as_ptr(), dst.cast::<u8>(), width) };
        NdarrayErr::Ok
    })
}

/// Read an N-dimensional tile, converting to `dst_t`.
///
/// # Safety
/// `origin` and `shape` must each point to `ndim` values; `dst` must be
/// writable, pointing either at storage large enough for the tile or at a
/// null pointer, in which case a buffer is allocated for the caller to
/// `free`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn asdf_ndarray_read_tile_ndim(
    ndarray: *mut asdf_ndarray_t,
    origin: *const u64,
    shape: *const u64,
    dst_t: ScalarTypeAbi,
    dst: *mut *mut c_void,
) -> NdarrayErr {
    guard("asdf_ndarray_read_tile_ndim", NdarrayErr::Inval, || {
        ndarray_read_tile_ndim(ndarray, origin, shape, dst_t, dst)
    })
}

/// Safe internal form of [`asdf_ndarray_read_tile_ndim`].
///
/// The exported entry point is `unsafe extern "C"`, so calling it from
/// inside the crate would need an `unsafe` block at every site to assert a
/// contract the crate itself is upholding. Callers use this instead.
pub(crate) fn ndarray_read_tile_ndim(
    ndarray: *mut asdf_ndarray_t,
    origin: *const u64,
    shape: *const u64,
    dst_t: ScalarTypeAbi,
    dst: *mut *mut c_void,
) -> NdarrayErr {
    let Some(state) = state_of(ndarray) else {
        return NdarrayErr::Inval;
    };
    if origin.is_null() || shape.is_null() {
        return NdarrayErr::Inval;
    }
    let ndim = state.shape.len();
    if ndim == 0 {
        return NdarrayErr::Inval;
    }
    let origin = unsafe { std::slice::from_raw_parts(origin, ndim) }.to_vec();
    let tile = unsafe { std::slice::from_raw_parts(shape, ndim) }.to_vec();

    // Every corner of the tile has to land inside the array.
    for axis in 0..ndim {
        let Some(end) = origin[axis].checked_add(tile[axis]) else {
            return NdarrayErr::OutOfBounds;
        };
        if end > state.shape[axis] {
            return NdarrayErr::OutOfBounds;
        }
    }

    let target = match scalar_from_abi(dst_t) {
        ScalarType::Unknown => state.parsed.datatype.scalar,
        other => other,
    };
    let Ok(width) = usize::try_from(target.size()) else {
        return NdarrayErr::Inval;
    };
    if width == 0 {
        return NdarrayErr::Conversion;
    }

    let mut count: u64 = 1;
    for extent in &tile {
        let Some(next) = count.checked_mul(*extent) else {
            return NdarrayErr::Inval;
        };
        count = next;
    }
    let Ok(count) = usize::try_from(count) else {
        return NdarrayErr::Inval;
    };
    if count == 0 {
        return deliver(&[], dst);
    }

    let Some(elements) = elements_of(state) else {
        return NdarrayErr::Inval;
    };

    // The tile is contiguous along the last axis only, so copy it one
    // run at a time and step the outer indices by hand.
    let run = tile[ndim - 1] as usize;
    let mut buffer = vec![0u8; count * width];
    let mut cursor = origin.clone();
    let mut written = 0usize;
    let mut overflowed = false;
    loop {
        let Some(flat) = flat_index(&state.shape, &cursor) else {
            return NdarrayErr::OutOfBounds;
        };
        let slice = &mut buffer[written * width..(written + run) * width];
        match write_elements(&elements, flat, run, target, width, slice) {
            NdarrayErr::Ok => {}
            NdarrayErr::Overflow => overflowed = true,
            err => return err,
        }
        written += run;

        // Advance the outer axes odometer-style; the last is the run.
        let mut axis = ndim as isize - 2;
        loop {
            if axis < 0 {
                let delivered = deliver(&buffer, dst);
                if delivered != NdarrayErr::Ok {
                    return delivered;
                }
                return if overflowed { NdarrayErr::Overflow } else { NdarrayErr::Ok };
            }
            let a = axis as usize;
            cursor[a] += 1;
            if cursor[a] < origin[a] + tile[a] {
                break;
            }
            cursor[a] = origin[a];
            axis -= 1;
        }
    }
}

/// Read a 2-D tile, converting to `dst_t`.
///
/// For an array of more than two dimensions, `plane_origin` gives the
/// `ndim - 2` outer coordinates; null selects the first plane. `x`/`width`
/// index the last axis and `y`/`height` the one before it.
///
/// # Safety
/// See [`asdf_ndarray_read_tile_ndim`]; `plane_origin`, when not null, must
/// point to `ndim - 2` values.
#[unsafe(no_mangle)]
#[allow(clippy::too_many_arguments)]
pub unsafe extern "C" fn asdf_ndarray_read_tile_2d(
    ndarray: *mut asdf_ndarray_t,
    x: u64,
    y: u64,
    width: u64,
    height: u64,
    plane_origin: *const u64,
    dst_t: ScalarTypeAbi,
    dst: *mut *mut c_void,
) -> NdarrayErr {
    guard("asdf_ndarray_read_tile_2d", NdarrayErr::Inval, || {
        let Some(state) = state_of(ndarray) else {
            return NdarrayErr::Inval;
        };
        let ndim = state.shape.len();
        if ndim < 2 {
            return NdarrayErr::Inval;
        }
        let planes = ndim - 2;

        let mut origin = vec![0u64; ndim];
        let mut tile = vec![1u64; ndim];
        if planes > 0 && !plane_origin.is_null() {
            let outer = unsafe { std::slice::from_raw_parts(plane_origin, planes) };
            origin[..planes].copy_from_slice(outer);
        }
        origin[ndim - 2] = y;
        origin[ndim - 1] = x;
        tile[ndim - 2] = height;
        tile[ndim - 1] = width;

        ndarray_read_tile_ndim(ndarray, origin.as_ptr(), tile.as_ptr(), dst_t, dst)
    })
}

// ---- Registry entry --------------------------------------------------
//
// See the matching section in `core_ext.rs`: generic callers reach an
// extension only through `asdf_extension_get` and
// `asdf_value_as_extension_type`, so the typed functions above are not
// enough on their own. This family is written out rather than generated
// because the ndarray extension's functions are hand-written too.

/// Deserialize through the registry's generic entry point.
///
/// # Safety
/// `value` must be a valid value handle and `out` writable.
unsafe extern "C" fn ndarray_ext_deserialize(
    value: *mut crate::file_ffi::AsdfValue,
    _userdata: *const c_void,
    out: *mut *mut c_void,
) -> crate::types::AsdfValueErr {
    let mut typed: *mut asdf_ndarray_t = std::ptr::null_mut();
    let err = unsafe { asdf_value_as_ndarray(value, &mut typed) };
    if err == crate::types::AsdfValueErr::Ok && !out.is_null() {
        unsafe { write_out(out, typed.cast::<c_void>()) };
    }
    err
}

/// Serialize through the registry's generic entry point.
///
/// # Safety
/// `obj` must be a valid `asdf_ndarray_t`.
unsafe extern "C" fn ndarray_ext_serialize(
    file: *mut crate::file_ffi::AsdfFile,
    obj: *const c_void,
    _userdata: *const c_void,
) -> *mut crate::file_ffi::AsdfValue {
    unsafe { asdf_value_of_ndarray(file, obj.cast::<asdf_ndarray_t>()) }
}

/// Deep-copy through the registry's generic entry point.
///
/// # Safety
/// `src` and `dst` must be valid `asdf_ndarray_t` values.
unsafe extern "C" fn ndarray_ext_copy(
    file: *mut crate::file_ffi::AsdfFile,
    src: *const c_void,
    dst: *mut c_void,
) -> bool {
    unsafe {
        asdf_ndarray_copy_into(file, src.cast::<asdf_ndarray_t>(), dst.cast::<asdf_ndarray_t>())
    }
}

/// De-initialise through the registry's generic entry point.
///
/// # Safety
/// `obj` must be a valid `asdf_ndarray_t`.
unsafe extern "C" fn ndarray_ext_deinit(obj: *mut c_void) {
    ndarray_deinit(obj.cast::<asdf_ndarray_t>());
}

/// Build the ndarray extension's registry entry.
///
/// Upstream registers both `ndarray-1.1.0` and `ndarray-1.0.0`: the newer
/// schema adds `float16` and requires one of `source`/`data`, but the same
/// deserializer reads both.
pub(crate) fn build_ndarray_extension() -> *mut crate::extension_ffi::asdf_extension_t {
    use crate::extension_ffi::{
        asdf_extension_t, asdf_extension_vtab_t, asdf_software_t, libasdf_software,
    };

    let tags: Vec<*const c_char> = vec![
        c"tag:stsci.edu:asdf/core/ndarray-1.1.0".as_ptr(),
        c"tag:stsci.edu:asdf/core/ndarray-1.0.0".as_ptr(),
        std::ptr::null(),
    ];
    let tags = Box::leak(tags.into_boxed_slice());

    let vtab = Box::leak(Box::new(asdf_extension_vtab_t {
        serialize: Some(ndarray_ext_serialize),
        deserialize: Some(ndarray_ext_deserialize),
        copy: Some(ndarray_ext_copy),
        deinit: Some(ndarray_ext_deinit),
        _reserved: [None; 4],
    }));

    Box::leak(Box::new(asdf_extension_t {
        tags: tags.as_ptr(),
        software: (&raw const libasdf_software).cast::<asdf_software_t>().cast_mut(),
        vtab: std::ptr::from_ref(vtab),
        size: std::mem::size_of::<asdf_ndarray_t>(),
        userdata: std::ptr::null_mut(),
    }))
}

#[cfg(test)]
mod tests {
    use super::*;
    use asdf_core::core::datatype::ByteOrder;
    use asdf_core::core::ndarray::Ndarray as CoreNdarray;
    use asdf_core::yaml::parse_document;

    /// Build a handle over a little-endian int32 array of the given values.
    fn int32_array(values: &[i32]) -> *mut asdf_ndarray_t {
        let doc = parse_document(&format!(
            "a:\n  source: 0\n  shape: [{}]\n  datatype: int32\n  byteorder: little\n",
            values.len()
        ))
        .unwrap();
        let root = doc.root().unwrap();
        let parsed = CoreNdarray::parse(&doc, doc.mapping_get(root, "a").unwrap()).unwrap();

        let array = make_ndarray(parsed, vec![values.len() as u64]);
        let bytes: Vec<u8> = values.iter().flat_map(|v| v.to_le_bytes()).collect();
        set_data(array, &bytes);
        array
    }

    /// A 3x4 little-endian int32 array holding 0..12 in row-major order.
    fn int32_grid() -> *mut asdf_ndarray_t {
        let doc = parse_document(
            "a:\n  source: 0\n  shape: [3, 4]\n  datatype: int32\n  byteorder: little\n",
        )
        .unwrap();
        let root = doc.root().unwrap();
        let parsed = CoreNdarray::parse(&doc, doc.mapping_get(root, "a").unwrap()).unwrap();
        let array = make_ndarray(parsed, vec![3, 4]);
        let bytes: Vec<u8> = (0i32..12).flat_map(i32::to_le_bytes).collect();
        set_data(array, &bytes);
        array
    }

    /// A value outside the destination's range saturates and reports
    /// overflow, rather than wrapping or refusing the whole read.
    #[test]
    fn out_of_range_values_saturate_and_report_overflow() {
        let mut out = [0u8; 8];

        // A negative integer into an unsigned type clamps at zero.
        assert_eq!(
            write_converted(&Element::Int(-5), ScalarType::Uint8, &mut out[..1]),
            NdarrayErr::Overflow
        );
        assert_eq!(out[0], 0);

        // Too large for the destination clamps at its maximum.
        assert_eq!(
            write_converted(&Element::Int(70_000), ScalarType::Uint16, &mut out[..2]),
            NdarrayErr::Overflow
        );
        assert_eq!(u16::from_ne_bytes([out[0], out[1]]), u16::MAX);

        // And at its minimum going the other way.
        assert_eq!(
            write_converted(&Element::Int(-70_000), ScalarType::Int16, &mut out[..2]),
            NdarrayErr::Overflow
        );
        assert_eq!(i16::from_ne_bytes([out[0], out[1]]), i16::MIN);

        // A value that fits is not an overflow.
        assert_eq!(
            write_converted(&Element::Int(42), ScalarType::Uint8, &mut out[..1]),
            NdarrayErr::Ok
        );
        assert_eq!(out[0], 42);
    }

    /// Losing precision is not overflow; leaving the representable range is.
    #[test]
    fn only_leaving_the_range_counts_as_overflow() {
        let mut out = [0u8; 8];

        // `i32::MAX` rounds when it becomes an `f32`, which is ordinary.
        assert_eq!(
            write_converted(&Element::Int(i64::from(i32::MAX)), ScalarType::Float32, &mut out[..4]),
            NdarrayErr::Ok
        );

        // `f64::MAX` has no `f32`, so it becomes an infinity, which is not.
        assert_eq!(
            write_converted(&Element::Float(f64::MAX), ScalarType::Float32, &mut out[..4]),
            NdarrayErr::Overflow
        );
        assert!(f32::from_ne_bytes([out[0], out[1], out[2], out[3]]).is_infinite());

        // An infinity that was already infinite stays one, and is not an
        // overflow: nothing was lost.
        assert_eq!(
            write_converted(&Element::Float(f64::INFINITY), ScalarType::Float32, &mut out[..4]),
            NdarrayErr::Ok
        );
    }

    /// A float into an integer truncates toward zero, and the non-finites
    /// saturate.
    #[test]
    fn floats_convert_to_integers_the_way_a_c_cast_does() {
        let mut out = [0u8; 8];

        assert_eq!(
            write_converted(&Element::Float(3.9), ScalarType::Int32, &mut out[..4]),
            NdarrayErr::Ok
        );
        assert_eq!(i32::from_ne_bytes([out[0], out[1], out[2], out[3]]), 3);

        assert_eq!(
            write_converted(&Element::Float(-3.9), ScalarType::Int32, &mut out[..4]),
            NdarrayErr::Ok
        );
        assert_eq!(i32::from_ne_bytes([out[0], out[1], out[2], out[3]]), -3);

        assert_eq!(
            write_converted(&Element::Float(f64::INFINITY), ScalarType::Int32, &mut out[..4]),
            NdarrayErr::Overflow
        );
        assert_eq!(i32::from_ne_bytes([out[0], out[1], out[2], out[3]]), i32::MAX);

        assert_eq!(
            write_converted(&Element::Float(f64::NEG_INFINITY), ScalarType::Int32, &mut out[..4]),
            NdarrayErr::Overflow
        );
        assert_eq!(i32::from_ne_bytes([out[0], out[1], out[2], out[3]]), i32::MIN);

        // A NaN has no integer, so any answer will do -- but it must not be
        // reported as an overflow, which would be a claim about magnitude.
        assert_eq!(
            write_converted(&Element::Float(f64::NAN), ScalarType::Int32, &mut out[..4]),
            NdarrayErr::Ok
        );
    }

    /// The whole array still comes back when one element overflows.
    #[test]
    fn an_overflow_does_not_abandon_the_read() {
        let array = int32_array(&[1, -1, 300]);
        let mut dst: *mut c_void = std::ptr::null_mut();
        assert_eq!(
            unsafe { asdf_ndarray_read_all(array, ScalarType::Uint8 as ScalarTypeAbi, &mut dst) },
            NdarrayErr::Overflow
        );
        assert!(!dst.is_null(), "the converted buffer is still delivered");

        let got = unsafe { std::slice::from_raw_parts(dst.cast::<u8>(), 3) };
        assert_eq!(got, [1, 0, 255], "each element saturates on its own");

        unsafe { libc::free(dst) };
        unsafe { asdf_ndarray_destroy(array) };
    }

    #[test]
    fn reads_one_element_at_indices() {
        let array = int32_grid();
        let indices: [u64; 2] = [2, 1];
        let mut out: i32 = 0;
        assert_eq!(
            unsafe {
                asdf_ndarray_read_at(
                    array,
                    indices.as_ptr(),
                    ScalarType::Int32 as ScalarTypeAbi,
                    std::ptr::from_mut(&mut out).cast(),
                )
            },
            NdarrayErr::Ok
        );
        assert_eq!(out, 9, "row 2, column 1 of a 3x4 array holding 0..12");

        // Converting on the way out is allowed.
        let mut wide: f64 = 0.0;
        assert_eq!(
            unsafe {
                asdf_ndarray_read_at(
                    array,
                    indices.as_ptr(),
                    ScalarType::Float64 as ScalarTypeAbi,
                    std::ptr::from_mut(&mut wide).cast(),
                )
            },
            NdarrayErr::Ok
        );
        assert!((wide - 9.0).abs() < f64::EPSILON);

        let past_end: [u64; 2] = [3, 0];
        assert_eq!(
            unsafe {
                asdf_ndarray_read_at(
                    array,
                    past_end.as_ptr(),
                    ScalarType::Int32 as ScalarTypeAbi,
                    std::ptr::from_mut(&mut out).cast(),
                )
            },
            NdarrayErr::OutOfBounds
        );
        unsafe { asdf_ndarray_destroy(array) };
    }

    #[test]
    fn reads_a_2d_tile() {
        let array = int32_grid();
        // A 2x2 tile whose origin is (x=1, y=1): rows 1-2, columns 1-2.
        let mut buffer = [0i32; 4];
        let mut dst = buffer.as_mut_ptr().cast::<c_void>();
        assert_eq!(
            unsafe {
                asdf_ndarray_read_tile_2d(
                    array,
                    1,
                    1,
                    2,
                    2,
                    std::ptr::null(),
                    ScalarType::Int32 as ScalarTypeAbi,
                    &mut dst,
                )
            },
            NdarrayErr::Ok
        );
        assert_eq!(buffer, [5, 6, 9, 10]);
        unsafe { asdf_ndarray_destroy(array) };
    }

    #[test]
    fn a_tile_may_not_run_past_the_edge() {
        let array = int32_grid();
        let mut buffer = [0i32; 4];
        let mut dst = buffer.as_mut_ptr().cast::<c_void>();
        assert_eq!(
            unsafe {
                asdf_ndarray_read_tile_2d(
                    array,
                    3,
                    1,
                    2,
                    2,
                    std::ptr::null(),
                    ScalarType::Int32 as ScalarTypeAbi,
                    &mut dst,
                )
            },
            NdarrayErr::OutOfBounds
        );
        unsafe { asdf_ndarray_destroy(array) };
    }

    #[test]
    fn an_ndim_tile_can_allocate_its_own_buffer() {
        let array = int32_grid();
        let origin: [u64; 2] = [0, 2];
        let shape: [u64; 2] = [3, 2];
        // A null destination asks the library to allocate.
        let mut dst: *mut c_void = std::ptr::null_mut();
        assert_eq!(
            unsafe {
                asdf_ndarray_read_tile_ndim(
                    array,
                    origin.as_ptr(),
                    shape.as_ptr(),
                    ScalarType::Int32 as ScalarTypeAbi,
                    &mut dst,
                )
            },
            NdarrayErr::Ok
        );
        assert!(!dst.is_null());
        let got = unsafe { std::slice::from_raw_parts(dst.cast::<i32>(), 6) };
        assert_eq!(got, [2, 3, 6, 7, 10, 11]);
        unsafe { libc::free(dst) };
        unsafe { asdf_ndarray_destroy(array) };
    }

    #[test]
    fn an_inline_array_has_no_block() {
        let array = int32_grid();
        // Built without a file behind it, so there is no block to hand back.
        assert!(unsafe { asdf_ndarray_block(array) }.is_null());
        unsafe { asdf_ndarray_destroy(array) };
    }

    #[test]
    fn reports_shape_and_sizes_through_the_public_fields() {
        let array = int32_array(&[1, 2, 3, 4]);
        let view = unsafe { &*array };

        assert_eq!(view.ndim, 1);
        assert_eq!(view.source, 0);
        assert!(!view.shape.is_null());
        assert_eq!(unsafe { *view.shape }, 4);
        assert_eq!(view.byteorder, ByteOrder::Little as i32);

        assert_eq!(unsafe { asdf_ndarray_size(array) }, 4);
        assert_eq!(unsafe { asdf_ndarray_nbytes(array) }, 16);

        unsafe { asdf_ndarray_destroy(array) };
    }

    #[test]
    fn datatype_size_is_computed_when_left_zero() {
        let mut dt = asdf_datatype_t {
            type_: scalar_abi(ScalarType::Float64),
            size: 0,
            name: std::ptr::null(),
            byteorder: 0,
            ndim: 0,
            shape: std::ptr::null(),
            nfields: 0,
            fields: std::ptr::null(),
        };
        assert_eq!(unsafe { asdf_datatype_size(&mut dt) }, 8);
        // ...and written back, as the header documents.
        assert_eq!(dt.size, 8);
    }

    #[test]
    fn scalar_type_names_round_trip() {
        for name in ["int8", "uint64", "float32", "complex128", "bool8", "ascii", "ucs4"] {
            let c = CString::new(name).unwrap();
            let code = unsafe { asdf_scalar_datatype_from_string(c.as_ptr()) };
            assert_ne!(code, 0, "{name}");
            let back = unsafe { CStr::from_ptr(asdf_scalar_datatype_to_string(code)) };
            assert_eq!(back.to_str().unwrap(), name);
        }
        // An unknown name is UNKNOWN, not a crash.
        let bogus = CString::new("float128").unwrap();
        assert_eq!(unsafe { asdf_scalar_datatype_from_string(bogus.as_ptr()) }, 0);
    }

    #[test]
    fn reads_the_whole_array_in_its_own_type() {
        let array = int32_array(&[10, -20, 30]);
        let mut dst: *mut c_void = std::ptr::null_mut();
        // ASDF_DATATYPE_SOURCE is UNKNOWN, meaning "keep the source type".
        assert_eq!(unsafe { asdf_ndarray_read_all(array, 0, &mut dst) }, NdarrayErr::Ok);
        assert!(!dst.is_null());
        let values = unsafe { std::slice::from_raw_parts(dst.cast::<i32>(), 3) };
        assert_eq!(values, [10, -20, 30]);

        unsafe { libc::free(dst) };
        unsafe { asdf_ndarray_destroy(array) };
    }

    #[test]
    fn reads_the_whole_array_converted() {
        let array = int32_array(&[1, 2, 3]);
        let mut dst: *mut c_void = std::ptr::null_mut();
        assert_eq!(
            unsafe { asdf_ndarray_read_all(array, scalar_abi(ScalarType::Float64), &mut dst) },
            NdarrayErr::Ok
        );
        let values = unsafe { std::slice::from_raw_parts(dst.cast::<f64>(), 3) };
        assert_eq!(values, [1.0, 2.0, 3.0]);
        unsafe { libc::free(dst) };
        unsafe { asdf_ndarray_destroy(array) };
    }

    #[test]
    fn read_all_fills_a_caller_supplied_buffer() {
        let array = int32_array(&[7, 8]);
        let mut buffer = [0i32; 2];
        let mut dst: *mut c_void = buffer.as_mut_ptr().cast();
        assert_eq!(unsafe { asdf_ndarray_read_all(array, 0, &mut dst) }, NdarrayErr::Ok);
        assert_eq!(buffer, [7, 8]);
        unsafe { asdf_ndarray_destroy(array) };
    }

    #[test]
    fn converting_a_value_that_does_not_fit_overflows() {
        let array = int32_array(&[1000]);
        let mut dst: *mut c_void = std::ptr::null_mut();
        assert_eq!(
            unsafe { asdf_ndarray_read_all(array, scalar_abi(ScalarType::Int8), &mut dst) },
            NdarrayErr::Overflow
        );

        // Overflow still delivers the buffer -- the caller gets the saturated
        // value *and* the report that it did not fit -- so `dst` owns an
        // allocation the caller frees, exactly as the header says.
        assert!(!dst.is_null());
        assert_eq!(unsafe { *dst.cast::<i8>() }, i8::MAX);
        unsafe { libc::free(dst) };

        unsafe { asdf_ndarray_destroy(array) };
    }

    #[test]
    fn reads_single_elements_by_index() {
        let array = int32_array(&[5, 6, 7]);

        for (index, expected) in [(0u64, 5i64), (1, 6), (2, 7)] {
            let mut err: c_int = -1;
            let value = unsafe { asdf_ndarray_read_int64_at(array, &index, &mut err) };
            assert_eq!(err, NdarrayErr::Ok as c_int);
            assert_eq!(value, expected);
        }
        unsafe { asdf_ndarray_destroy(array) };
    }

    #[test]
    fn out_of_bounds_reads_are_reported() {
        let array = int32_array(&[1, 2]);
        let index = 5u64;
        let mut err: c_int = -1;
        let value = unsafe { asdf_ndarray_read_int64_at(array, &index, &mut err) };
        assert_eq!(err, NdarrayErr::OutOfBounds as c_int);
        assert_eq!(value, 0, "a failed read returns a zero value");
        unsafe { asdf_ndarray_destroy(array) };
    }

    #[test]
    fn single_element_reads_convert_and_overflow() {
        let array = int32_array(&[300]);
        let index = 0u64;

        let mut err: c_int = -1;
        let wide = unsafe { asdf_ndarray_read_float64_at(array, &index, &mut err) };
        assert_eq!(err, NdarrayErr::Ok as c_int);
        assert_eq!(wide, 300.0);

        let mut err: c_int = -1;
        let narrow = unsafe { asdf_ndarray_read_uint8_at(array, &index, &mut err) };
        assert_eq!(err, NdarrayErr::Conversion as c_int);
        assert_eq!(narrow, 0);

        unsafe { asdf_ndarray_destroy(array) };
    }

    #[test]
    fn float16_reads_go_through_the_bit_pattern() {
        let array = int32_array(&[3]);
        let index = 0u64;
        let mut err: c_int = -1;
        let bits =
            unsafe { asdf_shim_ndarray_read_float16_bits_at(array.cast(), &index, &mut err) };
        assert_eq!(err, NdarrayErr::Ok as c_int);
        assert_eq!(half::f16::from_bits(bits).to_f64(), 3.0);
        unsafe { asdf_ndarray_destroy(array) };
    }

    #[test]
    fn data_alloc_is_idempotent_and_freeable() {
        let array = int32_array(&[0; 4]);
        let first = unsafe { asdf_ndarray_data_alloc(array) };
        let second = unsafe { asdf_ndarray_data_alloc(array) };
        assert!(!first.is_null());
        assert_eq!(first, second, "repeated calls return the same buffer");

        unsafe { asdf_ndarray_data_dealloc(array) };
        // Deallocating twice must be a no-op, as the header documents.
        unsafe { asdf_ndarray_data_dealloc(array) };
        unsafe { asdf_ndarray_destroy(array) };
    }

    #[test]
    fn data_copy_fills_the_allocated_buffer() {
        let array = int32_array(&[0; 3]);
        let source: Vec<i32> = vec![11, 22, 33];
        assert_eq!(
            unsafe { asdf_ndarray_data_copy(array, source.as_ptr().cast()) },
            NdarrayErr::Ok
        );

        let mut size = 0usize;
        let data = unsafe { asdf_ndarray_data(array, &mut size) };
        assert_eq!(size, 12);
        let values = unsafe { std::slice::from_raw_parts(data.cast::<i32>(), 3) };
        assert_eq!(values, [11, 22, 33]);

        unsafe { asdf_ndarray_data_dealloc(array) };
        unsafe { asdf_ndarray_destroy(array) };
    }

    /// C casts the data pointer to the element type before dereferencing, so
    /// an under-aligned buffer is undefined behaviour and, on a
    /// strict-alignment target, a bus error. `malloc` gives upstream this for
    /// free; holding the bytes in a `Vec<u8>` had quietly given it up. Found
    /// by Miri, which rejected `data.cast::<i32>()` over a 2-aligned buffer.
    ///
    /// Be aware of what this test does and does not prove. Rust's global
    /// allocator forwards to `malloc` for any alignment it already satisfies,
    /// so on glibc a `Vec<u8>` comes back 16-aligned anyway and this test
    /// passed even *with* the bug present. It is a tripwire for an allocator
    /// that honours the requested alignment of 1, and a statement of the
    /// contract. The gate that actually catches a regression here is Miri,
    /// which models the guarantee rather than the platform.
    #[test]
    fn the_data_pointer_is_aligned_for_any_element_type() {
        // Small sizes are the dangerous ones: a large allocation tends to be
        // aligned by luck, so a test using only those would pass regardless.
        for len in [1usize, 2, 3, 4, 6, 12, 20, 36] {
            let array = int32_array(&vec![0; len]);

            let allocated = unsafe { asdf_ndarray_data_alloc(array) };
            assert!(!allocated.is_null());
            assert_eq!(
                allocated as usize % 16,
                0,
                "data_alloc returned a {}-byte buffer aligned to {}",
                len * 4,
                1 << (allocated as usize).trailing_zeros().min(4)
            );

            let mut size = 0usize;
            let data = unsafe { asdf_ndarray_data(array, &mut size) };
            assert_eq!(data as usize % 16, 0, "asdf_ndarray_data returned an unaligned pointer");
            assert_eq!(size, len * 4);

            unsafe { asdf_ndarray_data_dealloc(array) };

            // The other buffer that escapes to C: data read from a file
            // rather than allocated by the caller.
            let bytes: Vec<u8> = (0..len as i32).flat_map(i32::to_le_bytes).collect();
            set_data(array, &bytes);
            let read = unsafe { asdf_ndarray_data(array, &mut size) };
            assert_eq!(read as usize % 16, 0, "file data was handed out unaligned");
            assert_eq!(unsafe { std::slice::from_raw_parts(read.cast::<u8>(), size) }, &bytes[..]);

            unsafe { asdf_ndarray_destroy(array) };
        }
    }

    #[test]
    fn compression_and_storage_settings() {
        let array = int32_array(&[1]);

        let zlib = CString::new("zlib").unwrap();
        assert_eq!(unsafe { asdf_ndarray_compression_set(array, zlib.as_ptr()) }, 0);
        let bogus = CString::new("zstd").unwrap();
        assert_eq!(unsafe { asdf_ndarray_compression_set(array, bogus.as_ptr()) }, -1);

        // Internal is the default when nothing has been set.
        assert_eq!(unsafe { asdf_ndarray_storage(array) }, AsdfArrayStorage::Internal);
        unsafe { asdf_ndarray_storage_set(array, AsdfArrayStorage::Inline) };
        assert_eq!(unsafe { asdf_ndarray_storage(array) }, AsdfArrayStorage::Inline);

        // External is not supported and must leave the setting alone.
        unsafe { asdf_ndarray_storage_set(array, AsdfArrayStorage::External) };
        assert_eq!(unsafe { asdf_ndarray_storage(array) }, AsdfArrayStorage::Inline);

        unsafe { asdf_ndarray_destroy(array) };
    }

    #[test]
    fn a_compound_datatype_exposes_its_fields() {
        let doc = parse_document(
            "a:\n  source: 0\n  shape: [2]\n  byteorder: little\n  \
             datatype:\n    - name: x\n      datatype: float64\n    \
             - name: y\n      datatype: int32\n",
        )
        .unwrap();
        let root = doc.root().unwrap();
        let parsed = CoreNdarray::parse(&doc, doc.mapping_get(root, "a").unwrap()).unwrap();
        let array = make_ndarray(parsed, vec![2]);

        let view = unsafe { &*array };
        assert_eq!(view.datatype.nfields, 2);
        assert!(!view.datatype.fields.is_null());

        let fields = unsafe { std::slice::from_raw_parts(view.datatype.fields, 2) };
        assert_eq!(fields[0].type_, scalar_abi(ScalarType::Float64));
        assert_eq!(fields[0].size, 8);
        assert_eq!(unsafe { CStr::from_ptr(fields[0].name) }.to_str().unwrap(), "x");
        assert_eq!(fields[1].type_, scalar_abi(ScalarType::Int32));
        assert_eq!(unsafe { CStr::from_ptr(fields[1].name) }.to_str().unwrap(), "y");

        unsafe { asdf_ndarray_destroy(array) };
    }

    #[test]
    fn multi_dimensional_indexing() {
        let doc = parse_document(
            "a:\n  source: 0\n  shape: [2, 3]\n  datatype: uint8\n  byteorder: little\n",
        )
        .unwrap();
        let root = doc.root().unwrap();
        let parsed = CoreNdarray::parse(&doc, doc.mapping_get(root, "a").unwrap()).unwrap();
        let array = make_ndarray(parsed, vec![2, 3]);
        set_data(array, &[1, 2, 3, 4, 5, 6]);

        // Row-major: [1][2] is the sixth element.
        let indices = [1u64, 2];
        let mut err: c_int = -1;
        let value = unsafe { asdf_ndarray_read_uint8_at(array, indices.as_ptr(), &mut err) };
        assert_eq!(err, NdarrayErr::Ok as c_int);
        assert_eq!(value, 6);

        // Out of range in the second dimension only.
        let bad = [0u64, 3];
        let mut err: c_int = -1;
        unsafe { asdf_ndarray_read_uint8_at(array, bad.as_ptr(), &mut err) };
        assert_eq!(err, NdarrayErr::OutOfBounds as c_int);

        unsafe { asdf_ndarray_destroy(array) };
    }

    #[test]
    fn err_discriminants_match_the_c_abi() {
        assert_eq!(NdarrayErr::Ok as i32, 0);
        assert_eq!(NdarrayErr::OutOfBounds as i32, 1);
        assert_eq!(NdarrayErr::Oom as i32, 2);
        assert_eq!(NdarrayErr::Inval as i32, 3);
        assert_eq!(NdarrayErr::Overflow as i32, 4);
        assert_eq!(NdarrayErr::Conversion as i32, 5);
    }

    #[test]
    fn null_handles_are_tolerated() {
        let null: *mut asdf_ndarray_t = std::ptr::null_mut();
        assert_eq!(unsafe { asdf_ndarray_size(null) }, 0);
        assert_eq!(unsafe { asdf_ndarray_nbytes(null) }, 0);
        assert!(unsafe { asdf_ndarray_data_alloc(null) }.is_null());
        unsafe { asdf_ndarray_data_dealloc(null) };
        assert_eq!(unsafe { asdf_ndarray_data_copy(null, std::ptr::null()) }, NdarrayErr::Inval);
        assert_eq!(unsafe { asdf_datatype_size(std::ptr::null_mut()) }, 0);
        unsafe { asdf_ndarray_destroy(null) };

        let mut size = 99usize;
        assert!(unsafe { asdf_ndarray_data(null, &mut size) }.is_null());
        assert_eq!(size, 0);
    }
}