packmem 0.3.3

Packed, operation-aware columns for record collections: filter and aggregate in memory without decompressing.
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
//! Mutable, schema-flexible table: append and update on top of packed chunks.
//!
//! Rows land in an uncompressed tail; every `CHUNK` rows the tail is sealed into packed
//! columns. Updates to sealed rows go to a small per-chunk patch map; a chunk with many
//! patches is re-encoded. Each chunk picks its own type and encoding, so a column may
//! change type over time without rewriting old data.
use crate::buf::Buf;
use crate::{Hint, PackedInts, PackedStrs};
use std::collections::{BTreeMap, HashMap};

pub const CHUNK: usize = 16_384;
const MAX_PATCHES: usize = CHUNK / 16;

/// One value. `Missing` = the record had no such key; `Json` = raw JSON text (nested values, big integers).
#[derive(Clone, Debug, PartialEq)]
pub enum Cell {
    Missing,
    Null,
    Bool(bool),
    Int(i64),
    Float(f64),
    Str(String),
    Json(String),
}

pub fn to_text(c: &Cell) -> String {
    match c {
        Cell::Missing => String::new(),
        Cell::Null => "null".into(),
        Cell::Bool(b) => b.to_string(),
        Cell::Int(i) => i.to_string(),
        Cell::Float(f) => {
            if f.is_nan() {
                "NaN".into()
            } else if f.is_infinite() {
                if *f > 0.0 {
                    "Infinity".into()
                } else {
                    "-Infinity".into()
                }
            } else {
                serde_json::to_string(f).unwrap()
            }
        }
        Cell::Str(s) => serde_json::to_string(s).unwrap(),
        Cell::Json(s) => s.clone(),
    }
}

pub fn from_text(t: &[u8]) -> Cell {
    if t.is_empty() {
        return Cell::Missing;
    }
    let s = std::str::from_utf8(t).unwrap_or("");
    match t[0] {
        // text that is not a valid Rust string (a lone UTF-16 surrogate escape) stays as raw JSON text
        b'"' => match serde_json::from_str(s) {
            Ok(x) => Cell::Str(x),
            Err(_) => Cell::Json(s.to_string()),
        },
        b'n' => Cell::Null,
        b't' => Cell::Bool(true),
        b'f' => Cell::Bool(false),
        b'[' | b'{' => Cell::Json(s.to_string()),
        _ => {
            if let Ok(i) = s.parse::<i64>() {
                return Cell::Int(i);
            }
            match s {
                "NaN" => return Cell::Float(f64::NAN),
                "Infinity" => return Cell::Float(f64::INFINITY),
                "-Infinity" => return Cell::Float(f64::NEG_INFINITY),
                _ => {}
            }
            if s.bytes().all(|b| b.is_ascii_digit() || b == b'-') {
                return Cell::Json(s.to_string());
            } // integer beyond 64 bits
            match s.parse::<f64>() {
                Ok(f) => Cell::Float(f),
                Err(_) => Cell::Json(s.to_string()),
            }
        }
    }
}

/// 1 for the ASCII bytes Python's `str.split()` treats as whitespace: space, tab to carriage return, 0x1c to 0x1f.
const ASCII_SPACE: [u8; 256] = {
    let mut t = [0u8; 256];
    let mut i = 0;
    while i < 256 {
        t[i] = (i == 0x20 || (i >= 0x09 && i <= 0x0d) || (i >= 0x1c && i <= 0x1f)) as u8;
        i += 1
    }
    t
};

/// What to measure of a string: see `DynTable::list_str_sum`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum StrMeasure {
    /// Whitespace-separated words, with Python's definition of whitespace (`len(s.split())`).
    Words,
    /// Unicode characters (`len(s)` in Python).
    Chars,
    /// UTF-8 bytes.
    Bytes,
}
impl StrMeasure {
    fn of(self, s: &str) -> i64 {
        // Python's str.isspace is Unicode White_Space plus the four ASCII separators 0x1c..0x1f
        let space = |c: char| c.is_whitespace() || ('\x1c'..='\x1f').contains(&c);
        match self {
            StrMeasure::Bytes => s.len() as i64,
            StrMeasure::Chars => s.chars().count() as i64,
            StrMeasure::Words if s.is_ascii() => {
                // the common case, counted on bytes: a word starts wherever a non-space follows a space
                let mut prev = 1u8;
                let mut n = 0i64;
                for &b in s.as_bytes() {
                    let sp = ASCII_SPACE[b as usize];
                    n += (prev & !sp & 1) as i64;
                    prev = sp
                }
                n
            }
            StrMeasure::Words => s.split(space).filter(|w| !w.is_empty()).count() as i64,
        }
    }
}
fn json_list_len(c: &Cell) -> Option<u32> {
    match c {
        Cell::Json(t) if t.starts_with('[') => {
            serde_json::from_str::<Vec<serde::de::IgnoredAny>>(t)
                .ok()
                .map(|v| v.len() as u32)
        }
        _ => None,
    }
}
fn json_list_str_sum(c: &Cell, field: &str, measure: StrMeasure) -> Option<i64> {
    let Cell::Json(t) = c else { return None };
    let serde_json::Value::Array(items) = serde_json::from_str(t).ok()? else {
        return None;
    };
    let mut sum = 0;
    for item in &items {
        match item {
            serde_json::Value::Object(m) => {
                if let Some(serde_json::Value::String(s)) = m.get(field) {
                    sum += measure.of(s)
                }
            }
            _ => return None,
        }
    }
    Some(sum)
}

/// One field of each record in a list held as JSON text; `None` when the value is not a list.
fn json_list_field(c: &Cell, field: &str) -> Option<Vec<Cell>> {
    let Cell::Json(t) = c else { return None };
    let items: Vec<&serde_json::value::RawValue> = serde_json::from_str(t).ok()?;
    Some(
        items
            .iter()
            .map(|item| {
                serde_json::from_str::<HashMap<&str, &serde_json::value::RawValue>>(item.get())
                    .ok()
                    .and_then(|m| m.get(field).map(|v| from_text(v.get().as_bytes())))
                    .unwrap_or(Cell::Missing)
            })
            .collect(),
    )
}

#[derive(Clone, Debug)]
pub enum Pred {
    Eq(Cell),
    Range {
        lo: f64,
        hi: f64,
        lo_incl: bool,
        hi_incl: bool,
    },
    Prefix(String),
    Contains(String),
}

fn has(h: &[u8], n: &[u8]) -> bool {
    n.is_empty() || h.windows(n.len()).any(|w| w == n)
}
pub fn matches(c: &Cell, p: &Pred) -> bool {
    match (p, c) {
        (Pred::Eq(Cell::Int(a)), Cell::Int(b)) => a == b,
        (Pred::Eq(Cell::Float(a)), Cell::Float(b)) => a == b,
        (Pred::Eq(Cell::Int(a)), Cell::Float(b)) | (Pred::Eq(Cell::Float(b)), Cell::Int(a)) => {
            *a as f64 == *b && (*b as i64) == *a
        }
        (Pred::Eq(Cell::Str(a)), Cell::Str(b)) => a == b,
        (Pred::Eq(Cell::Bool(a)), Cell::Bool(b)) => a == b,
        (Pred::Eq(Cell::Null), Cell::Null) => true,
        (
            Pred::Range {
                lo,
                hi,
                lo_incl,
                hi_incl,
            },
            Cell::Int(_) | Cell::Float(_),
        ) => {
            let v = match c {
                Cell::Int(i) => *i as f64,
                Cell::Float(f) => *f,
                _ => unreachable!(),
            };
            (v > *lo || (*lo_incl && v == *lo)) && (v < *hi || (*hi_incl && v == *hi))
        }
        (Pred::Prefix(a), Cell::Str(b)) => b.starts_with(a.as_str()),
        (Pred::Contains(a), Cell::Str(b)) => b.contains(a.as_str()),
        _ => false,
    }
}

/// Stored-integer range [l, h] whose decoded values `code / 10^scale` satisfy a float range. Decoding is monotonic in the
/// code, so the matching codes are contiguous. `None` when a bound is outside the exactly representable zone.
fn dec_bounds(lo: f64, hi: f64, lo_incl: bool, hi_incl: bool, scale: usize) -> Option<(i64, i64)> {
    if lo.is_nan() || hi.is_nan() {
        return Some((1, 0));
    }
    let p = POW10[scale];
    let val = |c: i64| c as f64 / p;
    let l = if lo == f64::NEG_INFINITY {
        i64::MIN
    } else {
        let g = (lo * p).floor();
        if !(g.abs() < 9.0e15) {
            return None;
        }
        let mut c = g as i64 - 2;
        while {
            let v = val(c);
            !(v > lo || (lo_incl && v == lo))
        } {
            c += 1
        }
        c
    };
    let h = if hi == f64::INFINITY {
        i64::MAX
    } else {
        let g = (hi * p).ceil();
        if !(g.abs() < 9.0e15) {
            return None;
        }
        let mut c = g as i64 + 2;
        while {
            let v = val(c);
            !(v < hi || (hi_incl && v == hi))
        } {
            c -= 1
        }
        c
    };
    Some((l, h))
}

/// Receives the cells of rows one at a time, without building intermediate `Cell`s for packed data.
/// Absent keys are simply not reported.
pub trait RowVisitor {
    fn begin(&mut self);
    fn end(&mut self);
    fn null(&mut self, col: usize);
    fn boolean(&mut self, col: usize, v: bool);
    fn int(&mut self, col: usize, v: i64);
    fn float(&mut self, col: usize, v: f64);
    fn str(&mut self, col: usize, s: &str);
    /// A dictionary-coded string. `(col, seg, code)` identifies the value for the duration of one visit, so it can be cached; `value` decodes it.
    fn dict_str(
        &mut self,
        col: usize,
        seg: usize,
        code: u32,
        dict_len: usize,
        value: &mut dyn FnMut() -> String,
    );
    /// Nested values and integers beyond 64 bits.
    fn other(&mut self, col: usize, c: &Cell);
    /// A nested value stored as sub-columns: a list of `len` records, or one record when `is_record`. Return `true`
    /// to receive it piece by piece: `nested_elem_begin`, then for each field `nested_key` followed by exactly one
    /// value call (`null`, `int`, `str`, ..., whose `col` is then the field's index), `nested_elem_end`, and finally
    /// `nested_end`. The default declines, and the value arrives as JSON text through `other`.
    fn nested_begin(&mut self, _col: usize, _is_record: bool, _len: usize) -> bool {
        false
    }
    fn nested_elem_begin(&mut self) {}
    fn nested_key(&mut self, _field: usize, _name: &str) {}
    fn nested_elem_end(&mut self) {}
    fn nested_end(&mut self, _col: usize) {}
}
fn emit_cell<V: RowVisitor>(v: &mut V, ci: usize, c: &Cell) {
    match c {
        Cell::Missing => {}
        Cell::Null => v.null(ci),
        Cell::Bool(b) => v.boolean(ci, *b),
        Cell::Int(i) => v.int(ci, *i),
        Cell::Float(f) => v.float(ci, *f),
        Cell::Str(s) => v.str(ci, s),
        Cell::Json(_) => v.other(ci, c),
    }
}

