rust-rocksdb 0.54.0

Rust wrapper for Facebook's RocksDB embeddable database
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
// Copyright 2020 Tyler Neely
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

use std::cell::RefCell;
use std::collections::{BTreeMap, HashMap};
use std::ffi::{CStr, CString};
use std::fmt;
use std::fs;
use std::iter;
use std::path::Path;
use std::path::PathBuf;
use std::ptr;
use std::slice;
use std::str;
use std::sync::Arc;
use std::time::Duration;

use crate::column_family::ColumnFamilyTtl;
use crate::ffi_util::CSlice;
use crate::{
    ColumnFamily, ColumnFamilyDescriptor, CompactOptions, DBIteratorWithThreadMode,
    DBPinnableBatch, DBPinnableSlice, DBRawIteratorWithThreadMode, DBWALIterator,
    DEFAULT_COLUMN_FAMILY_NAME, Direction, Error, FlushOptions, IngestExternalFileOptions,
    IteratorMode, Options, ReadOptions, SnapshotWithThreadMode, WaitForCompactOptions, WriteBatch,
    WriteBatchWithIndex, WriteOptions,
    column_family::{AsColumnFamilyRef, BoundColumnFamily, UnboundColumnFamily},
    compaction::CompactionOptions,
    db_options::{
        FlushWalOptions, ImportColumnFamilyOptions, OptionsMustOutliveDB, SizeApproximationFlags,
        SizeApproximationOptions,
    },
    event_listener::OwnedCompactionJobInfo,
    ffi,
    ffi_util::{
        CStrLike, convert_rocksdb_error, from_cstr_and_free, from_cstr_without_free,
        opt_bytes_to_ptr, raw_data, to_cpath,
    },
    metadata::{
        ColumnFamilyMetaDataOptions, LevelMetaData, LiveFilesStorageInfo,
        LiveFilesStorageInfoOptions, levels_from_cf_metadata_owned,
    },
    trace::{BlockCacheTraceOptions, BlockCacheTraceWriterOptions, Replayer, TraceOptions},
    wal::{OwnedWalFile, WalFiles},
};
use rust_librocksdb_sys::{
    rocksdb_livefile_destroy, rocksdb_livefile_t, rocksdb_livefiles_destroy, rocksdb_livefiles_t,
};

use libc::{self, c_char, c_int, c_uchar, c_void, size_t};
use parking_lot::RwLock;

// Default options are kept per-thread to avoid re-allocating on every call while
// also preventing cross-thread sharing. Some RocksDB option wrappers hold
// pointers into internal buffers and are not safe to share across threads.
// Using thread_local allows cheap reuse in the common "default options" path
// without synchronization overhead. Callers who need non-defaults must pass
// explicit options.
thread_local! { static DEFAULT_READ_OPTS: ReadOptions = ReadOptions::default(); }
thread_local! { static DEFAULT_WRITE_OPTS: WriteOptions = WriteOptions::default(); }
thread_local! { static DEFAULT_FLUSH_OPTS: FlushOptions = FlushOptions::default(); }
// Thread-local ReadOptions for hot prefix probes; preconfigured for prefix scans.
thread_local! { static PREFIX_READ_OPTS: RefCell<ReadOptions> = RefCell::new({ let mut o = ReadOptions::default(); o.set_prefix_same_as_start(true); o }); }

/// Runs `f` with `ReadOptions` bounded to `prefix` and `prefix_same_as_start`
/// enabled, reusing a thread-local instance when it is available.
///
/// The borrow is held across an FFI call that can synchronously re-enter Rust
/// through a user-supplied comparator or merge operator. If that callback probes
/// another prefix on the same thread, a plain `borrow_mut` would panic with
/// `BorrowMutError` — and because the callback runs inside an `extern "C"` frame
/// the panic aborts the process. Falling back to fresh options on contention
/// costs an allocation in that rare re-entrant case and keeps the fast path
/// allocation-free.
fn with_prefix_read_opts<R>(prefix: &[u8], f: impl FnOnce(&ReadOptions) -> R) -> R {
    PREFIX_READ_OPTS.with(|rc| {
        if let Ok(mut opts) = rc.try_borrow_mut() {
            opts.set_prefix_range_in_place(prefix);
            f(&opts)
        } else {
            let mut opts = ReadOptions::default();
            opts.set_prefix_same_as_start(true);
            opts.set_prefix_range_in_place(prefix);
            f(&opts)
        }
    })
}

/// A range of keys, `start_key` is included, but not `end_key`.
///
/// You should make sure `end_key` is not less than `start_key`.
pub struct Range<'a> {
    start_key: &'a [u8],
    end_key: &'a [u8],
}

impl<'a> Range<'a> {
    pub fn new(start_key: &'a [u8], end_key: &'a [u8]) -> Range<'a> {
        Range { start_key, end_key }
    }
}

/// Result of a [`get_into_buffer`](DBCommon::get_into_buffer) operation.
///
/// This enum represents the outcome of attempting to read a value directly
/// into a caller-provided buffer, avoiding memory allocation. This is the most
/// efficient way to read values when you have a pre-allocated buffer available.
///
/// # Performance
///
/// Using `get_into_buffer` with a reusable buffer can significantly reduce
/// allocation overhead in hot paths compared to [`get`](DBCommon::get) or even
/// [`get_pinned`](DBCommon::get_pinned):
///
/// - [`get`](DBCommon::get): Allocates a new `Vec<u8>` for each call
/// - [`get_pinned`](DBCommon::get_pinned): Pins memory in RocksDB's block cache
/// - `get_into_buffer`: Zero allocation when buffer is large enough
///
/// # Example
///
/// ```
/// use rust_rocksdb::{DB, GetIntoBufferResult};
///
/// # let tempdir = tempfile::Builder::new().prefix("ex").tempdir().unwrap();
/// let db = DB::open_default(tempdir.path()).unwrap();
/// db.put(b"key", b"value").unwrap();
///
/// let mut buffer = [0u8; 1024];
/// match db.get_into_buffer(b"key", &mut buffer).unwrap() {
///     GetIntoBufferResult::Found(len) => {
///         println!("Value: {:?}", &buffer[..len]);
///     }
///     GetIntoBufferResult::NotFound => {
///         println!("Key not found");
///     }
///     GetIntoBufferResult::BufferTooSmall(needed) => {
///         println!("Need a buffer of at least {} bytes", needed);
///     }
/// }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum GetIntoBufferResult {
    /// The key was not found in the database.
    NotFound,
    /// The value was found and successfully copied into the buffer.
    /// The `usize` contains the actual size of the value (number of bytes written).
    Found(usize),
    /// The value was found but the provided buffer was too small to hold it.
    /// The `usize` contains the actual size of the value, allowing the caller
    /// to allocate a larger buffer and retry.
    ///
    /// Note: When this variant is returned, no data is written to the buffer.
    BufferTooSmall(usize),
}

impl GetIntoBufferResult {
    /// Returns `true` if the key was found (regardless of buffer size).
    #[inline]
    pub fn is_found(&self) -> bool {
        matches!(self, Self::Found(_) | Self::BufferTooSmall(_))
    }

    /// Returns `true` if the key was not found.
    #[inline]
    pub fn is_not_found(&self) -> bool {
        matches!(self, Self::NotFound)
    }

    /// Returns the value size if the key was found, `None` otherwise.
    #[inline]
    pub fn value_size(&self) -> Option<usize> {
        match self {
            Self::Found(size) | Self::BufferTooSmall(size) => Some(*size),
            Self::NotFound => None,
        }
    }
}

/// Read options tuned for prefix probes.
fn prefix_probe_read_opts() -> ReadOptions {
    let mut opts = ReadOptions::default();
    opts.set_prefix_same_as_start(true);
    opts
}

/// A reusable prefix probe that avoids per-call iterator creation/destruction.
///
/// Use this when performing many prefix existence checks in a tight loop.
///
/// A prober reads the database as of the sequence number that was current when
/// it was created, and it pins the memtables and SST files that were current
/// then. Both are what [`refresh`](PrefixProber::refresh) exists to move
/// forward. A prober that is only used for a single burst of probes and then
/// dropped needs neither.
pub struct PrefixProber<'a, D: DBAccess> {
    raw: DBRawIteratorWithThreadMode<'a, D>,
}

impl<D: DBAccess> PrefixProber<'_, D> {
    /// Returns true if any key exists with the given prefix.
    /// This performs a seek to the prefix and checks the current key.
    ///
    /// # Errors
    ///
    /// Returns the RocksDB error if the seek failed. A seek that hit an error
    /// leaves the iterator invalid, so the key check below cannot observe one.
    pub fn exists(&mut self, prefix: &[u8]) -> Result<bool, Error> {
        self.raw.seek(prefix);
        if let Some(key) = self.raw.key() {
            return Ok(key.starts_with(prefix));
        }
        self.raw.status()?;
        Ok(false)
    }

    /// Moves the probe to the latest committed state of the database.
    ///
    /// Call this before reusing a prober that has been sitting idle. Writes
    /// that land after the prober was created or last refreshed are invisible
    /// to it until then.
    ///
    /// This is cheap when RocksDB's superversion has not changed, because the
    /// existing merge tree over the memtables and SST files is kept and only
    /// the read sequence moves. A flush or a compaction bumps the superversion
    /// and forces that tree to be rebuilt, which costs roughly what building a
    /// new prober costs. Refreshing a prober that has not probed yet is a
    /// pessimisation, because it builds the tree that the first
    /// [`exists`](PrefixProber::exists) call would otherwise build lazily.
    ///
    /// Refreshing also releases the memtables and SST files the prober was
    /// pinning, which is what lets a flush or a compaction reclaim them. A
    /// cached prober that is never refreshed holds them for as long as it
    /// lives, so pool them on a timer rather than on request arrival.
    ///
    /// # Errors
    ///
    /// Returns the RocksDB error if the refresh failed.
    pub fn refresh(&mut self) -> Result<(), Error> {
        self.raw.refresh()
    }
}

/// A [`PrefixProber`] that keeps the database open instead of borrowing it.
///
/// Use this to cache a prober beyond the scope that built it, for example one
/// per worker thread. [`PrefixProber`] borrows the database, so it cannot be
/// held in a thread local or in shared state.
///
/// Everything [`PrefixProber`] documents about staleness and pinning applies
/// here, and matters more, because the point of an owned prober is to outlive
/// the request that created it. Refresh or drop cached probers on a timer. An
/// idle one goes on pinning the memtables and SST files it was built over, and
/// nothing will reclaim them.
///
/// `D` is `'static` because the wrapper owns the database rather than borrowing
/// it. Every `DBWithThreadMode` satisfies that.
pub struct OwnedPrefixProber<D: DBAccess + 'static> {
    // Field order is load bearing. Fields drop in declaration order, so the
    // iterator is destroyed while `_db` still holds the database open.
    // Reordering these two is a use after free.
    prober: PrefixProber<'static, D>,
    _db: Arc<D>,
}

// No `Deref`/`DerefMut` to `PrefixProber`. `DerefMut` would let two owned
// probers swap their inner probers, leaving each holding an iterator into the
// other's database, and dropping one could then free a database the other still
// points at.
impl<D: DBAccess + 'static> OwnedPrefixProber<D> {
    /// Creates an owned prober over the default column family, using read
    /// options tuned for prefix probes.
    pub fn new(db: Arc<D>) -> Self {
        Self::with_opts(db, prefix_probe_read_opts())
    }

    /// Creates an owned prober over the default column family with the given
    /// read options.
    ///
    /// The prober owns `readopts` so that any buffers it points at, such as
    /// iterate bounds, stay alive for as long as the iterator.
    pub fn with_opts(db: Arc<D>, readopts: ReadOptions) -> Self {
        // A `'static` iterator stores no dangling reference: the database is
        // recorded on `DBRawIteratorWithThreadMode` as a `PhantomData` lifetime
        // and nothing reads through it. `_db` is what actually keeps the
        // database alive, and the field order on the struct is what guarantees
        // the iterator is destroyed first.
        let raw = DBRawIteratorWithThreadMode::new(&*db, readopts);
        Self {
            prober: PrefixProber { raw },
            _db: db,
        }
    }

    /// Creates an owned prober over one column family, using read options tuned
    /// for prefix probes.
    pub fn new_cf(db: Arc<D>, cf_handle: &impl AsColumnFamilyRef) -> Self {
        Self::cf_with_opts(db, cf_handle, prefix_probe_read_opts())
    }

    /// Creates an owned prober over one column family with the given read
    /// options.
    ///
    /// `cf_handle` is only read while the iterator is being created. RocksDB
    /// takes its own reference to the column family, so the handle itself does
    /// not have to outlive the prober. Dropping the column family while a
    /// prober over it is alive is still not supported: the prober keeps reading
    /// the state it was built over, which is no longer meaningful.
    pub fn cf_with_opts(
        db: Arc<D>,
        cf_handle: &impl AsColumnFamilyRef,
        readopts: ReadOptions,
    ) -> Self {
        // See the safety note in `with_opts`.
        let raw = DBRawIteratorWithThreadMode::new_cf_detached(&*db, cf_handle.inner(), readopts);
        Self {
            prober: PrefixProber { raw },
            _db: db,
        }
    }

    /// Returns true if any key exists with the given prefix.
    ///
    /// See [`PrefixProber::exists`].
    ///
    /// # Errors
    ///
    /// Returns the RocksDB error if the seek failed.
    pub fn exists(&mut self, prefix: &[u8]) -> Result<bool, Error> {
        self.prober.exists(prefix)
    }

    /// Moves the probe to the latest committed state of the database.
    ///
    /// See [`PrefixProber::refresh`].
    ///
    /// # Errors
    ///
    /// Returns the RocksDB error if the refresh failed.
    pub fn refresh(&mut self) -> Result<(), Error> {
        self.prober.refresh()
    }
}

/// Marker trait to specify single or multi threaded column family alternations for
/// [`DBWithThreadMode<T>`]
///
/// This arrangement makes differences in self mutability and return type in
/// some of `DBWithThreadMode` methods.
///
/// While being a marker trait to be generic over `DBWithThreadMode`, this trait
/// also has a minimum set of not-encapsulated internal methods between
/// [`SingleThreaded`] and [`MultiThreaded`].  These methods aren't expected to be
/// called and defined externally.
pub trait ThreadMode {
    /// Internal implementation for storing column family handles
    fn new_cf_map_internal(
        cf_map: BTreeMap<String, *mut ffi::rocksdb_column_family_handle_t>,
    ) -> Self;
    /// Internal implementation for dropping column family handles
    fn drop_all_cfs_internal(&mut self);
}

/// Actual marker type for the marker trait `ThreadMode`, which holds
/// a collection of column families without synchronization primitive, providing
/// no overhead for the single-threaded column family alternations. The other
/// mode is [`MultiThreaded`].
///
/// See [`DB`] for more details, including performance implications for each mode
pub struct SingleThreaded {
    pub(crate) cfs: HashMap<String, ColumnFamily>,
}

/// Actual marker type for the marker trait `ThreadMode`, which holds
/// a collection of column families wrapped in a RwLock to be mutated
/// concurrently. The other mode is [`SingleThreaded`].
///
/// See [`DB`] for more details, including performance implications for each mode
pub struct MultiThreaded {
    pub(crate) cfs: RwLock<HashMap<String, Arc<UnboundColumnFamily>>>,
}

impl ThreadMode for SingleThreaded {
    fn new_cf_map_internal(
        cfs: BTreeMap<String, *mut ffi::rocksdb_column_family_handle_t>,
    ) -> Self {
        Self {
            cfs: cfs
                .into_iter()
                .map(|(n, c)| (n, ColumnFamily { inner: c }))
                .collect(),
        }
    }

    fn drop_all_cfs_internal(&mut self) {
        // Cause all ColumnFamily objects to be Drop::drop()-ed.
        self.cfs.clear();
    }
}

impl ThreadMode for MultiThreaded {
    fn new_cf_map_internal(
        cfs: BTreeMap<String, *mut ffi::rocksdb_column_family_handle_t>,
    ) -> Self {
        Self {
            cfs: RwLock::new(
                cfs.into_iter()
                    .map(|(n, c)| (n, Arc::new(UnboundColumnFamily { inner: c })))
                    .collect(),
            ),
        }
    }

    fn drop_all_cfs_internal(&mut self) {
        // Cause all UnboundColumnFamily objects to be Drop::drop()-ed.
        self.cfs.write().clear();
    }
}

/// Get underlying `rocksdb_t`.
pub trait DBInner {
    fn inner(&self) -> *mut ffi::rocksdb_t;
}

/// A helper type to implement some common methods for [`DBWithThreadMode`]
/// and [`OptimisticTransactionDB`].
///
/// [`OptimisticTransactionDB`]: crate::OptimisticTransactionDB
///
/// When using [`SingleThreaded`] mode, `create_cf` requires `&mut self`,
/// preventing multiple immutable references from calling it concurrently:
///
/// ```compile_fail,E0596
/// use rust_rocksdb::{DBWithThreadMode, Options, SingleThreaded};
///
/// let db = DBWithThreadMode::<SingleThreaded>::open_default("/path/to/dummy").unwrap();
/// let db_ref1 = &db;
/// let db_ref2 = &db;
/// let opts = Options::default();
/// db_ref1.create_cf("cf1", &opts).unwrap();
/// db_ref2.create_cf("cf2", &opts).unwrap();
/// ```
///
/// [`SingleThreaded`]: crate::SingleThreaded
pub struct DBCommon<T: ThreadMode, D: DBInner> {
    pub(crate) inner: D,
    cfs: T, // Column families are held differently depending on thread mode
    path: PathBuf,
    _outlive: Vec<OptionsMustOutliveDB>,
    /// The TTL this DB was opened with, if it was opened with one.
    ///
    /// Two things need it. `create_cf_with_ttl` reaches a C function that casts the
    /// handle to `DBWithTTL` without checking, so calling it on any other kind of DB
    /// is undefined behaviour, and nothing in the C API can be asked after the fact.
    /// It is also the TTL that [`ColumnFamilyTtl::SameAsDb`] refers to.
    opened_with_ttl: Option<Duration>,
}

/// Minimal set of DB-related methods, intended to be generic over
/// `DBWithThreadMode<T>`. Mainly used internally
pub trait DBAccess {
    unsafe fn create_snapshot(&self) -> *const ffi::rocksdb_snapshot_t;

    unsafe fn release_snapshot(&self, snapshot: *const ffi::rocksdb_snapshot_t);

    unsafe fn create_iterator(&self, readopts: &ReadOptions) -> *mut ffi::rocksdb_iterator_t;

    unsafe fn create_iterator_cf(
        &self,
        cf_handle: *mut ffi::rocksdb_column_family_handle_t,
        readopts: &ReadOptions,
    ) -> *mut ffi::rocksdb_iterator_t;

    fn get_opt<K: AsRef<[u8]>>(
        &self,
        key: K,
        readopts: &ReadOptions,
    ) -> Result<Option<Vec<u8>>, Error>;

    fn get_cf_opt<K: AsRef<[u8]>>(
        &self,
        cf: &impl AsColumnFamilyRef,
        key: K,
        readopts: &ReadOptions,
    ) -> Result<Option<Vec<u8>>, Error>;

    fn get_pinned_opt<K: AsRef<[u8]>>(
        &'_ self,
        key: K,
        readopts: &ReadOptions,
    ) -> Result<Option<DBPinnableSlice<'_>>, Error>;

    fn get_pinned_cf_opt<K: AsRef<[u8]>>(
        &'_ self,
        cf: &impl AsColumnFamilyRef,
        key: K,
        readopts: &ReadOptions,
    ) -> Result<Option<DBPinnableSlice<'_>>, Error>;

    fn multi_get_opt<K, I>(
        &self,
        keys: I,
        readopts: &ReadOptions,
    ) -> Vec<Result<Option<Vec<u8>>, Error>>
    where
        K: AsRef<[u8]>,
        I: IntoIterator<Item = K>;

    fn multi_get_cf_opt<'b, K, I, W>(
        &self,
        keys_cf: I,
        readopts: &ReadOptions,
    ) -> Vec<Result<Option<Vec<u8>>, Error>>
    where
        K: AsRef<[u8]>,
        I: IntoIterator<Item = (&'b W, K)>,
        W: AsColumnFamilyRef + 'b;
}

impl<T: ThreadMode, D: DBInner> DBAccess for DBCommon<T, D> {
    unsafe fn create_snapshot(&self) -> *const ffi::rocksdb_snapshot_t {
        unsafe { ffi::rocksdb_create_snapshot(self.inner.inner()) }
    }

    unsafe fn release_snapshot(&self, snapshot: *const ffi::rocksdb_snapshot_t) {
        unsafe {
            ffi::rocksdb_release_snapshot(self.inner.inner(), snapshot);
        }
    }

    unsafe fn create_iterator(&self, readopts: &ReadOptions) -> *mut ffi::rocksdb_iterator_t {
        unsafe { ffi::rocksdb_create_iterator(self.inner.inner(), readopts.inner) }
    }

    unsafe fn create_iterator_cf(
        &self,
        cf_handle: *mut ffi::rocksdb_column_family_handle_t,
        readopts: &ReadOptions,
    ) -> *mut ffi::rocksdb_iterator_t {
        unsafe { ffi::rocksdb_create_iterator_cf(self.inner.inner(), readopts.inner, cf_handle) }
    }

    fn get_opt<K: AsRef<[u8]>>(
        &self,
        key: K,
        readopts: &ReadOptions,
    ) -> Result<Option<Vec<u8>>, Error> {
        self.get_opt(key, readopts)
    }

    fn get_cf_opt<K: AsRef<[u8]>>(
        &self,
        cf: &impl AsColumnFamilyRef,
        key: K,
        readopts: &ReadOptions,
    ) -> Result<Option<Vec<u8>>, Error> {
        self.get_cf_opt(cf, key, readopts)
    }

    fn get_pinned_opt<K: AsRef<[u8]>>(
        &'_ self,
        key: K,
        readopts: &ReadOptions,
    ) -> Result<Option<DBPinnableSlice<'_>>, Error> {
        self.get_pinned_opt(key, readopts)
    }

    fn get_pinned_cf_opt<K: AsRef<[u8]>>(
        &'_ self,
        cf: &impl AsColumnFamilyRef,
        key: K,
        readopts: &ReadOptions,
    ) -> Result<Option<DBPinnableSlice<'_>>, Error> {
        self.get_pinned_cf_opt(cf, key, readopts)
    }

    fn multi_get_opt<K, Iter>(
        &self,
        keys: Iter,
        readopts: &ReadOptions,
    ) -> Vec<Result<Option<Vec<u8>>, Error>>
    where
        K: AsRef<[u8]>,
        Iter: IntoIterator<Item = K>,
    {
        self.multi_get_opt(keys, readopts)
    }

    fn multi_get_cf_opt<'b, K, Iter, W>(
        &self,
        keys_cf: Iter,
        readopts: &ReadOptions,
    ) -> Vec<Result<Option<Vec<u8>>, Error>>
    where
        K: AsRef<[u8]>,
        Iter: IntoIterator<Item = (&'b W, K)>,
        W: AsColumnFamilyRef + 'b,
    {
        self.multi_get_cf_opt(keys_cf, readopts)
    }
}

pub struct DBWithThreadModeInner {
    inner: *mut ffi::rocksdb_t,
}

struct OwnedColumnFamilyHandle {
    inner: *mut ffi::rocksdb_column_family_handle_t,
}

struct PinnedMultiGetOutput {
    values: Vec<*mut ffi::rocksdb_pinnableslice_t>,
    errors: Vec<*mut c_char>,
}

/// The result of one `rocksdb_create_iterators` call: the iterator handles
/// plus the single `ReadOptions` they were all created from, which each
/// iterator must keep alive.
struct CreatedIterators {
    readopts: Arc<ReadOptions>,
    handles: Vec<*mut ffi::rocksdb_iterator_t>,
}

impl OwnedColumnFamilyHandle {
    fn default_for(db: *mut ffi::rocksdb_t) -> Self {
        Self {
            inner: unsafe { ffi::rocksdb_get_default_column_family_handle(db) },
        }
    }
}

impl Drop for OwnedColumnFamilyHandle {
    fn drop(&mut self) {
        unsafe {
            ffi::rocksdb_column_family_handle_destroy(self.inner);
        }
    }
}

impl DBInner for DBWithThreadModeInner {
    #[inline]
    fn inner(&self) -> *mut ffi::rocksdb_t {
        self.inner
    }
}

impl Drop for DBWithThreadModeInner {
    fn drop(&mut self) {
        unsafe {
            ffi::rocksdb_close(self.inner);
        }
    }
}

/// A type alias to RocksDB database.
///
/// See crate level documentation for a simple usage example.
/// See [`DBCommon`] for full list of methods.
pub type DBWithThreadMode<T> = DBCommon<T, DBWithThreadModeInner>;

/// A type alias to DB instance type with the single-threaded column family
/// creations/deletions
///
/// # Compatibility and multi-threaded mode
///
/// Previously, [`DB`] was defined as a direct `struct`. Now, it's type-aliased for
/// compatibility. Use `DBCommon<MultiThreaded>` for multi-threaded
/// column family alternations.
///
/// # Limited performance implication for single-threaded mode
///
/// Even with [`SingleThreaded`], almost all of RocksDB operations is
/// multi-threaded unless the underlying RocksDB instance is
/// specifically configured otherwise. `SingleThreaded` only forces
/// serialization of column family alternations by requiring `&mut self` of DB
/// instance due to its wrapper implementation details.
///
/// # Multi-threaded mode
///
/// [`MultiThreaded`] can be appropriate for the situation of multi-threaded
/// workload including multi-threaded column family alternations, costing the
/// RwLock overhead inside `DB`.
#[cfg(not(feature = "multi-threaded-cf"))]
pub type DB = DBWithThreadMode<SingleThreaded>;

#[cfg(feature = "multi-threaded-cf")]
pub type DB = DBWithThreadMode<MultiThreaded>;

// Safety note: auto-implementing Send on most db-related types is prevented by the inner FFI
// pointer. In most cases, however, this pointer is Send-safe because it is never aliased and
// rocksdb internally does not rely on thread-local information for its user-exposed types.
unsafe impl<T: ThreadMode + Send, I: DBInner> Send for DBCommon<T, I> {}

// Sync is similarly safe for many types because they do not expose interior mutability, and their
// use within the rocksdb library is generally behind a const reference
unsafe impl<T: ThreadMode, I: DBInner> Sync for DBCommon<T, I> {}