/// Rows not yet packed, for one column: a tag byte and an 8-byte payload per cell, with all string bytes in one buffer.
/// This is about a third of a `Vec<Cell>` and needs no allocation per string.
#[derive(Default)]
struct Tail {
    tags: Vec<u8>,
    vals: Vec<u64>,
    text: String,
    ends: Vec<usize>,
    /// Nested values (`T_NEST`), split into their fields as they arrive.
    nest: Option<Box<Nest>>,
    /// Splitting was tried for this chunk and a value did not fit: nested values are kept as text until `clear`.
    no_nest: bool,
    /// How deep this buffer sits inside nested values: 0 for a column of the table.
    level: u8,
}
/// The nested values of one column's unpacked rows, held as sub-columns from the start. Keeping their JSON text
/// until the chunk is packed would hold every such value twice while it is split.
struct Nest {
    sh: Shredder,
    /// For each nested row, in order: the number of elements once it has been added.
    ends: Vec<u32>,
    is_record: bool,
}
impl Tail {
    /// Bytes this buffer holds on to, used or not.
    fn reserved(&self) -> usize {
        self.tags.capacity()
            + self.vals.capacity() * 8
            + self.text.capacity()
            + self.ends.capacity() * std::mem::size_of::<usize>()
    }
}
impl Nest {
    fn range(&self, j: usize) -> (usize, usize) {
        (
            if j == 0 { 0 } else { self.ends[j - 1] as usize },
            self.ends[j] as usize,
        )
    }
    /// Nested row `j` as compact JSON text.
    fn text(&self, j: usize) -> String {
        let (a, b) = self.range(j);
        let mut out = String::new();
        if !self.is_record {
            out.push('[')
        }
        for e in a..b {
            if e > a {
                out.push(',')
            }
            out.push('{');
            for (k, &c) in self.sh.shapes[self.sh.shape_of[e] as usize]
                .iter()
                .enumerate()
            {
                if k > 0 {
                    out.push(',')
                }
                out.push_str(&serde_json::to_string(&self.sh.names[c as usize]).unwrap());
                out.push(':');
                out.push_str(&to_text(&self.sh.tails[c as usize].get(e)))
            }
            out.push('}')
        }
        if !self.is_record {
            out.push(']')
        }
        out
    }
}
const T_MISSING: u8 = 0;
const T_NULL: u8 = 1;
const T_BOOL: u8 = 2;
const T_INT: u8 = 3;
const T_FLOAT: u8 = 4;
const T_STR: u8 = 5;
const T_JSON: u8 = 6;
/// A nested value held in `Tail::nest`; the payload is its index among the nested rows.
const T_NEST: u8 = 7;
impl Tail {
    fn missing(n: usize) -> Tail {
        Tail {
            tags: vec![T_MISSING; n],
            vals: vec![0; n],
            ..Default::default()
        }
    }
    fn len(&self) -> usize {
        self.tags.len()
    }
    fn intern(&mut self, s: &str) -> u64 {
        self.text.push_str(s);
        self.ends.push(self.text.len());
        self.ends.len() as u64 - 1
    }
    fn enc(&mut self, c: &Cell) -> (u8, u64) {
        match c {
            Cell::Missing => (T_MISSING, 0),
            Cell::Null => (T_NULL, 0),
            Cell::Bool(b) => (T_BOOL, *b as u64),
            Cell::Int(i) => (T_INT, *i as u64),
            Cell::Float(f) => (T_FLOAT, f.to_bits()),
            Cell::Str(s) => (T_STR, self.intern(s)),
            Cell::Json(s) => match self.nest_push(s) {
                Some(j) => (T_NEST, j),
                None => (T_JSON, self.intern(s)),
            },
        }
    }
    /// Split a list of records (or a record) into the sub-columns of `nest`. `None` when the value is something
    /// else or does not fit with the nested rows before it; the chunk then keeps its nested values as text.
    fn nest_push(&mut self, s: &str) -> Option<u64> {
        use serde::de::DeserializeSeed;
        if self.no_nest || self.level >= 2 {
            return None;
        }
        let is_record = match s.as_bytes().first() {
            Some(b'{') => true,
            Some(b'[') => false,
            _ => return None, // an integer beyond 64 bits
        };
        let level = self.level + 1;
        let nest = self.nest.get_or_insert_with(|| {
            Box::new(Nest {
                sh: Shredder {
                    level,
                    ..Default::default()
                },
                ends: vec![],
                is_record,
            })
        });
        let before = nest.sh.elems;
        let mut de = serde_json::Deserializer::from_str(s);
        let ok = nest.is_record == is_record
            && if is_record {
                ElemSeed(&mut nest.sh).deserialize(&mut de).is_ok()
            } else {
                ListSeed(&mut nest.sh).deserialize(&mut de).is_ok()
            }
            && de.end().is_ok();
        match u32::try_from(nest.sh.elems) {
            Ok(n) if ok => {
                nest.ends.push(n);
                Some(nest.ends.len() as u64 - 1)
            }
            _ => {
                nest.sh.truncate(before);
                self.unnest();
                None
            }
        }
    }
    /// Turn the nested rows back into JSON text and stop splitting for this chunk.
    fn unnest(&mut self) {
        self.no_nest = true;
        let Some(nest) = self.nest.take() else {
            return;
        };
        for i in 0..self.tags.len() {
            if self.tags[i] == T_NEST {
                let text = nest.text(self.vals[i] as usize);
                self.vals[i] = self.intern(&text);
                self.tags[i] = T_JSON
            }
        }
        nest.recycle()
    }
    fn push(&mut self, c: &Cell) {
        let (t, v) = self.enc(c);
        self.tags.push(t);
        self.vals.push(v)
    }
    fn set(&mut self, i: usize, c: &Cell) {
        // nested rows are held in arrival order, which replacing one would break
        if self.nest.is_some() && (self.tags[i] == T_NEST || matches!(c, Cell::Json(_))) {
            self.unnest()
        }
        let (t, v) = self.enc(c);
        self.tags[i] = t;
        self.vals[i] = v
    }
    fn clear(&mut self) {
        self.tags.clear();
        self.vals.clear();
        self.text.clear();
        self.ends.clear();
        self.no_nest = false;
        if let Some(nest) = self.nest.take() {
            nest.recycle()
        }
    }
    fn truncate(&mut self, n: usize) {
        if let Some(nest) = &mut self.nest {
            if let Some(k) = (n..self.tags.len()).find(|&k| self.tags[k] == T_NEST) {
                let j = self.vals[k] as usize;
                nest.sh.truncate(nest.range(j).0);
                nest.ends.truncate(j)
            }
        }
        self.tags.truncate(n);
        self.vals.truncate(n)
    }
    #[inline]
    fn s(&self, i: usize) -> &str {
        let k = self.vals[i] as usize;
        &self.text[if k == 0 { 0 } else { self.ends[k - 1] }..self.ends[k]]
    }
    fn get(&self, i: usize) -> Cell {
        let v = self.vals[i];
        match self.tags[i] {
            T_MISSING => Cell::Missing,
            T_NULL => Cell::Null,
            T_BOOL => Cell::Bool(v != 0),
            T_INT => Cell::Int(v as i64),
            T_FLOAT => Cell::Float(f64::from_bits(v)),
            T_STR => Cell::Str(self.s(i).to_string()),
            T_NEST => Cell::Json(self.nest.as_ref().unwrap().text(v as usize)),
            _ => Cell::Json(self.s(i).to_string()),
        }
    }
    #[inline]
    fn emit<V: RowVisitor>(&self, i: usize, ci: usize, v: &mut V) {
        let x = self.vals[i];
        match self.tags[i] {
            T_MISSING => {}
            T_NULL => v.null(ci),
            T_BOOL => v.boolean(ci, x != 0),
            T_INT => v.int(ci, x as i64),
            T_FLOAT => v.float(ci, f64::from_bits(x)),
            T_STR => v.str(ci, self.s(i)),
            _ => v.other(ci, &self.get(i)),
        }
    }
    fn cells(&self) -> impl Iterator<Item = Cell> + '_ {
        (0..self.len()).map(|i| self.get(i))
    }
    fn bytes(&self) -> usize {
        self.tags.len() * 9 + self.text_bytes() + self.ends.len() * 8
    }
    /// Bytes of text held, counting the fields of nested values.
    fn text_bytes(&self) -> usize {
        let nested = self
            .nest
            .as_ref()
            .map_or(0, |n| n.sh.tails.iter().map(Tail::bytes).sum());
        self.text.len() + nested
    }
}

/// A small multiplicative hasher for byte-string keys (the FxHash scheme); the default SipHash dominates group-by otherwise.
#[derive(Default)]
struct Fx(u64);
impl std::hash::Hasher for Fx {
    fn finish(&self) -> u64 {
        self.0
    }
    fn write(&mut self, bytes: &[u8]) {
        for c in bytes.chunks(8) {
            let mut w = [0u8; 8];
            w[..c.len()].copy_from_slice(c);
            self.0 =
                (self.0.rotate_left(5) ^ u64::from_le_bytes(w)).wrapping_mul(0x517c_c1b7_2722_0a95)
        }
    }
}

type Bits = Buf<u64>;
fn bit(b: &Option<Bits>, i: usize) -> bool {
    match b {
        Some(v) => v[i >> 6] >> (i & 63) & 1 == 1,
        None => false,
    }
}
enum Data {
    Absent,
    Int {
        p: PackedInts,
        is_bool: bool,
    },
    Dec {
        scale: u8,
        p: PackedInts,
    },
    F64(Buf<f64>),
    Str(PackedStrs),
    Mixed(PackedStrs),
    /// A list of records per row (or one record per row), stored as sub-columns.
    List(Box<ListCol>),
}

/// Sub-column storage for a column whose values are lists of records, e.g. the turns of a conversation.
/// Row `i` owns elements `offs[i]..offs[i + 1]`; each field of the records is a packed column over all elements.
/// The layout is the one Arrow uses for a list of structs. Which keys an element has, and in what order, is its
/// shape; shapes are stored once and referenced per element, so records read back exactly as they were written.
struct ListCol {
    /// Every row holds a single record rather than a list of them.
    is_record: bool,
    /// Empty when every row owns exactly one element (a column of records with none absent): row `i` is element `i`.
    offs: Buf<u32>,
    rows: u32,
    names: Vec<String>,
    /// Each field name as a JSON string followed by a colon, ready to write.
    keys_json: Vec<String>,
    shapes: Vec<Vec<u16>>,
    shape_of: PackedInts,
    cols: Vec<Chunk>,
}

thread_local! {
    /// Emptied buffers from the last chunk that was split into sub-columns, reused by the next one. Regrowing them
    /// for every chunk leaves a trail of freed blocks that some allocators keep counted against the process.
    static SPARE_TAILS: std::cell::RefCell<Vec<Tail>> = const { std::cell::RefCell::new(Vec::new()) };
}
/// Drop the buffers kept between chunks; called when a bulk load ends.
fn release_spare_tails() {
    SPARE_TAILS.with(|s| *s.borrow_mut() = Vec::new())
}

/// Empty the reusable buffers that have grown past `keep` bytes each, on this thread and in `b`. A load thread calls
/// this between pieces: the buffers a stretch of long records grew would otherwise stay resident on every thread
/// until the load ends, while ordinary pieces only need small ones.
pub fn trim_buffers(b: &mut Buffers, keep: usize) {
    let trim = |tails: &mut Vec<Tail>| {
        for t in tails.iter_mut().filter(|t| t.reserved() > keep) {
            *t = Tail::default()
        }
    };
    trim(&mut b.0);
    SPARE_TAILS.with(|s| trim(&mut s.borrow_mut()))
}

/// Drop this thread's reusable buffers; for a worker thread that has finished building tables.
pub fn release_thread_buffers() {
    release_spare_tails();
    crate::ztext::release()
}