// Specifies whether open DB for read only.
enum AccessType<'a> {
    ReadWrite,
    ReadOnly { error_if_log_file_exist: bool },
    Secondary { secondary_path: &'a Path },
    WithTTL { ttl: Duration },
    TrimHistory { trim_ts: &'a [u8] },
}

/// Methods of `DBWithThreadMode`.
impl<T: ThreadMode> DBWithThreadMode<T> {
    /// Opens a database with default options.
    pub fn open_default<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
        let mut opts = Options::default();
        opts.create_if_missing(true);
        Self::open(&opts, path)
    }

    /// Opens the database with the specified options.
    pub fn open<P: AsRef<Path>>(opts: &Options, path: P) -> Result<Self, Error> {
        Self::open_cf(opts, path, None::<&str>)
    }

    /// Opens the database for read only with the specified options.
    pub fn open_for_read_only<P: AsRef<Path>>(
        opts: &Options,
        path: P,
        error_if_log_file_exist: bool,
    ) -> Result<Self, Error> {
        Self::open_cf_for_read_only(opts, path, None::<&str>, error_if_log_file_exist)
    }

    /// Opens the database as a secondary.
    pub fn open_as_secondary<P: AsRef<Path>>(
        opts: &Options,
        primary_path: P,
        secondary_path: P,
    ) -> Result<Self, Error> {
        Self::open_cf_as_secondary(opts, primary_path, secondary_path, None::<&str>)
    }

    /// Opens the database with a Time to Live compaction filter.
    ///
    /// This applies the given `ttl` to all column families created without an explicit TTL.
    /// See [`DB::open_cf_descriptors_with_ttl`] for more control over individual column family TTLs.
    ///
    /// RocksDB stores the TTL as a 32-bit second count, so a `ttl` longer than
    /// `i32::MAX` seconds (about 68 years) is clamped to that maximum rather
    /// than wrapping.
    pub fn open_with_ttl<P: AsRef<Path>>(
        opts: &Options,
        path: P,
        ttl: Duration,
    ) -> Result<Self, Error> {
        Self::open_cf_descriptors_with_ttl(opts, path, std::iter::empty(), ttl)
    }

    /// Opens the database with a Time to Live compaction filter and column family names.
    ///
    /// Column families opened using this function will be created with default `Options`.
    pub fn open_cf_with_ttl<P, I, N>(
        opts: &Options,
        path: P,
        cfs: I,
        ttl: Duration,
    ) -> Result<Self, Error>
    where
        P: AsRef<Path>,
        I: IntoIterator<Item = N>,
        N: AsRef<str>,
    {
        let cfs = cfs
            .into_iter()
            .map(|name| ColumnFamilyDescriptor::new(name.as_ref(), Options::default()));

        Self::open_cf_descriptors_with_ttl(opts, path, cfs, ttl)
    }

    /// Opens a database with the given database with a Time to Live compaction filter and
    /// column family descriptors.
    ///
    /// Applies the provided `ttl` as the default TTL for all column families.
    /// Column families will inherit this TTL by default, unless their descriptor explicitly
    /// sets a different TTL using [`ColumnFamilyTtl::Duration`] or opts out using [`ColumnFamilyTtl::Disabled`].
    ///
    /// *NOTE*: The `default` column family is opened with `Options::default()` unless
    /// explicitly configured within the `cfs` iterator.
    /// To customize the `default` column family's options, include a `ColumnFamilyDescriptor`
    /// with the name "default" in the `cfs` iterator.
    ///
    /// If you want to open `default` cf with different options, set them explicitly in `cfs`.
    pub fn open_cf_descriptors_with_ttl<P, I>(
        opts: &Options,
        path: P,
        cfs: I,
        ttl: Duration,
    ) -> Result<Self, Error>
    where
        P: AsRef<Path>,
        I: IntoIterator<Item = ColumnFamilyDescriptor>,
    {
        Self::open_cf_descriptors_internal(opts, path, cfs, &AccessType::WithTTL { ttl })
    }

    /// Opens the database and drops everything written after `trim_ts`.
    ///
    /// Column families opened using this function will be created with default
    /// `Options`. See [`open_cf_descriptors_and_trim_history`][Self::open_cf_descriptors_and_trim_history].
    ///
    /// # Errors
    ///
    /// See [`open_cf_descriptors_and_trim_history`][Self::open_cf_descriptors_and_trim_history].
    pub fn open_cf_and_trim_history<P, I, N>(
        opts: &Options,
        path: P,
        cfs: I,
        trim_ts: &[u8],
    ) -> Result<Self, Error>
    where
        P: AsRef<Path>,
        I: IntoIterator<Item = N>,
        N: AsRef<str>,
    {
        let cfs = cfs
            .into_iter()
            .map(|name| ColumnFamilyDescriptor::new(name.as_ref(), Options::default()));

        Self::open_cf_descriptors_and_trim_history(opts, path, cfs, trim_ts)
    }

    /// Opens the database and drops everything written after `trim_ts`, given column
    /// family descriptors.
    ///
    /// This is for recovering a column family that uses user-defined timestamps, where
    /// writes past a known good point have to be undone before anything reads them.
    /// Entries with a timestamp greater than `trim_ts` are gone once this returns.
    /// `trim_ts` is compared with the column family's comparator, so it has to be
    /// encoded the way that comparator expects. Column families without user-defined
    /// timestamps are left alone.
    ///
    /// The trim is permanent, so open a copy first if the discarded writes still
    /// matter.
    ///
    /// RocksDB marks the underlying API experimental and subject to change.
    ///
    /// *NOTE*: The `default` column family is opened with `Options::default()` unless
    /// explicitly configured within the `cfs` iterator. A column family that uses
    /// user-defined timestamps carries its comparator in its own options, so it has to
    /// be named here with those options even when it is the default one. Opening it
    /// with `Options::default()` instead fails with a comparator mismatch.
    ///
    /// # Errors
    ///
    /// Returns the RocksDB error if the database cannot be opened, which includes
    /// leaving out a column family that exists on disk. Also errors if a column family
    /// name contains an interior NUL byte, or if the directory cannot be created.
    pub fn open_cf_descriptors_and_trim_history<P, I>(
        opts: &Options,
        path: P,
        cfs: I,
        trim_ts: &[u8],
    ) -> Result<Self, Error>
    where
        P: AsRef<Path>,
        I: IntoIterator<Item = ColumnFamilyDescriptor>,
    {
        // The C function only takes the column family form, so make sure the open goes
        // down that path even when the caller named no families.
        let mut cfs: Vec<ColumnFamilyDescriptor> = cfs.into_iter().collect();
        if cfs.is_empty() {
            cfs.push(ColumnFamilyDescriptor::new(
                DEFAULT_COLUMN_FAMILY_NAME,
                Options::default(),
            ));
        }

        Self::open_cf_descriptors_internal(opts, path, cfs, &AccessType::TrimHistory { trim_ts })
    }

    /// Opens a database with the given database options and column family names.
    ///
    /// Column families opened using this function will be created with default `Options`.
    pub fn open_cf<P, I, N>(opts: &Options, path: P, cfs: I) -> Result<Self, Error>
    where
        P: AsRef<Path>,
        I: IntoIterator<Item = N>,
        N: AsRef<str>,
    {
        let cfs = cfs
            .into_iter()
            .map(|name| ColumnFamilyDescriptor::new(name.as_ref(), Options::default()));

        Self::open_cf_descriptors_internal(opts, path, cfs, &AccessType::ReadWrite)
    }

    /// Opens a database with the given database options and column family names.
    ///
    /// Column families opened using given `Options`.
    pub fn open_cf_with_opts<P, I, N>(opts: &Options, path: P, cfs: I) -> Result<Self, Error>
    where
        P: AsRef<Path>,
        I: IntoIterator<Item = (N, Options)>,
        N: AsRef<str>,
    {
        let cfs = cfs
            .into_iter()
            .map(|(name, opts)| ColumnFamilyDescriptor::new(name.as_ref(), opts));

        Self::open_cf_descriptors(opts, path, cfs)
    }

    /// Opens a database for read only with the given database options and column family names.
    /// *NOTE*: `default` column family is opened with `Options::default()`.
    /// If you want to open `default` cf with different options, set them explicitly in `cfs`.
    pub fn open_cf_for_read_only<P, I, N>(
        opts: &Options,
        path: P,
        cfs: I,
        error_if_log_file_exist: bool,
    ) -> Result<Self, Error>
    where
        P: AsRef<Path>,
        I: IntoIterator<Item = N>,
        N: AsRef<str>,
    {
        let cfs = cfs
            .into_iter()
            .map(|name| ColumnFamilyDescriptor::new(name.as_ref(), Options::default()));

        Self::open_cf_descriptors_internal(
            opts,
            path,
            cfs,
            &AccessType::ReadOnly {
                error_if_log_file_exist,
            },
        )
    }

    /// Opens a database for read only with the given database options and column family names.
    /// *NOTE*: `default` column family is opened with `Options::default()`.
    /// If you want to open `default` cf with different options, set them explicitly in `cfs`.
    pub fn open_cf_with_opts_for_read_only<P, I, N>(
        db_opts: &Options,
        path: P,
        cfs: I,
        error_if_log_file_exist: bool,
    ) -> Result<Self, Error>
    where
        P: AsRef<Path>,
        I: IntoIterator<Item = (N, Options)>,
        N: AsRef<str>,
    {
        let cfs = cfs
            .into_iter()
            .map(|(name, cf_opts)| ColumnFamilyDescriptor::new(name.as_ref(), cf_opts));

        Self::open_cf_descriptors_internal(
            db_opts,
            path,
            cfs,
            &AccessType::ReadOnly {
                error_if_log_file_exist,
            },
        )
    }

    /// Opens a database for ready only with the given database options and
    /// column family descriptors.
    /// *NOTE*: `default` column family is opened with `Options::default()`.
    /// If you want to open `default` cf with different options, set them explicitly in `cfs`.
    pub fn open_cf_descriptors_read_only<P, I>(
        opts: &Options,
        path: P,
        cfs: I,
        error_if_log_file_exist: bool,
    ) -> Result<Self, Error>
    where
        P: AsRef<Path>,
        I: IntoIterator<Item = ColumnFamilyDescriptor>,
    {
        Self::open_cf_descriptors_internal(
            opts,
            path,
            cfs,
            &AccessType::ReadOnly {
                error_if_log_file_exist,
            },
        )
    }

    /// Opens the database as a secondary with the given database options and column family names.
    /// *NOTE*: `default` column family is opened with `Options::default()`.
    /// If you want to open `default` cf with different options, set them explicitly in `cfs`.
    pub fn open_cf_as_secondary<P, I, N>(
        opts: &Options,
        primary_path: P,
        secondary_path: P,
        cfs: I,
    ) -> Result<Self, Error>
    where
        P: AsRef<Path>,
        I: IntoIterator<Item = N>,
        N: AsRef<str>,
    {
        let cfs = cfs
            .into_iter()
            .map(|name| ColumnFamilyDescriptor::new(name.as_ref(), Options::default()));

        Self::open_cf_descriptors_internal(
            opts,
            primary_path,
            cfs,
            &AccessType::Secondary {
                secondary_path: secondary_path.as_ref(),
            },
        )
    }

    /// Opens the database as a secondary with the given database options and
    /// column family descriptors.
    /// *NOTE*: `default` column family is opened with `Options::default()`.
    /// If you want to open `default` cf with different options, set them explicitly in `cfs`.
    pub fn open_cf_descriptors_as_secondary<P, I>(
        opts: &Options,
        path: P,
        secondary_path: P,
        cfs: I,
    ) -> Result<Self, Error>
    where
        P: AsRef<Path>,
        I: IntoIterator<Item = ColumnFamilyDescriptor>,
    {
        Self::open_cf_descriptors_internal(
            opts,
            path,
            cfs,
            &AccessType::Secondary {
                secondary_path: secondary_path.as_ref(),
            },
        )
    }

    /// Opens a database with the given database options and column family descriptors.
    /// *NOTE*: `default` column family is opened with `Options::default()`.
    /// If you want to open `default` cf with different options, set them explicitly in `cfs`.
    pub fn open_cf_descriptors<P, I>(opts: &Options, path: P, cfs: I) -> Result<Self, Error>
    where
        P: AsRef<Path>,
        I: IntoIterator<Item = ColumnFamilyDescriptor>,
    {
        Self::open_cf_descriptors_internal(opts, path, cfs, &AccessType::ReadWrite)
    }

    /// Internal implementation for opening RocksDB.
    fn open_cf_descriptors_internal<P, I>(
        opts: &Options,
        path: P,
        cfs: I,
        access_type: &AccessType,
    ) -> Result<Self, Error>
    where
        P: AsRef<Path>,
        I: IntoIterator<Item = ColumnFamilyDescriptor>,
    {
        let cfs: Vec<_> = cfs.into_iter().collect();
        let outlive = iter::once(opts.outlive.clone())
            .chain(cfs.iter().map(|cf| cf.options.outlive.clone()))
            .collect();

        let cpath = to_cpath(&path)?;

        if let Err(e) = fs::create_dir_all(&path) {
            return Err(Error::new(format!(
                "Failed to create RocksDB directory: `{e:?}`."
            )));
        }

        let db: *mut ffi::rocksdb_t;
        let mut cf_map = BTreeMap::new();

        if cfs.is_empty() {
            db = Self::open_raw(opts, &cpath, access_type)?;
        } else {
            let mut cfs_v = cfs;
            // Always open the default column family.
            if !cfs_v.iter().any(|cf| cf.name == DEFAULT_COLUMN_FAMILY_NAME) {
                cfs_v.push(ColumnFamilyDescriptor {
                    name: String::from(DEFAULT_COLUMN_FAMILY_NAME),
                    options: Options::default(),
                    ttl: ColumnFamilyTtl::SameAsDb,
                });
            }
            // We need to store our CStrings in an intermediate vector
            // so that their pointers remain valid.
            let c_cfs: Vec<CString> = cfs_v
                .iter()
                .map(|cf| CString::new(cf.name.as_bytes()).unwrap())
                .collect();

            let cfnames: Vec<_> = c_cfs.iter().map(|cf| cf.as_ptr()).collect();

            // These handles will be populated by DB.
            let mut cfhandles: Vec<_> = cfs_v.iter().map(|_| ptr::null_mut()).collect();

            let cfopts: Vec<_> = cfs_v
                .iter()
                .map(|cf| cf.options.inner.cast_const())
                .collect();

            db = Self::open_cf_raw(
                opts,
                &cpath,
                &cfs_v,
                &cfnames,
                &cfopts,
                &mut cfhandles,
                access_type,
            )?;
            for handle in &cfhandles {
                if handle.is_null() {
                    return Err(Error::new(
                        "Received null column family handle from DB.".to_owned(),
                    ));
                }
            }

            for (cf_desc, inner) in cfs_v.iter().zip(cfhandles) {
                cf_map.insert(cf_desc.name.clone(), inner);
            }
        }

        if db.is_null() {
            return Err(Error::new("Could not initialize database.".to_owned()));
        }

        Ok(Self {
            inner: DBWithThreadModeInner { inner: db },
            path: path.as_ref().to_path_buf(),
            cfs: T::new_cf_map_internal(cf_map),
            _outlive: outlive,
            opened_with_ttl: match access_type {
                AccessType::WithTTL { ttl } => Some(*ttl),
                _ => None,
            },
        })
    }

    fn open_raw(
        opts: &Options,
        cpath: &CString,
        access_type: &AccessType,
    ) -> Result<*mut ffi::rocksdb_t, Error> {
        let db = unsafe {
            match *access_type {
                AccessType::ReadOnly {
                    error_if_log_file_exist,
                } => ffi_try!(ffi::rocksdb_open_for_read_only(
                    opts.inner,
                    cpath.as_ptr(),
                    c_uchar::from(error_if_log_file_exist),
                )),
                AccessType::ReadWrite => {
                    ffi_try!(ffi::rocksdb_open(opts.inner, cpath.as_ptr()))
                }
                AccessType::TrimHistory { .. } => {
                    // open_cf_descriptors_and_trim_history always names at least the
                    // default column family, so this path is not reached.
                    return Err(Error::new(
                        "Trimming history requires opening with column families".to_owned(),
                    ));
                }
                AccessType::Secondary { secondary_path } => {
                    ffi_try!(ffi::rocksdb_open_as_secondary(
                        opts.inner,
                        cpath.as_ptr(),
                        to_cpath(secondary_path)?.as_ptr(),
                    ))
                }
                AccessType::WithTTL { ttl } => ffi_try!(ffi::rocksdb_open_with_ttl(
                    opts.inner,
                    cpath.as_ptr(),
                    ttl_to_seconds(ttl),
                )),
            }
        };
        Ok(db)
    }

    #[allow(clippy::pedantic)]
    fn open_cf_raw(
        opts: &Options,
        cpath: &CString,
        cfs_v: &[ColumnFamilyDescriptor],
        cfnames: &[*const c_char],
        cfopts: &[*const ffi::rocksdb_options_t],
        cfhandles: &mut [*mut ffi::rocksdb_column_family_handle_t],
        access_type: &AccessType,
    ) -> Result<*mut ffi::rocksdb_t, Error> {
        let db = unsafe {
            match *access_type {
                AccessType::ReadOnly {
                    error_if_log_file_exist,
                } => ffi_try!(ffi::rocksdb_open_for_read_only_column_families(
                    opts.inner,
                    cpath.as_ptr(),
                    cfs_v.len() as c_int,
                    cfnames.as_ptr(),
                    cfopts.as_ptr(),
                    cfhandles.as_mut_ptr(),
                    c_uchar::from(error_if_log_file_exist),
                )),
                AccessType::ReadWrite => ffi_try!(ffi::rocksdb_open_column_families(
                    opts.inner,
                    cpath.as_ptr(),
                    cfs_v.len() as c_int,
                    cfnames.as_ptr(),
                    cfopts.as_ptr(),
                    cfhandles.as_mut_ptr(),
                )),
                AccessType::Secondary { secondary_path } => {
                    ffi_try!(ffi::rocksdb_open_as_secondary_column_families(
                        opts.inner,
                        cpath.as_ptr(),
                        to_cpath(secondary_path)?.as_ptr(),
                        cfs_v.len() as c_int,
                        cfnames.as_ptr(),
                        cfopts.as_ptr(),
                        cfhandles.as_mut_ptr(),
                    ))
                }
                AccessType::WithTTL { ttl } => {
                    let ttls: Vec<_> = cfs_v
                        .iter()
                        .map(|cf| cf_ttl_to_seconds(cf.ttl, ttl))
                        .collect();

                    ffi_try!(ffi::rocksdb_open_column_families_with_ttl(
                        opts.inner,
                        cpath.as_ptr(),
                        cfs_v.len() as c_int,
                        cfnames.as_ptr(),
                        cfopts.as_ptr(),
                        cfhandles.as_mut_ptr(),
                        ttls.as_ptr(),
                    ))
                }
                AccessType::TrimHistory { trim_ts } => {
                    // The C function copies the timestamp into a std::string before
                    // doing anything with it, so this only has to stay alive across
                    // the call. It takes a non-const pointer without writing through
                    // it, hence the local copy rather than casting the borrow.
                    let mut trim_ts = trim_ts.to_vec();
                    ffi_try!(ffi::rocksdb_open_and_trim_history(
                        opts.inner,
                        cpath.as_ptr(),
                        cfs_v.len() as c_int,
                        cfnames.as_ptr(),
                        cfopts.as_ptr(),
                        cfhandles.as_mut_ptr(),
                        trim_ts.as_mut_ptr().cast::<c_char>(),
                        trim_ts.len(),
                    ))
                }
            }
        };
        Ok(db)
    }

    /// Removes the database entries in the range `["from", "to")` using given write options.
    pub fn delete_range_cf_opt<K: AsRef<[u8]>>(
        &self,
        cf: &impl AsColumnFamilyRef,
        from: K,
        to: K,
        writeopts: &WriteOptions,
    ) -> Result<(), Error> {
        let from = from.as_ref();
        let to = to.as_ref();

        unsafe {
            ffi_try!(ffi::rocksdb_delete_range_cf(
                self.inner.inner(),
                writeopts.inner,
                cf.inner(),
                from.as_ptr() as *const c_char,
                from.len() as size_t,
                to.as_ptr() as *const c_char,
                to.len() as size_t,
            ));
            Ok(())
        }
    }

    /// Removes the database entries in the range `["from", "to")` using default write options.
    pub fn delete_range_cf<K: AsRef<[u8]>>(
        &self,
        cf: &impl AsColumnFamilyRef,
        from: K,
        to: K,
    ) -> Result<(), Error> {
        DEFAULT_WRITE_OPTS.with(|opts| self.delete_range_cf_opt(cf, from, to, opts))
    }

    pub fn write_opt(&self, batch: &WriteBatch, writeopts: &WriteOptions) -> Result<(), Error> {
        unsafe {
            ffi_try!(ffi::rocksdb_write(
                self.inner.inner(),
                writeopts.inner,
                batch.inner
            ));
        }
        Ok(())
    }

    pub fn write(&self, batch: &WriteBatch) -> Result<(), Error> {
        DEFAULT_WRITE_OPTS.with(|opts| self.write_opt(batch, opts))
    }

    pub fn write_without_wal(&self, batch: &WriteBatch) -> Result<(), Error> {
        let mut wo = WriteOptions::new();
        wo.disable_wal(true);
        self.write_opt(batch, &wo)
    }

    pub fn write_wbwi(&self, wbwi: &WriteBatchWithIndex) -> Result<(), Error> {
        DEFAULT_WRITE_OPTS.with(|opts| self.write_wbwi_opt(wbwi, opts))
    }

    pub fn write_wbwi_opt(
        &self,
        wbwi: &WriteBatchWithIndex,
        writeopts: &WriteOptions,
    ) -> Result<(), Error> {
        unsafe {
            ffi_try!(ffi::rocksdb_write_writebatch_wi(
                self.inner.inner(),
                writeopts.inner,
                wbwi.inner
            ));

            Ok(())
        }
    }
}

/// A value read from a DB with user-defined timestamps, and the timestamp it carries.
///
/// Both halves are RocksDB allocations this owns, freed on drop. Read them as bytes
/// through `AsRef<[u8]>`.
///
/// The timestamp is the raw bytes RocksDB stored, in whatever width and encoding the
/// column family's comparator defines, so it is only meaningful to code that knows
/// that comparator. RocksDB's own `comparator_with_u64_ts` uses a little endian
/// `u64`.
pub struct TimestampedValue {
    /// The value stored under the key.
    pub value: CSlice,
    /// The timestamp the value was written with.
    pub timestamp: CSlice,
}

impl fmt::Debug for TimestampedValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TimestampedValue")
            .field("value", &self.value.as_ref().len())
            .field("timestamp", &self.timestamp.as_ref())
            .finish()
    }
}

/// What one `rocksdb_create_column_families` call managed to create.
///
/// The call is not atomic, so it can commit some families and then fail. Both
/// fields can be non-empty at once, and the handles have to be recorded even when
/// there is an error.
struct CreatedCfHandles {
    /// Owned handles for the families that were created, in the order the names
    /// were given. Each one needs `rocksdb_column_family_handle_destroy`.
    handles: Vec<*mut ffi::rocksdb_column_family_handle_t>,
    /// Why the remaining families were not created.
    error: Option<Error>,
}

impl CreatedCfHandles {
    /// Nothing was created, because the call never got as far as RocksDB.
    fn failed(error: Error) -> Self {
        Self {
            handles: Vec::new(),
            error: Some(error),
        }
    }
}

/// What a [`DBCommon::compact_files`] call produced.
pub struct CompactFilesResult {
    /// The SST files the compaction wrote, as RocksDB names them.
    ///
    /// Empty when the compaction had nothing to write, for instance when every
    /// input key was deleted.
    pub output_files: Vec<String>,
    /// Statistics and file lists for the compaction that just ran.
    ///
    /// `None` when [`CompactionOptions::set_allow_trivial_move`] is enabled.
    /// RocksDB can then satisfy the request by moving files between levels
    /// instead of rewriting them, and that path returns success without
    /// reporting anything about the work it did. Nothing distinguishes it from
    /// the rewriting path afterwards, so the statistics are not collected at all
    /// rather than sometimes being made up.
    ///
    /// [`CompactionOptions::set_allow_trivial_move`]:
    ///     crate::compaction::CompactionOptions::set_allow_trivial_move
    pub job_info: Option<OwnedCompactionJobInfo>,
}

impl fmt::Debug for CompactFilesResult {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CompactFilesResult")
            .field("output_files", &self.output_files)
            .field("job_info", &self.job_info)
            .finish()
    }
}

/// Splits an optional key into the pointer and length a RocksDB range bound wants.
///
/// A `None` bound becomes a null pointer, which RocksDB reads as unbounded. This is
/// why the bound is `Option<&T>` rather than `&[u8]`: an empty slice has a non-null
/// pointer and means the empty key, which is a different request.
fn optional_key_parts<T: AsRef<[u8]> + ?Sized>(key: Option<&T>) -> (*const c_char, usize) {
    (opt_bytes_to_ptr(key), key.map_or(0, |k| k.as_ref().len()))
}

/// Reads a `char**` array RocksDB allocated into owned `String`s and frees it.
///
/// The strings are read without freeing them individually because
/// `rocksdb_compact_files_output_file_names_destroy` frees the whole array,
/// entries included.
///
/// # Safety
///
/// `names` must be null, or an array of `count` NUL-terminated strings allocated
/// by `rocksdb_compact_files`, which nothing else will free.
unsafe fn collect_and_free_output_names(names: *mut *mut c_char, count: usize) -> Vec<String> {
    if names.is_null() || count == 0 {
        return Vec::new();
    }
    let collected = (0..count)
        .map(|i| unsafe { from_cstr_without_free(*names.add(i)) })
        .collect();
    unsafe { ffi::rocksdb_compact_files_output_file_names_destroy(names, count) };
    collected
}

/// The pointer arrays the `rocksdb_approximate_sizes*` family takes, kept in one
/// place because all five variants want the same six arguments.
///
/// The key pointers borrow from the `Range` slice, so this must not outlive it.
struct ApproximateSizesArgs {
    count: c_int,
    start_keys: Vec<*const c_char>,
    start_key_lens: Vec<usize>,
    end_keys: Vec<*const c_char>,
    end_key_lens: Vec<usize>,
    sizes: Vec<u64>,
}

impl ApproximateSizesArgs {
    fn new(ranges: &[Range]) -> Self {
        Self {
            count: c_int::try_from(ranges.len()).unwrap_or(c_int::MAX),
            start_keys: ranges
                .iter()
                .map(|x| x.start_key.as_ptr().cast::<c_char>())
                .collect(),
            start_key_lens: ranges.iter().map(|x| x.start_key.len()).collect(),
            end_keys: ranges
                .iter()
                .map(|x| x.end_key.as_ptr().cast::<c_char>())
                .collect(),
            end_key_lens: ranges.iter().map(|x| x.end_key.len()).collect(),
            sizes: vec![0; ranges.len()],
        }
    }

    /// Turns the `errptr` RocksDB filled in into a `Result`, yielding the sizes
    /// on success.
    ///
    /// RocksDB reports failures here through `errptr`. Ignoring it both leaked
    /// the `strdup`ed message and returned a vector of zeros that the caller
    /// could not distinguish from "these ranges are empty".
    fn finish(&mut self, err: *mut c_char) -> Result<Vec<u64>, Error> {
        if !err.is_null() {
            return Err(convert_rocksdb_error(err));
        }
        Ok(std::mem::take(&mut self.sizes))
    }
}

/// Common methods of `DBWithThreadMode` and `OptimisticTransactionDB`.
impl<T: ThreadMode, D: DBInner> DBCommon<T, D> {
    pub(crate) fn new(inner: D, cfs: T, path: PathBuf, outlive: Vec<OptionsMustOutliveDB>) -> Self {
        Self {
            inner,
            cfs,
            path,
            _outlive: outlive,
            opened_with_ttl: None,
        }
    }

    pub fn list_cf<P: AsRef<Path>>(opts: &Options, path: P) -> Result<Vec<String>, Error> {
        let cpath = to_cpath(path)?;
        let mut length = 0;

        unsafe {
            let ptr = ffi_try!(ffi::rocksdb_list_column_families(
                opts.inner,
                cpath.as_ptr(),
                &raw mut length,
            ));

            let vec = slice::from_raw_parts(ptr, length)
                .iter()
                .map(|ptr| from_cstr_without_free(*ptr))
                .collect();
            ffi::rocksdb_list_column_families_destroy(ptr, length);
            Ok(vec)
        }
    }

    pub fn destroy<P: AsRef<Path>>(opts: &Options, path: P) -> Result<(), Error> {
        let cpath = to_cpath(path)?;
        unsafe {
            ffi_try!(ffi::rocksdb_destroy_db(opts.inner, cpath.as_ptr()));
        }
        Ok(())
    }

    pub fn repair<P: AsRef<Path>>(opts: &Options, path: P) -> Result<(), Error> {
        let cpath = to_cpath(path)?;
        unsafe {
            ffi_try!(ffi::rocksdb_repair_db(opts.inner, cpath.as_ptr()));
        }
        Ok(())
    }

    /// Tries to clear a background error and resume writes.
    ///
    /// Returns `Ok` right away if no background error is stopping writes or
    /// background work. Recovering waits for running flushes and compactions to
    /// finish and then flushes every column family, so this can block for a
    /// while.
    ///
    /// Out of space is the only kind of I/O error this can recover from on the
    /// built-in filesystems: a full disk, or going over
    /// [`SstFileManager::set_max_allowed_space_usage`]. Other I/O errors are
    /// fatal with the default `paranoid_checks` and corruption is unrecoverable,
    /// so for those this returns the error and the DB has to be reopened.
    ///
    /// RocksDB normally recovers from out-of-space errors on its own. Every DB
    /// gets an [`SstFileManager`] even if you don't set one, and it retries
    /// every few seconds until enough space is free. While that is running this
    /// returns [`Busy`]. To recover manually instead, set the `&mut bool` passed
    /// to [`EventListener::on_error_recovery_begin`] to `false`, and only call
    /// this once space has been freed. A recovery flush that fails because the
    /// disk is still full can make the error fatal, and then only reopening
    /// helps.
    ///
    /// [`Options::set_max_bgerror_resume_count`] only applies to errors a
    /// filesystem marks as retryable, and the built-in ones never produce any
    /// that take that path.
    ///
    /// See also <https://github.com/facebook/rocksdb/wiki/Background-Error-Handling>.
    ///
    /// # Errors
    ///
    /// - [`Busy`] if automatic recovery is running. This doesn't wait for it.
    /// - The stored background error if it is fatal or unrecoverable.
    /// - The new error if the recovery flush fails, e.g. the disk is still full.
    ///
    /// [`Busy`]: crate::ErrorKind::Busy
    /// [`SstFileManager`]: crate::SstFileManager
    /// [`SstFileManager::set_max_allowed_space_usage`]: crate::SstFileManager::set_max_allowed_space_usage
    /// [`EventListener::on_error_recovery_begin`]: crate::event_listener::EventListener::on_error_recovery_begin
    pub fn resume(&self) -> Result<(), Error> {
        unsafe {
            ffi_try!(ffi::rust_rocksdb_resume(self.inner.inner()));
        }

        Ok(())
    }

    pub fn path(&self) -> &Path {
        self.path.as_path()
    }

    /// Flushes the WAL buffer. If `sync` is set to `true`, also syncs
    /// the data to disk.
    pub fn flush_wal(&self, sync: bool) -> Result<(), Error> {
        unsafe {
            ffi_try!(ffi::rocksdb_flush_wal(
                self.inner.inner(),
                c_uchar::from(sync)
            ));
        }
        Ok(())
    }

    /// Flushes the WAL buffer, taking the rate limiter priority as well as `sync`.
    ///
    /// [`flush_wal`](Self::flush_wal) covers the common case. Reach for this one to
    /// give the flush a priority other than the default, which decides how the WAL
    /// write is charged against a configured rate limiter.
    ///
    /// # Errors
    ///
    /// Returns the RocksDB error if the flush or the sync fails.
    pub fn flush_wal_with_options(&self, opts: &FlushWalOptions) -> Result<(), Error> {
        unsafe {
            ffi_try!(ffi::rocksdb_flush_wal_with_options(
                self.inner.inner(),
                opts.as_ptr()
            ));
        }
        Ok(())
    }

    /// Stops background flushes and compactions and waits for the ones already
    /// running to finish.
    ///
    /// Writes are not blocked, so they keep filling memtables that cannot be
    /// flushed. Enough of them and the DB stalls or hits the stop trigger, so pair
    /// this with [`continue_background_work`](Self::continue_background_work) and
    /// keep the gap short.
    ///
    /// Calls nest. Background work resumes once as many `continue` calls have been
    /// made as `pause` calls.
    ///
    /// # Errors
    ///
    /// Returns the RocksDB error if the DB is shutting down.
    pub fn pause_background_work(&self) -> Result<(), Error> {
        unsafe {
            ffi_try!(ffi::rocksdb_pause_background_work(self.inner.inner()));
        }
        Ok(())
    }

    /// Undoes one [`pause_background_work`](Self::pause_background_work) call.
    ///
    /// # Errors
    ///
    /// Returns the RocksDB error if background work was not paused, or if the DB is
    /// shutting down.
    pub fn continue_background_work(&self) -> Result<(), Error> {
        unsafe {
            ffi_try!(ffi::rocksdb_continue_background_work(self.inner.inner()));
        }
        Ok(())
    }

    /// Undoes one [`disable_manual_compaction`](Self::disable_manual_compaction) call.
    ///
    /// This is a counter, so it takes as many calls here as there were calls there
    /// before manual compactions start running again.
    ///
    /// Pair the two. RocksDB decrements without a floor, and the assertion that would
    /// catch it is compiled out of this build, so calling this more often than
    /// `disable_manual_compaction` drives the counter below zero. That reads as
    /// not paused, which looks fine, but it means the next
    /// `disable_manual_compaction` only brings the counter back to zero and does not
    /// actually pause anything.
    pub fn enable_manual_compaction(&self) {
        unsafe { ffi::rocksdb_enable_manual_compaction(self.inner.inner()) }
    }

    /// Cancels running manual compactions and makes later ones return immediately.
    ///
    /// Affects only manual compactions, so [`compact_range`](Self::compact_range),
    /// [`compact_files`](Self::compact_files) and the like. Automatic background
    /// compaction keeps going. Use it to get out of a long manual compaction during
    /// shutdown without waiting for it.
    ///
    /// This increments a counter, so it needs a matching
    /// [`enable_manual_compaction`](Self::enable_manual_compaction) call for each
    /// call here.
    pub fn disable_manual_compaction(&self) {
        unsafe { ffi::rocksdb_disable_manual_compaction(self.inner.inner()) }
    }

    /// Reads every live SST and blob file and checks its block checksums.
    ///
    /// Reads the whole DB, so it is as slow as the data is large.
    ///
    /// # Errors
    ///
    /// Returns the RocksDB error naming the first corrupt file found.
    pub fn verify_checksum(&self) -> Result<(), Error> {
        unsafe {
            ffi_try!(ffi::rocksdb_verify_checksum(self.inner.inner()));
        }
        Ok(())
    }

    /// Like [`verify_checksum`](Self::verify_checksum), reading through `readopts`.
    ///
    /// Worth setting when the default read path is not what you want for a full
    /// scan, for instance to keep the verification from filling the block cache or
    /// to give it a rate limiter priority.
    ///
    /// # Errors
    ///
    /// See [`verify_checksum`](Self::verify_checksum).
    pub fn verify_checksum_opt(&self, readopts: &ReadOptions) -> Result<(), Error> {
        unsafe {
            ffi_try!(ffi::rocksdb_verify_checksum_with_options(
                self.inner.inner(),
                readopts.inner
            ));
        }
        Ok(())
    }

    /// Recomputes each live file's whole file checksum and compares it against the
    /// one recorded in the manifest.
    ///
    /// This is the file level check, as opposed to the per block one
    /// [`verify_checksum`](Self::verify_checksum) does. It requires the DB to have
    /// been written with a file checksum generator, see
    /// [`Options::set_file_checksum_gen_factory`](crate::Options::set_file_checksum_gen_factory).
    ///
    /// # Errors
    ///
    /// Returns the RocksDB error naming the first file whose checksum does not match
    /// what the manifest recorded. Also errors when no generator is configured, since
    /// then there is nothing recorded to compare against, rather than treating that
    /// as having nothing to check.
    pub fn verify_file_checksums(&self) -> Result<(), Error> {
        unsafe {
            ffi_try!(ffi::rocksdb_verify_file_checksums(self.inner.inner()));
        }
        Ok(())
    }

    /// Like [`verify_file_checksums`](Self::verify_file_checksums), reading through
    /// `readopts`.
    ///
    /// # Errors
    ///
    /// See [`verify_file_checksums`](Self::verify_file_checksums).
    pub fn verify_file_checksums_opt(&self, readopts: &ReadOptions) -> Result<(), Error> {
        unsafe {
            ffi_try!(ffi::rocksdb_verify_file_checksums_with_options(
                self.inner.inner(),
                readopts.inner
            ));
        }
        Ok(())
    }

    /// Marks the files overlapping `[start, end)` for compaction and returns
    /// without compacting anything.
    ///
    /// Background compaction picks the marked files up on its own schedule, so this
    /// returns as soon as the marking is done. That makes it the cheap way to hint
    /// that a range is worth compacting, as opposed to
    /// [`compact_range`](Self::compact_range), which does the work before it
    /// returns.
    ///
    /// `None` for either bound means unbounded in that direction. An empty slice is
    /// a real empty key, not the same thing.
    ///
    /// # Errors
    ///
    /// Returns the RocksDB error if the range cannot be marked.
    pub fn suggest_compact_range<S: AsRef<[u8]>, E: AsRef<[u8]>>(
        &self,
        start: Option<S>,
        end: Option<E>,
    ) -> Result<(), Error> {
        let (start, start_len) = optional_key_parts(start.as_ref());
        let (end, end_len) = optional_key_parts(end.as_ref());
        unsafe {
            ffi_try!(ffi::rocksdb_suggest_compact_range(
                self.inner.inner(),
                start,
                start_len,
                end,
                end_len
            ));
        }
        Ok(())
    }

    /// Like [`suggest_compact_range`](Self::suggest_compact_range), for a single
    /// column family.
    ///
    /// # Errors
    ///
    /// See [`suggest_compact_range`](Self::suggest_compact_range).
    pub fn suggest_compact_range_cf<S: AsRef<[u8]>, E: AsRef<[u8]>>(
        &self,
        cf: &impl AsColumnFamilyRef,
        start: Option<S>,
        end: Option<E>,
    ) -> Result<(), Error> {
        let (start, start_len) = optional_key_parts(start.as_ref());
        let (end, end_len) = optional_key_parts(end.as_ref());
        unsafe {
            ffi_try!(ffi::rocksdb_suggest_compact_range_cf(
                self.inner.inner(),
                cf.inner(),
                start,
                start_len,
                end,
                end_len
            ));
        }
        Ok(())
    }

    /// Reads a key along with the user-defined timestamp its value was written with.
    ///
    /// Only meaningful on a column family configured for user-defined timestamps, so
    /// one whose comparator carries a timestamp size. The plain
    /// [`get`](Self::get) reads the same value but throws the timestamp away, and
    /// there is no pinned equivalent of this call in the C API.
    ///
    /// `readopts` decides which timestamp is read. Without a read timestamp set on
    /// it RocksDB rejects the read rather than picking one, see
    /// [`ReadOptions::set_timestamp`](crate::ReadOptions::set_timestamp).
    ///
    /// # Errors
    ///
    /// Returns the RocksDB error if the read fails. A key that is not present is
    /// `Ok(None)`, not an error.
    pub fn get_with_ts<K: AsRef<[u8]>>(
        &self,
        key: K,
        readopts: &ReadOptions,
    ) -> Result<Option<TimestampedValue>, Error> {
        let key = key.as_ref();
        self.get_with_ts_impl(readopts, |db, ro, vallen, ts, tslen, err| unsafe {
            ffi::rocksdb_get_with_ts(
                db,
                ro,
                key.as_ptr().cast::<c_char>(),
                key.len(),
                vallen,
                ts,
                tslen,
                err,
            )
        })
    }

    /// Like [`get_with_ts`](Self::get_with_ts), for a single column family.
    ///
    /// # Errors
    ///
    /// See [`get_with_ts`](Self::get_with_ts).
    pub fn get_cf_with_ts<K: AsRef<[u8]>>(
        &self,
        cf: &impl AsColumnFamilyRef,
        key: K,
        readopts: &ReadOptions,
    ) -> Result<Option<TimestampedValue>, Error> {
        let key = key.as_ref();
        let cf = cf.inner();
        self.get_with_ts_impl(readopts, |db, ro, vallen, ts, tslen, err| unsafe {
            ffi::rocksdb_get_cf_with_ts(
                db,
                ro,
                cf,
                key.as_ptr().cast::<c_char>(),
                key.len(),
                vallen,
                ts,
                tslen,
                err,
            )
        })
    }

    /// Shared tail of the two timestamped gets.
    ///
    /// `call` is handed the out-params and returns the value pointer. Note that
    /// RocksDB only writes through `ts` when the read succeeds, so `ts` starts as
    /// null here and a miss leaves it that way rather than leaving it indeterminate
    /// (c.cc:2592-2603).
    fn get_with_ts_impl(
        &self,
        readopts: &ReadOptions,
        call: impl FnOnce(
            *mut ffi::rocksdb_t,
            *const ffi::rocksdb_readoptions_t,
            *mut usize,
            *mut *mut c_char,
            *mut usize,
            *mut *mut c_char,
        ) -> *mut c_char,
    ) -> Result<Option<TimestampedValue>, Error> {
        let mut vallen: usize = 0;
        let mut ts: *mut c_char = ptr::null_mut();
        let mut tslen: usize = 0;
        let mut err: *mut c_char = ptr::null_mut();

        let value = call(
            self.inner.inner(),
            readopts.inner,
            &raw mut vallen,
            &raw mut ts,
            &raw mut tslen,
            &raw mut err,
        );

        if !err.is_null() {
            // RocksDB reports a failure without allocating either output, but free
            // anything it did hand back rather than trusting that on an error path.
            unsafe {
                if !value.is_null() {
                    ffi::rocksdb_free(value.cast::<c_void>());
                }
                if !ts.is_null() {
                    ffi::rocksdb_free(ts.cast::<c_void>());
                }
            }
            return Err(convert_rocksdb_error(err));
        }

        if value.is_null() {
            return Ok(None);
        }

        // SAFETY: both pointers came from RocksDB's `CopyString`, so they are
        // `malloc`ed buffers of the reported length that nothing else frees, which is
        // exactly what `CSlice` takes over.
        unsafe {
            Ok(Some(TimestampedValue {
                value: CSlice::from_raw_parts(value, vallen),
                timestamp: CSlice::from_raw_parts(ts, tslen),
            }))
        }
    }

    /// Reads many keys along with the timestamps their values were written with.
    ///
    /// One native batch, results in input order, one `Result` per key so a single
    /// bad key does not sink the batch. See [`get_with_ts`](Self::get_with_ts) for
    /// what the timestamp means and what `readopts` has to carry.
    pub fn multi_get_with_ts<K, I>(
        &self,
        keys: I,
        readopts: &ReadOptions,
    ) -> Vec<Result<Option<TimestampedValue>, Error>>
    where
        K: AsRef<[u8]>,
        I: IntoIterator<Item = K>,
    {
        let owned_keys: Vec<K> = keys.into_iter().collect();
        let (ptr_keys, keys_sizes) = key_ptrs_and_sizes(&owned_keys);
        let mut out = MultiGetTsOut::with_capacity(ptr_keys.len());

        unsafe {
            ffi::rocksdb_multi_get_with_ts(
                self.inner.inner(),
                readopts.inner,
                ptr_keys.len(),
                ptr_keys.as_ptr(),
                keys_sizes.as_ptr(),
                out.values.as_mut_ptr(),
                out.values_sizes.as_mut_ptr(),
                out.timestamps.as_mut_ptr(),
                out.timestamps_sizes.as_mut_ptr(),
                out.errors.as_mut_ptr(),
            );
            out.assume_filled(ptr_keys.len());
        }

        out.into_results()
    }