/// Nested JSON text with the whitespace between tokens removed. The parser has already validated it, so it is kept
/// as written (escapes, number text and key order included) instead of being parsed into a tree and written back.
pub fn compact_json(t: &str) -> String {
    let mut out = Vec::with_capacity(t.len());
    let (mut in_string, mut escaped) = (false, false);
    for &c in t.as_bytes() {
        if in_string {
            out.push(c);
            if escaped {
                escaped = false
            } else if c == b'\\' {
                escaped = true
            } else if c == b'"' {
                in_string = false
            }
        } else if c == b'"' {
            in_string = true;
            out.push(c)
        } else if !matches!(c, b' ' | b'\n' | b'\r' | b'\t') {
            out.push(c)
        }
    }
    // only ASCII whitespace outside strings was dropped, so the bytes are still valid UTF-8
    String::from_utf8(out).expect("compacting JSON keeps it valid UTF-8")
}

/// Collects the elements of a chunk's nested values into one tail per field.
#[derive(Default)]
struct Shredder {
    names: Vec<String>,
    index: HashMap<String, u16>,
    tails: Vec<Tail>,
    shapes: Vec<Vec<u16>>,
    shape_ix: HashMap<Vec<u16>, i64>,
    shape_of: Vec<i64>,
    shape: Vec<u16>,
    elems: usize,
    /// The `Tail::level` of the field buffers.
    level: u8,
}
impl Nest {
    /// Hand the emptied field buffers to the next chunk that is split on this thread.
    fn recycle(mut self: Box<Self>) {
        for tail in &mut self.sh.tails {
            tail.clear() // outside the borrow below: a field holding nested values recycles its own buffers here
        }
        SPARE_TAILS.with(|s| {
            let mut spare = s.borrow_mut();
            let room = 64usize.saturating_sub(spare.len());
            // last field first: the next chunk takes buffers off the end as it meets its fields, so each field gets
            // back the buffer it grew, and the large one does not go to a small field while another is grown
            spare.extend(self.sh.tails.drain(..).rev().take(room))
        })
    }
}
impl Shredder {
    /// Forget every element from `elems` on, after a value that could not be split.
    fn truncate(&mut self, elems: usize) {
        for t in &mut self.tails {
            t.truncate(elems)
        }
        self.shape_of.truncate(elems);
        self.shape.clear();
        self.elems = elems
    }
    fn field(&mut self, name: &str) -> Option<u16> {
        if let Some(&c) = self.index.get(name) {
            return Some(c);
        }
        let c = u16::try_from(self.names.len()).ok()?;
        self.names.push(name.to_string());
        self.index.insert(name.to_string(), c);
        let mut tail = SPARE_TAILS
            .with(|s| s.borrow_mut().pop())
            .unwrap_or_default();
        tail.level = self.level;
        tail.tags.resize(self.elems, T_MISSING);
        tail.vals.resize(self.elems, 0);
        self.tails.push(tail);
        Some(c)
    }
    fn put(&mut self, c: u16, text: &str) {
        let t = &mut self.tails[c as usize];
        let fresh = t.len() == self.elems;
        if fresh {
            self.shape.push(c)
        }
        let b = text.as_bytes();
        if fresh && b.first() == Some(&b'"') && !b.contains(&b'\\') {
            // a plain string goes straight into the field's text buffer, with no allocation of its own
            let v = t.intern(&text[1..text.len() - 1]);
            t.tags.push(T_STR);
            t.vals.push(v);
            return;
        }
        // nested text is kept without its whitespace wherever it ends up
        let cell = match b.first() {
            Some(b'[' | b'{') => Cell::Json(compact_json(text)),
            _ => from_text(b),
        };
        if fresh {
            t.push(&cell)
        } else {
            t.set(self.elems, &cell) // a repeated key: the last value wins, as in json.loads
        }
    }
    fn end_elem(&mut self) {
        for t in &mut self.tails {
            if t.len() == self.elems {
                t.push(&Cell::Missing)
            }
        }
        let next = self.shapes.len() as i64;
        let id = match self.shape_ix.get(&self.shape) {
            Some(&id) => id,
            None => {
                self.shapes.push(self.shape.clone());
                self.shape_ix.insert(self.shape.clone(), next);
                next
            }
        };
        self.shape_of.push(id);
        self.shape.clear();
        self.elems += 1
    }
}
struct FieldSeed<'a>(&'a mut Shredder);
impl<'de> serde::de::DeserializeSeed<'de> for FieldSeed<'_> {
    type Value = u16;
    fn deserialize<D: serde::Deserializer<'de>>(self, d: D) -> Result<u16, D::Error> {
        d.deserialize_str(self)
    }
}
impl<'de> serde::de::Visitor<'de> for FieldSeed<'_> {
    type Value = u16;
    fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.write_str("a key")
    }
    fn visit_str<E: serde::de::Error>(self, k: &str) -> Result<u16, E> {
        self.0
            .field(k)
            .ok_or_else(|| E::custom("too many distinct keys"))
    }
}
struct ElemSeed<'a>(&'a mut Shredder);
impl<'de> serde::de::DeserializeSeed<'de> for ElemSeed<'_> {
    type Value = ();
    fn deserialize<D: serde::Deserializer<'de>>(self, d: D) -> Result<(), D::Error> {
        d.deserialize_map(self)
    }
}
impl<'de> serde::de::Visitor<'de> for ElemSeed<'_> {
    type Value = ();
    fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.write_str("a record")
    }
    fn visit_map<A: serde::de::MapAccess<'de>>(self, mut m: A) -> Result<(), A::Error> {
        while let Some(c) = m.next_key_seed(FieldSeed(&mut *self.0))? {
            let v: &serde_json::value::RawValue = m.next_value()?;
            self.0.put(c, v.get())
        }
        self.0.end_elem();
        Ok(())
    }
}
struct ListSeed<'a>(&'a mut Shredder);
impl<'de> serde::de::DeserializeSeed<'de> for ListSeed<'_> {
    type Value = ();
    fn deserialize<D: serde::Deserializer<'de>>(self, d: D) -> Result<(), D::Error> {
        d.deserialize_seq(self)
    }
}
impl<'de> serde::de::Visitor<'de> for ListSeed<'_> {
    type Value = ();
    fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.write_str("a list of records")
    }
    fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<(), A::Error> {
        while seq.next_element_seed(ElemSeed(&mut *self.0))?.is_some() {}
        Ok(())
    }
}

impl ListCol {
    /// The sub-columns built while a chunk's rows arrived, packed. `None` when there is nothing to gain (only empty
    /// lists), in which case the chunk keeps its nested values as text.
    fn from_nest(t: &Tail, hint: Hint, depth: usize) -> Option<ListCol> {
        let nest = t.nest.as_ref()?;
        let sh = &nest.sh;
        if sh.elems == 0 {
            return None;
        }
        let mut offs = Vec::with_capacity(t.len() + 1);
        let mut at = 0u32;
        offs.push(at);
        for k in 0..t.len() {
            if t.tags[k] == T_NEST {
                at = nest.ends[t.vals[k] as usize]
            }
            offs.push(at)
        }
        Some(ListCol {
            is_record: nest.is_record,
            rows: t.len() as u32,
            offs: Self::sparse(offs),
            names: sh.names.clone(),
            keys_json: sh
                .names
                .iter()
                .map(|k| format!("{}:", serde_json::to_string(k).unwrap()))
                .collect(),
            shapes: sh.shapes.clone(),
            shape_of: PackedInts::encode(&sh.shape_of, hint),
            cols: sh
                .tails
                .iter()
                .map(|tail| Chunk::seal_at(tail, hint, depth + 1))
                .collect(),
        })
    }
    /// Offsets that say row `i` is element `i` are dropped: they cost four bytes a row to say nothing.
    fn sparse(offs: impl Into<Buf<u32>>) -> Buf<u32> {
        let offs = offs.into();
        if offs.iter().enumerate().all(|(i, &o)| o as usize == i) {
            Vec::new().into()
        } else {
            offs
        }
    }
    #[inline]
    fn range(&self, i: usize) -> (usize, usize) {
        if self.offs.is_empty() {
            (i, i + 1)
        } else {
            (self.offs[i] as usize, self.offs[i + 1] as usize)
        }
    }
    /// Row `i` as compact JSON text.
    fn text(&self, i: usize) -> String {
        let (a, b) = self.range(i);
        let mut out = String::new();
        if !self.is_record {
            out.push('[')
        }
        for e in a..b {
            if e > a {
                out.push(',')
            }
            out.push('{');
            for (k, &c) in self.shapes[self.shape_of.get(e) as usize]
                .iter()
                .enumerate()
            {
                if k > 0 {
                    out.push(',')
                }
                out.push_str(&self.keys_json[c as usize]);
                out.push_str(&to_text(&self.cols[c as usize].get(e)))
            }
            out.push('}')
        }
        if !self.is_record {
            out.push(']')
        }
        out
    }
    fn emit<V: RowVisitor>(&self, i: usize, ci: usize, seg: usize, v: &mut V, buf: &mut Vec<u8>) {
        let (a, b) = self.range(i);
        if !v.nested_begin(ci, self.is_record, b - a) {
            return v.other(ci, &Cell::Json(self.text(i)));
        }
        for e in a..b {
            v.nested_elem_begin();
            for &c in &self.shapes[self.shape_of.get(e) as usize] {
                v.nested_key(c as usize, &self.names[c as usize]);
                self.cols[c as usize].emit(e, c as usize, seg, v, buf)
            }
            v.nested_elem_end()
        }
        v.nested_end(ci)
    }
    fn write(&self, w: &mut W) {
        w.bool(self.is_record);
        w.u32(self.rows);
        w.v_u32(&self.offs);
        w.u64(self.shapes.len() as u64);
        for s in &self.shapes {
            w.v_u16(s)
        }
        self.shape_of.write(w);
        w.u64(self.names.len() as u64);
        for (name, col) in self.names.iter().zip(&self.cols) {
            w.bytes(name.as_bytes());
            col.write(w)
        }
    }
    fn read(r: &mut R) -> Res<ListCol> {
        let is_record = r.get_bool()?;
        // before format 5 the offsets were always written, and gave the row count
        let rows = if r.format >= 5 {
            Some(r.get_u32()?)
        } else {
            None
        };
        let offs = r.get_v_u32()?;
        let dense = rows.is_some() && offs.is_empty();
        if !dense
            && (offs.first() != Some(&0)
                || offs.windows(2).any(|p| p[0] > p[1])
                || rows.is_some_and(|n| n as usize != offs.len() - 1))
        {
            return bad("list offsets");
        }
        let rows = rows.unwrap_or(offs.len().max(1) as u32 - 1);
        let elems = if dense { rows } else { *offs.last().unwrap() } as usize;
        let mut shapes = Vec::new();
        for _ in 0..r.len(1)? {
            shapes.push(r.get_v_u16()?.to_vec())
        }
        let shape_of = PackedInts::read(r)?;
        let (mut names, mut cols) = (Vec::new(), Vec::new());
        for _ in 0..r.len(1)? {
            names.push(r.get_string()?);
            let col = Chunk::read_max(r, u32::MAX as usize)?;
            if col.len as usize != elems {
                return bad("sub-column length");
            }
            cols.push(col)
        }
        if shape_of.len() != elems
            || shapes.is_empty()
            || shapes.iter().flatten().any(|&c| c as usize >= names.len())
        {
            return bad("record shapes");
        }
        let keys_json = names
            .iter()
            .map(|k| format!("{}:", serde_json::to_string(k).unwrap()))
            .collect();
        Ok(ListCol {
            is_record,
            rows,
            offs: Self::sparse(offs),
            names,
            keys_json,
            shapes,
            shape_of,
            cols,
        })
    }
    fn bytes(&self) -> usize {
        self.offs.len() * 4
            + self.shape_of.bytes()
            + self.shapes.iter().map(|s| s.len() * 2 + 24).sum::<usize>()
            + self.names.iter().map(|n| n.len() * 2 + 48).sum::<usize>()
            + self.cols.iter().map(|c| c.bytes()).sum::<usize>()
    }
    fn describe(&self) -> String {
        let fields: Vec<String> = self
            .names
            .iter()
            .zip(&self.cols)
            .map(|(n, c)| format!("{n}: {}", c.describe()))
            .collect();
        format!(
            "{}<{}>",
            if self.is_record { "record" } else { "list" },
            fields.join(", ")
        )
    }
}
const POW10: [f64; 7] = [1.0, 10.0, 100.0, 1e3, 1e4, 1e5, 1e6];