    /// Like [`multi_get_with_ts`](Self::multi_get_with_ts), for one column family per
    /// key.
    pub fn multi_get_cf_with_ts<'c, K, I, W>(
        &self,
        keys: I,
        readopts: &ReadOptions,
    ) -> Vec<Result<Option<TimestampedValue>, Error>>
    where
        K: AsRef<[u8]>,
        I: IntoIterator<Item = (&'c W, K)>,
        W: AsColumnFamilyRef + 'c,
    {
        let (cfs, owned_keys): (Vec<_>, Vec<K>) = keys.into_iter().unzip();
        let cf_ptrs: Vec<*const ffi::rocksdb_column_family_handle_t> =
            cfs.iter().map(|cf| cf.inner().cast_const()).collect();
        let (ptr_keys, keys_sizes) = key_ptrs_and_sizes(&owned_keys);
        let mut out = MultiGetTsOut::with_capacity(ptr_keys.len());

        unsafe {
            ffi::rocksdb_multi_get_cf_with_ts(
                self.inner.inner(),
                readopts.inner,
                cf_ptrs.as_ptr(),
                ptr_keys.len(),
                ptr_keys.as_ptr(),
                keys_sizes.as_ptr(),
                out.values.as_mut_ptr(),
                out.values_sizes.as_mut_ptr(),
                out.timestamps.as_mut_ptr(),
                out.timestamps_sizes.as_mut_ptr(),
                out.errors.as_mut_ptr(),
            );
            out.assume_filled(ptr_keys.len());
        }

        out.into_results()
    }

    /// Changes DB wide mutable options at runtime.
    ///
    /// Takes the same option names and string values the RocksDB configuration
    /// strings use, so `max_background_jobs` or `bytes_per_sync`. Only options
    /// RocksDB marks mutable at the DB level can be set, and the whole call is
    /// rejected if any name or value is not accepted.
    ///
    /// [`set_options`](Self::set_options) is the column family equivalent.
    ///
    /// # Aborts
    ///
    /// Some unparseable values take the process down instead of returning an error.
    /// See [`set_options`](Self::set_options) for the details and why this is not
    /// caught.
    ///
    /// # Errors
    ///
    /// Returns the RocksDB error if a name is unknown or the option is not
    /// changeable at runtime, and for an empty `opts`, which RocksDB rejects as
    /// `empty input`. Also errors if any name or value contains an interior NUL
    /// byte.
    pub fn set_db_options(&self, opts: &[(&str, &str)]) -> Result<(), Error> {
        let copts = convert_options(opts)?;
        let names: Vec<*const c_char> = copts.iter().map(|(n, _)| n.as_ptr()).collect();
        let values: Vec<*const c_char> = copts.iter().map(|(_, v)| v.as_ptr()).collect();

        unsafe {
            ffi_try!(ffi::rocksdb_set_db_options(
                self.inner.inner(),
                option_count(&copts)?,
                names.as_ptr(),
                values.as_ptr(),
            ));
        }
        Ok(())
    }

    /// Suspend deleting obsolete files. Compactions will continue to occur,
    /// but no obsolete files will be deleted. To resume file deletions, each
    /// call to disable_file_deletions() must be matched by a subsequent call to
    /// enable_file_deletions(). For more details, see enable_file_deletions().
    pub fn disable_file_deletions(&self) -> Result<(), Error> {
        unsafe {
            ffi_try!(ffi::rocksdb_disable_file_deletions(self.inner.inner()));
        }
        Ok(())
    }

    /// Resume deleting obsolete files, following up on `disable_file_deletions()`.
    ///
    /// File deletions disabling and enabling is not controlled by a binary flag,
    /// instead it's represented as a counter to allow different callers to
    /// independently disable file deletion. Disabling file deletion can be
    /// critical for operations like making a backup. So the counter implementation
    /// makes the file deletion disabled as long as there is one caller requesting
    /// so, and only when every caller agrees to re-enable file deletion, it will
    /// be enabled. Two threads can call this method concurrently without
    /// synchronization -- i.e., file deletions will be enabled only after both
    /// threads call enable_file_deletions()
    pub fn enable_file_deletions(&self) -> Result<(), Error> {
        unsafe {
            ffi_try!(ffi::rocksdb_enable_file_deletions(self.inner.inner()));
        }
        Ok(())
    }

    /// Flushes database memtables to SST files on the disk.
    pub fn flush_opt(&self, flushopts: &FlushOptions) -> Result<(), Error> {
        unsafe {
            ffi_try!(ffi::rocksdb_flush(self.inner.inner(), flushopts.inner));
        }
        Ok(())
    }

    /// Flushes database memtables to SST files on the disk using default options.
    pub fn flush(&self) -> Result<(), Error> {
        DEFAULT_FLUSH_OPTS.with(|opts| self.flush_opt(opts))
    }

    /// Flushes database memtables to SST files on the disk for a given column family.
    pub fn flush_cf_opt(
        &self,
        cf: &impl AsColumnFamilyRef,
        flushopts: &FlushOptions,
    ) -> Result<(), Error> {
        unsafe {
            ffi_try!(ffi::rocksdb_flush_cf(
                self.inner.inner(),
                flushopts.inner,
                cf.inner()
            ));
        }
        Ok(())
    }

    /// Flushes multiple column families.
    ///
    /// If atomic flush is not enabled, it is equivalent to calling flush_cf multiple times.
    /// If atomic flush is enabled, it will flush all column families specified in `cfs` up to the latest sequence
    /// number at the time when flush is requested.
    pub fn flush_cfs_opt(
        &self,
        cfs: &[&impl AsColumnFamilyRef],
        opts: &FlushOptions,
    ) -> Result<(), Error> {
        let mut cfs = cfs.iter().map(|cf| cf.inner()).collect::<Vec<_>>();
        unsafe {
            ffi_try!(ffi::rocksdb_flush_cfs(
                self.inner.inner(),
                opts.inner,
                cfs.as_mut_ptr(),
                cfs.len() as libc::c_int,
            ));
        }
        Ok(())
    }

    /// Flushes database memtables to SST files on the disk for a given column family using default
    /// options.
    pub fn flush_cf(&self, cf: &impl AsColumnFamilyRef) -> Result<(), Error> {
        DEFAULT_FLUSH_OPTS.with(|opts| self.flush_cf_opt(cf, opts))
    }

    /// Return the bytes associated with a key value with read options. If you only intend to use
    /// the vector returned temporarily, consider using [`get_pinned_opt`](#method.get_pinned_opt)
    /// to avoid unnecessary memory copy.
    pub fn get_opt<K: AsRef<[u8]>>(
        &self,
        key: K,
        readopts: &ReadOptions,
    ) -> Result<Option<Vec<u8>>, Error> {
        self.get_pinned_opt(key, readopts)
            .map(|x| x.map(|v| v.as_ref().to_vec()))
    }

    /// Return the bytes associated with a key value. If you only intend to use the vector returned
    /// temporarily, consider using [`get_pinned`](#method.get_pinned) to avoid unnecessary memory
    /// copy.
    pub fn get<K: AsRef<[u8]>>(&self, key: K) -> Result<Option<Vec<u8>>, Error> {
        DEFAULT_READ_OPTS.with(|opts| self.get_opt(key.as_ref(), opts))
    }

    /// Return the bytes associated with a key value and the given column family with read options.
    /// If you only intend to use the vector returned temporarily, consider using
    /// [`get_pinned_cf_opt`](#method.get_pinned_cf_opt) to avoid unnecessary memory.
    pub fn get_cf_opt<K: AsRef<[u8]>>(
        &self,
        cf: &impl AsColumnFamilyRef,
        key: K,
        readopts: &ReadOptions,
    ) -> Result<Option<Vec<u8>>, Error> {
        self.get_pinned_cf_opt(cf, key, readopts)
            .map(|x| x.map(|v| v.as_ref().to_vec()))
    }

    /// Return the bytes associated with a key value and the given column family. If you only
    /// intend to use the vector returned temporarily, consider using
    /// [`get_pinned_cf`](#method.get_pinned_cf) to avoid unnecessary memory.
    pub fn get_cf<K: AsRef<[u8]>>(
        &self,
        cf: &impl AsColumnFamilyRef,
        key: K,
    ) -> Result<Option<Vec<u8>>, Error> {
        DEFAULT_READ_OPTS.with(|opts| self.get_cf_opt(cf, key.as_ref(), opts))
    }

    /// Return the value associated with a key using RocksDB's PinnableSlice
    /// so as to avoid unnecessary memory copy.
    pub fn get_pinned_opt<K: AsRef<[u8]>>(
        &'_ self,
        key: K,
        readopts: &ReadOptions,
    ) -> Result<Option<DBPinnableSlice<'_>>, Error> {
        if readopts.inner.is_null() {
            return Err(Error::new(
                "Unable to create RocksDB read options. This is a fairly trivial call, and its \
                 failure may be indicative of a mis-compiled or mis-loaded RocksDB library."
                    .to_owned(),
            ));
        }

        let key = key.as_ref();
        unsafe {
            let val = ffi_try!(ffi::rocksdb_get_pinned(
                self.inner.inner(),
                readopts.inner,
                key.as_ptr() as *const c_char,
                key.len() as size_t,
            ));
            if val.is_null() {
                Ok(None)
            } else {
                Ok(Some(DBPinnableSlice::from_c(val)))
            }
        }
    }

    /// Return the value associated with a key using RocksDB's PinnableSlice
    /// so as to avoid unnecessary memory copy. Similar to get_pinned_opt but
    /// leverages default options.
    pub fn get_pinned<K: AsRef<[u8]>>(
        &'_ self,
        key: K,
    ) -> Result<Option<DBPinnableSlice<'_>>, Error> {
        DEFAULT_READ_OPTS.with(|opts| self.get_pinned_opt(key, opts))
    }

    /// Return the value associated with a key using RocksDB's PinnableSlice
    /// so as to avoid unnecessary memory copy. Similar to get_pinned_opt but
    /// allows specifying ColumnFamily
    pub fn get_pinned_cf_opt<K: AsRef<[u8]>>(
        &'_ self,
        cf: &impl AsColumnFamilyRef,
        key: K,
        readopts: &ReadOptions,
    ) -> Result<Option<DBPinnableSlice<'_>>, Error> {
        if readopts.inner.is_null() {
            return Err(Error::new(
                "Unable to create RocksDB read options. This is a fairly trivial call, and its \
                 failure may be indicative of a mis-compiled or mis-loaded RocksDB library."
                    .to_owned(),
            ));
        }

        let key = key.as_ref();
        unsafe {
            let val = ffi_try!(ffi::rocksdb_get_pinned_cf(
                self.inner.inner(),
                readopts.inner,
                cf.inner(),
                key.as_ptr() as *const c_char,
                key.len() as size_t,
            ));
            if val.is_null() {
                Ok(None)
            } else {
                Ok(Some(DBPinnableSlice::from_c(val)))
            }
        }
    }

    /// Return the value associated with a key using RocksDB's PinnableSlice
    /// so as to avoid unnecessary memory copy. Similar to get_pinned_cf_opt but
    /// leverages default options.
    pub fn get_pinned_cf<K: AsRef<[u8]>>(
        &'_ self,
        cf: &impl AsColumnFamilyRef,
        key: K,
    ) -> Result<Option<DBPinnableSlice<'_>>, Error> {
        DEFAULT_READ_OPTS.with(|opts| self.get_pinned_cf_opt(cf, key, opts))
    }

    /// Read a value directly into a caller-provided buffer, avoiding memory allocation.
    ///
    /// This is the most efficient way to read values when you have a pre-allocated
    /// buffer. It completely avoids the allocation overhead of [`get`](#method.get)
    /// and even the pinning overhead of [`get_pinned`](#method.get_pinned).
    ///
    /// # Arguments
    ///
    /// * `key` - The key to look up
    /// * `buffer` - A mutable byte slice to write the value into. Can be empty if you
    ///   only want to check if a key exists and get its value size.
    ///
    /// # Returns
    ///
    /// * `Ok(GetIntoBufferResult::NotFound)` - The key doesn't exist
    /// * `Ok(GetIntoBufferResult::Found(size))` - Value was copied into the buffer.
    ///   `size` is the number of bytes written.
    /// * `Ok(GetIntoBufferResult::BufferTooSmall(size))` - The value exists but the buffer
    ///   is too small. `size` is the actual value size needed. No data is written.
    /// * `Err(...)` - Database error occurred
    ///
    /// # Performance
    ///
    /// This method is ideal for high-throughput scenarios where you can reuse a buffer:
    ///
    /// ```ignore
    /// use rust_rocksdb::{DB, GetIntoBufferResult};
    ///
    /// let db: DB = /* open database */;
    /// let keys_to_lookup: Vec<&[u8]> = /* keys to look up */;
    /// let mut buffer = vec![0u8; 4096]; // Reusable buffer
    ///
    /// for key in keys_to_lookup {
    ///     match db.get_into_buffer(key, &mut buffer).unwrap() {
    ///         GetIntoBufferResult::Found(len) => {
    ///             process_value(&buffer[..len]);
    ///         }
    ///         GetIntoBufferResult::BufferTooSmall(needed) => {
    ///             buffer.resize(needed, 0);
    ///             // Retry with larger buffer...
    ///         }
    ///         GetIntoBufferResult::NotFound => {}
    ///     }
    /// }
    /// ```
    ///
    /// # Example
    ///
    /// ```
    /// use rust_rocksdb::{DB, GetIntoBufferResult};
    ///
    /// let tempdir = tempfile::Builder::new()
    ///     .prefix("rocksdb_get_into_buffer")
    ///     .tempdir()
    ///     .unwrap();
    /// let db = DB::open_default(tempdir.path()).unwrap();
    /// db.put(b"key", b"value").unwrap();
    ///
    /// let mut buffer = [0u8; 100];
    /// match db.get_into_buffer(b"key", &mut buffer).unwrap() {
    ///     GetIntoBufferResult::Found(size) => {
    ///         assert_eq!(&buffer[..size], b"value");
    ///     }
    ///     GetIntoBufferResult::NotFound => panic!("expected value"),
    ///     GetIntoBufferResult::BufferTooSmall(needed) => {
    ///         panic!("buffer too small, need {} bytes", needed)
    ///     }
    /// }
    /// ```
    pub fn get_into_buffer<K: AsRef<[u8]>>(
        &self,
        key: K,
        buffer: &mut [u8],
    ) -> Result<GetIntoBufferResult, Error> {
        DEFAULT_READ_OPTS.with(|opts| self.get_into_buffer_opt(key, buffer, opts))
    }

    /// Read a value directly into a caller-provided buffer with custom read options.
    ///
    /// This is the same as [`get_into_buffer`](#method.get_into_buffer) but allows
    /// specifying custom [`ReadOptions`], such as setting a snapshot or fill cache behavior.
    ///
    /// See [`get_into_buffer`](#method.get_into_buffer) for full documentation.
    pub fn get_into_buffer_opt<K: AsRef<[u8]>>(
        &self,
        key: K,
        buffer: &mut [u8],
        readopts: &ReadOptions,
    ) -> Result<GetIntoBufferResult, Error> {
        if readopts.inner.is_null() {
            return Err(Error::new(
                "Unable to create RocksDB read options. This is a fairly trivial call, and its \
                 failure may be indicative of a mis-compiled or mis-loaded RocksDB library."
                    .to_owned(),
            ));
        }

        let key = key.as_ref();
        let mut val_len: size_t = 0;
        let mut found: c_uchar = 0;

        unsafe {
            let success = ffi_try!(ffi::rocksdb_get_into_buffer(
                self.inner.inner(),
                readopts.inner,
                key.as_ptr() as *const c_char,
                key.len() as size_t,
                buffer.as_mut_ptr() as *mut c_char,
                buffer.len() as size_t,
                &raw mut val_len,
                &raw mut found,
            ));

            if found == 0 {
                Ok(GetIntoBufferResult::NotFound)
            } else if success != 0 {
                Ok(GetIntoBufferResult::Found(val_len))
            } else {
                Ok(GetIntoBufferResult::BufferTooSmall(val_len))
            }
        }
    }

    /// Read a value from a column family directly into a caller-provided buffer.
    ///
    /// This is the column family variant of [`get_into_buffer`](#method.get_into_buffer).
    /// See that method for full documentation on the zero-allocation buffer API.
    ///
    /// # Arguments
    ///
    /// * `cf` - The column family to read from
    /// * `key` - The key to look up
    /// * `buffer` - A mutable byte slice to write the value into
    pub fn get_into_buffer_cf<K: AsRef<[u8]>>(
        &self,
        cf: &impl AsColumnFamilyRef,
        key: K,
        buffer: &mut [u8],
    ) -> Result<GetIntoBufferResult, Error> {
        DEFAULT_READ_OPTS.with(|opts| self.get_into_buffer_cf_opt(cf, key, buffer, opts))
    }

    /// Read a value from a column family directly into a caller-provided buffer
    /// with custom read options.
    ///
    /// This is the column family variant of [`get_into_buffer_opt`](#method.get_into_buffer_opt).
    /// See [`get_into_buffer`](#method.get_into_buffer) for full documentation.
    pub fn get_into_buffer_cf_opt<K: AsRef<[u8]>>(
        &self,
        cf: &impl AsColumnFamilyRef,
        key: K,
        buffer: &mut [u8],
        readopts: &ReadOptions,
    ) -> Result<GetIntoBufferResult, Error> {
        if readopts.inner.is_null() {
            return Err(Error::new(
                "Unable to create RocksDB read options. This is a fairly trivial call, and its \
                 failure may be indicative of a mis-compiled or mis-loaded RocksDB library."
                    .to_owned(),
            ));
        }

        let key = key.as_ref();
        let mut val_len: size_t = 0;
        let mut found: c_uchar = 0;

        unsafe {
            let success = ffi_try!(ffi::rocksdb_get_into_buffer_cf(
                self.inner.inner(),
                readopts.inner,
                cf.inner(),
                key.as_ptr() as *const c_char,
                key.len() as size_t,
                buffer.as_mut_ptr() as *mut c_char,
                buffer.len() as size_t,
                &raw mut val_len,
                &raw mut found,
            ));

            if found == 0 {
                Ok(GetIntoBufferResult::NotFound)
            } else if success != 0 {
                Ok(GetIntoBufferResult::Found(val_len))
            } else {
                Ok(GetIntoBufferResult::BufferTooSmall(val_len))
            }
        }
    }

    /// Return the values associated with the given keys.
    pub fn multi_get<K, I>(&self, keys: I) -> Vec<Result<Option<Vec<u8>>, Error>>
    where
        K: AsRef<[u8]>,
        I: IntoIterator<Item = K>,
    {
        DEFAULT_READ_OPTS.with(|opts| self.multi_get_opt(keys, opts))
    }

    /// Return the values associated with the given keys using read options.
    pub fn multi_get_opt<K, I>(
        &self,
        keys: I,
        readopts: &ReadOptions,
    ) -> Vec<Result<Option<Vec<u8>>, Error>>
    where
        K: AsRef<[u8]>,
        I: IntoIterator<Item = K>,
    {
        let owned_keys: Vec<K> = keys.into_iter().collect();
        let (ptr_keys, keys_sizes): (Vec<*const c_char>, Vec<usize>) = owned_keys
            .iter()
            .map(|k| {
                let key = k.as_ref();
                (key.as_ptr() as *const c_char, key.len())
            })
            .unzip();

        let mut values: Vec<*mut c_char> = Vec::with_capacity(ptr_keys.len());
        let mut values_sizes: Vec<usize> = Vec::with_capacity(ptr_keys.len());
        let mut errors: Vec<*mut c_char> = Vec::with_capacity(ptr_keys.len());
        unsafe {
            ffi::rocksdb_multi_get(
                self.inner.inner(),
                readopts.inner,
                ptr_keys.len(),
                ptr_keys.as_ptr(),
                keys_sizes.as_ptr(),
                values.as_mut_ptr(),
                values_sizes.as_mut_ptr(),
                errors.as_mut_ptr(),
            );
        }

        unsafe {
            values.set_len(ptr_keys.len());
            values_sizes.set_len(ptr_keys.len());
            errors.set_len(ptr_keys.len());
        }

        convert_values(values, values_sizes, errors)
    }

    /// Returns pinned values associated with the given keys using default read options.
    ///
    /// RocksDB processes the keys in one native batch. Results stay in input order.
    pub fn multi_get_pinned<K, I>(
        &'_ self,
        keys: I,
    ) -> Vec<Result<Option<DBPinnableSlice<'_>>, Error>>
    where
        K: AsRef<[u8]>,
        I: IntoIterator<Item = K>,
    {
        DEFAULT_READ_OPTS.with(|opts| self.multi_get_pinned_opt(keys, opts))
    }

    /// Returns pinned values associated with the given keys using the provided read options.
    ///
    /// RocksDB processes the keys in one native batch. Results stay in input order.
    pub fn multi_get_pinned_opt<K, I>(
        &'_ self,
        keys: I,
        readopts: &ReadOptions,
    ) -> Vec<Result<Option<DBPinnableSlice<'_>>, Error>>
    where
        K: AsRef<[u8]>,
        I: IntoIterator<Item = K>,
    {
        let mut keys = keys.into_iter();
        let Some(first) = keys.next() else {
            return Vec::new();
        };
        // Decide before collecting. A single key does not benefit from the
        // native batch, and buying a key-slice vector, two result vectors and
        // a default column family handle to do one point lookup is a loss.
        let Some(second) = keys.next() else {
            return vec![self.get_pinned_opt(first.as_ref(), readopts)];
        };
        let mut owned_keys = Vec::with_capacity(2 + keys.size_hint().0);
        owned_keys.push(first);
        owned_keys.push(second);
        owned_keys.extend(keys);
        self.batched_multi_get_pinned_owned(&owned_keys, false, readopts)
    }

    /// Returns pinned values associated with the given keys and column families
    /// using default read options.
    pub fn multi_get_pinned_cf<'a, 'b: 'a, K, I, W>(
        &'a self,
        keys: I,
    ) -> Vec<Result<Option<DBPinnableSlice<'a>>, Error>>
    where
        K: AsRef<[u8]>,
        I: IntoIterator<Item = (&'b W, K)>,
        W: 'b + AsColumnFamilyRef,
    {
        DEFAULT_READ_OPTS.with(|opts| self.multi_get_pinned_cf_opt(keys, opts))
    }

    /// Returns pinned values associated with the given keys and column families
    /// using the provided read options.
    pub fn multi_get_pinned_cf_opt<'a, 'b: 'a, K, I, W>(
        &'a self,
        keys: I,
        readopts: &ReadOptions,
    ) -> Vec<Result<Option<DBPinnableSlice<'a>>, Error>>
    where
        K: AsRef<[u8]>,
        I: IntoIterator<Item = (&'b W, K)>,
        W: 'b + AsColumnFamilyRef,
    {
        keys.into_iter()
            .map(|(cf, k)| self.get_pinned_cf_opt(cf, k, readopts))
            .collect()
    }

    /// Returns pinned values for default-column-family keys in one native batch.
    ///
    /// Set `sorted_input` only when keys are sorted according to the column
    /// family's comparator. Results stay in input order, including duplicates.
    pub fn batched_multi_get_pinned<K, I>(
        &'_ self,
        keys: I,
        sorted_input: bool,
    ) -> Vec<Result<Option<DBPinnableSlice<'_>>, Error>>
    where
        K: AsRef<[u8]>,
        I: IntoIterator<Item = K>,
    {
        DEFAULT_READ_OPTS.with(|opts| self.batched_multi_get_pinned_opt(keys, sorted_input, opts))
    }

    /// Returns pinned values for default-column-family keys in one native batch
    /// using the provided read options.
    pub fn batched_multi_get_pinned_opt<K, I>(
        &'_ self,
        keys: I,
        sorted_input: bool,
        readopts: &ReadOptions,
    ) -> Vec<Result<Option<DBPinnableSlice<'_>>, Error>>
    where
        K: AsRef<[u8]>,
        I: IntoIterator<Item = K>,
    {
        let owned_keys: Vec<K> = keys.into_iter().collect();
        self.batched_multi_get_pinned_owned(&owned_keys, sorted_input, readopts)
    }

    /// Returns pinned values for keys in one column family using one native batch.
    ///
    /// Set `sorted_input` only when keys are sorted according to the column
    /// family's comparator. Results stay in input order, including duplicates.
    pub fn batched_multi_get_pinned_cf<K, I>(
        &'_ self,
        cf: &impl AsColumnFamilyRef,
        keys: I,
        sorted_input: bool,
    ) -> Vec<Result<Option<DBPinnableSlice<'_>>, Error>>
    where
        K: AsRef<[u8]>,
        I: IntoIterator<Item = K>,
    {
        DEFAULT_READ_OPTS
            .with(|opts| self.batched_multi_get_pinned_cf_opt(cf, keys, sorted_input, opts))
    }

    /// Returns pinned values for keys in one column family using one native batch
    /// and the provided read options.
    pub fn batched_multi_get_pinned_cf_opt<K, I>(
        &'_ self,
        cf: &impl AsColumnFamilyRef,
        keys: I,
        sorted_input: bool,
        readopts: &ReadOptions,
    ) -> Vec<Result<Option<DBPinnableSlice<'_>>, Error>>
    where
        K: AsRef<[u8]>,
        I: IntoIterator<Item = K>,
    {
        let owned_keys: Vec<K> = keys.into_iter().collect();
        let key_slices = Self::key_slices(&owned_keys);
        self.batched_multi_get_pinned_inner(cf.inner(), &key_slices, sorted_input, readopts)
    }

    /// Returns one owner for all default-column-family pinned results.
    ///
    /// Values borrow from the returned batch, avoiding one native wrapper
    /// allocation and one destroy call per successful key.
    pub fn batched_multi_get_pinned_batch<K, I>(
        &'_ self,
        keys: I,
        sorted_input: bool,
    ) -> Result<DBPinnableBatch<'_>, Error>
    where
        K: AsRef<[u8]>,
        I: IntoIterator<Item = K>,
    {
        DEFAULT_READ_OPTS
            .with(|opts| self.batched_multi_get_pinned_batch_opt(keys, sorted_input, opts))
    }

    /// Returns one owner for all default-column-family pinned results using
    /// the provided read options.
    pub fn batched_multi_get_pinned_batch_opt<K, I>(
        &'_ self,
        keys: I,
        sorted_input: bool,
        readopts: &ReadOptions,
    ) -> Result<DBPinnableBatch<'_>, Error>
    where
        K: AsRef<[u8]>,
        I: IntoIterator<Item = K>,
    {
        let owned_keys: Vec<K> = keys.into_iter().collect();
        let key_slices = Self::key_slices(&owned_keys);
        self.create_pinnable_batch(ptr::null_mut(), &key_slices, sorted_input, readopts)
    }

    /// Returns one owner for all pinned results from one column family.
    pub fn batched_multi_get_pinned_batch_cf<K, I>(
        &'_ self,
        cf: &impl AsColumnFamilyRef,
        keys: I,
        sorted_input: bool,
    ) -> Result<DBPinnableBatch<'_>, Error>
    where
        K: AsRef<[u8]>,
        I: IntoIterator<Item = K>,
    {
        DEFAULT_READ_OPTS
            .with(|opts| self.batched_multi_get_pinned_batch_cf_opt(cf, keys, sorted_input, opts))
    }

    /// Returns one owner for all pinned results from one column family using
    /// the provided read options.
    pub fn batched_multi_get_pinned_batch_cf_opt<K, I>(
        &'_ self,
        cf: &impl AsColumnFamilyRef,
        keys: I,
        sorted_input: bool,
        readopts: &ReadOptions,
    ) -> Result<DBPinnableBatch<'_>, Error>
    where
        K: AsRef<[u8]>,
        I: IntoIterator<Item = K>,
    {
        let owned_keys: Vec<K> = keys.into_iter().collect();
        let key_slices = Self::key_slices(&owned_keys);
        self.create_pinnable_batch(cf.inner(), &key_slices, sorted_input, readopts)
    }

    /// Return the values associated with the given keys and column families.
    pub fn multi_get_cf<'a, 'b: 'a, K, I, W>(
        &'a self,
        keys: I,
    ) -> Vec<Result<Option<Vec<u8>>, Error>>
    where
        K: AsRef<[u8]>,
        I: IntoIterator<Item = (&'b W, K)>,
        W: 'b + AsColumnFamilyRef,
    {
        DEFAULT_READ_OPTS.with(|opts| self.multi_get_cf_opt(keys, opts))
    }

    /// Return the values associated with the given keys and column families using read options.
    pub fn multi_get_cf_opt<'a, 'b: 'a, K, I, W>(
        &'a self,
        keys: I,
        readopts: &ReadOptions,
    ) -> Vec<Result<Option<Vec<u8>>, Error>>
    where
        K: AsRef<[u8]>,
        I: IntoIterator<Item = (&'b W, K)>,
        W: 'b + AsColumnFamilyRef,
    {
        let cfs_and_owned_keys: Vec<(&'b W, K)> = keys.into_iter().collect();
        let (ptr_keys, keys_sizes): (Vec<*const c_char>, Vec<usize>) = cfs_and_owned_keys
            .iter()
            .map(|(_, k)| {
                let key = k.as_ref();
                (key.as_ptr() as *const c_char, key.len())
            })
            .unzip();
        let ptr_cfs: Vec<*const ffi::rocksdb_column_family_handle_t> = cfs_and_owned_keys
            .iter()
            .map(|(c, _)| c.inner().cast_const())
            .collect();
        let mut values: Vec<*mut c_char> = Vec::with_capacity(ptr_keys.len());
        let mut values_sizes: Vec<usize> = Vec::with_capacity(ptr_keys.len());
        let mut errors: Vec<*mut c_char> = Vec::with_capacity(ptr_keys.len());
        unsafe {
            ffi::rocksdb_multi_get_cf(
                self.inner.inner(),
                readopts.inner,
                ptr_cfs.as_ptr(),
                ptr_keys.len(),
                ptr_keys.as_ptr(),
                keys_sizes.as_ptr(),
                values.as_mut_ptr(),
                values_sizes.as_mut_ptr(),
                errors.as_mut_ptr(),
            );
        }

        unsafe {
            values.set_len(ptr_keys.len());
            values_sizes.set_len(ptr_keys.len());
            errors.set_len(ptr_keys.len());
        }

        convert_values(values, values_sizes, errors)
    }

    /// Return the values associated with the given keys and the specified column family
    /// where internally the read requests are processed in batch if block-based table
    /// SST format is used.  It is a more optimized version of multi_get_cf.
    pub fn batched_multi_get_cf<'a, K, I>(
        &'_ self,
        cf: &impl AsColumnFamilyRef,
        keys: I,
        sorted_input: bool,
    ) -> Vec<Result<Option<DBPinnableSlice<'_>>, Error>>
    where
        K: AsRef<[u8]> + 'a + ?Sized,
        I: IntoIterator<Item = &'a K>,
    {
        DEFAULT_READ_OPTS.with(|opts| self.batched_multi_get_cf_opt(cf, keys, sorted_input, opts))
    }

    /// Return the values associated with the given keys and the specified column family
    /// where internally the read requests are processed in batch if block-based table
    /// SST format is used. It is a more optimized version of multi_get_cf_opt.
    pub fn batched_multi_get_cf_opt<'a, K, I>(
        &'_ self,
        cf: &impl AsColumnFamilyRef,
        keys: I,
        sorted_input: bool,
        readopts: &ReadOptions,
    ) -> Vec<Result<Option<DBPinnableSlice<'_>>, Error>>
    where
        K: AsRef<[u8]> + 'a + ?Sized,
        I: IntoIterator<Item = &'a K>,
    {
        let key_slices: Vec<_> = keys
            .into_iter()
            .map(|k| {
                let k = k.as_ref();
                ffi::rocksdb_slice_t {
                    data: k.as_ptr() as *const c_char,
                    size: k.len(),
                }
            })
            .collect();
        self.batched_multi_get_pinned_inner(cf.inner(), &key_slices, sorted_input, readopts)
    }

    /// Return the values associated with the given keys and the specified column family
    /// using an optimized slice-based API.
    ///
    /// This method uses RocksDB's optimized `rocksdb_batched_multi_get_cf_slice` C API,
    /// which takes a `rocksdb_slice_t` array directly. This eliminates the internal
    /// overhead of converting keys from separate pointer+size arrays to Slice objects.
    ///
    /// # Arguments
    ///
    /// * `cf` - The column family to read from
    /// * `keys` - An iterator of keys to look up
    /// * `sorted_input` - If `true`, indicates the keys are already sorted in ascending
    ///   order, which allows RocksDB to skip internal sorting and improve performance.
    ///   **Important**: If you pass `true` but keys are not sorted, results may be incorrect.
    ///
    /// # Returns
    ///
    /// A vector of results in the same order as the input keys. Each element is:
    /// - `Ok(Some(DBPinnableSlice))` if the key was found
    /// - `Ok(None)` if the key was not found
    /// - `Err(...)` if an error occurred for that key
    ///
    /// # Performance
    ///
    /// This is the fastest batch lookup method when:
    /// - You're looking up many keys (10+) from the same column family
    /// - You can pre-sort your keys (set `sorted_input = true`)
    /// - Block-based table format is used (default)
    ///
    /// For small numbers of keys, the overhead of batching may not be worth it.
    /// Consider using [`get_pinned_cf`](#method.get_pinned_cf) for single key lookups.
    ///
    /// # Example
    ///
    /// ```
    /// use rust_rocksdb::{DB, Options, ColumnFamilyDescriptor};
    ///
    /// let tempdir = tempfile::Builder::new().prefix("batch_slice").tempdir().unwrap();
    /// let mut opts = Options::default();
    /// opts.create_if_missing(true);
    /// opts.create_missing_column_families(true);
    /// let db = DB::open_cf_descriptors(&opts, tempdir.path(),
    ///     vec![ColumnFamilyDescriptor::new("cf", Options::default())]).unwrap();
    ///
    /// let cf = db.cf_handle("cf").unwrap();
    /// db.put_cf(&cf, b"k1", b"v1").unwrap();
    /// db.put_cf(&cf, b"k2", b"v2").unwrap();
    ///
    /// // Keys are sorted, so we can set sorted_input = true
    /// let keys: Vec<&[u8]> = vec![b"k1", b"k2", b"k3"];
    /// let results = db.batched_multi_get_cf_slice(&cf, keys, true);
    ///
    /// assert!(results[0].as_ref().unwrap().is_some()); // k1 found
    /// assert!(results[1].as_ref().unwrap().is_some()); // k2 found
    /// assert!(results[2].as_ref().unwrap().is_none()); // k3 not found
    /// ```
    pub fn batched_multi_get_cf_slice<'a, K, I>(
        &'_ self,
        cf: &impl AsColumnFamilyRef,
        keys: I,
        sorted_input: bool,
    ) -> Vec<Result<Option<DBPinnableSlice<'_>>, Error>>
    where
        K: AsRef<[u8]> + 'a + ?Sized,
        I: IntoIterator<Item = &'a K>,
    {
        DEFAULT_READ_OPTS
            .with(|opts| self.batched_multi_get_cf_slice_opt(cf, keys, sorted_input, opts))
    }

    /// Return the values associated with the given keys and the specified column family
    /// using an optimized slice-based API with custom read options.
    ///
    /// This is the same as [`batched_multi_get_cf_slice`](#method.batched_multi_get_cf_slice)
    /// but allows specifying custom [`ReadOptions`].
    ///
    /// See [`batched_multi_get_cf_slice`](#method.batched_multi_get_cf_slice) for full documentation.
    pub fn batched_multi_get_cf_slice_opt<'a, K, I>(
        &'_ self,
        cf: &impl AsColumnFamilyRef,
        keys: I,
        sorted_input: bool,
        readopts: &ReadOptions,
    ) -> Vec<Result<Option<DBPinnableSlice<'_>>, Error>>
    where
        K: AsRef<[u8]> + 'a + ?Sized,
        I: IntoIterator<Item = &'a K>,
    {
        // Convert keys to rocksdb_slice_t array
        let slices: Vec<ffi::rocksdb_slice_t> = keys
            .into_iter()
            .map(|k| {
                let k = k.as_ref();
                ffi::rocksdb_slice_t {
                    data: k.as_ptr() as *const c_char,
                    size: k.len(),
                }
            })
            .collect();

        self.batched_multi_get_pinned_inner(cf.inner(), &slices, sorted_input, readopts)
    }

    fn key_slices<K: AsRef<[u8]>>(keys: &[K]) -> Vec<ffi::rocksdb_slice_t> {
        keys.iter()
            .map(|key| {
                let key = key.as_ref();
                ffi::rocksdb_slice_t {
                    data: key.as_ptr() as *const c_char,
                    size: key.len(),
                }
            })
            .collect()
    }

    fn batched_multi_get_pinned_owned<'a, K: AsRef<[u8]>>(
        &'a self,
        keys: &[K],
        sorted_input: bool,
        readopts: &ReadOptions,
    ) -> Vec<Result<Option<DBPinnableSlice<'a>>, Error>> {
        let key_slices = Self::key_slices(keys);
        if key_slices.is_empty() {
            return Vec::new();
        }
        let default_cf = OwnedColumnFamilyHandle::default_for(self.inner.inner());
        self.batched_multi_get_pinned_inner(default_cf.inner, &key_slices, sorted_input, readopts)
    }

    fn create_pinnable_batch<'a>(
        &'a self,
        cf: *mut ffi::rocksdb_column_family_handle_t,
        keys: &[ffi::rocksdb_slice_t],
        sorted_input: bool,
        readopts: &ReadOptions,
    ) -> Result<DBPinnableBatch<'a>, Error> {
        let batch = unsafe {
            ffi_try!(ffi::rust_rocksdb_batched_multi_get_pinned(
                self.inner.inner(),
                readopts.inner,
                cf,
                keys.len(),
                keys.as_ptr(),
                c_uchar::from(sorted_input),
            ))
        };
        if batch.is_null() {
            // `ffi_try!` only returns early when the extension set `errptr`.
            // A null batch with no error means the extension could not even
            // allocate the message, so report it instead of unwrapping.
            return Err(Error::new(
                "rust_rocksdb_batched_multi_get_pinned returned no batch".to_owned(),
            ));
        }
        // SAFETY: The extension returns a uniquely owned batch.
        Ok(unsafe { DBPinnableBatch::from_c(batch) })
    }

    fn batched_multi_get_pinned_inner<'a>(
        &'a self,
        cf: *mut ffi::rocksdb_column_family_handle_t,
        keys: &[ffi::rocksdb_slice_t],
        sorted_input: bool,
        readopts: &ReadOptions,
    ) -> Vec<Result<Option<DBPinnableSlice<'a>>, Error>> {
        if keys.is_empty() {
            return Vec::new();
        }
        let output = match self.execute_batched_multi_get(cf, keys, sorted_input, readopts) {
            Ok(output) => output,
            Err(error) => {
                let message = error.to_string();
                return (0..keys.len())
                    .map(|_| Err(Error::new(message.clone())))
                    .collect();
            }
        };
        output
            .values
            .into_iter()
            .zip(output.errors)
            .map(|(value, error)| unsafe { Self::convert_pinned_result(value, error) })
            .collect()
    }

    fn execute_batched_multi_get(
        &self,
        cf: *mut ffi::rocksdb_column_family_handle_t,
        keys: &[ffi::rocksdb_slice_t],
        sorted_input: bool,
        readopts: &ReadOptions,
    ) -> Result<PinnedMultiGetOutput, Error> {
        let mut pinned_values = vec![ptr::null_mut(); keys.len()];
        let mut errors = vec![ptr::null_mut(); keys.len()];
        unsafe {
            ffi_try!(ffi::rust_rocksdb_batched_multi_get_cf_slice_safe(
                self.inner.inner(),
                readopts.inner,
                cf,
                keys.len(),
                keys.as_ptr(),
                pinned_values.as_mut_ptr(),
                errors.as_mut_ptr(),
                c_uchar::from(sorted_input),
            ));
        }
        Ok(PinnedMultiGetOutput {
            values: pinned_values,
            errors,
        })
    }

    /// Converts one result returned by `rocksdb_batched_multi_get_cf_slice`.
    ///
    /// # Safety
    ///
    /// `value` must be null or an owned pinnable slice. `error` must be null or
    /// an owned RocksDB error string.
    unsafe fn convert_pinned_result<'a>(
        value: *mut ffi::rocksdb_pinnableslice_t,
        error: *mut c_char,
    ) -> Result<Option<DBPinnableSlice<'a>>, Error> {
        if error.is_null() {
            return Ok((!value.is_null()).then(|| unsafe { DBPinnableSlice::from_c(value) }));
        }
        if !value.is_null() {
            unsafe {
                ffi::rocksdb_pinnableslice_destroy(value);
            }
        }
        Err(convert_rocksdb_error(error))
    }

    /// Returns `false` if the given key definitely doesn't exist in the database, otherwise returns
    /// `true`. This function uses default `ReadOptions`.
    pub fn key_may_exist<K: AsRef<[u8]>>(&self, key: K) -> bool {
        DEFAULT_READ_OPTS.with(|opts| self.key_may_exist_opt(key, opts))
    }

    /// Returns `false` if the given key definitely doesn't exist in the database, otherwise returns
    /// `true`.
    pub fn key_may_exist_opt<K: AsRef<[u8]>>(&self, key: K, readopts: &ReadOptions) -> bool {
        let key = key.as_ref();
        unsafe {
            0 != ffi::rocksdb_key_may_exist(
                self.inner.inner(),
                readopts.inner,
                key.as_ptr() as *const c_char,
                key.len() as size_t,
                ptr::null_mut(), /*value*/
                ptr::null_mut(), /*val_len*/
                ptr::null(),     /*timestamp*/
                0,               /*timestamp_len*/
                ptr::null_mut(), /*value_found*/
            )
        }
    }

    /// Returns `false` if the given key definitely doesn't exist in the specified column family,
    /// otherwise returns `true`. This function uses default `ReadOptions`.
    pub fn key_may_exist_cf<K: AsRef<[u8]>>(&self, cf: &impl AsColumnFamilyRef, key: K) -> bool {
        DEFAULT_READ_OPTS.with(|opts| self.key_may_exist_cf_opt(cf, key, opts))
    }

    /// Returns `false` if the given key definitely doesn't exist in the specified column family,
    /// otherwise returns `true`.
    pub fn key_may_exist_cf_opt<K: AsRef<[u8]>>(
        &self,
        cf: &impl AsColumnFamilyRef,
        key: K,
        readopts: &ReadOptions,
    ) -> bool {
        let key = key.as_ref();
        0 != unsafe {
            ffi::rocksdb_key_may_exist_cf(
                self.inner.inner(),
                readopts.inner,
                cf.inner(),
                key.as_ptr() as *const c_char,
                key.len() as size_t,
                ptr::null_mut(), /*value*/
                ptr::null_mut(), /*val_len*/
                ptr::null(),     /*timestamp*/
                0,               /*timestamp_len*/
                ptr::null_mut(), /*value_found*/
            )
        }
    }

    /// If the key definitely does not exist in the database, then this method
    /// returns `(false, None)`, else `(true, None)` if it may.
    /// If the key is found in memory, then it returns `(true, Some<CSlice>)`.
    ///
    /// This check is potentially lighter-weight than calling `get()`. One way
    /// to make this lighter weight is to avoid doing any IOs.
    pub fn key_may_exist_cf_opt_value<K: AsRef<[u8]>>(
        &self,
        cf: &impl AsColumnFamilyRef,
        key: K,
        readopts: &ReadOptions,
    ) -> (bool, Option<CSlice>) {
        let key = key.as_ref();
        let mut val: *mut c_char = ptr::null_mut();
        let mut val_len: usize = 0;
        let mut value_found: c_uchar = 0;
        let may_exists = 0
            != unsafe {
                ffi::rocksdb_key_may_exist_cf(
                    self.inner.inner(),
                    readopts.inner,
                    cf.inner(),
                    key.as_ptr() as *const c_char,
                    key.len() as size_t,
                    &raw mut val,         /*value*/
                    &raw mut val_len,     /*val_len*/
                    ptr::null(),          /*timestamp*/
                    0,                    /*timestamp_len*/
                    &raw mut value_found, /*value_found*/
                )
            };
        // The value is only allocated (using malloc) and returned if it is found and
        // value_found isn't NULL. In that case the user is responsible for freeing it.
        if may_exists && value_found != 0 {
            (
                may_exists,
                Some(unsafe { CSlice::from_raw_parts(val, val_len) }),
            )
        } else {
            (may_exists, None)
        }
    }

    fn create_inner_cf_handle(
        &self,
        name: impl CStrLike,
        opts: &Options,
    ) -> Result<*mut ffi::rocksdb_column_family_handle_t, Error> {
        let cf_name = name.bake().map_err(|err| {
            Error::new(format!(
                "Failed to convert path to CString when creating cf: {err}"
            ))
        })?;

        // Can't use ffi_try: rocksdb_create_column_family has a bug where it allocates a
        // result that needs to be freed on error
        let mut err: *mut ::libc::c_char = ::std::ptr::null_mut();
        let cf_handle = unsafe {
            ffi::rocksdb_create_column_family(
                self.inner.inner(),
                opts.inner,
                cf_name.as_ptr(),
                &raw mut err,
            )
        };
        if !err.is_null() {
            if !cf_handle.is_null() {
                unsafe { ffi::rocksdb_column_family_handle_destroy(cf_handle) };
            }
            return Err(convert_rocksdb_error(err));
        }
        Ok(cf_handle)
    }

    /// Creates every named column family in one call.
    ///
    /// This is not atomic. RocksDB creates the families one at a time and stops at
    /// the first failure, so the ones before it are already committed and stay that
    /// way. Only the options file write at the end is shared, which is the whole
    /// saving over calling [`create_cf`](Self::create_cf) in a loop.
    ///
    /// Returns the handles that were created, in the order the names were given,
    /// alongside the error that stopped the rest. The caller owns those handles and
    /// has to record them in its column family map even when there is an error,
    /// because the families exist either way.
    fn create_inner_cf_handles(
        &self,
        names: &[(String, CString)],
        opts: &Options,
    ) -> CreatedCfHandles {
        let name_ptrs: Vec<*const c_char> = names.iter().map(|(_, name)| name.as_ptr()).collect();
        let Ok(count) = c_int::try_from(names.len()) else {
            return CreatedCfHandles::failed(Error::new(format!(
                "Too many column families to create at once: {}",
                names.len()
            )));
        };

        let mut len: usize = 0;
        let mut err: *mut ::libc::c_char = ::std::ptr::null_mut();
        // Can't use ffi_try: like rocksdb_create_column_family, this allocates a result
        // that needs to be freed on error.
        let list = unsafe {
            ffi::rocksdb_create_column_families(
                self.inner.inner(),
                opts.inner,
                count,
                name_ptrs.as_ptr(),
                &raw mut len,
                &raw mut err,
            )
        };

        // Two allocations come back: the array, and a handle per family. Freeing the
        // array does not touch the handles, so take copies of them and release the
        // array on its own.
        let handles = if list.is_null() {
            Vec::new()
        } else {
            let handles = unsafe { std::slice::from_raw_parts(list, len) }.to_vec();
            unsafe { ffi::rocksdb_create_column_families_destroy(list) };
            handles
        };

        if !err.is_null() {
            // Hand the handles back even though this failed. The families they name
            // were committed before the failing one and are still there, so the caller
            // needs them to be able to use or drop those families.
            return CreatedCfHandles {
                handles,
                error: Some(convert_rocksdb_error(err)),
            };
        }

        let created = handles.len();
        let error = (created != names.len()).then(|| {
            Error::new(format!(
                "Expected {} column family handles, got {created}",
                names.len(),
            ))
        });

        CreatedCfHandles { handles, error }
    }

    /// Creates one column family whose entries expire after `ttl`.
    ///
    /// Only valid on a DB opened with a TTL. The C function casts the handle to
    /// `DBWithTTL` unchecked, so the caller has to have proven that already.
    fn create_inner_cf_handle_with_ttl(
        &self,
        name: impl CStrLike,
        opts: &Options,
        ttl: ColumnFamilyTtl,
    ) -> Result<*mut ffi::rocksdb_column_family_handle_t, Error> {
        let Some(db_ttl) = self.opened_with_ttl else {
            return Err(Error::new(
                "create_cf_with_ttl requires a database opened with DB::open_with_ttl \
                 or one of the open_cf*_with_ttl functions"
                    .to_owned(),
            ));
        };

        let cf_name = name.bake().map_err(|err| {
            Error::new(format!(
                "Failed to convert name to CString when creating cf with ttl: {err}"
            ))
        })?;
        let ttl = cf_ttl_to_seconds(ttl, db_ttl);

        // Can't use ffi_try: like rocksdb_create_column_family, this allocates a result
        // that needs to be freed on error.
        let mut err: *mut ::libc::c_char = ::std::ptr::null_mut();
        let cf_handle = unsafe {
            ffi::rocksdb_create_column_family_with_ttl(
                self.inner.inner(),
                opts.inner,
                cf_name.as_ptr(),
                ttl,
                &raw mut err,
            )
        };
        if !err.is_null() {
            if !cf_handle.is_null() {
                unsafe { ffi::rocksdb_column_family_handle_destroy(cf_handle) };
            }
            return Err(convert_rocksdb_error(err));
        }
        Ok(cf_handle)
    }

    pub fn iterator<'a: 'b, 'b>(
        &'a self,
        mode: IteratorMode,
    ) -> DBIteratorWithThreadMode<'b, Self> {
        let readopts = ReadOptions::default();
        self.iterator_opt(mode, readopts)
    }

    pub fn iterator_opt<'a: 'b, 'b>(
        &'a self,
        mode: IteratorMode,
        readopts: ReadOptions,
    ) -> DBIteratorWithThreadMode<'b, Self> {
        DBIteratorWithThreadMode::new(self, readopts, mode)
    }

    /// Opens an iterator using the provided ReadOptions.
    /// This is used when you want to iterate over a specific ColumnFamily with a modified ReadOptions
    pub fn iterator_cf_opt<'a: 'b, 'b>(
        &'a self,
        cf_handle: &impl AsColumnFamilyRef,
        readopts: ReadOptions,
        mode: IteratorMode,
    ) -> DBIteratorWithThreadMode<'b, Self> {
        DBIteratorWithThreadMode::new_cf(self, cf_handle.inner(), readopts, mode)
    }

    /// Opens an iterator with `set_total_order_seek` enabled.
    /// This must be used to iterate across prefixes when `set_memtable_factory` has been called
    /// with a Hash-based implementation.
    pub fn full_iterator<'a: 'b, 'b>(
        &'a self,
        mode: IteratorMode,
    ) -> DBIteratorWithThreadMode<'b, Self> {
        let mut opts = ReadOptions::default();
        opts.set_total_order_seek(true);
        DBIteratorWithThreadMode::new(self, opts, mode)
    }

    pub fn prefix_iterator<'a: 'b, 'b, P: AsRef<[u8]>>(
        &'a self,
        prefix: P,
    ) -> DBIteratorWithThreadMode<'b, Self> {
        let mut opts = ReadOptions::default();
        opts.set_prefix_same_as_start(true);
        DBIteratorWithThreadMode::new(
            self,
            opts,
            IteratorMode::From(prefix.as_ref(), Direction::Forward),
        )
    }

    pub fn iterator_cf<'a: 'b, 'b>(
        &'a self,
        cf_handle: &impl AsColumnFamilyRef,
        mode: IteratorMode,
    ) -> DBIteratorWithThreadMode<'b, Self> {
        let opts = ReadOptions::default();
        DBIteratorWithThreadMode::new_cf(self, cf_handle.inner(), opts, mode)
    }

    pub fn full_iterator_cf<'a: 'b, 'b>(
        &'a self,
        cf_handle: &impl AsColumnFamilyRef,
        mode: IteratorMode,
    ) -> DBIteratorWithThreadMode<'b, Self> {
        let mut opts = ReadOptions::default();
        opts.set_total_order_seek(true);
        DBIteratorWithThreadMode::new_cf(self, cf_handle.inner(), opts, mode)
    }

    pub fn prefix_iterator_cf<'a, P: AsRef<[u8]>>(
        &'a self,
        cf_handle: &impl AsColumnFamilyRef,
        prefix: P,
    ) -> DBIteratorWithThreadMode<'a, Self> {
        let mut opts = ReadOptions::default();
        opts.set_prefix_same_as_start(true);
        DBIteratorWithThreadMode::<'a, Self>::new_cf(
            self,
            cf_handle.inner(),
            opts,
            IteratorMode::From(prefix.as_ref(), Direction::Forward),
        )
    }

    /// Returns `true` if there exists at least one key with the given prefix
    /// in the default column family using default read options.
    ///
    /// When to use: prefer this for one-shot checks. It enables
    /// `prefix_same_as_start(true)` and bounds the iterator to the
    /// prefix via `PrefixRange`, minimizing stray IO per call.
    pub fn prefix_exists<P: AsRef<[u8]>>(&self, prefix: P) -> Result<bool, Error> {
        let p = prefix.as_ref();
        with_prefix_read_opts(p, |opts| self.prefix_exists_opt(p, opts))
    }

    /// Returns `true` if there exists at least one key with the given prefix
    /// in the default column family using the provided read options.
    pub fn prefix_exists_opt<P: AsRef<[u8]>>(
        &self,
        prefix: P,
        readopts: &ReadOptions,
    ) -> Result<bool, Error> {
        let prefix = prefix.as_ref();
        let iter = unsafe { self.create_iterator(readopts) };
        let res = unsafe {
            ffi::rocksdb_iter_seek(
                iter,
                prefix.as_ptr() as *const c_char,
                prefix.len() as size_t,
            );
            if ffi::rocksdb_iter_valid(iter) != 0 {
                let mut key_len: size_t = 0;
                let key_ptr = ffi::rocksdb_iter_key(iter, &raw mut key_len);
                // An empty key is legal, and `from_raw_parts` wants a
                // dereferenceable pointer even at length 0.
                let key = if key_len == 0 {
                    &[][..]
                } else {
                    slice::from_raw_parts(key_ptr.cast::<u8>(), key_len as usize)
                };
                Ok(key.starts_with(prefix))
            } else if let Err(e) = (|| {
                // Check status to differentiate end-of-range vs error
                ffi_try!(ffi::rocksdb_iter_get_error(iter));
                Ok::<(), Error>(())
            })() {
                Err(e)
            } else {
                Ok(false)
            }
        };
        unsafe { ffi::rocksdb_iter_destroy(iter) };
        res
    }

    /// Creates a reusable prefix prober over the default column family using
    /// read options optimized for prefix probes.
    ///
    /// When to use: prefer this in hot loops with many checks per second. It
    /// reuses a raw iterator to avoid per-call allocation/FFI overhead. If you
    /// need custom tuning (e.g. async IO, readahead, cache-only), use
    /// `prefix_prober_with_opts`.
    pub fn prefix_prober(&self) -> PrefixProber<'_, Self> {
        PrefixProber {
            raw: DBRawIteratorWithThreadMode::new(self, prefix_probe_read_opts()),
        }
    }

    /// Creates a reusable prefix prober over the default column family using
    /// the provided read options (owned).
    ///
    /// When to use: advanced tuning for heavy workloads. Callers can set
    /// `set_async_io(true)`, `set_readahead_size`, `set_read_tier`, etc. Note:
    /// the prober owns `ReadOptions` to keep internal buffers alive.
    pub fn prefix_prober_with_opts(&self, readopts: ReadOptions) -> PrefixProber<'_, Self> {
        PrefixProber {
            raw: DBRawIteratorWithThreadMode::new(self, readopts),
        }
    }

    /// Creates a reusable prefix prober over the specified column family using
    /// read options optimized for prefix probes.
    pub fn prefix_prober_cf(&self, cf_handle: &impl AsColumnFamilyRef) -> PrefixProber<'_, Self> {
        PrefixProber {
            raw: DBRawIteratorWithThreadMode::new_cf(
                self,
                cf_handle.inner(),
                prefix_probe_read_opts(),
            ),
        }
    }

    /// Creates a reusable prefix prober over the specified column family using
    /// the provided read options (owned).
    ///
    /// When to use: advanced tuning for heavy workloads on a specific CF.
    pub fn prefix_prober_cf_with_opts(
        &self,
        cf_handle: &impl AsColumnFamilyRef,
        readopts: ReadOptions,
    ) -> PrefixProber<'_, Self> {
        PrefixProber {
            raw: DBRawIteratorWithThreadMode::new_cf(self, cf_handle.inner(), readopts),
        }
    }

    /// Returns `true` if there exists at least one key with the given prefix
    /// in the specified column family using default read options.
    ///
    /// When to use: one-shot checks on a CF. Enables
    /// `prefix_same_as_start(true)` and bounds the iterator via `PrefixRange`.
    pub fn prefix_exists_cf<P: AsRef<[u8]>>(
        &self,
        cf_handle: &impl AsColumnFamilyRef,
        prefix: P,
    ) -> Result<bool, Error> {
        let p = prefix.as_ref();
        with_prefix_read_opts(p, |opts| self.prefix_exists_cf_opt(cf_handle, p, opts))
    }

    /// Returns `true` if there exists at least one key with the given prefix
    /// in the specified column family using the provided read options.
    pub fn prefix_exists_cf_opt<P: AsRef<[u8]>>(
        &self,
        cf_handle: &impl AsColumnFamilyRef,
        prefix: P,
        readopts: &ReadOptions,
    ) -> Result<bool, Error> {
        let prefix = prefix.as_ref();
        let iter = unsafe { self.create_iterator_cf(cf_handle.inner(), readopts) };
        let res = unsafe {
            ffi::rocksdb_iter_seek(
                iter,
                prefix.as_ptr() as *const c_char,
                prefix.len() as size_t,
            );
            if ffi::rocksdb_iter_valid(iter) != 0 {
                let mut key_len: size_t = 0;
                let key_ptr = ffi::rocksdb_iter_key(iter, &raw mut key_len);
                // An empty key is legal, and `from_raw_parts` wants a
                // dereferenceable pointer even at length 0.
                let key = if key_len == 0 {
                    &[][..]
                } else {
                    slice::from_raw_parts(key_ptr.cast::<u8>(), key_len as usize)
                };
                Ok(key.starts_with(prefix))
            } else if let Err(e) = (|| {
                ffi_try!(ffi::rocksdb_iter_get_error(iter));
                Ok::<(), Error>(())
            })() {
                Err(e)
            } else {
                Ok(false)
            }
        };
        unsafe { ffi::rocksdb_iter_destroy(iter) };
        res
    }

    /// Opens a raw iterator over the database, using the default read options
    pub fn raw_iterator<'a: 'b, 'b>(&'a self) -> DBRawIteratorWithThreadMode<'b, Self> {
        let opts = ReadOptions::default();
        DBRawIteratorWithThreadMode::new(self, opts)
    }

    /// Opens a raw iterator over the given column family, using the default read options
    pub fn raw_iterator_cf<'a: 'b, 'b>(
        &'a self,
        cf_handle: &impl AsColumnFamilyRef,
    ) -> DBRawIteratorWithThreadMode<'b, Self> {
        let opts = ReadOptions::default();
        DBRawIteratorWithThreadMode::new_cf(self, cf_handle.inner(), opts)
    }

    /// Opens raw iterators for multiple column families from one consistent
    /// RocksDB state.
    ///
    /// The returned iterators match the input column family order and own their
    /// native handles. They share one `ReadOptions`, because one native
    /// `rocksdb_create_iterators` call applies a single options object to every
    /// iterator it creates.
    pub fn raw_iterators_cf<'a, 'b, W, I>(
        &'a self,
        column_families: I,
    ) -> Result<Vec<DBRawIteratorWithThreadMode<'a, Self>>, Error>
    where
        W: AsColumnFamilyRef + 'b,
        I: IntoIterator<Item = &'b W>,
    {
        let mut cf_handles: Vec<_> = column_families
            .into_iter()
            .map(AsColumnFamilyRef::inner)
            .collect();
        if cf_handles.is_empty() {
            return Ok(Vec::new());
        }
        let created = self.create_iterators_cf(&mut cf_handles)?;
        Ok(created
            .handles
            .into_iter()
            .map(|handle| {
                DBRawIteratorWithThreadMode::from_inner(handle, Arc::clone(&created.readopts))
            })
            .collect())
    }

    fn create_iterators_cf(
        &self,
        cf_handles: &mut [*mut ffi::rocksdb_column_family_handle_t],
    ) -> Result<CreatedIterators, Error> {
        let mut iterator_handles = vec![ptr::null_mut(); cf_handles.len()];
        // Every iterator gets a handle on this. RocksDB's `DBIter` stores raw
        // `Slice*` into the options for iterate_lower_bound, iterate_upper_bound
        // and the read timestamps, and `ArenaWrappedDBIter::Refresh` re-reads
        // them, so the options have to outlive the last iterator rather than
        // this function. See issue #660.
        let readopts = Arc::new(ReadOptions::default());
        unsafe {
            ffi_try!(ffi::rust_rocksdb_create_iterators_safe(
                self.inner.inner(),
                readopts.inner,
                cf_handles.as_mut_ptr(),
                iterator_handles.as_mut_ptr(),
                iterator_handles.len(),
            ));
        }
        Self::validate_created_iterators(&iterator_handles)?;
        Ok(CreatedIterators {
            readopts,
            handles: iterator_handles,
        })
    }

    fn validate_created_iterators(
        iterator_handles: &[*mut ffi::rocksdb_iterator_t],
    ) -> Result<(), Error> {
        if iterator_handles.iter().any(|iterator| iterator.is_null()) {
            unsafe {
                Self::destroy_iterators(iterator_handles);
            }
            return Err(Error::new(
                "rocksdb_create_iterators returned a null iterator".to_owned(),
            ));
        }
        Ok(())
    }

    /// Destroys non-null iterator handles owned by the caller.
    ///
    /// # Safety
    ///
    /// Every non-null pointer must identify a live, uniquely owned RocksDB iterator.
    unsafe fn destroy_iterators(iterators: &[*mut ffi::rocksdb_iterator_t]) {
        for &iterator in iterators {
            if !iterator.is_null() {
                unsafe {
                    ffi::rocksdb_iter_destroy(iterator);
                }
            }
        }
    }

    /// Opens a raw iterator over the database, using the given read options
    pub fn raw_iterator_opt<'a: 'b, 'b>(
        &'a self,
        readopts: ReadOptions,
    ) -> DBRawIteratorWithThreadMode<'b, Self> {
        DBRawIteratorWithThreadMode::new(self, readopts)
    }

    /// Opens a raw iterator over the given column family, using the given read options
    pub fn raw_iterator_cf_opt<'a: 'b, 'b>(
        &'a self,
        cf_handle: &impl AsColumnFamilyRef,
        readopts: ReadOptions,
    ) -> DBRawIteratorWithThreadMode<'b, Self> {
        DBRawIteratorWithThreadMode::new_cf(self, cf_handle.inner(), readopts)
    }

    pub fn snapshot(&'_ self) -> SnapshotWithThreadMode<'_, Self> {
        SnapshotWithThreadMode::<Self>::new(self)
    }

    pub fn put_opt<K, V>(&self, key: K, value: V, writeopts: &WriteOptions) -> Result<(), Error>
    where
        K: AsRef<[u8]>,
        V: AsRef<[u8]>,
    {
        let key = key.as_ref();
        let value = value.as_ref();

        unsafe {
            ffi_try!(ffi::rocksdb_put(
                self.inner.inner(),
                writeopts.inner,
                key.as_ptr() as *const c_char,
                key.len() as size_t,
                value.as_ptr() as *const c_char,
                value.len() as size_t,
            ));
            Ok(())
        }
    }

    pub fn put_cf_opt<K, V>(
        &self,
        cf: &impl AsColumnFamilyRef,
        key: K,
        value: V,
        writeopts: &WriteOptions,
    ) -> Result<(), Error>
    where
        K: AsRef<[u8]>,
        V: AsRef<[u8]>,
    {
        let key = key.as_ref();
        let value = value.as_ref();

        unsafe {
            ffi_try!(ffi::rocksdb_put_cf(
                self.inner.inner(),
                writeopts.inner,
                cf.inner(),
                key.as_ptr() as *const c_char,
                key.len() as size_t,
                value.as_ptr() as *const c_char,
                value.len() as size_t,
            ));
            Ok(())
        }
    }

    /// Set the database entry for "key" to "value" with WriteOptions.
    /// If "key" already exists, it will coexist with previous entry.
    /// `Get` with a timestamp ts specified in ReadOptions will return
    /// the most recent key/value whose timestamp is smaller than or equal to ts.
    /// Takes an additional argument `ts` as the timestamp.
    /// Note: the DB must be opened with user defined timestamp enabled.
    pub fn put_with_ts_opt<K, V, S>(
        &self,
        key: K,
        ts: S,
        value: V,
        writeopts: &WriteOptions,
    ) -> Result<(), Error>
    where
        K: AsRef<[u8]>,
        V: AsRef<[u8]>,
        S: AsRef<[u8]>,
    {
        let key = key.as_ref();
        let value = value.as_ref();
        let ts = ts.as_ref();
        unsafe {
            ffi_try!(ffi::rocksdb_put_with_ts(
                self.inner.inner(),
                writeopts.inner,
                key.as_ptr() as *const c_char,
                key.len() as size_t,
                ts.as_ptr() as *const c_char,
                ts.len() as size_t,
                value.as_ptr() as *const c_char,
                value.len() as size_t,
            ));
            Ok(())
        }
    }

    /// Put with timestamp in a specific column family with WriteOptions.
    /// If "key" already exists, it will coexist with previous entry.
    /// `Get` with a timestamp ts specified in ReadOptions will return
    /// the most recent key/value whose timestamp is smaller than or equal to ts.
    /// Takes an additional argument `ts` as the timestamp.
    /// Note: the DB must be opened with user defined timestamp enabled.
    pub fn put_cf_with_ts_opt<K, V, S>(
        &self,
        cf: &impl AsColumnFamilyRef,
        key: K,
        ts: S,
        value: V,
        writeopts: &WriteOptions,
    ) -> Result<(), Error>
    where
        K: AsRef<[u8]>,
        V: AsRef<[u8]>,
        S: AsRef<[u8]>,
    {
        let key = key.as_ref();
        let value = value.as_ref();
        let ts = ts.as_ref();
        unsafe {
            ffi_try!(ffi::rocksdb_put_cf_with_ts(
                self.inner.inner(),
                writeopts.inner,
                cf.inner(),
                key.as_ptr() as *const c_char,
                key.len() as size_t,
                ts.as_ptr() as *const c_char,
                ts.len() as size_t,
                value.as_ptr() as *const c_char,
                value.len() as size_t,
            ));
            Ok(())
        }
    }

    pub fn merge_opt<K, V>(&self, key: K, value: V, writeopts: &WriteOptions) -> Result<(), Error>
    where
        K: AsRef<[u8]>,
        V: AsRef<[u8]>,
    {
        let key = key.as_ref();
        let value = value.as_ref();

        unsafe {
            ffi_try!(ffi::rocksdb_merge(
                self.inner.inner(),
                writeopts.inner,
                key.as_ptr() as *const c_char,
                key.len() as size_t,
                value.as_ptr() as *const c_char,
                value.len() as size_t,
            ));
            Ok(())
        }
    }

    pub fn merge_cf_opt<K, V>(
        &self,
        cf: &impl AsColumnFamilyRef,
        key: K,
        value: V,
        writeopts: &WriteOptions,
    ) -> Result<(), Error>
    where
        K: AsRef<[u8]>,
        V: AsRef<[u8]>,
    {
        let key = key.as_ref();
        let value = value.as_ref();

        unsafe {
            ffi_try!(ffi::rocksdb_merge_cf(
                self.inner.inner(),
                writeopts.inner,
                cf.inner(),
                key.as_ptr() as *const c_char,
                key.len() as size_t,
                value.as_ptr() as *const c_char,
                value.len() as size_t,
            ));
            Ok(())
        }
    }

    pub fn delete_opt<K: AsRef<[u8]>>(
        &self,
        key: K,
        writeopts: &WriteOptions,
    ) -> Result<(), Error> {
        let key = key.as_ref();

        unsafe {
            ffi_try!(ffi::rocksdb_delete(
                self.inner.inner(),
                writeopts.inner,
                key.as_ptr() as *const c_char,
                key.len() as size_t,
            ));
            Ok(())
        }
    }

    pub fn delete_cf_opt<K: AsRef<[u8]>>(
        &self,
        cf: &impl AsColumnFamilyRef,
        key: K,
        writeopts: &WriteOptions,
    ) -> Result<(), Error> {
        let key = key.as_ref();

        unsafe {
            ffi_try!(ffi::rocksdb_delete_cf(
                self.inner.inner(),
                writeopts.inner,
                cf.inner(),
                key.as_ptr() as *const c_char,
                key.len() as size_t,
            ));
            Ok(())
        }
    }

    /// Remove the database entry (if any) for "key" with WriteOptions.
    /// Takes an additional argument `ts` as the timestamp.
    /// Note: the DB must be opened with user defined timestamp enabled.
    pub fn delete_with_ts_opt<K, S>(
        &self,
        key: K,
        ts: S,
        writeopts: &WriteOptions,
    ) -> Result<(), Error>
    where
        K: AsRef<[u8]>,
        S: AsRef<[u8]>,
    {
        let key = key.as_ref();
        let ts = ts.as_ref();
        unsafe {
            ffi_try!(ffi::rocksdb_delete_with_ts(
                self.inner.inner(),
                writeopts.inner,
                key.as_ptr() as *const c_char,
                key.len() as size_t,
                ts.as_ptr() as *const c_char,
                ts.len() as size_t,
            ));
            Ok(())
        }
    }

    /// Delete with timestamp in a specific column family with WriteOptions.
    /// Takes an additional argument `ts` as the timestamp.
    /// Note: the DB must be opened with user defined timestamp enabled.
    pub fn delete_cf_with_ts_opt<K, S>(
        &self,
        cf: &impl AsColumnFamilyRef,
        key: K,
        ts: S,
        writeopts: &WriteOptions,
    ) -> Result<(), Error>
    where
        K: AsRef<[u8]>,
        S: AsRef<[u8]>,
    {
        let key = key.as_ref();
        let ts = ts.as_ref();
        unsafe {
            ffi_try!(ffi::rocksdb_delete_cf_with_ts(
                self.inner.inner(),
                writeopts.inner,
                cf.inner(),
                key.as_ptr() as *const c_char,
                key.len() as size_t,
                ts.as_ptr() as *const c_char,
                ts.len() as size_t,
            ));
            Ok(())
        }
    }

    pub fn put<K, V>(&self, key: K, value: V) -> Result<(), Error>
    where
        K: AsRef<[u8]>,
        V: AsRef<[u8]>,
    {
        DEFAULT_WRITE_OPTS.with(|opts| self.put_opt(key, value, opts))
    }

    pub fn put_cf<K, V>(&self, cf: &impl AsColumnFamilyRef, key: K, value: V) -> Result<(), Error>
    where
        K: AsRef<[u8]>,
        V: AsRef<[u8]>,
    {
        DEFAULT_WRITE_OPTS.with(|opts| self.put_cf_opt(cf, key, value, opts))
    }

    /// Set the database entry for "key" to "value".
    /// If "key" already exists, it will coexist with previous entry.
    /// `Get` with a timestamp ts specified in ReadOptions will return
    /// the most recent key/value whose timestamp is smaller than or equal to ts.
    /// Takes an additional argument `ts` as the timestamp.
    /// Note: the DB must be opened with user defined timestamp enabled.
    pub fn put_with_ts<K, V, S>(&self, key: K, ts: S, value: V) -> Result<(), Error>
    where
        K: AsRef<[u8]>,
        V: AsRef<[u8]>,
        S: AsRef<[u8]>,
    {
        DEFAULT_WRITE_OPTS
            .with(|opts| self.put_with_ts_opt(key.as_ref(), ts.as_ref(), value.as_ref(), opts))
    }

    /// Put with timestamp in a specific column family.
    /// If "key" already exists, it will coexist with previous entry.
    /// `Get` with a timestamp ts specified in ReadOptions will return
    /// the most recent key/value whose timestamp is smaller than or equal to ts.
    /// Takes an additional argument `ts` as the timestamp.
    /// Note: the DB must be opened with user defined timestamp enabled.
    pub fn put_cf_with_ts<K, V, S>(
        &self,
        cf: &impl AsColumnFamilyRef,
        key: K,
        ts: S,
        value: V,
    ) -> Result<(), Error>
    where
        K: AsRef<[u8]>,
        V: AsRef<[u8]>,
        S: AsRef<[u8]>,
    {
        DEFAULT_WRITE_OPTS.with(|opts| {
            self.put_cf_with_ts_opt(cf, key.as_ref(), ts.as_ref(), value.as_ref(), opts)
        })
    }

    pub fn merge<K, V>(&self, key: K, value: V) -> Result<(), Error>
    where
        K: AsRef<[u8]>,
        V: AsRef<[u8]>,
    {
        DEFAULT_WRITE_OPTS.with(|opts| self.merge_opt(key, value, opts))
    }

    pub fn merge_cf<K, V>(&self, cf: &impl AsColumnFamilyRef, key: K, value: V) -> Result<(), Error>
    where
        K: AsRef<[u8]>,
        V: AsRef<[u8]>,
    {
        DEFAULT_WRITE_OPTS.with(|opts| self.merge_cf_opt(cf, key, value, opts))
    }

    pub fn delete<K: AsRef<[u8]>>(&self, key: K) -> Result<(), Error> {
        DEFAULT_WRITE_OPTS.with(|opts| self.delete_opt(key, opts))
    }

    pub fn delete_cf<K: AsRef<[u8]>>(
        &self,
        cf: &impl AsColumnFamilyRef,
        key: K,
    ) -> Result<(), Error> {
        DEFAULT_WRITE_OPTS.with(|opts| self.delete_cf_opt(cf, key, opts))
    }

    /// Remove the database entry (if any) for "key".
    /// Takes an additional argument `ts` as the timestamp.
    /// Note: the DB must be opened with user defined timestamp enabled.
    pub fn delete_with_ts<K: AsRef<[u8]>, S: AsRef<[u8]>>(
        &self,
        key: K,
        ts: S,
    ) -> Result<(), Error> {
        DEFAULT_WRITE_OPTS.with(|opts| self.delete_with_ts_opt(key, ts, opts))
    }

    /// Delete with timestamp in a specific column family.
    /// Takes an additional argument `ts` as the timestamp.
    /// Note: the DB must be opened with user defined timestamp enabled.
    pub fn delete_cf_with_ts<K: AsRef<[u8]>, S: AsRef<[u8]>>(
        &self,
        cf: &impl AsColumnFamilyRef,
        key: K,
        ts: S,
    ) -> Result<(), Error> {
        DEFAULT_WRITE_OPTS.with(|opts| self.delete_cf_with_ts_opt(cf, key, ts, opts))
    }

    /// Remove the database entry for "key" with WriteOptions.
    ///
    /// Requires that the key exists and was not overwritten. Returns OK on success,
    /// and a non-OK status on error. It is not an error if "key" did not exist in the database.
    ///
    /// If a key is overwritten (by calling Put() multiple times), then the result
    /// of calling SingleDelete() on this key is undefined. SingleDelete() only
    /// behaves correctly if there has been only one Put() for this key since the
    /// previous call to SingleDelete() for this key.
    ///
    /// This feature is currently an experimental performance optimization
    /// for a very specific workload. It is up to the caller to ensure that
    /// SingleDelete is only used for a key that is not deleted using Delete() or
    /// written using Merge(). Mixing SingleDelete operations with Deletes and
    /// Merges can result in undefined behavior.
    ///
    /// Note: consider setting options.sync = true.
    ///
    /// For more information, see <https://github.com/facebook/rocksdb/wiki/Single-Delete>
    pub fn single_delete_opt<K: AsRef<[u8]>>(
        &self,
        key: K,
        writeopts: &WriteOptions,
    ) -> Result<(), Error> {
        let key = key.as_ref();

        unsafe {
            ffi_try!(ffi::rocksdb_singledelete(
                self.inner.inner(),
                writeopts.inner,
                key.as_ptr() as *const c_char,
                key.len() as size_t,
            ));
            Ok(())
        }
    }

    /// Remove the database entry for "key" from a specific column family with WriteOptions.
    ///
    /// See single_delete_opt() for detailed behavior and restrictions.
    pub fn single_delete_cf_opt<K: AsRef<[u8]>>(
        &self,
        cf: &impl AsColumnFamilyRef,
        key: K,
        writeopts: &WriteOptions,
    ) -> Result<(), Error> {
        let key = key.as_ref();

        unsafe {
            ffi_try!(ffi::rocksdb_singledelete_cf(
                self.inner.inner(),
                writeopts.inner,
                cf.inner(),
                key.as_ptr() as *const c_char,
                key.len() as size_t,
            ));
            Ok(())
        }
    }

    /// Remove the database entry for "key" with WriteOptions.
    ///
    /// Takes an additional argument `ts` as the timestamp.
    /// Note: the DB must be opened with user defined timestamp enabled.
    ///
    /// See single_delete_opt() for detailed behavior and restrictions.
    pub fn single_delete_with_ts_opt<K, S>(
        &self,
        key: K,
        ts: S,
        writeopts: &WriteOptions,
    ) -> Result<(), Error>
    where
        K: AsRef<[u8]>,
        S: AsRef<[u8]>,
    {
        let key = key.as_ref();
        let ts = ts.as_ref();
        unsafe {
            ffi_try!(ffi::rocksdb_singledelete_with_ts(
                self.inner.inner(),
                writeopts.inner,
                key.as_ptr() as *const c_char,
                key.len() as size_t,
                ts.as_ptr() as *const c_char,
                ts.len() as size_t,
            ));
            Ok(())
        }
    }

    /// Remove the database entry for "key" from a specific column family with WriteOptions.
    ///
    /// Takes an additional argument `ts` as the timestamp.
    /// Note: the DB must be opened with user defined timestamp enabled.
    ///
    /// See single_delete_opt() for detailed behavior and restrictions.
    pub fn single_delete_cf_with_ts_opt<K, S>(
        &self,
        cf: &impl AsColumnFamilyRef,
        key: K,
        ts: S,
        writeopts: &WriteOptions,
    ) -> Result<(), Error>
    where
        K: AsRef<[u8]>,
        S: AsRef<[u8]>,
    {
        let key = key.as_ref();
        let ts = ts.as_ref();
        unsafe {
            ffi_try!(ffi::rocksdb_singledelete_cf_with_ts(
                self.inner.inner(),
                writeopts.inner,
                cf.inner(),
                key.as_ptr() as *const c_char,
                key.len() as size_t,
                ts.as_ptr() as *const c_char,
                ts.len() as size_t,
            ));
            Ok(())
        }
    }

    /// Remove the database entry for "key".
    ///
    /// See single_delete_opt() for detailed behavior and restrictions.
    pub fn single_delete<K: AsRef<[u8]>>(&self, key: K) -> Result<(), Error> {
        DEFAULT_WRITE_OPTS.with(|opts| self.single_delete_opt(key, opts))
    }

    /// Remove the database entry for "key" from a specific column family.
    ///
    /// See single_delete_opt() for detailed behavior and restrictions.
    pub fn single_delete_cf<K: AsRef<[u8]>>(
        &self,
        cf: &impl AsColumnFamilyRef,
        key: K,
    ) -> Result<(), Error> {
        DEFAULT_WRITE_OPTS.with(|opts| self.single_delete_cf_opt(cf, key, opts))
    }

    /// Remove the database entry for "key".
    ///
    /// Takes an additional argument `ts` as the timestamp.
    /// Note: the DB must be opened with user defined timestamp enabled.
    ///
    /// See single_delete_opt() for detailed behavior and restrictions.
    pub fn single_delete_with_ts<K: AsRef<[u8]>, S: AsRef<[u8]>>(
        &self,
        key: K,
        ts: S,
    ) -> Result<(), Error> {
        DEFAULT_WRITE_OPTS.with(|opts| self.single_delete_with_ts_opt(key, ts, opts))
    }

    /// Remove the database entry for "key" from a specific column family.
    ///
    /// Takes an additional argument `ts` as the timestamp.
    /// Note: the DB must be opened with user defined timestamp enabled.
    ///
    /// See single_delete_opt() for detailed behavior and restrictions.
    pub fn single_delete_cf_with_ts<K: AsRef<[u8]>, S: AsRef<[u8]>>(
        &self,
        cf: &impl AsColumnFamilyRef,
        key: K,
        ts: S,
    ) -> Result<(), Error> {
        DEFAULT_WRITE_OPTS.with(|opts| self.single_delete_cf_with_ts_opt(cf, key, ts, opts))
    }

    /// Runs a manual compaction on the Range of keys given. This is not likely to be needed for typical usage.
    pub fn compact_range<S: AsRef<[u8]>, E: AsRef<[u8]>>(&self, start: Option<S>, end: Option<E>) {
        unsafe {
            let start = start.as_ref().map(AsRef::as_ref);
            let end = end.as_ref().map(AsRef::as_ref);

            ffi::rocksdb_compact_range(
                self.inner.inner(),
                opt_bytes_to_ptr(start),
                start.map_or(0, <[u8]>::len) as size_t,
                opt_bytes_to_ptr(end),
                end.map_or(0, <[u8]>::len) as size_t,
            );
        }
    }

    /// Same as `compact_range` but with custom options.
    pub fn compact_range_opt<S: AsRef<[u8]>, E: AsRef<[u8]>>(
        &self,
        start: Option<S>,
        end: Option<E>,
        opts: &CompactOptions,
    ) {
        unsafe {
            let start = start.as_ref().map(AsRef::as_ref);
            let end = end.as_ref().map(AsRef::as_ref);

            ffi::rocksdb_compact_range_opt(
                self.inner.inner(),
                opts.inner,
                opt_bytes_to_ptr(start),
                start.map_or(0, <[u8]>::len) as size_t,
                opt_bytes_to_ptr(end),
                end.map_or(0, <[u8]>::len) as size_t,
            );
        }
    }

    /// Runs a manual compaction on the Range of keys given on the
    /// given column family. This is not likely to be needed for typical usage.
    pub fn compact_range_cf<S: AsRef<[u8]>, E: AsRef<[u8]>>(
        &self,
        cf: &impl AsColumnFamilyRef,
        start: Option<S>,
        end: Option<E>,
    ) {
        unsafe {
            let start = start.as_ref().map(AsRef::as_ref);
            let end = end.as_ref().map(AsRef::as_ref);

            ffi::rocksdb_compact_range_cf(
                self.inner.inner(),
                cf.inner(),
                opt_bytes_to_ptr(start),
                start.map_or(0, <[u8]>::len) as size_t,
                opt_bytes_to_ptr(end),
                end.map_or(0, <[u8]>::len) as size_t,
            );
        }
    }

    /// Same as `compact_range_cf` but with custom options.
    pub fn compact_range_cf_opt<S: AsRef<[u8]>, E: AsRef<[u8]>>(
        &self,
        cf: &impl AsColumnFamilyRef,
        start: Option<S>,
        end: Option<E>,
        opts: &CompactOptions,
    ) {
        unsafe {
            let start = start.as_ref().map(AsRef::as_ref);
            let end = end.as_ref().map(AsRef::as_ref);

            ffi::rocksdb_compact_range_cf_opt(
                self.inner.inner(),
                cf.inner(),
                opts.inner,
                opt_bytes_to_ptr(start),
                start.map_or(0, <[u8]>::len) as size_t,
                opt_bytes_to_ptr(end),
                end.map_or(0, <[u8]>::len) as size_t,
            );
        }
    }

    /// Wait for all flush and compactions jobs to finish. Jobs to wait include the
    /// unscheduled (queued, but not scheduled yet).
    ///
    /// NOTE: This may also never return if there's sufficient ongoing writes that
    /// keeps flush and compaction going without stopping. The user would have to
    /// cease all the writes to DB to make this eventually return in a stable
    /// state. The user may also use timeout option in WaitForCompactOptions to
    /// make this stop waiting and return when timeout expires.
    pub fn wait_for_compact(&self, opts: &WaitForCompactOptions) -> Result<(), Error> {
        unsafe {
            ffi_try!(ffi::rocksdb_wait_for_compact(
                self.inner.inner(),
                opts.inner
            ));
        }
        Ok(())
    }

    /// Changes mutable column family options on the default column family at
    /// runtime.
    ///
    /// [`set_db_options`](Self::set_db_options) is the DB wide equivalent. Either the
    /// whole set is applied or none of it is.
    ///
    /// # Aborts
    ///
    /// Some unparseable values take the process down instead of returning an error,
    /// so validate values before passing them here.
    ///
    /// RocksDB parses integers with `std::stoi` and friends
    /// (`util/string_util.cc:378`), which throw `std::invalid_argument`. It does try
    /// to catch that, but not everywhere, and an integer-valued option such as
    /// `write_buffer_size` given a non-numeric value aborts the process with
    /// "Rust cannot catch foreign exceptions". A boolean-valued option such as
    /// `disable_auto_compactions` returns an error instead. Do not rely on which
    /// options fall on which side of that line.
    ///
    /// Catching it here is not an option. `ColumnFamilyData::SetOptions` runs inside
    /// a callback that `VersionSet::LogAndApply` invokes while holding the DB mutex
    /// as the exclusive manifest writer (`db/db_impl/db_impl.cc:1655`), so unwinding
    /// through it leaves that state behind and the next option change on the DB
    /// blocks forever in `InstrumentedCondVar::Wait`. That was reproducible under
    /// ASAN and silent otherwise, which is worse than aborting.
    ///
    /// # Errors
    ///
    /// Returns the RocksDB error if a name is unknown or the option is not changeable
    /// at runtime. Also errors if any name or value contains an interior NUL byte.
    pub fn set_options(&self, opts: &[(&str, &str)]) -> Result<(), Error> {
        let copts = convert_options(opts)?;
        let cnames: Vec<*const c_char> = copts.iter().map(|opt| opt.0.as_ptr()).collect();
        let cvalues: Vec<*const c_char> = copts.iter().map(|opt| opt.1.as_ptr()).collect();
        unsafe {
            ffi_try!(ffi::rocksdb_set_options(
                self.inner.inner(),
                option_count(&copts)?,
                cnames.as_ptr(),
                cvalues.as_ptr(),
            ));
        }
        Ok(())
    }

    /// Like [`set_options`](Self::set_options), for a single column family.
    ///
    /// # Aborts
    ///
    /// See [`set_options`](Self::set_options).
    ///
    /// # Errors
    ///
    /// See [`set_options`](Self::set_options).
    pub fn set_options_cf(
        &self,
        cf: &impl AsColumnFamilyRef,
        opts: &[(&str, &str)],
    ) -> Result<(), Error> {
        let copts = convert_options(opts)?;
        let cnames: Vec<*const c_char> = copts.iter().map(|opt| opt.0.as_ptr()).collect();
        let cvalues: Vec<*const c_char> = copts.iter().map(|opt| opt.1.as_ptr()).collect();
        unsafe {
            ffi_try!(ffi::rocksdb_set_options_cf(
                self.inner.inner(),
                cf.inner(),
                option_count(&copts)?,
                cnames.as_ptr(),
                cvalues.as_ptr(),
            ));
        }
        Ok(())
    }

    /// Implementation for property_value et al methods.
    ///
    /// `name` is the name of the property.  It will be converted into a CString
    /// and passed to `get_property` as argument.  `get_property` reads the
    /// specified property and either returns NULL or a pointer to a C allocated
    /// string; this method takes ownership of that string and will free it at
    /// the end. That string is parsed using `parse` callback which produces
    /// the returned result.
    fn property_value_impl<R>(
        name: impl CStrLike,
        get_property: impl FnOnce(*const c_char) -> *mut c_char,
        parse: impl FnOnce(&str) -> Result<R, Error>,
    ) -> Result<Option<R>, Error> {
        let value = match name.bake() {
            Ok(prop_name) => get_property(prop_name.as_ptr()),
            Err(e) => {
                return Err(Error::new(format!(
                    "Failed to convert property name to CString: {e}"
                )));
            }
        };
        if value.is_null() {
            return Ok(None);
        }
        let result = match unsafe { CStr::from_ptr(value) }.to_str() {
            Ok(s) => parse(s).map(|value| Some(value)),
            Err(e) => Err(Error::new(format!(
                "Failed to convert property value to string: {e}"
            ))),
        };
        unsafe {
            ffi::rocksdb_free(value as *mut c_void);
        }
        result
    }

    /// Retrieves a RocksDB property by name.
    ///
    /// Full list of properties could be find
    /// [here](https://github.com/facebook/rocksdb/blob/08809f5e6cd9cc4bc3958dd4d59457ae78c76660/include/rocksdb/db.h#L428-L634).
    pub fn property_value(&self, name: impl CStrLike) -> Result<Option<String>, Error> {
        Self::property_value_impl(
            name,
            |prop_name| unsafe { ffi::rocksdb_property_value(self.inner.inner(), prop_name) },
            |str_value| Ok(str_value.to_owned()),
        )
    }

    /// Retrieves a RocksDB property by name, for a specific column family.
    ///
    /// Full list of properties could be find
    /// [here](https://github.com/facebook/rocksdb/blob/08809f5e6cd9cc4bc3958dd4d59457ae78c76660/include/rocksdb/db.h#L428-L634).
    pub fn property_value_cf(
        &self,
        cf: &impl AsColumnFamilyRef,
        name: impl CStrLike,
    ) -> Result<Option<String>, Error> {
        Self::property_value_impl(
            name,
            |prop_name| unsafe {
                ffi::rocksdb_property_value_cf(self.inner.inner(), cf.inner(), prop_name)
            },
            |str_value| Ok(str_value.to_owned()),
        )
    }

    fn property_int_value_impl(
        name: impl CStrLike,
        get_property: impl FnOnce(*const c_char, *mut u64) -> c_int,
        get_string_property: impl FnOnce(*const c_char) -> *mut c_char,
    ) -> Result<Option<u64>, Error> {
        let prop_name = name.bake().map_err(|err| {
            Error::new(format!("Failed to convert property name to CString: {err}"))
        })?;
        let mut value = 0;
        if get_property(prop_name.as_ptr(), &raw mut value) == 0 {
            return Ok(Some(value));
        }

        Self::property_value_impl(
            prop_name.as_ref(),
            get_string_property,
            Self::parse_property_int_value,
        )
    }

    fn parse_property_int_value(value: &str) -> Result<u64, Error> {
        value.parse::<u64>().map_err(|err| {
            Error::new(format!(
                "Failed to convert property value {value} to int: {err}"
            ))
        })
    }

    /// Retrieves a RocksDB property and casts it to an integer.
    ///
    /// Full list of properties that return int values could be find
    /// [here](https://github.com/facebook/rocksdb/blob/08809f5e6cd9cc4bc3958dd4d59457ae78c76660/include/rocksdb/db.h#L654-L689).
    pub fn property_int_value(&self, name: impl CStrLike) -> Result<Option<u64>, Error> {
        Self::property_int_value_impl(
            name,
            |prop_name, value| unsafe {
                ffi::rocksdb_property_int(self.inner.inner(), prop_name, value)
            },
            |prop_name| unsafe { ffi::rocksdb_property_value(self.inner.inner(), prop_name) },
        )
    }

    /// Retrieves a RocksDB property for a specific column family and casts it to an integer.
    ///
    /// Full list of properties that return int values could be find
    /// [here](https://github.com/facebook/rocksdb/blob/08809f5e6cd9cc4bc3958dd4d59457ae78c76660/include/rocksdb/db.h#L654-L689).
    pub fn property_int_value_cf(
        &self,
        cf: &impl AsColumnFamilyRef,
        name: impl CStrLike,
    ) -> Result<Option<u64>, Error> {
        Self::property_int_value_impl(
            name,
            |prop_name, value| unsafe {
                ffi::rocksdb_property_int_cf(self.inner.inner(), cf.inner(), prop_name, value)
            },
            |prop_name| unsafe {
                ffi::rocksdb_property_value_cf(self.inner.inner(), cf.inner(), prop_name)
            },
        )
    }

    /// The sequence number of the most recent transaction.
    pub fn latest_sequence_number(&self) -> u64 {
        unsafe { ffi::rocksdb_get_latest_sequence_number(self.inner.inner()) }
    }

    /// Return the approximate file system space used by keys in each ranges.
    ///
    /// Note that the returned sizes measure file system space usage, so
    /// if the user data compresses by a factor of ten, the returned
    /// sizes will be one-tenth the size of the corresponding user data size.
    ///
    /// Due to lack of abi, only data flushed to disk is taken into account.
    /// # Errors
    ///
    /// Returns the RocksDB error if the size estimate fails, for instance on an
    /// I/O error reading the manifest. No partial sizes are reported in that
    /// case.
    pub fn get_approximate_sizes(&self, ranges: &[Range]) -> Result<Vec<u64>, Error> {
        self.get_approximate_sizes_cfopt(None::<&ColumnFamily>, ranges)
    }

    /// Like [`Self::get_approximate_sizes`], for a single column family.
    ///
    /// # Errors
    ///
    /// See [`Self::get_approximate_sizes`].
    pub fn get_approximate_sizes_cf(
        &self,
        cf: &impl AsColumnFamilyRef,
        ranges: &[Range],
    ) -> Result<Vec<u64>, Error> {
        self.get_approximate_sizes_cfopt(Some(cf), ranges)
    }

    fn get_approximate_sizes_cfopt(
        &self,
        cf: Option<&impl AsColumnFamilyRef>,
        ranges: &[Range],
    ) -> Result<Vec<u64>, Error> {
        let mut args = ApproximateSizesArgs::new(ranges);
        let mut err: *mut c_char = ptr::null_mut();
        match cf {
            None => unsafe {
                ffi::rocksdb_approximate_sizes(
                    self.inner.inner(),
                    args.count,
                    args.start_keys.as_ptr(),
                    args.start_key_lens.as_ptr(),
                    args.end_keys.as_ptr(),
                    args.end_key_lens.as_ptr(),
                    args.sizes.as_mut_ptr(),
                    &raw mut err,
                );
            },
            Some(cf) => unsafe {
                ffi::rocksdb_approximate_sizes_cf(
                    self.inner.inner(),
                    cf.inner(),
                    args.count,
                    args.start_keys.as_ptr(),
                    args.start_key_lens.as_ptr(),
                    args.end_keys.as_ptr(),
                    args.end_key_lens.as_ptr(),
                    args.sizes.as_mut_ptr(),
                    &raw mut err,
                );
            },
        }
        args.finish(err)
    }

    /// Like [`Self::get_approximate_sizes`], but lets the caller say what counts
    /// towards the total and how precise the answer has to be.
    ///
    /// [`Self::get_approximate_sizes`] counts SST files only. Pass a
    /// [`SizeApproximationOptions`] with
    /// [`set_include_memtables`](SizeApproximationOptions::set_include_memtables)
    /// on to include writes that have not been flushed yet.
    ///
    /// # Errors
    ///
    /// See [`Self::get_approximate_sizes`].
    pub fn get_approximate_sizes_with_options(
        &self,
        opts: &SizeApproximationOptions,
        ranges: &[Range],
    ) -> Result<Vec<u64>, Error> {
        let mut args = ApproximateSizesArgs::new(ranges);
        let mut err: *mut c_char = ptr::null_mut();
        unsafe {
            ffi::rocksdb_approximate_sizes_with_options(
                self.inner.inner(),
                opts.as_ptr(),
                args.count,
                args.start_keys.as_ptr(),
                args.start_key_lens.as_ptr(),
                args.end_keys.as_ptr(),
                args.end_key_lens.as_ptr(),
                args.sizes.as_mut_ptr(),
                &raw mut err,
            );
        }
        args.finish(err)
    }

    /// Like [`Self::get_approximate_sizes_with_options`], for a single column
    /// family.
    ///
    /// # Errors
    ///
    /// See [`Self::get_approximate_sizes`].
    pub fn get_approximate_sizes_cf_with_options(
        &self,
        cf: &impl AsColumnFamilyRef,
        opts: &SizeApproximationOptions,
        ranges: &[Range],
    ) -> Result<Vec<u64>, Error> {
        let mut args = ApproximateSizesArgs::new(ranges);
        let mut err: *mut c_char = ptr::null_mut();
        unsafe {
            ffi::rocksdb_approximate_sizes_cf_with_options(
                self.inner.inner(),
                cf.inner(),
                opts.as_ptr(),
                args.count,
                args.start_keys.as_ptr(),
                args.start_key_lens.as_ptr(),
                args.end_keys.as_ptr(),
                args.end_key_lens.as_ptr(),
                args.sizes.as_mut_ptr(),
                &raw mut err,
            );
        }
        args.finish(err)
    }

    /// Like [`Self::get_approximate_sizes_cf_with_options`], but selects what
    /// counts with a flag set instead of an options object.
    ///
    /// Prefer [`Self::get_approximate_sizes_cf_with_options`], which can also
    /// set an error margin. This variant exists because it is the form RocksDB
    /// offers without allocating.
    ///
    /// # Errors
    ///
    /// See [`Self::get_approximate_sizes`].
    pub fn get_approximate_sizes_cf_with_flags(
        &self,
        cf: &impl AsColumnFamilyRef,
        flags: SizeApproximationFlags,
        ranges: &[Range],
    ) -> Result<Vec<u64>, Error> {
        let mut args = ApproximateSizesArgs::new(ranges);
        let mut err: *mut c_char = ptr::null_mut();
        unsafe {
            ffi::rocksdb_approximate_sizes_cf_with_flags(
                self.inner.inner(),
                cf.inner(),
                args.count,
                args.start_keys.as_ptr(),
                args.start_key_lens.as_ptr(),
                args.end_keys.as_ptr(),
                args.end_key_lens.as_ptr(),
                flags.bits(),
                args.sizes.as_mut_ptr(),
                &raw mut err,
            );
        }
        args.finish(err)
    }

    /// Iterate over batches of write operations since a given sequence.
    ///
    /// Produce an iterator that will provide the batches of write operations
    /// that have occurred since the given sequence (see
    /// `latest_sequence_number()`). Use the provided iterator to retrieve each
    /// (`u64`, `WriteBatch`) tuple, and then gather the individual puts and
    /// deletes using the `WriteBatch::iterate()` function.
    ///
    /// Calling `get_updates_since()` with a sequence number that is out of
    /// bounds will return an error.
    pub fn get_updates_since(&self, seq_number: u64) -> Result<DBWALIterator, Error> {
        unsafe {
            // rocksdb_wal_readoptions_t does not appear to have any functions
            // for creating and destroying it; fortunately we can pass a nullptr
            // here to get the default behavior
            let opts: *const ffi::rocksdb_wal_readoptions_t = ptr::null();
            let iter = ffi_try!(ffi::rocksdb_get_updates_since(
                self.inner.inner(),
                seq_number,
                opts
            ));
            Ok(DBWALIterator {
                inner: iter,
                start_seq_number: seq_number,
            })
        }
    }

    /// Tries to catch up with the primary by reading as much as possible from the
    /// log files.
    pub fn try_catch_up_with_primary(&self) -> Result<(), Error> {
        unsafe {
            ffi_try!(ffi::rocksdb_try_catch_up_with_primary(self.inner.inner()));
        }
        Ok(())
    }

    /// Loads a list of external SST files created with SstFileWriter into the DB with default opts
    pub fn ingest_external_file<P: AsRef<Path>>(&self, paths: Vec<P>) -> Result<(), Error> {
        let opts = IngestExternalFileOptions::default();
        self.ingest_external_file_opts(&opts, paths)
    }

    /// Loads a list of external SST files created with SstFileWriter into the DB
    pub fn ingest_external_file_opts<P: AsRef<Path>>(
        &self,
        opts: &IngestExternalFileOptions,
        paths: Vec<P>,
    ) -> Result<(), Error> {
        let paths_v: Vec<CString> = paths.iter().map(to_cpath).collect::<Result<Vec<_>, _>>()?;
        let cpaths: Vec<_> = paths_v.iter().map(|path| path.as_ptr()).collect();

        self.ingest_external_file_raw(opts, &paths_v, &cpaths)
    }

    /// Loads a list of external SST files created with SstFileWriter into the DB for given Column Family
    /// with default opts
    pub fn ingest_external_file_cf<P: AsRef<Path>>(
        &self,
        cf: &impl AsColumnFamilyRef,
        paths: Vec<P>,
    ) -> Result<(), Error> {
        let opts = IngestExternalFileOptions::default();
        self.ingest_external_file_cf_opts(cf, &opts, paths)
    }

    /// Loads a list of external SST files created with SstFileWriter into the DB for given Column Family
    pub fn ingest_external_file_cf_opts<P: AsRef<Path>>(
        &self,
        cf: &impl AsColumnFamilyRef,
        opts: &IngestExternalFileOptions,
        paths: Vec<P>,
    ) -> Result<(), Error> {
        let paths_v: Vec<CString> = paths.iter().map(to_cpath).collect::<Result<Vec<_>, _>>()?;
        let cpaths: Vec<_> = paths_v.iter().map(|path| path.as_ptr()).collect();

        self.ingest_external_file_raw_cf(cf, opts, &paths_v, &cpaths)
    }

    fn ingest_external_file_raw(
        &self,
        opts: &IngestExternalFileOptions,
        paths_v: &[CString],
        cpaths: &[*const c_char],
    ) -> Result<(), Error> {
        unsafe {
            ffi_try!(ffi::rocksdb_ingest_external_file(
                self.inner.inner(),
                cpaths.as_ptr(),
                paths_v.len(),
                opts.inner.cast_const()
            ));
            Ok(())
        }
    }

    fn ingest_external_file_raw_cf(
        &self,
        cf: &impl AsColumnFamilyRef,
        opts: &IngestExternalFileOptions,
        paths_v: &[CString],
        cpaths: &[*const c_char],
    ) -> Result<(), Error> {
        unsafe {
            ffi_try!(ffi::rocksdb_ingest_external_file_cf(
                self.inner.inner(),
                cf.inner(),
                cpaths.as_ptr(),
                paths_v.len(),
                opts.inner.cast_const()
            ));
            Ok(())
        }
    }

    /// Obtains the LSM-tree meta data of the default column family of the DB
    pub fn get_column_family_metadata(&self) -> ColumnFamilyMetaData {
        unsafe {
            let ptr = ffi::rocksdb_get_column_family_metadata(self.inner.inner());

            let metadata = ColumnFamilyMetaData {
                size: ffi::rocksdb_column_family_metadata_get_size(ptr),
                name: from_cstr_and_free(ffi::rocksdb_column_family_metadata_get_name(ptr)),
                file_count: ffi::rocksdb_column_family_metadata_get_file_count(ptr),
            };

            // destroy
            ffi::rocksdb_column_family_metadata_destroy(ptr);

            // return
            metadata
        }
    }

    /// Obtains the LSM-tree meta data of the specified column family of the DB
    pub fn get_column_family_metadata_cf(
        &self,
        cf: &impl AsColumnFamilyRef,
    ) -> ColumnFamilyMetaData {
        unsafe {
            let ptr = ffi::rocksdb_get_column_family_metadata_cf(self.inner.inner(), cf.inner());

            let metadata = ColumnFamilyMetaData {
                size: ffi::rocksdb_column_family_metadata_get_size(ptr),
                name: from_cstr_and_free(ffi::rocksdb_column_family_metadata_get_name(ptr)),
                file_count: ffi::rocksdb_column_family_metadata_get_file_count(ptr),
            };

            // destroy
            ffi::rocksdb_column_family_metadata_destroy(ptr);

            // return
            metadata
        }
    }

    /// Compacts the named SST files into `output_level`, giving the caller
    /// control over exactly which files are merged.
    ///
    /// [`Self::compact_range`] picks the files itself from a key range. This
    /// picks them by name, which is what a tool driving compaction from
    /// [`Self::live_files`] or [`Self::get_column_family_metadata_with_options`]
    /// needs. The file names come from that metadata, not from the filesystem.
    ///
    /// Runs on the calling thread, so it blocks until the compaction finishes.
    ///
    /// # Errors
    ///
    /// Returns the RocksDB error if any input file is unknown, if the files do
    /// not form a compactible set, or if the compaction itself fails. Nothing is
    /// compacted in that case.
    pub fn compact_files<I, N>(
        &self,
        opts: &CompactionOptions,
        input_file_names: I,
        output_level: i32,
    ) -> Result<CompactFilesResult, Error>
    where
        I: IntoIterator<Item = N>,
        N: CStrLike,
    {
        self.compact_files_impl(None::<&ColumnFamily>, opts, input_file_names, output_level)
    }

    /// Like [`Self::compact_files`], for a single column family.
    ///
    /// # Errors
    ///
    /// See [`Self::compact_files`].
    pub fn compact_files_cf<I, N>(
        &self,
        cf: &impl AsColumnFamilyRef,
        opts: &CompactionOptions,
        input_file_names: I,
        output_level: i32,
    ) -> Result<CompactFilesResult, Error>
    where
        I: IntoIterator<Item = N>,
        N: CStrLike,
    {
        self.compact_files_impl(Some(cf), opts, input_file_names, output_level)
    }

    fn compact_files_impl<I, N>(
        &self,
        cf: Option<&impl AsColumnFamilyRef>,
        opts: &CompactionOptions,
        input_file_names: I,
        output_level: i32,
    ) -> Result<CompactFilesResult, Error>
    where
        I: IntoIterator<Item = N>,
        N: CStrLike,
    {
        let names = input_file_names
            .into_iter()
            .map(CStrLike::into_c_string)
            .collect::<Result<Vec<_>, _>>()
            .map_err(|e| Error::new(format!("Invalid input file name: {e}")))?;
        let name_ptrs: Vec<*const c_char> = names.iter().map(|n| n.as_ptr()).collect();

        let mut output_names: *mut *mut c_char = ptr::null_mut();
        let mut output_count: usize = 0;

        // A trivial move returns from `CompactFilesImpl` before
        // `BuildCompactionJobInfo` runs, so it leaves a caller-allocated job info
        // untouched while still reporting success, and nothing afterwards says
        // which path ran. Asking for the job info only when that path is off
        // keeps every value handed out one RocksDB actually wrote.
        let mut job_info = (!opts.get_allow_trivial_move()).then(OwnedCompactionJobInfo::new);
        let job_info_ptr = job_info
            .as_mut()
            .map_or(ptr::null_mut(), OwnedCompactionJobInfo::as_mut_ptr);

        // `output_path_id` 0 means the first configured DB path. RocksDB has no
        // named constant for it and the crate does not expose `cf_paths`
        // selection here, so it is fixed rather than a parameter nobody could
        // use meaningfully.
        let output_path_id = 0;

        unsafe {
            match cf {
                None => ffi_try!(ffi::rocksdb_compact_files(
                    self.inner.inner(),
                    opts.inner.cast_const(),
                    name_ptrs.as_ptr(),
                    name_ptrs.len(),
                    output_level,
                    output_path_id,
                    &raw mut output_names,
                    &raw mut output_count,
                    job_info_ptr,
                )),
                Some(cf) => ffi_try!(ffi::rocksdb_compact_files_cf(
                    self.inner.inner(),
                    cf.inner(),
                    opts.inner.cast_const(),
                    name_ptrs.as_ptr(),
                    name_ptrs.len(),
                    output_level,
                    output_path_id,
                    &raw mut output_names,
                    &raw mut output_count,
                    job_info_ptr,
                )),
            }
        }

        // On failure RocksDB returns before touching either out-param, so this
        // only runs once the call succeeded and both are known good.
        let output_files = unsafe { collect_and_free_output_names(output_names, output_count) };

        Ok(CompactFilesResult {
            output_files,
            job_info,
        })
    }

    /// Obtains the LSM-tree meta data of the default column family, reporting
    /// only the levels and files `opts` selects.
    ///
    /// Unlike [`Self::get_column_family_metadata`], which returns only the
    /// totals, this reports every level and every SST file in it.
    pub fn get_column_family_metadata_with_options(
        &self,
        opts: &ColumnFamilyMetaDataOptions,
    ) -> Vec<LevelMetaData> {
        unsafe {
            let ptr = ffi::rocksdb_get_column_family_metadata_with_options(
                self.inner.inner(),
                opts.inner,
            );
            // The level and file handles borrow from `ptr`, so the returned
            // values own it and destroy it when the last one drops.
            levels_from_cf_metadata_owned(ptr)
        }
    }

    /// Like [`Self::get_column_family_metadata_with_options`], for a single
    /// column family.
    pub fn get_column_family_metadata_cf_with_options(
        &self,
        cf: &impl AsColumnFamilyRef,
        opts: &ColumnFamilyMetaDataOptions,
    ) -> Vec<LevelMetaData> {
        unsafe {
            let ptr = ffi::rocksdb_get_column_family_metadata_cf_with_options(
                self.inner.inner(),
                cf.inner(),
                opts.inner,
            );
            levels_from_cf_metadata_owned(ptr)
        }
    }

    /// Returns every file RocksDB needs in order to restore this DB, which is
    /// what a copy-based backup has to capture.
    ///
    /// This covers more than [`Self::live_files`] does: alongside the SST files
    /// it reports the WAL, manifest, options and `CURRENT` files, each with the
    /// size and, when `opts` asks for it, the checksum needed to verify a copy.
    ///
    /// # Errors
    ///
    /// Returns the RocksDB error if the file list cannot be gathered, for
    /// instance when a flush it needs to run fails.
    pub fn get_livefiles_storage_info(
        &self,
        opts: &LiveFilesStorageInfoOptions,
    ) -> Result<LiveFilesStorageInfo, Error> {
        unsafe {
            let ptr = ffi_try!(ffi::rocksdb_get_livefiles_storage_info(
                self.inner.inner(),
                opts.inner,
            ));
            if ptr.is_null() {
                return Err(Error::new(
                    "Could not get live files storage info".to_owned(),
                ));
            }
            Ok(LiveFilesStorageInfo::from_ptr(ptr))
        }
    }

    /// Returns every WAL file the DB currently knows about, oldest first,
    /// including the one being written to.
    ///
    /// # Errors
    ///
    /// Returns the RocksDB error if the WAL directory cannot be listed.
    pub fn get_sorted_wal_files(&self) -> Result<WalFiles, Error> {
        unsafe {
            let ptr = ffi_try!(ffi::rocksdb_get_sorted_wal_files(self.inner.inner()));
            if ptr.is_null() {
                return Err(Error::new("Could not get sorted WAL files".to_owned()));
            }
            Ok(WalFiles::from_ptr(ptr))
        }
    }

    /// Returns the WAL file currently being written to.
    ///
    /// Reported as alive, with its size read from the filesystem, and with a
    /// [`start_sequence`](crate::wal::WalFile::start_sequence) of 0 rather than a
    /// real sequence number.
    ///
    /// # Errors
    ///
    /// Returns the RocksDB error if the current WAL file cannot be identified.
    pub fn get_current_wal_file(&self) -> Result<OwnedWalFile, Error> {
        unsafe {
            let ptr = ffi_try!(ffi::rocksdb_get_current_wal_file(self.inner.inner()));
            if ptr.is_null() {
                return Err(Error::new("Could not get current WAL file".to_owned()));
            }
            Ok(OwnedWalFile::from_ptr(ptr))
        }
    }

    /// Starts recording every read and write to a trace file at `trace_path`,
    /// which [`Self::new_default_replayer`] can later replay against a DB.
    ///
    /// The trace file is written through the DB's own `Env` with default file
    /// options, so it is not rate limited.
    ///
    /// Call [`Self::end_trace`] to stop.
    ///
    /// Starting a second trace without ending the first does not fail. `StartTrace`
    /// installs the new tracer unconditionally, and the old one is dropped without
    /// its buffered records being written, so the first trace file is left
    /// truncated. Unlike [`Self::start_io_trace`] and
    /// [`Self::start_block_cache_trace`], which report `Busy`, this one is the
    /// caller's to get right.
    ///
    /// # Errors
    ///
    /// Returns the RocksDB error if the trace file cannot be created.
    pub fn start_trace<P: AsRef<Path>>(
        &self,
        opts: &TraceOptions,
        trace_path: P,
    ) -> Result<(), Error> {
        let cpath = to_cpath(trace_path)?;
        unsafe {
            // Null `env` uses the DB's own `Env`, which the DB already keeps
            // alive, and null `env_options` uses RocksDB's defaults. Passing an
            // `EnvOptions` here would be unsound: the trace writer keeps its
            // `rate_limiter` as a borrowed pointer for the life of the trace,
            // but the reference counting it lives behind stays in the caller's
            // handle.
            ffi_try!(ffi::rocksdb_start_trace(
                self.inner.inner(),
                ptr::null_mut(),
                ptr::null(),
                opts.inner,
                cpath.as_ptr(),
            ));
        }
        Ok(())
    }

    /// Stops the trace started by [`Self::start_trace`] and closes the file.
    ///
    /// # Errors
    ///
    /// Returns the RocksDB error if no trace is running or the file cannot be
    /// closed cleanly.
    pub fn end_trace(&self) -> Result<(), Error> {
        unsafe {
            ffi_try!(ffi::rocksdb_end_trace(self.inner.inner()));
        }
        Ok(())
    }

    /// Starts recording file system operations to a trace file at `trace_path`,
    /// for diagnosing IO behaviour rather than replaying queries.
    ///
    /// Written the same way as [`Self::start_trace`]. Call [`Self::end_io_trace`]
    /// to stop.
    ///
    /// # Errors
    ///
    /// Returns the RocksDB error if the trace file cannot be created, or `Busy` if
    /// an IO trace is already running.
    pub fn start_io_trace<P: AsRef<Path>>(
        &self,
        opts: &TraceOptions,
        trace_path: P,
    ) -> Result<(), Error> {
        let cpath = to_cpath(trace_path)?;
        unsafe {
            ffi_try!(ffi::rocksdb_start_io_trace(
                self.inner.inner(),
                ptr::null_mut(),
                ptr::null(),
                opts.inner,
                cpath.as_ptr(),
            ));
        }
        Ok(())
    }

    /// Stops the IO trace started by [`Self::start_io_trace`].
    ///
    /// Does nothing if no IO trace is running.
    ///
    /// # Errors
    ///
    /// `EndIOTrace` always reports success, so this only fails if a future RocksDB
    /// gives it something to report. It returns a `Result` to keep that a
    /// non-breaking change.
    pub fn end_io_trace(&self) -> Result<(), Error> {
        unsafe {
            ffi_try!(ffi::rocksdb_end_io_trace(self.inner.inner()));
        }
        Ok(())
    }

    /// Starts recording block cache accesses to a trace file at `trace_path`,
    /// which the `block_cache_trace_analyzer` tool can then simulate cache
    /// configurations against.
    ///
    /// Written the same way as [`Self::start_trace`]. Call
    /// [`Self::end_block_cache_trace`] to stop.
    ///
    /// # Errors
    ///
    /// Returns the RocksDB error if the trace file cannot be created, or `Busy` if
    /// a block cache trace is already running.
    pub fn start_block_cache_trace<P: AsRef<Path>>(
        &self,
        opts: &BlockCacheTraceOptions,
        writer_opts: &BlockCacheTraceWriterOptions,
        trace_path: P,
    ) -> Result<(), Error> {
        let cpath = to_cpath(trace_path)?;
        unsafe {
            ffi_try!(ffi::rocksdb_start_block_cache_trace_with_options(
                self.inner.inner(),
                ptr::null_mut(),
                ptr::null(),
                opts.inner,
                writer_opts.inner,
                cpath.as_ptr(),
            ));
        }
        Ok(())
    }

    /// Stops the block cache trace started by [`Self::start_block_cache_trace`].
    ///
    /// Does nothing if no block cache trace is running.
    ///
    /// # Errors
    ///
    /// `EndBlockCacheTrace` always reports success, so this only fails if a future
    /// RocksDB gives it something to report. It returns a `Result` to keep that a
    /// non-breaking change.
    pub fn end_block_cache_trace(&self) -> Result<(), Error> {
        unsafe {
            ffi_try!(ffi::rocksdb_end_block_cache_trace(self.inner.inner()));
        }
        Ok(())
    }

    /// Builds a replayer that replays the trace at `trace_path` against this DB.
    ///
    /// `column_families` must name every column family other than the default
    /// that the trace touched, or replay fails with
    /// `Corruption: Invalid Column Family ID.`. The default column family is
    /// always included, so an empty list replays it alone.
    ///
    /// # Errors
    ///
    /// Returns the RocksDB error if the trace file cannot be opened or read.
    pub fn new_default_replayer<'cf, W, I, P>(
        &self,
        column_families: I,
        trace_path: P,
    ) -> Result<Replayer<'_>, Error>
    where
        W: AsColumnFamilyRef + 'cf,
        I: IntoIterator<Item = &'cf W>,
        P: AsRef<Path>,
    {
        let cpath = to_cpath(trace_path)?;
        unsafe {
            Replayer::create_default(
                self.inner.inner(),
                column_families,
                ptr::null_mut(),
                ptr::null(),
                &cpath,
            )
        }
    }

    /// Returns a list of all table files with their level, start key
    /// and end key
    pub fn live_files(&self) -> Result<Vec<LiveFile>, Error> {
        unsafe {
            let livefiles_ptr = ffi::rocksdb_livefiles(self.inner.inner());
            if livefiles_ptr.is_null() {
                Err(Error::new("Could not get live files".to_owned()))
            } else {
                let files = LiveFile::from_rocksdb_livefiles_ptr(livefiles_ptr);

                // destroy livefiles metadata(s)
                ffi::rocksdb_livefiles_destroy(livefiles_ptr);

                // return
                Ok(files)
            }
        }
    }

    /// Delete sst files whose keys are entirely in the given range.
    ///
    /// Could leave some keys in the range which are in files which are not
    /// entirely in the range.
    ///
    /// Note: L0 files are left regardless of whether they're in the range.
    ///
    /// SnapshotWithThreadModes before the delete might not see the data in the given range.
    pub fn delete_file_in_range<K: AsRef<[u8]>>(&self, from: K, to: K) -> Result<(), Error> {
        let from = from.as_ref();
        let to = to.as_ref();
        unsafe {
            ffi_try!(ffi::rocksdb_delete_file_in_range(
                self.inner.inner(),
                from.as_ptr() as *const c_char,
                from.len() as size_t,
                to.as_ptr() as *const c_char,
                to.len() as size_t,
            ));
            Ok(())
        }
    }

    /// Same as `delete_file_in_range` but only for specific column family
    pub fn delete_file_in_range_cf<K: AsRef<[u8]>>(
        &self,
        cf: &impl AsColumnFamilyRef,
        from: K,
        to: K,
    ) -> Result<(), Error> {
        let from = from.as_ref();
        let to = to.as_ref();
        unsafe {
            ffi_try!(ffi::rocksdb_delete_file_in_range_cf(
                self.inner.inner(),
                cf.inner(),
                from.as_ptr() as *const c_char,
                from.len() as size_t,
                to.as_ptr() as *const c_char,
                to.len() as size_t,
            ));
            Ok(())
        }
    }

    /// Request stopping background work, if wait is true wait until it's done.
    pub fn cancel_all_background_work(&self, wait: bool) {
        unsafe {
            ffi::rocksdb_cancel_all_background_work(self.inner.inner(), c_uchar::from(wait));
        }
    }

    /// Marks the column family as dropped in RocksDB.
    ///
    /// Deliberately does not take ownership of the handle. Callers must take
    /// the handle out of their map first, so that only one caller can ever
    /// *destroy* a given handle, and must put it back if this fails: destroying
    /// it on failure would leave the column family still present in the DB with
    /// no reachable handle, so the only way to touch it again would be to
    /// reopen the database.
    ///
    /// Taking it out of the map does not make the caller the only *reader*. In
    /// `MultiThreaded` mode `cf_handle` clones the same `Arc`, so other threads
    /// can still hold a live `BoundColumnFamily` for this handle. That is fine:
    /// the refcount keeps the handle alive until the last of them is gone.
    fn mark_column_family_dropped(
        &self,
        cf_inner: *mut ffi::rocksdb_column_family_handle_t,
    ) -> Result<(), Error> {
        unsafe {
            ffi_try!(ffi::rocksdb_drop_column_family(
                self.inner.inner(),
                cf_inner
            ));
        }
        Ok(())
    }

    /// Increase the full_history_ts of column family. The new ts_low value should
    /// be newer than current full_history_ts value.
    /// If another thread updates full_history_ts_low concurrently to a higher
    /// timestamp than the requested ts_low, a try again error will be returned.
    pub fn increase_full_history_ts_low<S: AsRef<[u8]>>(
        &self,
        cf: &impl AsColumnFamilyRef,
        ts: S,
    ) -> Result<(), Error> {
        let ts = ts.as_ref();
        unsafe {
            ffi_try!(ffi::rocksdb_increase_full_history_ts_low(
                self.inner.inner(),
                cf.inner(),
                ts.as_ptr() as *const c_char,
                ts.len() as size_t,
            ));
            Ok(())
        }
    }

    /// Get current full_history_ts value.
    pub fn get_full_history_ts_low(&self, cf: &impl AsColumnFamilyRef) -> Result<Vec<u8>, Error> {
        unsafe {
            let mut ts_lowlen = 0;
            let ts = ffi_try!(ffi::rocksdb_get_full_history_ts_low(
                self.inner.inner(),
                cf.inner(),
                &raw mut ts_lowlen,
            ));

            if ts.is_null() {
                Err(Error::new("Could not get full_history_ts_low".to_owned()))
            } else {
                let mut vec = vec![0; ts_lowlen];
                ptr::copy_nonoverlapping(ts.cast::<u8>(), vec.as_mut_ptr(), ts_lowlen);
                ffi::rocksdb_free(ts as *mut c_void);
                Ok(vec)
            }
        }
    }

    /// Returns the DB identity. This is typically ASCII bytes, but that is not guaranteed.
    pub fn get_db_identity(&self) -> Result<Vec<u8>, Error> {
        unsafe {
            let mut length: usize = 0;
            let identity_ptr = ffi::rocksdb_get_db_identity(self.inner.inner(), &raw mut length);
            let identity_vec = raw_data(identity_ptr, length);
            ffi::rocksdb_free(identity_ptr as *mut c_void);
            // In RocksDB: get_db_identity copies a std::string so it should not fail, but
            // the API allows it to be overridden, so it might
            identity_vec.ok_or_else(|| Error::new("get_db_identity returned NULL".to_string()))
        }
    }
}