/// `safe_sum`: every stored integer is below 2^46 in magnitude, so a 64-bit sum of the chunk cannot overflow.
struct Chunk {
    data: Data,
    nulls: Option<Bits>,
    missing: Option<Bits>,
    fill: i64,
    holes: u32,
    len: u32,
    safe_sum: bool,
    patches: BTreeMap<u32, Cell>,
}

impl Chunk {
    fn absent(len: usize) -> Chunk {
        Chunk {
            data: Data::Absent,
            nulls: None,
            missing: None,
            fill: 0,
            holes: len as u32,
            len: len as u32,
            safe_sum: true,
            patches: BTreeMap::new(),
        }
    }
    fn seal_cells(cells: &[Cell], hint: Hint) -> Chunk {
        let mut t = Tail::default();
        for c in cells {
            t.push(c)
        }
        Chunk::seal(&t, hint)
    }
    fn seal(t: &Tail, hint: Hint) -> Chunk {
        Chunk::seal_at(t, hint, 0)
    }
    /// `depth` counts how many nested lists this column is inside; sub-columns are not split further beyond two levels.
    fn seal_at(t: &Tail, hint: Hint, depth: usize) -> Chunk {
        let n = t.len();
        let mut cnt = [0usize; 8];
        for &g in &t.tags {
            cnt[g as usize] += 1
        }
        let (miss, holes) = (
            cnt[T_MISSING as usize],
            (cnt[T_MISSING as usize] + cnt[T_NULL as usize]) as u32,
        );
        let vals = n - holes as usize;
        let bits = |tag: u8| -> Option<Bits> {
            if cnt[tag as usize] == 0 {
                return None;
            }
            let mut v = vec![0u64; (n + 63) / 64];
            for (k, &g) in t.tags.iter().enumerate() {
                if g == tag {
                    v[k >> 6] |= 1 << (k & 63)
                }
            }
            Some(v.into())
        };
        let mk = |data, fill, safe_sum| Chunk {
            data,
            nulls: bits(T_NULL),
            missing: bits(T_MISSING),
            fill,
            holes,
            len: n as u32,
            safe_sum,
            patches: BTreeMap::new(),
        };
        let small = |v: &[i64]| v.iter().all(|x| x.unsigned_abs() < 1 << 46);
        if miss == n {
            return Chunk::absent(n);
        }
        if vals > 0 && (cnt[T_INT as usize] == vals || cnt[T_BOOL as usize] == vals) {
            let is = |g: u8| g == T_INT || g == T_BOOL;
            let fill = t.vals[t.tags.iter().position(|&g| is(g)).unwrap()] as i64;
            let v: Vec<i64> = t
                .tags
                .iter()
                .zip(&t.vals)
                .map(|(&g, &x)| if is(g) { x as i64 } else { fill })
                .collect();
            let ok = small(&v);
            return mk(
                Data::Int {
                    p: PackedInts::encode(&v, hint),
                    is_bool: cnt[T_BOOL as usize] == vals,
                },
                fill,
                ok,
            );
        }
        if vals > 0 && cnt[T_FLOAT as usize] == vals {
            let fv = |k: usize| {
                if t.tags[k] == T_FLOAT {
                    Some(f64::from_bits(t.vals[k]))
                } else {
                    None
                }
            };
            // decimal scaling: if every value is exactly k-decimal, store round(v * 10^k) as integers
            'scale: for k in 0..POW10.len() {
                let mut v = Vec::with_capacity(n);
                let mut fill = None;
                for c in 0..n {
                    match fv(c) {
                        Some(x) => {
                            let sc = (x * POW10[k]).round();
                            if !(sc.abs() < 9.0e15)
                                || (sc / POW10[k]).to_bits() != x.to_bits()
                                || (x == 0.0 && x.is_sign_negative())
                            {
                                continue 'scale;
                            }
                            fill.get_or_insert(sc as i64);
                            v.push(Some(sc as i64))
                        }
                        None => v.push(None),
                    }
                }
                let fill = fill.unwrap();
                let v: Vec<i64> = v.into_iter().map(|x| x.unwrap_or(fill)).collect();
                let ok = small(&v);
                return mk(
                    Data::Dec {
                        scale: k as u8,
                        p: PackedInts::encode(&v, hint),
                    },
                    fill,
                    ok,
                );
            }
            return mk(
                Data::F64((0..n).map(|k| fv(k).unwrap_or(0.0)).collect()),
                0,
                true,
            );
        }
        if vals > 0 && cnt[T_STR as usize] == vals {
            let v: Vec<&str> = (0..n)
                .map(|k| if t.tags[k] == T_STR { t.s(k) } else { "" })
                .collect();
            return mk(Data::Str(PackedStrs::encode(&v, hint)), 0, true);
        }
        if vals > 0 && cnt[T_NEST as usize] == vals && depth < 2 {
            if let Some(list) = ListCol::from_nest(t, hint, depth) {
                return mk(Data::List(Box::new(list)), 0, true);
            }
        }
        let v: Vec<String> = t.cells().map(|c| to_text(&c)).collect();
        Chunk {
            data: Data::Mixed(PackedStrs::encode(&v, hint)),
            nulls: None,
            missing: None,
            fill: 0,
            holes,
            len: n as u32,
            safe_sum: true,
            patches: BTreeMap::new(),
        }
    }
    fn stored(&self, i: usize) -> Cell {
        if let Data::Mixed(p) = &self.data {
            let mut b = vec![];
            return from_text(p.get(i, &mut b));
        }
        if bit(&self.missing, i) {
            return Cell::Missing;
        }
        if bit(&self.nulls, i) {
            return Cell::Null;
        }
        match &self.data {
            Data::Absent => Cell::Missing,
            Data::Int { p, is_bool } => {
                if *is_bool {
                    Cell::Bool(p.get(i) != 0)
                } else {
                    Cell::Int(p.get(i))
                }
            }
            Data::Dec { scale, p } => Cell::Float(p.get(i) as f64 / POW10[*scale as usize]),
            Data::F64(v) => Cell::Float(v[i]),
            Data::Str(p) => Cell::Str(p.get_string(i)),
            Data::List(l) => Cell::Json(l.text(i)),
            Data::Mixed(_) => unreachable!(),
        }
    }
    #[inline]
    fn get(&self, i: usize) -> Cell {
        if !self.patches.is_empty() {
            if let Some(c) = self.patches.get(&(i as u32)) {
                return c.clone();
            }
        }
        self.stored(i)
    }
    #[inline]
    fn emit<V: RowVisitor>(&self, o: usize, ci: usize, seg: usize, v: &mut V, buf: &mut Vec<u8>) {
        if !self.patches.is_empty() {
            if let Some(c) = self.patches.get(&(o as u32)) {
                return emit_cell(v, ci, c);
            }
        }
        match &self.data {
            Data::Absent => {}
            Data::Mixed(p) => {
                let c = from_text(p.get(o, buf));
                emit_cell(v, ci, &c)
            }
            d => {
                if self.holes > 0 {
                    if bit(&self.missing, o) {
                        return;
                    }
                    if bit(&self.nulls, o) {
                        return v.null(ci);
                    }
                }
                match d {
                    Data::Int { p, is_bool } => {
                        if *is_bool {
                            v.boolean(ci, p.get(o) != 0)
                        } else {
                            v.int(ci, p.get(o))
                        }
                    }
                    Data::Dec { scale, p } => v.float(ci, p.get(o) as f64 / POW10[*scale as usize]),
                    Data::F64(x) => v.float(ci, x[o]),
                    Data::Str(p) => match p.dict_code(o) {
                        Some((code, n)) => v.dict_str(ci, seg, code, n, &mut || p.dict_value(code)),
                        None => v.str(ci, &String::from_utf8_lossy(p.get(o, buf))),
                    },
                    Data::List(l) => l.emit(o, ci, seg, v, buf),
                    Data::Absent | Data::Mixed(_) => unreachable!(),
                }
            }
        }
    }
    fn clean(&self) -> bool {
        self.patches.is_empty()
    }
    /// Is row `i` present and not null?
    fn has_value(&self, i: usize, buf: &mut Vec<u8>) -> bool {
        if !self.patches.is_empty() {
            if let Some(c) = self.patches.get(&(i as u32)) {
                return !matches!(c, Cell::Missing | Cell::Null);
            }
        }
        match &self.data {
            Data::Absent => false,
            Data::Mixed(p) => !matches!(p.get(i, buf), b"" | b"null"),
            _ => !self.hole(i),
        }
    }
    /// A measure of every row's string value; rows that are not strings count as zero.
    fn str_measures(&self, measure: StrMeasure, buf: &mut Vec<u8>) -> Vec<i64> {
        let n = self.len as usize;
        match (&self.data, self.clean()) {
            (Data::Str(p), true) => {
                // a dictionary column is measured once per distinct value
                let mut memo: Vec<Option<i64>> = Vec::new();
                (0..n)
                    .map(|i| {
                        if self.holes > 0 && self.hole(i) {
                            return 0;
                        }
                        match p.dict_code(i) {
                            Some((code, len)) => {
                                if memo.is_empty() {
                                    memo.resize(len, None)
                                }
                                *memo[code as usize]
                                    .get_or_insert_with(|| measure.of(&p.dict_value(code)))
                            }
                            None => measure.of(&String::from_utf8_lossy(p.get(i, buf))),
                        }
                    })
                    .collect()
            }
            _ => (0..n)
                .map(|i| match self.get(i) {
                    Cell::Str(s) => measure.of(&s),
                    _ => 0,
                })
                .collect(),
        }
    }
    fn hole(&self, i: usize) -> bool {
        bit(&self.missing, i) || bit(&self.nulls, i)
    }
    fn bytes(&self) -> usize {
        (match &self.data {
            Data::Absent => 0,
            Data::Int { p, .. } | Data::Dec { p, .. } => p.bytes(),
            Data::F64(v) => v.len() * 8,
            Data::Str(p) | Data::Mixed(p) => p.bytes(),
            Data::List(l) => l.bytes(),
        }) + self.nulls.as_ref().map_or(0, |b| b.len() * 8)
            + self.missing.as_ref().map_or(0, |b| b.len() * 8)
            + self
                .patches
                .values()
                .map(|c| {
                    48 + match c {
                        Cell::Str(s) | Cell::Json(s) => s.len(),
                        _ => 0,
                    }
                })
                .sum::<usize>()
            + 96
    }
    fn describe(&self) -> String {
        match &self.data {
            Data::Absent => "absent".into(),
            Data::Int { p, is_bool } => {
                format!("{}:{}", if *is_bool { "bool" } else { "int" }, p.describe())
            }
            Data::Dec { scale, p } => format!("decimal{}:{}", scale, p.describe()),
            Data::F64(_) => "f64".into(),
            Data::Str(p) => format!("str:{}", p.describe()),
            Data::Mixed(p) => format!("mixed:{}", p.describe()),
            Data::List(l) => l.describe(),
        }
    }
    fn select(&self, pred: &Pred, base: u32, out: &mut Vec<u32>) {
        let n = self.len as usize;
        let start = out.len();
        let mut fast = false;
        if self.clean() {
            match (&self.data, pred) {
                (Data::Absent, _) => fast = true,
                (Data::Int { p, is_bool: false }, Pred::Eq(Cell::Int(v))) => {
                    p.select_range(*v, *v, out);
                    fast = true
                }
                (
                    Data::Int { p, is_bool: false },
                    Pred::Range {
                        lo,
                        hi,
                        lo_incl,
                        hi_incl,
                    },
                ) => {
                    let l = if *lo <= -9.2e18 {
                        i64::MIN
                    } else if *lo >= 9.2e18 {
                        i64::MAX
                    } else {
                        let c = lo.ceil();
                        (c as i64) + (c == *lo && !*lo_incl) as i64
                    };
                    let h = if *hi >= 9.2e18 {
                        i64::MAX
                    } else if *hi <= -9.2e18 {
                        i64::MIN
                    } else {
                        let f = hi.floor();
                        (f as i64) - (f == *hi && !*hi_incl) as i64
                    };
                    if l <= h && !lo.is_nan() && !hi.is_nan() {
                        p.select_range(l, h, out)
                    }
                    fast = true
                }
                (
                    Data::Dec { scale, p },
                    Pred::Range {
                        lo,
                        hi,
                        lo_incl,
                        hi_incl,
                    },
                ) => {
                    if let Some((l, h)) = dec_bounds(*lo, *hi, *lo_incl, *hi_incl, *scale as usize)
                    {
                        if l <= h {
                            p.select_range(l, h, out)
                        }
                        fast = true
                    }
                }
                (Data::Dec { scale, p }, Pred::Eq(Cell::Float(x))) => {
                    if let Some((l, h)) = dec_bounds(*x, *x, true, true, *scale as usize) {
                        if l <= h {
                            p.select_range(l, h, out)
                        }
                        fast = true
                    }
                }
                (Data::Str(p), Pred::Eq(Cell::Str(s))) => {
                    p.select_where(|b| b == s.as_bytes(), out);
                    fast = true
                }
                (Data::Str(p), Pred::Prefix(s)) => {
                    p.select_where(|b| b.starts_with(s.as_bytes()), out);
                    fast = true
                }
                (Data::Str(p), Pred::Contains(s)) => {
                    p.select_where(|b| has(b, s.as_bytes()), out);
                    fast = true
                }
                (Data::Str(_), Pred::Range { .. })
                | (Data::Int { is_bool: false, .. }, Pred::Prefix(_) | Pred::Contains(_)) => {
                    fast = true
                } // type can never match
                _ => {}
            }
        }
        if fast {
            if self.holes > 0 && !matches!(self.data, Data::Absent) {
                let mut w = start;
                for r in start..out.len() {
                    let i = out[r];
                    if !self.hole(i as usize) {
                        out[w] = i;
                        w += 1
                    }
                }
                out.truncate(w)
            }
            for x in &mut out[start..] {
                *x += base
            }
        } else {
            for i in 0..n {
                if matches(&self.get(i), pred) {
                    out.push(base + i as u32)
                }
            }
        }
    }
}