impl<I: DBInner> DBCommon<SingleThreaded, I> {
    /// Creates column family with given name and options
    pub fn create_cf<N: AsRef<str>>(&mut self, name: N, opts: &Options) -> Result<(), Error> {
        let inner = self.create_inner_cf_handle(name.as_ref(), opts)?;
        self.cfs
            .cfs
            .insert(name.as_ref().to_string(), ColumnFamily { inner });
        Ok(())
    }

    /// Creates a column family whose entries expire after `ttl`, on a DB that was
    /// opened with a TTL.
    ///
    /// [`ColumnFamilyDescriptor::new_with_ttl`] sets this at open time. This is the
    /// way to add such a family to a DB that is already open.
    ///
    /// # Errors
    ///
    /// Errors if the DB was not opened with [`DB::open_with_ttl`] or one of the
    /// `open_cf*_with_ttl` functions, since RocksDB would otherwise treat the handle
    /// as a type it is not. Also returns the RocksDB error if the family already
    /// exists or cannot be created, and errors if the name contains an interior NUL
    /// byte.
    pub fn create_cf_with_ttl<N: AsRef<str>>(
        &mut self,
        name: N,
        opts: &Options,
        ttl: ColumnFamilyTtl,
    ) -> Result<(), Error> {
        let inner = self.create_inner_cf_handle_with_ttl(name.as_ref(), opts, ttl)?;
        self.cfs
            .cfs
            .insert(name.as_ref().to_string(), ColumnFamily { inner });
        Ok(())
    }