/// Full chunks, then an optional sealed partial chunk (`plen` rows), then the uncompressed tail.
struct Column {
    chunks: Vec<Chunk>,
    partial: Option<Chunk>,
    tail: Tail,
}
const MIN_COMPACT: usize = 8192;
/// A chunk with at least this much string data is packed on a background thread during a parallel bulk load.
const PARALLEL_TEXT_BYTES: usize = 4 << 20;

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Num {
    Int(i128),
    Float(f64),
}
impl Num {
    fn add(self, c: &Cell) -> Num {
        match (self, c) {
            (Num::Int(a), Cell::Int(b)) => Num::Int(a + *b as i128),
            (Num::Int(a), Cell::Bool(b)) => Num::Int(a + *b as i128),
            (Num::Float(a), Cell::Int(b)) => Num::Float(a + *b as f64),
            (Num::Float(a), Cell::Bool(b)) => Num::Float(a + *b as i64 as f64),
            (Num::Int(a), Cell::Float(b)) => Num::Float(a as f64 + b),
            (Num::Float(a), Cell::Float(b)) => Num::Float(a + b),
            (s, _) => s,
        }
    }
    fn plus(self, o: Num) -> Num {
        match (self, o) {
            (Num::Int(a), Num::Int(b)) => Num::Int(a + b),
            (Num::Int(a), Num::Float(b)) | (Num::Float(b), Num::Int(a)) => Num::Float(a as f64 + b),
            (Num::Float(a), Num::Float(b)) => Num::Float(a + b),
        }
    }
}

impl Column {
    fn sealed(&self) -> impl Iterator<Item = &Chunk> {
        self.chunks.iter().chain(self.partial.iter())
    }
    /// Pack every row after the last full chunk (sealed partial + tail) into one chunk. With `keep`, the tail's buffers are
    /// emptied but stay allocated for the next chunk, which avoids regrowing them during a bulk load.
    fn seal_open(&mut self, hint: Hint, keep: bool) -> Chunk {
        let ch = match self.partial.take() {
            None => Chunk::seal(&self.tail, hint),
            Some(p) => {
                let mut t = Tail::default();
                for i in 0..p.len as usize {
                    t.push(&p.get(i))
                }
                for c in self.tail.cells() {
                    t.push(&c)
                }
                Chunk::seal(&t, hint)
            }
        };
        if keep {
            self.tail.clear()
        } else {
            self.tail = Tail::default()
        }
        ch
    }
}

/// Whole-column queries on at least this many chunks are split across threads.
const PAR_MIN_CHUNKS: usize = 16;
/// Threads for whole-column queries: `PACKMEM_THREADS` if set (1 turns threading off), else the cores, at most 8.
pub fn query_threads() -> usize {
    static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
    *N.get_or_init(|| {
        if cfg!(target_family = "wasm") {
            return 1;
        }
        std::env::var("PACKMEM_THREADS")
            .ok()
            .and_then(|v| v.parse().ok())
            .unwrap_or_else(|| std::thread::available_parallelism().map_or(1, |n| n.get().min(8)))
            .max(1)
    })
}
/// Run `f(index of the first chunk, chunks)` over contiguous runs of chunks, on threads when there are enough of them.
/// Results come back in chunk order.
fn par_runs<R: Send>(chunks: &[Chunk], f: impl Fn(usize, &[Chunk]) -> R + Sync) -> Vec<R> {
    let n = query_threads().min(chunks.len() / (PAR_MIN_CHUNKS / 2));
    if chunks.len() < PAR_MIN_CHUNKS || n < 2 {
        return vec![f(0, chunks)];
    }
    let per = chunks.len().div_ceil(n);
    std::thread::scope(|sc| {
        let f = &f;
        let hs: Vec<_> = chunks
            .chunks(per)
            .enumerate()
            .map(|(i, part)| sc.spawn(move || f(i * per, part)))
            .collect();
        hs.into_iter()
            .map(|h| h.join().expect("query thread panicked"))
            .collect()
    })
}

/// Emptied row buffers passed from one table to the next.
#[derive(Default)]
pub struct Buffers(Vec<Tail>);

pub struct DynTable {
    names: Vec<String>,
    index: HashMap<String, usize>,
    cols: Vec<Column>,
    len: usize,
    plen: usize,
    epoch: u64,
    cur: usize,
    bulk: bool,
    /// Chunks being packed on background threads during a parallel bulk load, oldest first.
    sealers: std::collections::VecDeque<std::thread::JoinHandle<(Vec<Chunk>, Vec<Tail>)>>,
    /// Emptied tail buffers handed back by finished background threads, reused for the next chunk.
    spare_tails: Vec<Tail>,
    seal_threads: usize,
    pub hint: Hint,
}

impl DynTable {
    pub fn new(hint: Hint) -> Self {
        DynTable {
            names: vec![],
            index: HashMap::new(),
            cols: vec![],
            len: 0,
            plen: 0,
            epoch: 0,
            cur: 0,
            bulk: false,
            sealers: std::collections::VecDeque::new(),
            spare_tails: Vec::new(),
            seal_threads: 0,
            hint,
        }
    }
    pub fn len(&self) -> usize {
        self.len
    }
    pub fn names(&self) -> &[String] {
        &self.names
    }
    pub fn col_index(&self, name: &str) -> Option<usize> {
        self.index.get(name).copied()
    }
    fn tail_len(&self) -> usize {
        self.len % CHUNK - self.plen
    }
    fn col_or_create(&mut self, name: &str) -> usize {
        if let Some(&i) = self.index.get(name) {
            return i;
        }
        // chunks still being packed in the background are added when they finish, for every column
        let nch = self.len / CHUNK - self.sealers.len();
        let tl = self.tail_len();
        let pl = self.plen;
        self.cols.push(Column {
            chunks: (0..nch).map(|_| Chunk::absent(CHUNK)).collect(),
            partial: if pl > 0 {
                Some(Chunk::absent(pl))
            } else {
                None
            },
            tail: match self.spare_tails.pop() {
                Some(mut t) if tl == 0 => {
                    t.level = 0;
                    t
                }
                _ => Tail::missing(tl),
            },
        });
        self.names.push(name.to_string());
        self.index.insert(name.to_string(), self.cols.len() - 1);
        self.cols.len() - 1
    }
    /// Append one record. Unknown keys create a column; keys absent from this record read back as `Missing`.
    pub fn append<'a>(&mut self, row: impl IntoIterator<Item = (&'a str, Cell)>) {
        for (k, v) in row {
            let c = self.col_for(k);
            self.put_at(c, v)
        }
        self.end_row()
    }
    /// Column for the next key of the row being built. Records usually repeat the same key order, so the expected position is tried before hashing.
    pub fn col_for(&mut self, name: &str) -> usize {
        let j = self.cur;
        let c = if j < self.names.len() && self.names[j] == name {
            j
        } else {
            self.col_or_create(name)
        };
        self.cur = c + 1;
        c
    }
    /// Set one cell of the row being built (`col_for`, `put_at`..., then `end_row`; `abort_row` discards it).
    pub fn put_at(&mut self, c: usize, v: Cell) {
        let slot = self.tail_len();
        let t = &mut self.cols[c].tail;
        if t.len() == slot {
            t.push(&v)
        } else {
            t.set(slot, &v)
        }
    }
    /// Put a list of records or a record, given as JSON text, straight into the column's sub-columns. False when it
    /// does not fit there; the caller then stores it with `put_at`.
    pub fn put_nested_at(&mut self, c: usize, json: &str) -> bool {
        let slot = self.tail_len();
        let t = &mut self.cols[c].tail;
        if t.len() != slot {
            return false;
        }
        match t.nest_push(json) {
            Some(j) => {
                t.tags.push(T_NEST);
                t.vals.push(j);
                true
            }
            None => false,
        }
    }
    /// Same as `put_at` with a string cell, without building a `Cell`.
    pub fn put_str_at(&mut self, c: usize, s: &str) {
        let slot = self.tail_len();
        let t = &mut self.cols[c].tail;
        let v = t.intern(s);
        if t.len() == slot {
            t.tags.push(T_STR);
            t.vals.push(v)
        } else {
            t.tags[slot] = T_STR;
            t.vals[slot] = v
        }
    }
    pub fn end_row(&mut self) {
        let slot = self.tail_len();
        self.cur = 0;
        for c in &mut self.cols {
            if c.tail.len() == slot {
                c.tail.push(&Cell::Missing)
            }
        }
        self.len += 1;
        // Compressing text is what makes packing slow, so a chunk holding a lot of it is handed to a background thread
        // while parsing continues. Chunks of numbers and short strings are packed here: handing them off would only
        // keep more unpacked buffers alive.
        let heavy = self.len % CHUNK == 0
            && self.bulk
            && self.seal_threads > 0
            && self.plen == 0
            && self.cols.iter().map(|c| c.tail.text_bytes()).sum::<usize>() >= PARALLEL_TEXT_BYTES;
        if heavy {
            if self.sealers.len() >= self.seal_threads {
                self.join_oldest()
            }
            let h = self.hint;
            let spares = &mut self.spare_tails;
            let tails: Vec<Tail> = self
                .cols
                .iter_mut()
                .map(|c| std::mem::replace(&mut c.tail, spares.pop().unwrap_or_default()))
                .collect();
            self.sealers.push_back(std::thread::spawn(move || {
                let chunks = tails.iter().map(|t| Chunk::seal(t, h)).collect();
                (chunks, tails)
            }));
            self.epoch += 1
        } else if self.len % CHUNK == 0 {
            self.join_all();
            let (h, keep) = (self.hint, self.bulk);
            for c in &mut self.cols {
                let ch = c.seal_open(h, keep);
                c.chunks.push(ch)
            }
            self.plen = 0;
            self.epoch += 1
        } else if !self.bulk && self.tail_len() >= MIN_COMPACT.max(self.plen) {
            self.compact()
        }
    }
    pub fn abort_row(&mut self) {
        let slot = self.tail_len();
        self.cur = 0;
        for c in &mut self.cols {
            c.tail.truncate(slot)
        }
    }
    /// Like `set_bulk(true)`, and full chunks are packed on up to `threads` background threads while the caller keeps
    /// appending. The table must not be read until `set_bulk(false)`, which waits for them. The result is identical
    /// to a single-threaded load; up to `threads` unpacked chunks are held at once.
    pub fn set_bulk_parallel(&mut self, threads: usize) {
        self.bulk = true;
        self.seal_threads = threads
    }
    fn join_oldest(&mut self) {
        let Some(h) = self.sealers.pop_front() else {
            return;
        };
        let (chunks, mut tails) = h.join().unwrap_or_else(|e| std::panic::resume_unwind(e));
        for t in &mut tails {
            t.clear()
        }
        self.spare_tails.append(&mut tails);
        let mut chunks = chunks.into_iter();
        for c in &mut self.cols {
            // a column created after this chunk was handed off has no values in it
            c.chunks
                .push(chunks.next().unwrap_or_else(|| Chunk::absent(CHUNK)))
        }
    }
    fn join_all(&mut self) {
        while !self.sealers.is_empty() {
            self.join_oldest()
        }
    }
    /// While on, rows are only packed when a chunk fills, which avoids re-packing the open chunk as it grows. Turning it off packs what is left.
    pub fn set_bulk(&mut self, on: bool) {
        self.bulk = on;
        if !on {
            self.seal_threads = 0;
            self.compact();
            self.spare_tails = Vec::new();
            release_spare_tails();
            crate::ztext::release();
            for c in &mut self.cols {
                if c.tail.len() == 0 {
                    c.tail = Tail::default()
                }
            }
        }
    }
    /// Report rows `a..b` to a visitor, cell by cell in column order.
    pub fn visit_rows<V: RowVisitor>(&self, a: usize, b: usize, v: &mut V) {
        let b = b.min(self.len);
        let nfull = self.len / CHUNK;
        let mut r = a;
        let mut buf = Vec::new();
        while r < b {
            let (k, o) = (r / CHUNK, r % CHUNK);
            let (seg_end, tail) = if k < nfull {
                ((k + 1) * CHUNK, false)
            } else if o < self.plen {
                (k * CHUNK + self.plen, false)
            } else {
                (self.len, true)
            };
            let e = seg_end.min(b);
            for row in r..e {
                let o = row % CHUNK;
                v.begin();
                for (ci, c) in self.cols.iter().enumerate() {
                    if tail {
                        c.tail.emit(o - self.plen, ci, v)
                    } else {
                        let ch = if k < nfull {
                            &c.chunks[k]
                        } else {
                            c.partial.as_ref().unwrap()
                        };
                        ch.emit(o, ci, k, v, &mut buf)
                    }
                }
                v.end()
            }
            r = e
        }
    }
    /// Pack the rows that are still uncompressed. Called automatically as the table grows (amortised), and by bulk loaders when they finish.
    pub fn compact(&mut self) {
        self.join_all();
        if self.tail_len() == 0 {
            return;
        }
        let h = self.hint;
        for c in &mut self.cols {
            c.partial = Some(c.seal_open(h, false))
        }
        self.plen = self.len % CHUNK;
        self.epoch += 1
    }
    #[inline]
    pub fn get(&self, row: usize, col: usize) -> Cell {
        let c = &self.cols[col];
        let (k, o) = (row / CHUNK, row % CHUNK);
        if k < c.chunks.len() {
            c.chunks[k].get(o)
        } else if o < self.plen {
            c.partial.as_ref().unwrap().get(o)
        } else {
            c.tail.get(o - self.plen)
        }
    }
    /// Update one cell in place. Sealed rows are patched; heavily patched chunks are re-encoded.
    pub fn set(&mut self, row: usize, col: usize, v: Cell) {
        let h = self.hint;
        self.epoch += 1;
        let c = &mut self.cols[col];
        let k = row / CHUNK;
        let o = row % CHUNK;
        if k >= c.chunks.len() && o >= self.plen {
            c.tail.set(o - self.plen, &v);
            return;
        }
        let ch = if k < c.chunks.len() {
            &mut c.chunks[k]
        } else {
            c.partial.as_mut().unwrap()
        };
        ch.patches.insert(o as u32, v);
        if ch.patches.len() > MAX_PATCHES {
            let cells: Vec<Cell> = (0..ch.len as usize).map(|i| ch.get(i)).collect();
            *ch = Chunk::seal_cells(&cells, h)
        }
    }
    pub fn set_by_name(&mut self, row: usize, name: &str, v: Cell) {
        let c = self.col_or_create(name);
        self.set(row, c, v)
    }
    fn chunk_of(&self, row: usize, col: usize) -> Option<(usize, &Chunk, usize)> {
        let c = &self.cols[col];
        let (k, o) = (row / CHUNK, row % CHUNK);
        if k < c.chunks.len() {
            Some((k, &c.chunks[k], o))
        } else if o < self.plen {
            c.partial.as_ref().map(|p| (k, p, o))
        } else {
            None
        }
    }
    /// For a dictionary-encoded string cell: (chunk id, dictionary code, dictionary size). Lets callers cache decoded values per chunk.
    #[inline]
    pub fn str_code(&self, row: usize, col: usize) -> Option<(usize, u32, usize)> {
        let (k, ch, o) = self.chunk_of(row, col)?;
        if !ch.clean() || ch.holes > 0 {
            return None;
        }
        match &ch.data {
            Data::Str(p) => p.dict_code(o).map(|(code, n)| (k, code, n)),
            _ => None,
        }
    }
    pub fn dict_value(&self, row: usize, col: usize, code: u32) -> String {
        match self.chunk_of(row, col) {
            Some((
                _,
                Chunk {
                    data: Data::Str(p), ..
                },
                _,
            )) => p.dict_value(code),
            _ => String::new(),
        }
    }
    /// Changes whenever sealed data is rewritten, so per-chunk caches can be invalidated.
    pub fn epoch(&self) -> u64 {
        self.epoch
    }
    pub fn row(&self, row: usize) -> Vec<Cell> {
        (0..self.cols.len()).map(|c| self.get(row, c)).collect()
    }
    /// Row ids matching a predicate on one column; evaluated on encoded chunks where possible.
    pub fn select(&self, col: usize, pred: &Pred) -> Vec<u32> {
        let c = &self.cols[col];
        let mut parts = par_runs(&c.chunks, |k0, part| {
            let mut out = vec![];
            for (k, ch) in part.iter().enumerate() {
                ch.select(pred, ((k0 + k) * CHUNK) as u32, &mut out)
            }
            out
        });
        let mut out = if parts.len() == 1 {
            parts.pop().unwrap()
        } else {
            parts.concat()
        };
        if let Some(ch) = &c.partial {
            ch.select(pred, (c.chunks.len() * CHUNK) as u32, &mut out)
        }
        let base = (c.chunks.len() * CHUNK + self.plen) as u32;
        for (i, cell) in c.tail.cells().enumerate() {
            if matches(&cell, pred) {
                out.push(base + i as u32)
            }
        }
        out
    }
    pub fn sum(&self, col: usize, sel: Option<&[u32]>) -> Num {
        let c = &self.cols[col];
        let mut s = Num::Int(0);
        if let Some(sel) = sel {
            // work through the selection one chunk at a time, so the chunk and its encoding are resolved once per run
            let (mut i, mut offs) = (0, Vec::new());
            while i < sel.len() {
                let k = sel[i] as usize / CHUNK;
                let j = i + sel[i..]
                    .iter()
                    .take_while(|&&r| r as usize / CHUNK == k)
                    .count();
                let run = &sel[i..j];
                i = j;
                match self.chunk_of(run[0] as usize, col) {
                    Some((_, ch, _))
                        if ch.clean()
                            && (run[run.len() - 1] as usize % CHUNK) < ch.len as usize =>
                    {
                        match (&ch.data, s) {
                            (Data::Absent | Data::Str(_), _) => {}
                            (Data::Int { p, .. }, Num::Int(acc)) if ch.safe_sum => {
                                offs.clear();
                                offs.extend(
                                    run.iter()
                                        .map(|&r| r % CHUNK as u32)
                                        .filter(|&o| ch.holes == 0 || !ch.hole(o as usize)),
                                );
                                s = Num::Int(acc + p.sum_at(&offs) as i128)
                            }
                            (Data::Dec { scale, p }, _) => {
                                let d = POW10[*scale as usize];
                                for &r in run {
                                    let o = r as usize % CHUNK;
                                    if ch.holes == 0 || !ch.hole(o) {
                                        s = s.add(&Cell::Float(p.get(o) as f64 / d))
                                    }
                                }
                            }
                            _ => {
                                for &r in run {
                                    s = s.add(&ch.get(r as usize % CHUNK))
                                }
                            }
                        }
                    }
                    _ => {
                        for &r in run {
                            s = s.add(&self.get(r as usize, col))
                        }
                    }
                }
            }
            return s;
        }
        // each packed chunk's total is worked out on its own, then the totals are added in chunk order, so the
        // answer does not depend on how many threads ran
        let fast = |ch: &Chunk| -> Result<Option<Num>, ()> {
            let hole_adj = ch.fill.wrapping_mul(ch.holes as i64);
            match (&ch.data, ch.clean() && ch.safe_sum) {
                (Data::Absent | Data::Str(_), true) => Ok(None),
                (Data::Int { p, .. }, true) => Ok(Some(Num::Int((p.sum() - hole_adj) as i128))),
                (Data::Dec { scale, p }, true) => Ok(Some(Num::Float(
                    (p.sum() - hole_adj) as f64 / POW10[*scale as usize],
                ))),
                (Data::F64(v), true) => Ok(Some(Num::Float(v.iter().sum()))),
                _ => Err(()),
            }
        };
        // whole-number chunks keep enough about themselves to be summed almost for free, so threads only cost there
        let cheap = |ch: &Chunk| matches!(ch.data, Data::Int { .. } | Data::Absent);
        let totals = if c.chunks.iter().all(cheap) {
            vec![c.chunks.iter().map(fast).collect::<Vec<_>>()]
        } else {
            par_runs(&c.chunks, |_, part| part.iter().map(fast).collect())
        };
        for (ch, t) in c
            .chunks
            .iter()
            .zip(totals.into_iter().flatten())
            .chain(c.partial.iter().map(|ch| (ch, fast(ch))))
        {
            match t {
                Ok(None) => {}
                Ok(Some(t)) => s = s.plus(t),
                Err(()) => {
                    for i in 0..ch.len as usize {
                        s = s.add(&ch.get(i))
                    }
                }
            }
        }
        for cell in c.tail.cells() {
            s = s.add(&cell)
        }
        s
    }
    /// GROUP BY value -> count. Keys are returned as cells.
    pub fn group_count(&self, col: usize, sel: Option<&[u32]>) -> Vec<(Cell, usize)> {
        let c = &self.cols[col];
        let mut m: HashMap<String, usize> = HashMap::new();
        // plain string chunks are counted by their bytes, which skips a JSON encode and decode per group
        let mut strs: HashMap<Box<[u8]>, usize, std::hash::BuildHasherDefault<Fx>> =
            HashMap::default();
        if let Some(sel) = sel {
            // dictionary columns: count codes per chunk and decode each distinct value once
            let (mut i, mut counts) = (0, Vec::<usize>::new());
            while i < sel.len() {
                let k = sel[i] as usize / CHUNK;
                let j = i + sel[i..]
                    .iter()
                    .take_while(|&&r| r as usize / CHUNK == k)
                    .count();
                let run = &sel[i..j];
                i = j;
                let dict = match self.chunk_of(run[0] as usize, col) {
                    Some((_, ch, _))
                        if ch.clean()
                            && ch.holes == 0
                            && (run[run.len() - 1] as usize % CHUNK) < ch.len as usize =>
                    {
                        match &ch.data {
                            Data::Str(p) => p.dict_code(0).map(|(_, n)| (p, n)),
                            _ => None,
                        }
                    }
                    _ => None,
                };
                match dict {
                    Some((p, n)) => {
                        counts.clear();
                        counts.resize(n, 0);
                        for &r in run {
                            counts[p.dict_code(r as usize % CHUNK).unwrap().0 as usize] += 1
                        }
                        for (code, &n) in counts.iter().enumerate().filter(|(_, n)| **n > 0) {
                            *m.entry(serde_json::to_string(&p.dict_value(code as u32)).unwrap())
                                .or_default() += n
                        }
                    }
                    None => {
                        for &r in run {
                            *m.entry(to_text(&self.get(r as usize, col))).or_default() += 1
                        }
                    }
                }
            }
        } else {
            type Strs = HashMap<Box<[u8]>, usize, std::hash::BuildHasherDefault<Fx>>;
            let count = |part: &[Chunk], m: &mut HashMap<String, usize>, strs: &mut Strs| {
                for ch in part {
                    match (&ch.data, ch.clean() && ch.holes == 0) {
                        (Data::Str(p), true) => p.for_each_group(|k, n| match strs.get_mut(k) {
                            Some(v) => *v += n,
                            None => {
                                strs.insert(k.into(), n);
                            }
                        }),
                        _ => {
                            for i in 0..ch.len as usize {
                                *m.entry(to_text(&ch.get(i))).or_default() += 1
                            }
                        }
                    }
                }
            };
            let mut parts = par_runs(&c.chunks, |_, part| {
                let (mut m, mut strs) = (HashMap::new(), Strs::default());
                count(part, &mut m, &mut strs);
                (m, strs)
            })
            .into_iter();
            (m, strs) = parts.next().unwrap();
            for (pm, ps) in parts {
                for (k, n) in pm {
                    *m.entry(k).or_default() += n
                }
                for (k, n) in ps {
                    *strs.entry(k).or_default() += n
                }
            }
            count(c.partial.as_slice(), &mut m, &mut strs);
            for cell in c.tail.cells() {
                *m.entry(to_text(&cell)).or_default() += 1
            }
        }
        if !m.is_empty() {
            // some chunks went through the general path: fold the string counts in so each value appears once
            for (k, n) in strs.drain() {
                *m.entry(serde_json::to_string(&String::from_utf8_lossy(&k)).unwrap())
                    .or_default() += n
            }
        }
        strs.into_iter()
            .map(|(k, n)| (Cell::Str(String::from_utf8_lossy(&k).into_owned()), n))
            .chain(m.into_iter().map(|(k, n)| (from_text(k.as_bytes()), n)))
            .collect()
    }
    /// Approximate bytes held (packed chunks + uncompressed tail).
    pub fn bytes(&self) -> usize {
        self.cols
            .iter()
            .map(|c| c.sealed().map(|ch| ch.bytes()).sum::<usize>() + c.tail.bytes())
            .sum()
    }
    pub fn describe(&self) -> Vec<(String, String, usize)> {
        self.names
            .iter()
            .zip(&self.cols)
            .map(|(n, c)| {
                let mut kinds: Vec<String> = vec![];
                for ch in c.sealed() {
                    let d = ch.describe();
                    if !kinds.contains(&d) {
                        kinds.push(d)
                    }
                }
                (
                    n.clone(),
                    if kinds.len() > 3 {
                        format!("{} (+{} more)", kinds[..3].join(", "), kinds.len() - 3)
                    } else {
                        kinds.join(", ")
                    },
                    c.sealed().map(|ch| ch.bytes()).sum(),
                )
            })
            .collect()
    }
    /// A new table holding the given rows of this one, in the given order (rows may repeat or be left out).
    /// Sorting, deleting and inserting in the middle are built on this; each is a full rebuild, O(rows).
    pub fn take(&self, order: &[u32]) -> DynTable {
        let mut t = DynTable::new(self.hint);
        for name in &self.names {
            t.col_or_create(name);
        }
        t.set_bulk(true);
        for &r in order {
            for c in 0..self.cols.len() {
                match self.get(r as usize, c) {
                    Cell::Missing => {}
                    cell => t.put_at(c, cell),
                }
            }
            t.end_row();
        }
        t.set_bulk(false);
        t
    }
    /// Replace or create a whole column from one value per row, packing it chunk by chunk. Far cheaper than updating
    /// every row, which would patch each packed chunk over and over.
    pub fn set_column(&mut self, name: &str, mut value: impl FnMut(usize) -> Cell) {
        self.compact();
        let c = self.col_or_create(name);
        let (h, nfull, plen) = (self.hint, self.len / CHUNK, self.plen);
        let mut t = Tail::default();
        let mut seal = |start: usize, n: usize| {
            t.clear();
            for i in 0..n {
                t.push(&value(start + i))
            }
            Chunk::seal(&t, h)
        };
        let chunks: Vec<Chunk> = (0..nfull).map(|k| seal(k * CHUNK, CHUNK)).collect();
        let partial = (plen > 0).then(|| seal(nfull * CHUNK, plen));
        self.cols[c] = Column {
            chunks,
            partial,
            tail: Tail::default(),
        };
        self.epoch += 1;
    }
    /// Append every row of `other`, matching columns by name, without leaving native code.
    pub fn extend_from(&mut self, other: &DynTable) {
        let map: Vec<usize> = other.names.iter().map(|n| self.col_or_create(n)).collect();
        let was_bulk = self.bulk;
        self.bulk = true;
        for r in 0..other.len {
            for (c, &dst) in map.iter().enumerate() {
                match other.get(r, c) {
                    Cell::Missing => {}
                    cell => self.put_at(dst, cell),
                }
            }
            self.end_row();
        }
        if !was_bulk {
            self.set_bulk(false)
        }
    }
    /// Take the emptied row buffers out of a table whose rows are all packed, to give to `reuse_buffers` on the next
    /// table built on this thread. Building many short-lived tables then stops allocating a fresh set each time.
    pub fn take_buffers(&mut self) -> Buffers {
        let mut out = std::mem::take(&mut self.spare_tails);
        // last column first, so the next table's columns take back the buffers they grew (see `Nest::recycle`)
        for c in self.cols.iter_mut().rev() {
            if c.tail.len() == 0 {
                out.push(std::mem::take(&mut c.tail))
            }
        }
        Buffers(out)
    }
    pub fn reuse_buffers(&mut self, b: Buffers) {
        self.spare_tails.extend(b.0)
    }
    /// Append another table's rows. When this table ends on a chunk boundary and the other holds only whole packed
    /// chunks, the chunks are moved over as they are; otherwise the rows are copied one by one.
    pub fn append_table(&mut self, mut other: DynTable) {
        other.join_all();
        let whole = |t: &DynTable| t.len % CHUNK == 0 && t.plen == 0 && t.sealers.is_empty();
        if !(whole(self) && whole(&other)) {
            return self.extend_from(&other);
        }
        let k = other.len / CHUNK;
        let mut theirs: Vec<Option<Vec<Chunk>>> = (0..self.cols.len()).map(|_| None).collect();
        for (name, col) in other.names.iter().zip(other.cols) {
            let dst = self.col_or_create(name);
            if dst == theirs.len() {
                theirs.push(None)
            }
            theirs[dst] = Some(col.chunks)
        }
        for (c, chunks) in self.cols.iter_mut().zip(theirs) {
            match chunks {
                Some(chunks) => c.chunks.extend(chunks),
                None => c.chunks.extend((0..k).map(|_| Chunk::absent(CHUNK))),
            }
        }
        self.len += other.len;
        self.epoch += 1
    }
    /// For every row: does it have a value for this column (the key is present and not null)?
    pub fn notna(&self, col: usize) -> Vec<bool> {
        let c = &self.cols[col];
        let mut out = Vec::with_capacity(self.len);
        let mut buf = Vec::new();
        for ch in c.sealed() {
            for i in 0..ch.len as usize {
                out.push(ch.has_value(i, &mut buf))
            }
        }
        out.extend(c.tail.tags.iter().map(|&t| t != T_MISSING && t != T_NULL));
        out
    }
    /// For every row: the number of elements in its list value, or `None` when the value is not a list.
    pub fn list_len(&self, col: usize) -> Vec<Option<u32>> {
        let c = &self.cols[col];
        let mut out = Vec::with_capacity(self.len);
        for ch in c.sealed() {
            match (&ch.data, ch.clean()) {
                (Data::List(l), true) if !l.is_record => {
                    for i in 0..ch.len as usize {
                        out.push((!ch.hole(i)).then(|| {
                            let (a, b) = l.range(i);
                            (b - a) as u32
                        }))
                    }
                }
                _ => out.extend((0..ch.len as usize).map(|i| json_list_len(&ch.get(i)))),
            }
        }
        out.extend(c.tail.cells().map(|cell| json_list_len(&cell)));
        out
    }
    /// For every row: the sum, over the records in its list value, of a measure of one string field (`Words` counts
    /// whitespace-separated words as Python's `str.split()` does). `None` when the value is not a list of records.
    pub fn list_str_sum(&self, col: usize, field: &str, measure: StrMeasure) -> Vec<Option<i64>> {
        let c = &self.cols[col];
        let mut out = Vec::with_capacity(self.len);
        let mut buf = Vec::new();
        for ch in c.sealed() {
            match (&ch.data, ch.clean()) {
                (Data::List(l), true) if !l.is_record => {
                    let per_elem = l
                        .names
                        .iter()
                        .position(|n| n == field)
                        .map(|f| l.cols[f].str_measures(measure, &mut buf));
                    for i in 0..ch.len as usize {
                        out.push((!ch.hole(i)).then(|| {
                            let (a, b) = l.range(i);
                            per_elem.as_ref().map_or(0, |m| m[a..b].iter().sum())
                        }))
                    }
                }
                _ => out.extend(
                    (0..ch.len as usize).map(|i| json_list_str_sum(&ch.get(i), field, measure)),
                ),
            }
        }
        out.extend(
            c.tail
                .cells()
                .map(|cell| json_list_str_sum(&cell, field, measure)),
        );
        out
    }
    /// For every row holding a list: the value of `field` in each of its records, `Missing` where a record lacks it
    /// or the element is not a record. `None` for rows whose value is not a list. Read from the field's sub-column
    /// alone, where there is one.
    pub fn list_field(&self, col: usize, field: &str) -> Vec<Option<Vec<Cell>>> {
        let c = &self.cols[col];
        let mut out = Vec::with_capacity(self.len);
        for ch in c.sealed() {
            match (&ch.data, ch.clean()) {
                (Data::List(l), true) if !l.is_record => {
                    let sub = l.names.iter().position(|n| n == field).map(|f| &l.cols[f]);
                    for i in 0..ch.len as usize {
                        out.push((!ch.hole(i)).then(|| {
                            let (a, b) = l.range(i);
                            (a..b)
                                .map(|e| sub.map_or(Cell::Missing, |s| s.get(e)))
                                .collect()
                        }))
                    }
                }
                _ => out.extend((0..ch.len as usize).map(|i| json_list_field(&ch.get(i), field))),
            }
        }
        out.extend(c.tail.cells().map(|cell| json_list_field(&cell, field)));
        out
    }
    /// Rows currently held uncompressed.
    pub fn tail_rows(&self) -> usize {
        self.tail_len()
    }
}