    /// Creates the named column families, all sharing `opts`.
    ///
    /// This saves one options file write over calling
    /// [`create_cf`](Self::create_cf) in a loop. It is not a saving on manifest
    /// writes, and it is not atomic.
    ///
    /// # Errors
    ///
    /// Returns the RocksDB error if a family already exists or cannot be created,
    /// and errors if a name contains an interior NUL byte.
    ///
    /// RocksDB creates the families in order and stops at the first failure, so on
    /// error the families named before the failing one already exist and stay that
    /// way. Those are recorded here as usual and can be used or dropped, so retrying
    /// with the same list will fail again on the ones that now exist.
    pub fn create_cfs<Iter, N>(&mut self, names: Iter, opts: &Options) -> Result<(), Error>
    where
        Iter: IntoIterator<Item = N>,
        N: AsRef<str>,
    {
        let names = convert_cf_names(names)?;
        let created = self.create_inner_cf_handles(&names, opts);
        for ((name, _), inner) in names.into_iter().zip(created.handles) {
            self.cfs.cfs.insert(name, ColumnFamily { inner });
        }
        match created.error {
            Some(err) => Err(err),
            None => Ok(()),
        }
    }

    #[doc = include_str!("db_create_column_family_with_import.md")]
    pub fn create_column_family_with_import<N: AsRef<str>>(
        &mut self,
        options: &Options,
        column_family_name: N,
        import_options: &ImportColumnFamilyOptions,
        metadata: &ExportImportFilesMetaData,
    ) -> Result<(), Error> {
        let name = column_family_name.as_ref();
        let c_name = CString::new(name).map_err(|err| {
            Error::new(format!(
                "Failed to convert name to CString while importing column family: {err}"
            ))
        })?;
        let inner = unsafe {
            ffi_try!(ffi::rocksdb_create_column_family_with_import(
                self.inner.inner(),
                options.inner,
                c_name.as_ptr(),
                import_options.inner,
                metadata.inner
            ))
        };
        self.cfs
            .cfs
            .insert(column_family_name.as_ref().into(), ColumnFamily { inner });
        Ok(())
    }

    /// Drops the column family with the given name
    pub fn drop_cf(&mut self, name: &str) -> Result<(), Error> {
        let Some(cf) = self.cfs.cfs.remove(name) else {
            return Err(Error::new(format!("Invalid column family: {name}")));
        };
        match self.mark_column_family_dropped(cf.inner) {
            // `cf` is dropped here. In single-threaded mode that destroys the
            // handle; in `MultiThreaded` mode it drops one `Arc` reference and
            // the handle is destroyed once the last `BoundColumnFamily` clone
            // handed out by `cf_handle` is gone.
            Ok(()) => Ok(()),
            Err(e) => {
                // The column family is still there, so put the handle back
                // rather than destroying the only way to reach it.
                self.cfs.cfs.insert(name.to_owned(), cf);
                Err(e)
            }
        }
    }

    /// Returns the underlying column family handle
    pub fn cf_handle(&self, name: &str) -> Option<&ColumnFamily> {
        self.cfs.cfs.get(name)
    }

    /// Returns the list of column families currently open.
    ///
    /// The order of names is unspecified and may vary between calls.
    pub fn cf_names(&self) -> Vec<String> {
        self.cfs.cfs.keys().cloned().collect()
    }
}

impl<I: DBInner> DBCommon<MultiThreaded, I> {
    /// Creates column family with given name and options
    pub fn create_cf<N: AsRef<str>>(&self, name: N, opts: &Options) -> Result<(), Error> {
        // Note that we acquire the cfs lock before inserting: otherwise we might race
        // another caller who observed the handle as missing.
        let mut cfs = self.cfs.cfs.write();
        let inner = self.create_inner_cf_handle(name.as_ref(), opts)?;
        cfs.insert(
            name.as_ref().to_string(),
            Arc::new(UnboundColumnFamily { inner }),
        );
        Ok(())
    }