use crate::wire::{R, Res, W, bad};
const MAGIC: &[u8; 4] = b"PKMT";
const MAGIC_0_2: &[u8; 4] = b"PKM2";
/// Raised whenever a reader built before the change could misread the bytes.
pub const FORMAT: u8 = 5;

fn write_cell(w: &mut W, c: &Cell) {
    match c {
        Cell::Missing => w.u8(T_MISSING),
        Cell::Null => w.u8(T_NULL),
        Cell::Bool(b) => {
            w.u8(T_BOOL);
            w.bool(*b)
        }
        Cell::Int(i) => {
            w.u8(T_INT);
            w.i64(*i)
        }
        Cell::Float(f) => {
            w.u8(T_FLOAT);
            w.f64(*f)
        }
        Cell::Str(s) => {
            w.u8(T_STR);
            w.bytes(s.as_bytes())
        }
        Cell::Json(s) => {
            w.u8(T_JSON);
            w.bytes(s.as_bytes())
        }
    }
}
fn read_cell(r: &mut R) -> Res<Cell> {
    Ok(match r.get_u8()? {
        T_MISSING => Cell::Missing,
        T_NULL => Cell::Null,
        T_BOOL => Cell::Bool(r.get_bool()?),
        T_INT => Cell::Int(r.get_i64()?),
        T_FLOAT => Cell::Float(r.get_f64()?),
        T_STR => Cell::Str(r.get_string()?),
        T_JSON => Cell::Json(r.get_string()?),
        _ => return bad("cell kind"),
    })
}
fn write_bits(w: &mut W, b: &Option<Bits>) {
    match b {
        None => w.u8(0),
        Some(v) => {
            w.u8(1);
            w.v_u64(v)
        }
    }
}
fn read_bits(r: &mut R, len: usize) -> Res<Option<Bits>> {
    Ok(match r.get_u8()? {
        0 => None,
        _ => {
            let v = r.get_v_u64()?;
            if v.len() != len.div_ceil(64) {
                return bad("bitmap size");
            }
            Some(v)
        }
    })
}