    /// Creates a column family whose entries expire after `ttl`, on a DB that was
    /// opened with a TTL.
    ///
    /// [`ColumnFamilyDescriptor::new_with_ttl`] sets this at open time. This is the
    /// way to add such a family to a DB that is already open.
    ///
    /// # Errors
    ///
    /// Errors if the DB was not opened with [`DB::open_with_ttl`] or one of the
    /// `open_cf*_with_ttl` functions, since RocksDB would otherwise treat the handle
    /// as a type it is not. Also returns the RocksDB error if the family already
    /// exists or cannot be created, and errors if the name contains an interior NUL
    /// byte.
    pub fn create_cf_with_ttl<N: AsRef<str>>(
        &self,
        name: N,
        opts: &Options,
        ttl: ColumnFamilyTtl,
    ) -> Result<(), Error> {
        // Note that we acquire the cfs lock before inserting: otherwise we might race
        // another caller who observed the handle as missing.
        let mut cfs = self.cfs.cfs.write();
        let inner = self.create_inner_cf_handle_with_ttl(name.as_ref(), opts, ttl)?;
        cfs.insert(
            name.as_ref().to_string(),
            Arc::new(UnboundColumnFamily { inner }),
        );
        Ok(())
    }

    /// Creates the named column families, all sharing `opts`.
    ///
    /// See [`DBCommon::create_cfs`](DBCommon::<SingleThreaded, I>::create_cfs),
    /// including the note that this is not atomic.
    ///
    /// # Errors
    ///
    /// Returns the RocksDB error if a family already exists or cannot be created,
    /// and errors if a name contains an interior NUL byte. On error the families
    /// named before the failing one already exist and are recorded here.
    pub fn create_cfs<Iter, N>(&self, names: Iter, opts: &Options) -> Result<(), Error>
    where
        Iter: IntoIterator<Item = N>,
        N: AsRef<str>,
    {
        let names = convert_cf_names(names)?;
        // Note that we acquire the cfs lock before creating: otherwise we might race
        // another caller who observed the handles as missing.
        let mut cfs = self.cfs.cfs.write();
        let created = self.create_inner_cf_handles(&names, opts);
        for ((name, _), inner) in names.into_iter().zip(created.handles) {
            cfs.insert(name, Arc::new(UnboundColumnFamily { inner }));
        }
        match created.error {
            Some(err) => Err(err),
            None => Ok(()),
        }
    }

    #[doc = include_str!("db_create_column_family_with_import.md")]
    pub fn create_column_family_with_import<N: AsRef<str>>(
        &self,
        options: &Options,
        column_family_name: N,
        import_options: &ImportColumnFamilyOptions,
        metadata: &ExportImportFilesMetaData,
    ) -> Result<(), Error> {
        // Acquire CF lock upfront, before creating the CF, to avoid a race with concurrent creators
        let mut cfs = self.cfs.cfs.write();
        let name = column_family_name.as_ref();
        let c_name = CString::new(name).map_err(|err| {
            Error::new(format!(
                "Failed to convert name to CString while importing column family: {err}"
            ))
        })?;
        let inner = unsafe {
            ffi_try!(ffi::rocksdb_create_column_family_with_import(
                self.inner.inner(),
                options.inner,
                c_name.as_ptr(),
                import_options.inner,
                metadata.inner
            ))
        };
        cfs.insert(
            column_family_name.as_ref().to_string(),
            Arc::new(UnboundColumnFamily { inner }),
        );
        Ok(())
    }

    /// Drops the column family with the given name by internally locking the inner column
    /// family map. This avoids needing `&mut self` reference
    pub fn drop_cf(&self, name: &str) -> Result<(), Error> {
        // Take the handle out under the write lock before touching RocksDB.
        // Looking it up under a read lock and removing it afterwards would let
        // two concurrent callers observe the same handle: the first would drop
        // and destroy it, and the second would then hand a freed pointer to
        // `rocksdb_drop_column_family`.
        let Some(cf) = self.cfs.cfs.write().remove(name) else {
            return Err(Error::new(format!("Invalid column family: {name}")));
        };
        match self.mark_column_family_dropped(cf.inner) {
            // `cf` is dropped here. In single-threaded mode that destroys the
            // handle; in `MultiThreaded` mode it drops one `Arc` reference and
            // the handle is destroyed once the last `BoundColumnFamily` clone
            // handed out by `cf_handle` is gone.
            Ok(()) => Ok(()),
            Err(e) => {
                // The column family is still there, so put the handle back
                // rather than destroying the only way to reach it.
                self.cfs.cfs.write().insert(name.to_owned(), cf);
                Err(e)
            }
        }
    }

    /// Returns the underlying column family handle
    pub fn cf_handle(&'_ self, name: &str) -> Option<Arc<BoundColumnFamily<'_>>> {
        self.cfs
            .cfs
            .read()
            .get(name)
            .cloned()
            .map(UnboundColumnFamily::bound_column_family)
    }

    /// Returns the list of column families currently open.
    ///
    /// The order of names is unspecified and may vary between calls.
    pub fn cf_names(&self) -> Vec<String> {
        self.cfs.cfs.read().keys().cloned().collect()
    }
}

impl<T: ThreadMode, I: DBInner> Drop for DBCommon<T, I> {
    fn drop(&mut self) {
        self.cfs.drop_all_cfs_internal();
    }
}

impl<T: ThreadMode, I: DBInner> fmt::Debug for DBCommon<T, I> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "RocksDB {{ path: {} }}", self.path().display())
    }
}

/// The metadata that describes a column family.
#[derive(Debug, Clone)]
pub struct ColumnFamilyMetaData {
    // The size of this column family in bytes, which is equal to the sum of
    // the file size of its "levels".
    pub size: u64,
    // The name of the column family.
    pub name: String,
    // The number of files in this column family.
    pub file_count: usize,
}

/// The metadata that describes a SST file
#[derive(Debug, Clone)]
pub struct LiveFile {
    /// Name of the column family the file belongs to
    pub column_family_name: String,
    /// Name of the file
    pub name: String,
    /// The directory containing the file, without a trailing '/'. This could be
    /// a DB path, wal_dir, etc.
    pub directory: String,
    /// Size of the file
    pub size: usize,
    /// Level at which this file resides
    pub level: i32,
    /// Smallest user defined key in the file
    pub start_key: Option<Vec<u8>>,
    /// Largest user defined key in the file
    pub end_key: Option<Vec<u8>>,
    pub smallest_seqno: u64,
    pub largest_seqno: u64,
    /// Number of entries/alive keys in the file
    pub num_entries: u64,
    /// Number of deletions/tomb key(s) in the file
    pub num_deletions: u64,
}

impl LiveFile {
    /// Create a `Vec<LiveFile>` from a `rocksdb_livefiles_t` pointer
    pub(crate) fn from_rocksdb_livefiles_ptr(
        files: *const ffi::rocksdb_livefiles_t,
    ) -> Vec<LiveFile> {
        unsafe {
            let n = ffi::rocksdb_livefiles_count(files);

            let mut livefiles = Vec::with_capacity(n as usize);
            let mut key_size: usize = 0;

            for i in 0..n {
                // rocksdb_livefiles_* returns pointers to strings, not copies
                let column_family_name =
                    from_cstr_without_free(ffi::rocksdb_livefiles_column_family_name(files, i));
                let name = from_cstr_without_free(ffi::rocksdb_livefiles_name(files, i));
                let directory = from_cstr_without_free(ffi::rocksdb_livefiles_directory(files, i));
                let size = ffi::rocksdb_livefiles_size(files, i);
                let level = ffi::rocksdb_livefiles_level(files, i);

                // get smallest key inside file
                let smallest_key = ffi::rocksdb_livefiles_smallestkey(files, i, &raw mut key_size);
                let smallest_key = raw_data(smallest_key, key_size);

                // get largest key inside file
                let largest_key = ffi::rocksdb_livefiles_largestkey(files, i, &raw mut key_size);
                let largest_key = raw_data(largest_key, key_size);

                livefiles.push(LiveFile {
                    column_family_name,
                    name,
                    directory,
                    size,
                    level,
                    start_key: smallest_key,
                    end_key: largest_key,
                    largest_seqno: ffi::rocksdb_livefiles_largest_seqno(files, i),
                    smallest_seqno: ffi::rocksdb_livefiles_smallest_seqno(files, i),
                    num_entries: ffi::rocksdb_livefiles_entries(files, i),
                    num_deletions: ffi::rocksdb_livefiles_deletions(files, i),
                });
            }

            livefiles
        }
    }
}

struct LiveFileGuard(*mut rocksdb_livefile_t);

impl LiveFileGuard {
    fn into_raw(mut self) -> *mut rocksdb_livefile_t {
        let ptr = self.0;
        self.0 = ptr::null_mut();
        ptr
    }
}

impl Drop for LiveFileGuard {
    fn drop(&mut self) {
        if !self.0.is_null() {
            unsafe {
                rocksdb_livefile_destroy(self.0);
            }
        }
    }
}

struct LiveFilesGuard(*mut rocksdb_livefiles_t);

impl LiveFilesGuard {
    fn into_raw(mut self) -> *mut rocksdb_livefiles_t {
        let ptr = self.0;
        self.0 = ptr::null_mut();
        ptr
    }
}

impl Drop for LiveFilesGuard {
    fn drop(&mut self) {
        if !self.0.is_null() {
            unsafe {
                rocksdb_livefiles_destroy(self.0);
            }
        }
    }
}

/// Metadata returned as output from [`Checkpoint::export_column_family`][export_column_family] and
/// used as input to [`DB::create_column_family_with_import`].
///
/// [export_column_family]: crate::checkpoint::Checkpoint::export_column_family
#[derive(Debug)]
pub struct ExportImportFilesMetaData {
    pub(crate) inner: *mut ffi::rocksdb_export_import_files_metadata_t,
}

impl ExportImportFilesMetaData {
    pub fn get_db_comparator_name(&self) -> String {
        unsafe {
            let c_name =
                ffi::rocksdb_export_import_files_metadata_get_db_comparator_name(self.inner);
            from_cstr_and_free(c_name)
        }
    }

    pub fn set_db_comparator_name(&mut self, name: &str) {
        let c_name = CString::new(name.as_bytes()).unwrap();
        unsafe {
            ffi::rocksdb_export_import_files_metadata_set_db_comparator_name(
                self.inner,
                c_name.as_ptr(),
            );
        };
    }

    pub fn get_files(&self) -> Vec<LiveFile> {
        unsafe {
            let livefiles_ptr = ffi::rocksdb_export_import_files_metadata_get_files(self.inner);
            let files = LiveFile::from_rocksdb_livefiles_ptr(livefiles_ptr);
            ffi::rocksdb_livefiles_destroy(livefiles_ptr);
            files
        }
    }

    pub fn set_files(&mut self, files: &[LiveFile]) -> Result<(), Error> {
        // Use a non-null empty pointer for zero-length keys
        static EMPTY: [u8; 0] = [];
        let empty_ptr = EMPTY.as_ptr() as *const libc::c_char;

        unsafe {
            let live_files = LiveFilesGuard(ffi::rocksdb_livefiles_create());

            for file in files {
                let live_file = LiveFileGuard(ffi::rocksdb_livefile_create());
                ffi::rocksdb_livefile_set_level(live_file.0, file.level);

                // SAFETY: C strings are copied inside the FFI layer so do not need to be kept alive
                let c_cf_name = CString::new(file.column_family_name.as_str()).map_err(|err| {
                    Error::new(format!("Unable to convert column family to CString: {err}"))
                })?;
                ffi::rocksdb_livefile_set_column_family_name(live_file.0, c_cf_name.as_ptr());

                let c_name = CString::new(file.name.as_str()).map_err(|err| {
                    Error::new(format!("Unable to convert file name to CString: {err}"))
                })?;
                ffi::rocksdb_livefile_set_name(live_file.0, c_name.as_ptr());

                let c_directory = CString::new(file.directory.as_str()).map_err(|err| {
                    Error::new(format!("Unable to convert directory to CString: {err}"))
                })?;
                ffi::rocksdb_livefile_set_directory(live_file.0, c_directory.as_ptr());

                ffi::rocksdb_livefile_set_size(live_file.0, file.size);

                let (start_key_ptr, start_key_len) = match &file.start_key {
                    None => (empty_ptr, 0),
                    Some(key) => (key.as_ptr() as *const libc::c_char, key.len()),
                };
                ffi::rocksdb_livefile_set_smallest_key(live_file.0, start_key_ptr, start_key_len);

                let (largest_key_ptr, largest_key_len) = match &file.end_key {
                    None => (empty_ptr, 0),
                    Some(key) => (key.as_ptr() as *const libc::c_char, key.len()),
                };
                ffi::rocksdb_livefile_set_largest_key(
                    live_file.0,
                    largest_key_ptr,
                    largest_key_len,
                );
                ffi::rocksdb_livefile_set_smallest_seqno(live_file.0, file.smallest_seqno);
                ffi::rocksdb_livefile_set_largest_seqno(live_file.0, file.largest_seqno);
                ffi::rocksdb_livefile_set_num_entries(live_file.0, file.num_entries);
                ffi::rocksdb_livefile_set_num_deletions(live_file.0, file.num_deletions);

                // moves ownership of live_files into live_file
                ffi::rocksdb_livefiles_add(live_files.0, live_file.into_raw());
            }

            // moves ownership of live_files into inner
            ffi::rocksdb_export_import_files_metadata_set_files(self.inner, live_files.into_raw());
            Ok(())
        }
    }
}

impl Default for ExportImportFilesMetaData {
    fn default() -> Self {
        let inner = unsafe { ffi::rocksdb_export_import_files_metadata_create() };
        assert!(
            !inner.is_null(),
            "Could not create rocksdb_export_import_files_metadata_t"
        );

        Self { inner }
    }
}

impl Drop for ExportImportFilesMetaData {
    fn drop(&mut self) {
        unsafe {
            ffi::rocksdb_export_import_files_metadata_destroy(self.inner);
        }
    }
}

unsafe impl Send for ExportImportFilesMetaData {}
unsafe impl Sync for ExportImportFilesMetaData {}

/// Converts a TTL to the `int` seconds count RocksDB's TTL API takes,
/// saturating instead of wrapping.
///
/// `Duration::as_secs` is a `u64`, so a plain `as i32` cast wraps: a TTL of
/// `Duration::from_secs(4_294_967_301)` (~136 years, i.e. "effectively never")
/// became `5`, and RocksDB then compaction-deleted the whole column family a few
/// seconds after the data was written.
///
/// Clamping to `i32::MAX` (~68 years) rather than mapping an over-large TTL to
/// RocksDB's never-expire sentinel (`ttl <= 0`, see `DBWithTTLImpl::IsStale`) is
/// deliberate: silently turning a finite TTL the caller asked for into "keep
/// forever" is a worse surprise than expiring it 68 years out, and `i32::MAX` is
/// the longest TTL the C API can express anyway.
fn ttl_to_seconds(ttl: Duration) -> c_int {
    c_int::try_from(ttl.as_secs()).unwrap_or(c_int::MAX)
}

/// Resolves a column family's TTL against the TTL the DB was opened with.
///
/// [`ColumnFamilyTtl::Disabled`] maps to the longest TTL the C API can express rather
/// than RocksDB's never-expire sentinel, for the reason on [`ttl_to_seconds`].
fn cf_ttl_to_seconds(ttl: ColumnFamilyTtl, db_ttl: Duration) -> c_int {
    match ttl {
        ColumnFamilyTtl::Disabled => c_int::MAX,
        ColumnFamilyTtl::Duration(duration) => ttl_to_seconds(duration),
        ColumnFamilyTtl::SameAsDb => ttl_to_seconds(db_ttl),
    }
}

/// Converts column family names to C strings, keeping the given order.
///
/// # Errors
///
/// Errors if a name contains an interior NUL byte.
fn convert_cf_names<I, N>(names: I) -> Result<Vec<(String, CString)>, Error>
where
    I: IntoIterator<Item = N>,
    N: AsRef<str>,
{
    names
        .into_iter()
        .map(|name| {
            let name = name.as_ref();
            let cname = CString::new(name).map_err(|err| {
                Error::new(format!(
                    "Failed to convert column family name to CString: {err}"
                ))
            })?;
            Ok((name.to_owned(), cname))
        })
        .collect()
}

/// The option count as the `int` the C API takes.
///
/// # Errors
///
/// Errors rather than truncating if there are more options than an `int` can count.
fn option_count(opts: &[(CString, CString)]) -> Result<c_int, Error> {
    c_int::try_from(opts.len())
        .map_err(|_| Error::new(format!("Too many options to set at once: {}", opts.len())))
}

fn convert_options(opts: &[(&str, &str)]) -> Result<Vec<(CString, CString)>, Error> {
    opts.iter()
        .map(|(name, value)| {
            let cname = match CString::new(name.as_bytes()) {
                Ok(cname) => cname,
                Err(e) => return Err(Error::new(format!("Invalid option name `{e}`"))),
            };
            let cvalue = match CString::new(value.as_bytes()) {
                Ok(cvalue) => cvalue,
                Err(e) => return Err(Error::new(format!("Invalid option value: `{e}`"))),
            };
            Ok((cname, cvalue))
        })
        .collect()
}

/// Borrows each key as the pointer and length pair the multi-get calls want.
///
/// The returned pointers borrow `keys`, so `keys` has to outlive them.
fn key_ptrs_and_sizes<K: AsRef<[u8]>>(keys: &[K]) -> (Vec<*const c_char>, Vec<usize>) {
    keys.iter()
        .map(|k| {
            let key = k.as_ref();
            (key.as_ptr().cast::<c_char>(), key.len())
        })
        .unzip()
}

/// The five output arrays `rocksdb_multi_get_*_with_ts` fills in.
///
/// Kept together because they are only ever allocated, passed and consumed as a set,
/// and because the unsafe `set_len` after the call has to cover all five or none.
struct MultiGetTsOut {
    values: Vec<*mut c_char>,
    values_sizes: Vec<usize>,
    timestamps: Vec<*mut c_char>,
    timestamps_sizes: Vec<usize>,
    errors: Vec<*mut c_char>,
}

impl MultiGetTsOut {
    fn with_capacity(n: usize) -> Self {
        Self {
            values: Vec::with_capacity(n),
            values_sizes: Vec::with_capacity(n),
            timestamps: Vec::with_capacity(n),
            timestamps_sizes: Vec::with_capacity(n),
            errors: Vec::with_capacity(n),
        }
    }

    /// Publishes the `n` entries RocksDB wrote into the spare capacity.
    ///
    /// # Safety
    ///
    /// `n` must be the key count the call was given, and the call must have returned.
    /// RocksDB writes every one of the five arrays at every index, either a pointer it
    /// allocated or null (c.cc:2694-2711), so no element is left uninitialised.
    unsafe fn assume_filled(&mut self, n: usize) {
        unsafe {
            self.values.set_len(n);
            self.values_sizes.set_len(n);
            self.timestamps.set_len(n);
            self.timestamps_sizes.set_len(n);
            self.errors.set_len(n);
        }
    }

    /// Takes ownership of every buffer RocksDB allocated and pairs it with its key.
    ///
    /// A null value with no error is a key that was not found. An error is reported
    /// with both buffers already null, so there is nothing to free on that path.
    fn into_results(self) -> Vec<Result<Option<TimestampedValue>, Error>> {
        self.values
            .into_iter()
            .zip(self.values_sizes)
            .zip(self.timestamps.into_iter().zip(self.timestamps_sizes))
            .zip(self.errors)
            .map(|(((value, vallen), (ts, tslen)), err)| {
                if !err.is_null() {
                    return Err(convert_rocksdb_error(err));
                }
                if value.is_null() {
                    return Ok(None);
                }
                // SAFETY: RocksDB allocated both with `CopyString` at the reported
                // lengths and nothing else frees them.
                unsafe {
                    Ok(Some(TimestampedValue {
                        value: CSlice::from_raw_parts(value, vallen),
                        timestamp: CSlice::from_raw_parts(ts, tslen),
                    }))
                }
            })
            .collect()
    }
}

pub(crate) fn convert_values(
    values: Vec<*mut c_char>,
    values_sizes: Vec<usize>,
    errors: Vec<*mut c_char>,
) -> Vec<Result<Option<Vec<u8>>, Error>> {
    values
        .into_iter()
        .zip(values_sizes)
        .zip(errors)
        .map(|((v, s), e)| {
            if e.is_null() {
                let value = unsafe { crate::ffi_util::raw_data(v, s) };
                unsafe {
                    ffi::rocksdb_free(v as *mut c_void);
                }
                Ok(value)
            } else {
                Err(convert_rocksdb_error(e))
            }
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use crate::{ColumnFamilyDescriptor, DB, Options};

    /// One `rocksdb_create_iterators` call applies a single `ReadOptions` to
    /// every iterator it builds, and RocksDB's `DBIter` keeps raw `Slice*`
    /// into that object for the iterate bounds and read timestamps. So all the
    /// returned iterators have to keep the *same* options object alive, not a
    /// copy each and not none at all. Dropping it at the end of
    /// `create_iterators_cf` left those pointers dangling. See issue #660.
    #[test]
    fn raw_iterators_cf_share_one_live_readopts() {
        let dir = tempfile::Builder::new()
            .prefix("rocksdb-raw-iterators-cf-readopts")
            .tempdir()
            .unwrap();

        let mut opts = Options::default();
        opts.create_if_missing(true);
        opts.create_missing_column_families(true);
        let db = DB::open_cf_descriptors(
            &opts,
            dir.path(),
            [
                ColumnFamilyDescriptor::new("first", Options::default()),
                ColumnFamilyDescriptor::new("second", Options::default()),
            ],
        )
        .unwrap();

        let first = db.cf_handle("first").unwrap();
        let second = db.cf_handle("second").unwrap();
        let iterators = db.raw_iterators_cf([&first, &second]).unwrap();
        assert_eq!(iterators.len(), 2);

        let shared = iterators[0].readopts_ptr();
        assert!(!shared.is_null());
        for iterator in &iterators {
            assert_eq!(
                iterator.readopts_ptr(),
                shared,
                "each iterator must hold the options object it was created from"
            );
        }
    }
}