impl Chunk {
    fn write(&self, w: &mut W) {
        match &self.data {
            Data::Absent => w.u8(0),
            Data::Int { p, is_bool } => {
                w.u8(1);
                w.bool(*is_bool);
                p.write(w)
            }
            Data::Dec { scale, p } => {
                w.u8(2);
                w.u8(*scale);
                p.write(w)
            }
            Data::F64(v) => {
                w.u8(3);
                w.v_f64(v)
            }
            Data::Str(p) => {
                w.u8(4);
                p.write(w)
            }
            Data::Mixed(p) => {
                w.u8(5);
                p.write(w)
            }
            Data::List(l) => {
                w.u8(6);
                l.write(w)
            }
        }
        w.u32(self.len);
        w.u32(self.holes);
        w.i64(self.fill);
        w.bool(self.safe_sum);
        write_bits(w, &self.nulls);
        write_bits(w, &self.missing);
        w.u64(self.patches.len() as u64);
        for (i, c) in &self.patches {
            w.u32(*i);
            write_cell(w, c)
        }
    }
    fn read(r: &mut R) -> Res<Chunk> {
        Chunk::read_max(r, CHUNK)
    }
    /// `max` is the most rows the chunk may hold: a table chunk is bounded, a sub-column holds every element of one.
    fn read_max(r: &mut R, max: usize) -> Res<Chunk> {
        let data = match r.get_u8()? {
            0 => Data::Absent,
            1 => {
                let is_bool = r.get_bool()?;
                Data::Int {
                    p: PackedInts::read(r)?,
                    is_bool,
                }
            }
            2 => {
                let scale = r.get_u8()?;
                if scale as usize >= POW10.len() {
                    return bad("decimal scale");
                }
                Data::Dec {
                    scale,
                    p: PackedInts::read(r)?,
                }
            }
            3 => Data::F64(r.get_v_f64()?),
            4 => Data::Str(PackedStrs::read(r)?),
            5 => Data::Mixed(PackedStrs::read(r)?),
            6 => Data::List(Box::new(ListCol::read(r)?)),
            _ => return bad("column kind"),
        };
        let (len, holes, fill, safe_sum) =
            (r.get_u32()?, r.get_u32()?, r.get_i64()?, r.get_bool()?);
        let n = len as usize;
        let stored = match &data {
            Data::Absent => n,
            Data::Int { p, .. } | Data::Dec { p, .. } => p.len(),
            Data::F64(v) => v.len(),
            Data::Str(p) | Data::Mixed(p) => p.len(),
            Data::List(l) => l.rows as usize,
        };
        if n > max || stored != n || holes > len {
            return bad("chunk length");
        }
        let (nulls, missing) = (read_bits(r, n)?, read_bits(r, n)?);
        let mut patches = BTreeMap::new();
        for _ in 0..r.len(2)? {
            let i = r.get_u32()?;
            if i >= len {
                return bad("patch position");
            }
            patches.insert(i, read_cell(r)?);
        }
        Ok(Chunk {
            data,
            nulls,
            missing,
            fill,
            holes,
            len,
            safe_sum,
            patches,
        })
    }
}

impl DynTable {
    /// The table as bytes, holding the packed columns as they are. Reading them back with `from_bytes` does not re-encode
    /// anything, so it costs about one copy of the packed size. The format is tied to this version of the library.
    pub fn to_bytes(&mut self) -> Vec<u8> {
        let mut out = vec![0u8; self.byte_len()];
        self.write_bytes(&mut out);
        out
    }
    /// Size of the table's byte form. Packs any rows still held uncompressed first.
    pub fn byte_len(&mut self) -> usize {
        self.compact();
        let mut w = W::counting();
        self.write(&mut w);
        w.written()
    }
    /// Write the byte form into `out`, which must be exactly `byte_len()` long (call that first: it packs the open rows).
    pub fn write_bytes(&self, out: &mut [u8]) {
        assert_eq!(self.tail_len(), 0, "call byte_len() before write_bytes()");
        let mut w = W::into(out);
        self.write(&mut w);
    }
    /// Stream the byte form to `sink` in small pieces (for writing to a file). Call `byte_len()` first: it packs the
    /// open rows.
    pub fn write_to(
        &self,
        sink: &mut dyn FnMut(&[u8]) -> std::io::Result<()>,
    ) -> std::io::Result<usize> {
        assert_eq!(self.tail_len(), 0, "call byte_len() before write_to()");
        let mut w = W::to_sink(sink);
        self.write(&mut w);
        w.finish()
    }
    fn write(&self, w: &mut W) {
        w.raw(MAGIC);
        w.u8(FORMAT);
        w.u8(match self.hint {
            Hint::Memory => 0,
            Hint::Balanced => 1,
            Hint::Speed => 2,
            Hint::Compact => 3,
        });
        w.u64(self.len as u64);
        w.u64(self.cols.len() as u64);
        for (name, c) in self.names.iter().zip(&self.cols) {
            w.bytes(name.as_bytes());
            for ch in c.sealed() {
                ch.write(w)
            }
        }
    }
    /// Read a table by copying its packed columns out of `b`.
    pub fn from_bytes(b: &[u8]) -> Res<DynTable> {
        Self::read(R::new(b))
    }
    /// Open a table whose packed columns stay in `owner`'s bytes (a memory-mapped file) and are read in place: nothing
    /// is copied, and every process mapping the same file shares the same pages. The bytes must not change while the
    /// table, or anything derived from it by reference, is alive.
    pub fn from_backing(owner: std::sync::Arc<dyn crate::buf::Backing>) -> Res<DynTable> {
        Self::read(R::borrowing(&owner))
    }
    fn read(mut r: R) -> Res<DynTable> {
        let magic = r.take(4)?;
        let format = if magic == MAGIC {
            r.get_u8()?
        } else if magic == MAGIC_0_2 {
            2
        } else {
            return Err("not packed table data, or written by packmem 0.1".into());
        };
        if format > FORMAT {
            return Err(format!(
                "written by a newer packmem (format {format}, this build reads up to {FORMAT}): upgrade packmem to read it"
            )
            .into());
        }
        // formats 2 and 3 wrote every single integer at full width
        r.fixed = format < 4;
        r.format = format;
        let hint = match r.get_u8()? {
            0 => Hint::Memory,
            1 => Hint::Balanced,
            2 => Hint::Speed,
            3 => Hint::Compact,
            _ => return bad("hint"),
        };
        let len = r.get_u64()? as usize;
        let (nfull, plen) = (len / CHUNK, len % CHUNK);
        let mut t = DynTable::new(hint);
        for _ in 0..r.len(1)? {
            let name = r.get_string()?;
            let mut col = Column {
                chunks: Vec::new(),
                partial: None,
                tail: Tail::default(),
            };
            for _ in 0..nfull {
                let ch = Chunk::read(&mut r)?;
                if ch.len as usize != CHUNK {
                    return bad("chunk length");
                }
                col.chunks.push(ch)
            }
            if plen > 0 {
                let ch = Chunk::read(&mut r)?;
                if ch.len as usize != plen {
                    return bad("chunk length");
                }
                col.partial = Some(ch)
            }
            if t.index.insert(name.clone(), t.cols.len()).is_some() {
                return bad("duplicate column");
            }
            t.names.push(name);
            t.cols.push(col)
        }
        if !r.done() {
            return bad("trailing bytes");
        }
        (t.len, t.plen) = (len, plen);
        Ok(t)
    }
}