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
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
// 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::panic::{AssertUnwindSafe, catch_unwind};
use std::path::Path;
use std::ptr::{NonNull, null_mut};
use std::slice;
use std::sync::Arc;

use libc::{self, c_char, c_double, c_int, c_uchar, c_uint, c_void, size_t};

use crate::cache::{Cache, MemoryAllocator};
use crate::column_family::ColumnFamilyTtl;
use crate::compaction_service::{CompactionService, new_compaction_service};
use crate::event_listener::{EventListener, new_event_listener};
use crate::ffi_util::from_cstr_and_free;
use crate::file_checksum::FileChecksumGenFactory;
use crate::metadata::FileType;
use crate::sst_file_manager::SstFileManager;
use crate::sst_partitioner::SstPartitionerFactory;
use crate::statistics::{Histogram, HistogramData, StatsLevel};
use crate::table_properties::TableProperties;
use crate::wal_filter::{OwnedWalFilter, WalFilter, new_wal_filter};
use crate::write_buffer_manager::WriteBufferManager;
use crate::{
    ColumnFamilyDescriptor, Error, SnapshotWithThreadMode,
    compaction_filter::{self, CompactionFilterCallback, CompactionFilterFn},
    compaction_filter_factory::{self, CompactionFilterFactory},
    comparator::{
        Comparator, ComparatorCallback, ComparatorWithTsCallback, CompareFn, CompareTsFn,
        CompareWithoutTsFn,
    },
    db::DBAccess,
    env::{Env, IoPriority},
    ffi,
    ffi_util::{CStrLike, to_cpath},
    merge_operator::{
        self, MergeFn, MergeOperatorCallback, full_merge_callback, partial_merge_callback,
    },
    slice_transform::SliceTransform,
    statistics::Ticker,
};

// must be Send and Sync because it will be called by RocksDB from different threads
type LogCallbackFn = dyn Fn(LogLevel, &str) + 'static + Send + Sync;

/// Type for log callbacks used by [`Options::set_info_logger`]. Use Box to pass a thin pointer to
/// the C callback.
type LoggerCallback = Box<dyn Fn(LogLevel, &str) + Sync + Send>;

// Holds a log callback to ensure it outlives any Options and DBs that use it.
struct LogCallback {
    callback: Box<LogCallbackFn>,
}

/// Options that must outlive the DB, and may be shared between DBs. This is cloned and stored
/// with every DB that is created from the options.
#[derive(Default)]
pub(crate) struct OptionsMustOutliveDB {
    env: Option<Env>,
    row_cache: Option<Cache>,
    blob_cache: Option<Cache>,
    block_based: Option<BlockBasedOptionsMustOutliveDB>,
    write_buffer_manager: Option<WriteBufferManager>,
    sst_file_manager: Option<SstFileManager>,
    log_callback: Option<Arc<LogCallback>>,
    comparator: Option<Arc<Comparator>>,
    compaction_filter: Option<Arc<OwnedCompactionFilter>>,
    logger_callback: Option<Arc<LoggerCallback>>,
    wal_filter: Option<Arc<OwnedWalFilter>>,
}

impl OptionsMustOutliveDB {
    pub(crate) fn clone(&self) -> Self {
        Self {
            env: self.env.clone(),
            row_cache: self.row_cache.clone(),
            blob_cache: self.blob_cache.clone(),
            block_based: self
                .block_based
                .as_ref()
                .map(BlockBasedOptionsMustOutliveDB::clone),
            write_buffer_manager: self.write_buffer_manager.clone(),
            sst_file_manager: self.sst_file_manager.clone(),
            log_callback: self.log_callback.clone(),
            comparator: self.comparator.clone(),
            compaction_filter: self.compaction_filter.clone(),
            logger_callback: self.logger_callback.clone(),
            wal_filter: self.wal_filter.clone(),
        }
    }
}

/// Stores a `rocksdb_compactionfilter_t` and destroys it when dropped.
///
/// Needed because the C API only ever borrows the filter it is handed, both from
/// [`Options`] and from `CompactionServiceOptionsOverride`, so whoever set it has to
/// outlive it and free it.
pub(crate) struct OwnedCompactionFilter {
    inner: NonNull<ffi::rocksdb_compactionfilter_t>,
}

impl OwnedCompactionFilter {
    pub(crate) fn new(inner: NonNull<ffi::rocksdb_compactionfilter_t>) -> Self {
        Self { inner }
    }
}

impl Drop for OwnedCompactionFilter {
    fn drop(&mut self) {
        unsafe {
            ffi::rocksdb_compactionfilter_destroy(self.inner.as_ptr());
        }
    }
}

#[derive(Default)]
struct BlockBasedOptionsMustOutliveDB {
    block_cache: Option<Cache>,
}

impl BlockBasedOptionsMustOutliveDB {
    fn clone(&self) -> Self {
        Self {
            block_cache: self.block_cache.clone(),
        }
    }
}

/// Database-wide options around performance and behavior.
///
/// Please read the official tuning [guide](https://github.com/facebook/rocksdb/wiki/RocksDB-Tuning-Guide)
/// and most importantly, measure performance under realistic workloads with realistic hardware.
///
/// # Examples
///
/// ```
/// use rust_rocksdb::{Options, DB};
/// use rust_rocksdb::DBCompactionStyle;
///
/// fn badly_tuned_for_somebody_elses_disk() -> DB {
///    let path = "path/for/rocksdb/storageX";
///    let mut opts = Options::default();
///    opts.create_if_missing(true);
///    opts.set_max_open_files(10000);
///    opts.set_use_fsync(false);
///    opts.set_bytes_per_sync(8388608);
///    opts.optimize_for_point_lookup(1024);
///    opts.set_table_cache_num_shard_bits(6);
///    opts.set_max_write_buffer_number(32);
///    opts.set_write_buffer_size(536870912);
///    opts.set_target_file_size_base(1073741824);
///    opts.set_min_write_buffer_number_to_merge(4);
///    opts.set_level_zero_stop_writes_trigger(2000);
///    opts.set_level_zero_slowdown_writes_trigger(0);
///    opts.set_compaction_style(DBCompactionStyle::Universal);
///    opts.set_disable_auto_compactions(true);
///
///    DB::open(&opts, path).unwrap()
/// }
/// ```
pub struct Options {
    pub(crate) inner: *mut ffi::rocksdb_options_t,
    pub(crate) outlive: OptionsMustOutliveDB,
}

/// Optionally disable WAL or sync for this write.
///
/// # Examples
///
/// Making an unsafe write of a batch:
///
/// ```
/// use rust_rocksdb::{DB, Options, WriteBatch, WriteOptions};
///
/// let tempdir = tempfile::Builder::new()
///     .prefix("_path_for_rocksdb_storageY1")
///     .tempdir()
///     .expect("Failed to create temporary path for the _path_for_rocksdb_storageY1");
/// let path = tempdir.path();
/// {
///     let db = DB::open_default(path).unwrap();
///     let mut batch = WriteBatch::default();
///     batch.put(b"my key", b"my value");
///     batch.put(b"key2", b"value2");
///     batch.put(b"key3", b"value3");
///
///     let mut write_options = WriteOptions::default();
///     write_options.set_sync(false);
///     write_options.disable_wal(true);
///
///     db.write_opt(&batch, &write_options);
/// }
/// let _ = DB::destroy(&Options::default(), path);
/// ```
pub struct WriteOptions {
    pub(crate) inner: *mut ffi::rocksdb_writeoptions_t,
}

pub struct LruCacheOptions {
    pub(crate) inner: *mut ffi::rocksdb_lru_cache_options_t,
}

/// Optionally wait for the memtable flush to be performed.
///
/// # Examples
///
/// Manually flushing the memtable:
///
/// ```
/// use rust_rocksdb::{DB, Options, FlushOptions};
///
/// let tempdir = tempfile::Builder::new()
///     .prefix("_path_for_rocksdb_storageY2")
///     .tempdir()
///     .expect("Failed to create temporary path for the _path_for_rocksdb_storageY2");
/// let path = tempdir.path();
/// {
///     let db = DB::open_default(path).unwrap();
///
///     let mut flush_options = FlushOptions::default();
///     flush_options.set_wait(true);
///
///     db.flush_opt(&flush_options);
/// }
/// let _ = DB::destroy(&Options::default(), path);
/// ```
pub struct FlushOptions {
    pub(crate) inner: *mut ffi::rocksdb_flushoptions_t,
}

/// Options for the `_with_options` variants of
/// [`DB::get_approximate_sizes`](crate::DB::get_approximate_sizes).
///
/// At least one of [`set_include_memtables`](Self::set_include_memtables),
/// [`set_include_files`](Self::set_include_files) and
/// [`set_include_blob_files`](Self::set_include_blob_files) has to be on, or
/// there is nothing left to measure.
pub struct SizeApproximationOptions {
    pub(crate) inner: *mut ffi::rocksdb_size_approximation_options_t,
}

/// Which kinds of data [`DB::get_approximate_sizes_cf_with_flags`] counts.
///
/// This is the older flag-based form of [`SizeApproximationOptions`], kept
/// because it is the only variant RocksDB exposes for a single column family
/// without allocating an options object. It cannot express an error margin.
///
/// [`DB::get_approximate_sizes_cf_with_flags`]: crate::DB::get_approximate_sizes_cf_with_flags
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
pub struct SizeApproximationFlags(u8);

impl SizeApproximationFlags {
    /// Count nothing, which makes every returned size zero.
    pub const NONE: Self = Self(ffi::rocksdb_size_approximation_flags_none as u8);
    /// Count data still in the memtables.
    pub const INCLUDE_MEMTABLE: Self =
        Self(ffi::rocksdb_size_approximation_flags_include_memtable as u8);
    /// Count data in SST files.
    pub const INCLUDE_FILES: Self = Self(ffi::rocksdb_size_approximation_flags_include_files as u8);
    /// Count a prorated share of the blob files, as described on
    /// [`SizeApproximationOptions::set_include_blob_files`].
    pub const INCLUDE_BLOB_FILES: Self =
        Self(ffi::rocksdb_size_approximation_flags_include_blob_files as u8);

    pub(crate) fn bits(self) -> u8 {
        self.0
    }
}

impl std::ops::BitOr for SizeApproximationFlags {
    type Output = Self;

    fn bitor(self, rhs: Self) -> Self {
        Self(self.0 | rhs.0)
    }
}

impl std::ops::BitOrAssign for SizeApproximationFlags {
    fn bitor_assign(&mut self, rhs: Self) {
        self.0 |= rhs.0;
    }
}

/// Options for [`DB::flush_wal_with_options`](crate::DB::flush_wal_with_options).
///
/// Flushing the WAL moves buffered writes from RocksDB's own memory into the
/// operating system, which is what makes them survive a process crash. It takes
/// an `fsync` on top of that, requested with [`set_sync`](Self::set_sync), to
/// survive losing the machine.
pub struct FlushWalOptions {
    pub(crate) inner: *mut ffi::rocksdb_flushwaloptions_t,
}

/// For configuring block-based file storage.
pub struct BlockBasedOptions {
    pub(crate) inner: *mut ffi::rocksdb_block_based_table_options_t,
    outlive: BlockBasedOptionsMustOutliveDB,
}

pub struct ReadOptions {
    pub(crate) inner: *mut ffi::rocksdb_readoptions_t,
    // The `ReadOptions` owns a copy of the timestamp and iteration bounds.
    // This is necessary to ensure the pointers we pass over the FFI live as
    // long as the `ReadOptions`. This way, when performing the read operation,
    // the pointers are guaranteed to be valid.
    timestamp: Option<Vec<u8>>,
    iter_start_ts: Option<Vec<u8>>,
    iterate_upper_bound: Option<Vec<u8>>,
    iterate_lower_bound: Option<Vec<u8>>,
}

/// Configuration of cuckoo-based storage.
pub struct CuckooTableOptions {
    pub(crate) inner: *mut ffi::rocksdb_cuckoo_table_options_t,
}

/// For configuring external files ingestion.
///
/// # Examples
///
/// Move files instead of copying them:
///
/// ```
/// use rust_rocksdb::{DB, IngestExternalFileOptions, SstFileWriter, Options};
///
/// let writer_opts = Options::default();
/// let mut writer = SstFileWriter::create(&writer_opts);
/// let tempdir = tempfile::Builder::new()
///     .tempdir()
///     .expect("Failed to create temporary folder for the _path_for_sst_file");
/// let path1 = tempdir.path().join("_path_for_sst_file");
/// writer.open(path1.clone()).unwrap();
/// writer.put(b"k1", b"v1").unwrap();
/// writer.finish().unwrap();
///
/// let tempdir2 = tempfile::Builder::new()
///     .prefix("_path_for_rocksdb_storageY3")
///     .tempdir()
///     .expect("Failed to create temporary path for the _path_for_rocksdb_storageY3");
/// let path2 = tempdir2.path();
/// {
///   let db = DB::open_default(&path2).unwrap();
///   let mut ingest_opts = IngestExternalFileOptions::default();
///   ingest_opts.set_move_files(true);
///   db.ingest_external_file_opts(&ingest_opts, vec![path1]).unwrap();
/// }
/// let _ = DB::destroy(&Options::default(), path2);
/// ```
pub struct IngestExternalFileOptions {
    pub(crate) inner: *mut ffi::rocksdb_ingestexternalfileoptions_t,
}

// 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 Send for Options {}
unsafe impl Send for WriteOptions {}
unsafe impl Send for LruCacheOptions {}
unsafe impl Send for FlushOptions {}
unsafe impl Send for BlockBasedOptions {}
unsafe impl Send for CuckooTableOptions {}
unsafe impl Send for ReadOptions {}
unsafe impl Send for IngestExternalFileOptions {}
unsafe impl Send for CompactOptions {}
unsafe impl Send for ImportColumnFamilyOptions {}
unsafe impl Send for OwnedCompactionFilter {}

// 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 Sync for Options {}
unsafe impl Sync for WriteOptions {}
unsafe impl Sync for LruCacheOptions {}
unsafe impl Sync for FlushOptions {}
unsafe impl Sync for BlockBasedOptions {}
unsafe impl Sync for CuckooTableOptions {}
unsafe impl Sync for ReadOptions {}
unsafe impl Sync for IngestExternalFileOptions {}
unsafe impl Sync for CompactOptions {}
unsafe impl Sync for ImportColumnFamilyOptions {}
unsafe impl Sync for OwnedCompactionFilter {}

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

impl Clone for Options {
    fn clone(&self) -> Self {
        let inner = unsafe { ffi::rocksdb_options_create_copy(self.inner) };
        assert!(!inner.is_null(), "Could not copy RocksDB options");

        Self {
            inner,
            outlive: self.outlive.clone(),
        }
    }
}

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

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

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

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

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

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

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

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

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

/// Copies a `const char*` plus length pair that the C API borrows out of an options object.
///
/// Every getter that uses this returns `opt->rep.<field>.data()` or a factory's `Name()` (see
/// `db/c.cc`), so the bytes belong to RocksDB and must be copied rather than freed. Invalid
/// UTF-8 is replaced, matching [`from_cstr_and_free`].
///
/// # Safety
///
/// `ptr` must either be null or point to `len` readable bytes that stay valid for the call.
unsafe fn borrowed_string(ptr: *const c_char, len: usize) -> String {
    if ptr.is_null() || len == 0 {
        return String::new();
    }
    let bytes = unsafe { slice::from_raw_parts(ptr.cast::<u8>(), len) };
    String::from_utf8_lossy(bytes).into_owned()
}

/// Maps a [`FileType`] onto the `rocksdb::FileType` value the checksum handoff set accepts.
///
/// `checksum_handoff_file_types` is a `SmallEnumSet<FileType, kBlobFile>`, so RocksDB asserts
/// on any value above `kBlobFile`. [`FileType::CompactionProgressFile`] and
/// [`FileType::Unknown`] sit above it and have no representation in the set.
fn checksum_handoff_file_type_raw(file_type: FileType) -> Option<c_int> {
    // Variants below `kBlobFile` are their own `rocksdb::FileType` value, so
    // the discriminant is the raw int; the enum is the only place the mapping
    // is written down.
    match file_type {
        FileType::CompactionProgressFile | FileType::Unknown => None,
        representable => Some(representable as c_int),
    }
}

impl BlockBasedOptions {
    /// Approximate size of user data packed per block. Note that the
    /// block size specified here corresponds to uncompressed data. The
    /// actual size of the unit read from disk may be smaller if
    /// compression is enabled. This parameter can be changed dynamically.
    pub fn set_block_size(&mut self, size: usize) {
        unsafe {
            ffi::rocksdb_block_based_options_set_block_size(self.inner, size);
        }
    }

    /// Block size for partitioned metadata. Currently applied to indexes when
    /// kTwoLevelIndexSearch is used and to filters when partition_filters is used.
    /// Note: Since in the current implementation the filters and index partitions
    /// are aligned, an index/filter block is created when either index or filter
    /// block size reaches the specified limit.
    ///
    /// Note: this limit is currently applied to only index blocks; a filter
    /// partition is cut right after an index block is cut.
    pub fn set_metadata_block_size(&mut self, size: usize) {
        unsafe {
            ffi::rocksdb_block_based_options_set_metadata_block_size(self.inner, size as u64);
        }
    }

    /// Note: currently this option requires kTwoLevelIndexSearch to be set as
    /// well.
    ///
    /// Use partitioned full filters for each SST file. This option is
    /// incompatible with block-based filters.
    pub fn set_partition_filters(&mut self, size: bool) {
        unsafe {
            ffi::rocksdb_block_based_options_set_partition_filters(self.inner, c_uchar::from(size));
        }
    }

    /// Sets global cache for blocks (user data is stored in a set of blocks, and
    /// a block is the unit of reading from disk).
    ///
    /// If set, use the specified cache for blocks.
    /// By default, rocksdb will automatically create and use an 8MB internal cache.
    pub fn set_block_cache(&mut self, cache: &Cache) {
        unsafe {
            ffi::rocksdb_block_based_options_set_block_cache(self.inner, cache.0.inner.as_ptr());
        }
        self.outlive.block_cache = Some(cache.clone());
    }

    /// Disable block cache
    pub fn disable_cache(&mut self) {
        unsafe {
            ffi::rocksdb_block_based_options_set_no_block_cache(self.inner, c_uchar::from(true));
        }
    }

    /// Sets a [Bloom filter](https://github.com/facebook/rocksdb/wiki/RocksDB-Bloom-Filter)
    /// policy to reduce disk reads.
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::BlockBasedOptions;
    ///
    /// let mut opts = BlockBasedOptions::default();
    /// opts.set_bloom_filter(10.0, true);
    /// ```
    pub fn set_bloom_filter(&mut self, bits_per_key: c_double, block_based: bool) {
        unsafe {
            let bloom = if block_based {
                ffi::rocksdb_filterpolicy_create_bloom(bits_per_key as _)
            } else {
                ffi::rocksdb_filterpolicy_create_bloom_full(bits_per_key as _)
            };

            ffi::rocksdb_block_based_options_set_filter_policy(self.inner, bloom);
        }
    }

    /// Sets a [Ribbon filter](http://rocksdb.org/blog/2021/12/29/ribbon-filter.html)
    /// policy to reduce disk reads.
    ///
    /// Ribbon filters use less memory in exchange for slightly more CPU usage
    /// compared to an equivalent bloom filter.
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::BlockBasedOptions;
    ///
    /// let mut opts = BlockBasedOptions::default();
    /// opts.set_ribbon_filter(10.0);
    /// ```
    pub fn set_ribbon_filter(&mut self, bloom_equivalent_bits_per_key: c_double) {
        unsafe {
            let ribbon = ffi::rocksdb_filterpolicy_create_ribbon(bloom_equivalent_bits_per_key);
            ffi::rocksdb_block_based_options_set_filter_policy(self.inner, ribbon);
        }
    }

    /// Sets a hybrid [Ribbon filter](http://rocksdb.org/blog/2021/12/29/ribbon-filter.html)
    /// policy to reduce disk reads.
    ///
    /// Uses Bloom filters before the given level, and Ribbon filters for all
    /// other levels. This combines the memory savings from Ribbon filters
    /// with the lower CPU usage of Bloom filters.
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::BlockBasedOptions;
    ///
    /// let mut opts = BlockBasedOptions::default();
    /// opts.set_hybrid_ribbon_filter(10.0, 2);
    /// ```
    pub fn set_hybrid_ribbon_filter(
        &mut self,
        bloom_equivalent_bits_per_key: c_double,
        bloom_before_level: c_int,
    ) {
        unsafe {
            let ribbon = ffi::rocksdb_filterpolicy_create_ribbon_hybrid(
                bloom_equivalent_bits_per_key,
                bloom_before_level,
            );
            ffi::rocksdb_block_based_options_set_filter_policy(self.inner, ribbon);
        }
    }

    /// Whether to put index/filter blocks in the block cache. When false,
    /// each "table reader" object will pre-load index/filter blocks during
    /// table initialization. Index and filter partition blocks always use
    /// block cache regardless of this option.
    ///
    /// Default: false
    pub fn set_cache_index_and_filter_blocks(&mut self, v: bool) {
        unsafe {
            ffi::rocksdb_block_based_options_set_cache_index_and_filter_blocks(
                self.inner,
                c_uchar::from(v),
            );
        }
    }

    /// If `cache_index_and_filter_blocks` is enabled, cache index and filter
    /// blocks with high priority. Depending on the block cache implementation,
    /// index, filter, and other metadata blocks may be less likely to be
    /// evicted than data blocks when this is set to true.
    ///
    /// Default: true.
    pub fn set_cache_index_and_filter_blocks_with_high_priority(&mut self, v: bool) {
        unsafe {
            ffi::rocksdb_block_based_options_set_cache_index_and_filter_blocks_with_high_priority(
                self.inner,
                c_uchar::from(v),
            );
        }
    }

    /// Defines the index type to be used for SS-table lookups.
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::{BlockBasedOptions, BlockBasedIndexType, Options};
    ///
    /// let mut opts = Options::default();
    /// let mut block_opts = BlockBasedOptions::default();
    /// block_opts.set_index_type(BlockBasedIndexType::HashSearch);
    /// ```
    pub fn set_index_type(&mut self, index_type: BlockBasedIndexType) {
        let index = index_type as i32;
        unsafe {
            ffi::rocksdb_block_based_options_set_index_type(self.inner, index);
        }
    }

    /// Selects the search algorithm used inside each index block at lookup
    /// time.
    ///
    /// Use [`IndexBlockSearchType::Interpolation`] when keys in index blocks
    /// are known to be uniformly distributed and the byte-wise comparator is
    /// in use, or [`IndexBlockSearchType::Auto`] to let RocksDB choose per
    /// block. `Auto` requires the corresponding write-path threshold to be
    /// set via [`Self::set_uniform_cv_threshold`]; otherwise it falls back to
    /// binary search.
    ///
    /// Default: `IndexBlockSearchType::Binary`
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::{BlockBasedOptions, IndexBlockSearchType};
    ///
    /// let mut block_opts = BlockBasedOptions::default();
    /// block_opts.set_index_block_search_type(IndexBlockSearchType::Auto);
    /// block_opts.set_uniform_cv_threshold(0.2);
    /// ```
    pub fn set_index_block_search_type(&mut self, search_type: IndexBlockSearchType) {
        unsafe {
            ffi::rocksdb_block_based_options_set_index_block_search_type(
                self.inner,
                search_type as c_int,
            );
        }
    }

    /// Coefficient of variation (CV) threshold used on the write path to
    /// decide whether an index block's keys are "uniform" enough to benefit
    /// from interpolation search at read time. When the CV of key gaps within
    /// an index block is below this threshold, the per-block "is_uniform"
    /// footer bit is set, which
    /// [`IndexBlockSearchType::Auto`](Self::set_index_block_search_type)
    /// consults at lookup time.
    ///
    /// Any negative value disables the feature; the magnitude is ignored.
    /// With the default disabled value, [`IndexBlockSearchType::Auto`]
    /// degenerates to binary search at read time because the per-block
    /// "is_uniform" bit is never written. The recommended enabled range is
    /// `0.0..=1.0`; a typical value is `0.2`.
    ///
    /// Note: currently only index blocks honour this; the value has no effect
    /// on data blocks today.
    ///
    /// Default: `-1.0` (disabled)
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::BlockBasedOptions;
    ///
    /// let mut block_opts = BlockBasedOptions::default();
    /// block_opts.set_uniform_cv_threshold(0.2);
    /// ```
    pub fn set_uniform_cv_threshold(&mut self, threshold: f64) {
        unsafe {
            ffi::rocksdb_block_based_options_set_uniform_cv_threshold(self.inner, threshold);
        }
    }

    /// If cache_index_and_filter_blocks is true and the below is true, then
    /// filter and index blocks are stored in the cache, but a reference is
    /// held in the "table reader" object so the blocks are pinned and only
    /// evicted from cache when the table reader is freed.
    ///
    /// Default: false.
    pub fn set_pin_l0_filter_and_index_blocks_in_cache(&mut self, v: bool) {
        unsafe {
            ffi::rocksdb_block_based_options_set_pin_l0_filter_and_index_blocks_in_cache(
                self.inner,
                c_uchar::from(v),
            );
        }
    }

    /// If cache_index_and_filter_blocks is true and the below is true, then
    /// the top-level index of partitioned filter and index blocks are stored in
    /// the cache, but a reference is held in the "table reader" object so the
    /// blocks are pinned and only evicted from cache when the table reader is
    /// freed. This is not limited to l0 in LSM tree.
    ///
    /// Default: true.
    pub fn set_pin_top_level_index_and_filter(&mut self, v: bool) {
        unsafe {
            ffi::rocksdb_block_based_options_set_pin_top_level_index_and_filter(
                self.inner,
                c_uchar::from(v),
            );
        }
    }

    /// Format version, reserved for backward compatibility.
    ///
    /// See full [list](https://github.com/facebook/rocksdb/blob/v11.12/include/rocksdb/table.h#L726-L760)
    /// of the supported versions.
    ///
    /// Default: 7, which needs RocksDB 10.4.0 or newer to read. Lower it if
    /// older readers have to open the files.
    pub fn set_format_version(&mut self, version: i32) {
        unsafe {
            ffi::rocksdb_block_based_options_set_format_version(self.inner, version);
        }
    }

    /// Use delta encoding to compress keys in blocks.
    /// ReadOptions::pin_data requires this option to be disabled.
    ///
    /// Default: true
    pub fn set_use_delta_encoding(&mut self, enable: bool) {
        unsafe {
            ffi::rocksdb_block_based_options_set_use_delta_encoding(
                self.inner,
                c_uchar::from(enable),
            );
        }
    }

    /// Number of keys between restart points for delta encoding of keys.
    /// This parameter can be changed dynamically. Most clients should
    /// leave this parameter alone. The minimum value allowed is 1. Any smaller
    /// value will be silently overwritten with 1.
    ///
    /// Default: 16.
    pub fn set_block_restart_interval(&mut self, interval: i32) {
        unsafe {
            ffi::rocksdb_block_based_options_set_block_restart_interval(self.inner, interval);
        }
    }

    /// Same as block_restart_interval but used for the index block.
    /// If you don't plan to run RocksDB before version 5.16 and you are
    /// using `index_block_restart_interval` > 1, you should
    /// probably set the `format_version` to >= 4 as it would reduce the index size.
    ///
    /// Default: 1.
    pub fn set_index_block_restart_interval(&mut self, interval: i32) {
        unsafe {
            ffi::rocksdb_block_based_options_set_index_block_restart_interval(self.inner, interval);
        }
    }

    /// Set the data block index type for point lookups:
    ///  `DataBlockIndexType::BinarySearch` to use binary search within the data block.
    ///  `DataBlockIndexType::BinaryAndHash` to use the data block hash index in combination with
    ///  the normal binary search.
    ///
    /// The hash table utilization ratio is adjustable using [`set_data_block_hash_ratio`](#method.set_data_block_hash_ratio), which is
    /// valid only when using `DataBlockIndexType::BinaryAndHash`.
    ///
    /// Default: `BinarySearch`
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::{BlockBasedOptions, DataBlockIndexType, Options};
    ///
    /// let mut opts = Options::default();
    /// let mut block_opts = BlockBasedOptions::default();
    /// block_opts.set_data_block_index_type(DataBlockIndexType::BinaryAndHash);
    /// block_opts.set_data_block_hash_ratio(0.85);
    /// ```
    pub fn set_data_block_index_type(&mut self, index_type: DataBlockIndexType) {
        let index_t = index_type as i32;
        unsafe {
            ffi::rocksdb_block_based_options_set_data_block_index_type(self.inner, index_t);
        }
    }

    /// Set the data block hash index utilization ratio.
    ///
    /// The smaller the utilization ratio, the less hash collisions happen, and so reduce the risk for a
    /// point lookup to fall back to binary search due to the collisions. A small ratio means faster
    /// lookup at the price of more space overhead.
    ///
    /// Default: 0.75
    pub fn set_data_block_hash_ratio(&mut self, ratio: f64) {
        unsafe {
            ffi::rocksdb_block_based_options_set_data_block_hash_ratio(self.inner, ratio);
        }
    }

    /// If false, place only prefixes in the filter, not whole keys.
    ///
    /// Defaults to true.
    pub fn set_whole_key_filtering(&mut self, v: bool) {
        unsafe {
            ffi::rocksdb_block_based_options_set_whole_key_filtering(self.inner, c_uchar::from(v));
        }
    }

    /// Use the specified checksum type.
    /// Newly created table files will be protected with this checksum type.
    /// Old table files will still be readable, even though they have different checksum type.
    pub fn set_checksum_type(&mut self, checksum_type: ChecksumType) {
        unsafe {
            ffi::rocksdb_block_based_options_set_checksum(self.inner, checksum_type as c_char);
        }
    }

    /// If true, generate Bloom/Ribbon filters that minimize memory internal
    /// fragmentation.
    /// See official [wiki](
    /// https://github.com/facebook/rocksdb/wiki/RocksDB-Bloom-Filter#reducing-internal-fragmentation)
    /// for more information.
    ///
    /// Default: true.
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::BlockBasedOptions;
    ///
    /// let mut opts = BlockBasedOptions::default();
    /// opts.set_bloom_filter(10.0, true);
    /// opts.set_optimize_filters_for_memory(true);
    /// ```
    pub fn set_optimize_filters_for_memory(&mut self, v: bool) {
        unsafe {
            ffi::rocksdb_block_based_options_set_optimize_filters_for_memory(
                self.inner,
                c_uchar::from(v),
            );
        }
    }

    /// The tier of block-based tables whose top-level index into metadata
    /// partitions will be pinned. Currently indexes and filters may be
    /// partitioned.
    ///
    /// Note `cache_index_and_filter_blocks` must be true for this option to have
    /// any effect. Otherwise any top-level index into metadata partitions would be
    /// held in table reader memory, outside the block cache.
    ///
    /// Default: `BlockBasedPinningTier:Fallback`
    ///
    /// # Example
    ///
    /// ```
    /// use rust_rocksdb::{BlockBasedOptions, BlockBasedPinningTier, Options};
    ///
    /// let mut opts = Options::default();
    /// let mut block_opts = BlockBasedOptions::default();
    /// block_opts.set_top_level_index_pinning_tier(BlockBasedPinningTier::FlushAndSimilar);
    /// ```
    pub fn set_top_level_index_pinning_tier(&mut self, tier: BlockBasedPinningTier) {
        unsafe {
            ffi::rocksdb_block_based_options_set_top_level_index_pinning_tier(
                self.inner,
                tier as c_int,
            );
        }
    }

    /// The tier of block-based tables whose metadata partitions will be pinned.
    /// Currently indexes and filters may be partitioned.
    ///
    /// Default: `BlockBasedPinningTier:Fallback`
    ///
    /// # Example
    ///
    /// ```
    /// use rust_rocksdb::{BlockBasedOptions, BlockBasedPinningTier, Options};
    ///
    /// let mut opts = Options::default();
    /// let mut block_opts = BlockBasedOptions::default();
    /// block_opts.set_partition_pinning_tier(BlockBasedPinningTier::FlushAndSimilar);
    /// ```
    pub fn set_partition_pinning_tier(&mut self, tier: BlockBasedPinningTier) {
        unsafe {
            ffi::rocksdb_block_based_options_set_partition_pinning_tier(self.inner, tier as c_int);
        }
    }

    /// The tier of block-based tables whose unpartitioned metadata blocks will be
    /// pinned.
    ///
    /// Note `cache_index_and_filter_blocks` must be true for this option to have
    /// any effect. Otherwise the unpartitioned meta-blocks would be held in table
    /// reader memory, outside the block cache.
    ///
    /// Default: `BlockBasedPinningTier:Fallback`
    ///
    /// # Example
    ///
    /// ```
    /// use rust_rocksdb::{BlockBasedOptions, BlockBasedPinningTier, Options};
    ///
    /// let mut opts = Options::default();
    /// let mut block_opts = BlockBasedOptions::default();
    /// block_opts.set_unpartitioned_pinning_tier(BlockBasedPinningTier::FlushAndSimilar);
    /// ```
    pub fn set_unpartitioned_pinning_tier(&mut self, tier: BlockBasedPinningTier) {
        unsafe {
            ffi::rocksdb_block_based_options_set_unpartitioned_pinning_tier(
                self.inner,
                tier as c_int,
            );
        }
    }

    /// Align data blocks on lesser of page size and block size
    pub fn get_block_align(&self) -> bool {
        unsafe { ffi::rocksdb_block_based_options_get_block_align(self.inner) != 0 }
    }

    /// Number of keys between restart points for delta encoding of keys. This parameter can
    /// be changed dynamically.  Most clients should leave this parameter alone.  The minimum
    /// value allowed is 1.  Any smaller value will be silently overwritten with 1.
    pub fn get_block_restart_interval(&self) -> c_int {
        unsafe { ffi::rocksdb_block_based_options_get_block_restart_interval(self.inner) }
    }

    /// Approximate size of user data packed per block.  Note that the block size specified
    /// here corresponds to uncompressed data.  The actual size of the unit read from disk may
    /// be smaller if compression is enabled.  This parameter can be changed dynamically.
    pub fn get_block_size(&self) -> u64 {
        unsafe { ffi::rocksdb_block_based_options_get_block_size(self.inner) }
    }

    /// This is used to close a block before it reaches the configured 'block_size'. If the
    /// percentage of free space in the current block is less than this specified number and
    /// adding a new record to the block will exceed the configured block size, then this
    /// block will be closed and the new record will be written to the next block.
    pub fn get_block_size_deviation(&self) -> c_int {
        unsafe { ffi::rocksdb_block_based_options_get_block_size_deviation(self.inner) }
    }

    /// TODO(kailiu) Temporarily disable this feature by making the default value to be false.
    ///
    /// TODO(ajkr) we need to update names of variables controlling meta-block caching as they
    /// should now apply to range tombstone and compression dictionary meta-blocks, in
    /// addition to index and filter meta-blocks.
    ///
    /// Whether to put index/filter blocks in the block cache. When false, each "table reader"
    /// object will pre-load index/filter blocks during table initialization. Index and filter
    /// partition blocks always use block cache regardless of this option.
    pub fn get_cache_index_and_filter_blocks(&self) -> bool {
        unsafe {
            ffi::rocksdb_block_based_options_get_cache_index_and_filter_blocks(self.inner) != 0
        }
    }

    /// If cache_index_and_filter_blocks is enabled, cache index and filter blocks with high
    /// priority. If set to true, depending on implementation of block cache, index, filter,
    /// and other metadata blocks may be less likely to be evicted than data blocks.
    pub fn get_cache_index_and_filter_blocks_with_high_priority(&self) -> bool {
        unsafe {
            ffi::rocksdb_block_based_options_get_cache_index_and_filter_blocks_with_high_priority(
                self.inner,
            ) != 0
        }
    }

    /// Use the specified checksum type. Newly created table files will be protected with this
    /// checksum type. Old table files will still be readable, even though they have different
    /// checksum type.
    pub fn get_checksum(&self) -> c_int {
        unsafe { ffi::rocksdb_block_based_options_get_checksum(self.inner) }
    }

    /// #entries/#buckets. It is valid only when data_block_hash_index_type is
    /// kDataBlockBinaryAndHash.
    pub fn set_data_block_hash_table_util_ratio(&mut self, val: f64) {
        unsafe {
            ffi::rocksdb_block_based_options_set_data_block_hash_table_util_ratio(self.inner, val);
        }
    }

    /// Returns the value of the `data_block_hash_table_util_ratio` option.
    pub fn get_data_block_hash_table_util_ratio(&self) -> f64 {
        unsafe { ffi::rocksdb_block_based_options_get_data_block_hash_table_util_ratio(self.inner) }
    }

    /// Returns the value of the `data_block_index_type` option.
    pub fn get_data_block_index_type(&self) -> c_int {
        unsafe { ffi::rocksdb_block_based_options_get_data_block_index_type(self.inner) }
    }

    /// When both partitioned indexes and partitioned filters are enabled, this enables
    /// independent partitioning boundaries between the two. Most notably, this enables these
    /// metadata blocks to hit their target size much more accurately, as there is often a
    /// disparity between index sizes and filter sizes. This should reduce fragmentation and
    /// metadata overheads in the block cache, as well as treat blocks more fairly for cache
    /// eviction purposes.
    ///
    /// There are no SST format compatibility issues with this option. (All versions of
    /// RocksDB able to read partitioned filters are able to read decoupled partitioned
    /// filters.)
    ///
    /// decouple_partitioned_filters = true is the new default. This option is now DEPRECATED
    /// and might be ignored and/or removed in a future release.
    ///
    /// NOTE: decouple_partitioned_filters = false with partition_filters = true disables
    /// parallel compression (CompressionOptions::parallel_threads sanitized to 1).
    pub fn set_decouple_partitioned_filters(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_block_based_options_set_decouple_partitioned_filters(
                self.inner,
                c_uchar::from(val),
            );
        }
    }

    /// Returns the value of the `decouple_partitioned_filters` option.
    pub fn get_decouple_partitioned_filters(&self) -> bool {
        unsafe {
            ffi::rocksdb_block_based_options_get_decouple_partitioned_filters(self.inner) != 0
        }
    }

    /// If true, detect corruption during Bloom Filter (format_version >= 5) and Ribbon Filter
    /// construction.
    ///
    /// This is an extra check that is only useful in detecting software bugs or CPU+memory
    /// malfunction. Turning on this feature increases filter construction time by 30%.
    ///
    /// TODO: optimize this performance
    pub fn set_detect_filter_construct_corruption(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_block_based_options_set_detect_filter_construct_corruption(
                self.inner,
                c_uchar::from(val),
            );
        }
    }

    /// Returns the value of the `detect_filter_construct_corruption` option.
    pub fn get_detect_filter_construct_corruption(&self) -> bool {
        unsafe {
            ffi::rocksdb_block_based_options_get_detect_filter_construct_corruption(self.inner) != 0
        }
    }

    /// Store index blocks on disk in compressed format. Changing this option to false  will
    /// avoid the overhead of decompression if index blocks are evicted and read back
    pub fn set_enable_index_compression(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_block_based_options_set_enable_index_compression(
                self.inner,
                c_uchar::from(val),
            );
        }
    }

    /// Returns the value of the `enable_index_compression` option.
    pub fn get_enable_index_compression(&self) -> bool {
        unsafe { ffi::rocksdb_block_based_options_get_enable_index_compression(self.inner) != 0 }
    }

    /// EXPERIMENTAL
    ///
    /// Return an error Status if a user_defined_index_factory is configured, but there's no
    /// corresponding UDI block in the SST file being opened. When use_udi_as_primary_index is
    /// true, this check is automatically enforced (a missing UDI block is always an error in
    /// primary mode).
    pub fn set_fail_if_no_udi_on_open(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_block_based_options_set_fail_if_no_udi_on_open(
                self.inner,
                c_uchar::from(val),
            );
        }
    }

    /// Returns the value of the `fail_if_no_udi_on_open` option.
    pub fn get_fail_if_no_udi_on_open(&self) -> bool {
        unsafe { ffi::rocksdb_block_based_options_get_fail_if_no_udi_on_open(self.inner) != 0 }
    }

    /// We currently have these format versions: 0 - 1 -- No longer supported. Attempting to
    /// read files with these format versions will return an error. To upgrade, load the data
    /// with RocksDB >= 4.6.0 and < 11.0.0, then run a full compaction.
    /// - Can be read by RocksDB's versions since 3.10. Changes the way we encode compressed
    ///   blocks with LZ4, BZip2 and Zlib compression. If you don't plan to run RocksDB
    ///   before version 3.10, you should probably use this.
    /// - Can be read by RocksDB's versions since 5.15. Changes the way we encode the keys
    ///   in index blocks. If you don't plan to run RocksDB before version 5.15, you should
    ///   probably use this. This option only affects newly written tables. When reading
    ///   existing tables, the information about version is read from the footer.
    /// - Can be read by RocksDB's versions since 5.16. Changes the way we encode the values
    ///   in index blocks. If you don't plan to run RocksDB before version 5.16 and you are
    ///   using index_block_restart_interval > 1, you should probably use this as it would
    ///   reduce the index size. This option only affects newly written tables. When reading
    ///   existing tables, the information about version is read from the footer.
    /// - Can be read by RocksDB's versions since 6.6.0. Full and partitioned filters use a
    ///   generally faster and more accurate Bloom filter implementation, with a different
    ///   schema.
    /// - Modified the file footer and checksum matching so that SST data misplaced within
    ///   or between files is as likely to fail checksum verification as random corruption.
    ///   Also checksum-protects SST footer. Can be read by RocksDB versions >= 8.6.0.
    /// - Support for custom compression algorithms with a CompressionManager using a
    ///   non-built-in CompatibilityName(). See `compression_manager` in
    ///   ColumnFamilyOptions. Also changes the format of TableProperties field
    ///   `compression_name`. Can be read by RocksDB versions >= 10.4.0.
    ///
    /// Using the default setting of format_version is strongly recommended, so that available
    /// enhancements are adopted eventually and automatically. The default setting will only
    /// update to the latest after thorough production validation and sufficient time and
    /// number of releases have elapsed (6 months recommended) to ensure a clean
    /// downgrade/revert path for users who might only upgrade a few times per year.
    pub fn get_format_version(&self) -> u32 {
        unsafe { ffi::rocksdb_block_based_options_get_format_version(self.inner) }
    }

    /// Same as block_restart_interval but used for the index block.
    pub fn get_index_block_restart_interval(&self) -> c_int {
        unsafe { ffi::rocksdb_block_based_options_get_index_block_restart_interval(self.inner) }
    }

    /// Returns the value of the `index_block_search_type` option.
    pub fn get_index_block_search_type(&self) -> c_int {
        unsafe { ffi::rocksdb_block_based_options_get_index_block_search_type(self.inner) }
    }

    /// Sets the `index_shortening` option.
    pub fn set_index_shortening(&mut self, val: c_int) {
        unsafe {
            ffi::rocksdb_block_based_options_set_index_shortening(self.inner, val);
        }
    }

    /// Returns the value of the `index_shortening` option.
    pub fn get_index_shortening(&self) -> c_int {
        unsafe { ffi::rocksdb_block_based_options_get_index_shortening(self.inner) }
    }

    /// Returns the value of the `index_type` option.
    pub fn get_index_type(&self) -> c_int {
        unsafe { ffi::rocksdb_block_based_options_get_index_type(self.inner) }
    }

    /// RocksDB does auto-readahead for iterators on noticing more than two reads for a table
    /// file if user doesn't provide readahead_size. The readahead size starts at
    /// initial_auto_readahead_size and doubles on every additional read upto
    /// BlockBasedTableOptions.max_auto_readahead_size. max_auto_readahead_size can also be
    /// configured.
    ///
    /// Scenarios:
    /// - If initial_auto_readahead_size is set 0 then it will disabled the implicit auto
    ///   prefetching irrespective of max_auto_readahead_size.
    /// - If max_auto_readahead_size is set 0, it will disable the internal prefetching
    ///   irrespective of initial_auto_readahead_size.
    /// - If initial_auto_readahead_size > max_auto_readahead_size, then RocksDB will
    ///   sanitize the value of initial_auto_readahead_size to max_auto_readahead_size and
    ///   readahead_size will be max_auto_readahead_size.
    ///
    /// Value should be provided along with KB i.e. 8 * 1024 as it will prefetch the blocks.
    ///
    /// Default: 8 KB (8 * 1024).
    pub fn set_initial_auto_readahead_size(&mut self, val: usize) {
        unsafe {
            ffi::rocksdb_block_based_options_set_initial_auto_readahead_size(self.inner, val);
        }
    }

    /// Returns the value of the `initial_auto_readahead_size` option.
    pub fn get_initial_auto_readahead_size(&self) -> usize {
        unsafe { ffi::rocksdb_block_based_options_get_initial_auto_readahead_size(self.inner) }
    }

    /// RocksDB does auto-readahead for iterators on noticing more than two reads for a table
    /// file if user doesn't provide readahead_size. The readahead starts at
    /// BlockBasedTableOptions.initial_auto_readahead_size (default: 8KB) and doubles on every
    /// additional read upto max_auto_readahead_size and max_auto_readahead_size can be
    /// configured.
    ///
    /// Special Value: 0 - If max_auto_readahead_size is set 0 then it will disable the
    /// implicit auto prefetching. If max_auto_readahead_size provided is less than
    /// initial_auto_readahead_size, then RocksDB will sanitize the
    /// initial_auto_readahead_size and set it to max_auto_readahead_size.
    ///
    /// Value should be provided along with KB i.e. 256 * 1024 as it will prefetch the blocks.
    ///
    /// Found that 256 KB readahead size provides the best performance, based on experiments,
    /// for auto readahead. Experiment data is in PR #3282.
    ///
    /// Default: 256 KB (256 * 1024).
    pub fn set_max_auto_readahead_size(&mut self, val: usize) {
        unsafe {
            ffi::rocksdb_block_based_options_set_max_auto_readahead_size(self.inner, val);
        }
    }

    /// Returns the value of the `max_auto_readahead_size` option.
    pub fn get_max_auto_readahead_size(&self) -> usize {
        unsafe { ffi::rocksdb_block_based_options_get_max_auto_readahead_size(self.inner) }
    }

    /// Target block size for partitioned metadata. Currently applied to indexes when
    /// kTwoLevelIndexSearch is used and to filters when partition_filters is used. When
    /// decouple_partitioned_filters=false (original behavior), there is much more deviation
    /// from this target size. See the comment on decouple_partitioned_filters.
    pub fn get_metadata_block_size(&self) -> u64 {
        unsafe { ffi::rocksdb_block_based_options_get_metadata_block_size(self.inner) }
    }

    /// Disable block cache. If this is set to true, then no block cache will be configured
    /// (block_cache reset to nullptr).
    ///
    /// This option should not be used with SetOptions.
    pub fn get_no_block_cache(&self) -> bool {
        unsafe { ffi::rocksdb_block_based_options_get_no_block_cache(self.inner) != 0 }
    }

    /// RocksDB does auto-readahead for iterators on noticing more than two reads for a table
    /// file if user doesn't provide readahead_size and reads are sequential.
    /// num_file_reads_for_auto_readahead indicates after how many sequential reads internal
    /// auto prefetching should be start.
    ///
    /// For example, if value is 2 then after reading 2 sequential data blocks on third data
    /// block prefetching will start. If set 0, it will start prefetching from the first read.
    ///
    /// This parameter can be changed dynamically by
    /// DB::SetOptions({{"block_based_table_factory",
    /// "{num_file_reads_for_auto_readahead=0;}"}}));
    ///
    /// Changing the value dynamically will only affect files opened after the change.
    ///
    /// Default: 2
    pub fn set_num_file_reads_for_auto_readahead(&mut self, val: u64) {
        unsafe {
            ffi::rocksdb_block_based_options_set_num_file_reads_for_auto_readahead(self.inner, val);
        }
    }

    /// Returns the value of the `num_file_reads_for_auto_readahead` option.
    pub fn get_num_file_reads_for_auto_readahead(&self) -> u64 {
        unsafe {
            ffi::rocksdb_block_based_options_get_num_file_reads_for_auto_readahead(self.inner)
        }
    }

    /// Option to generate Bloom/Ribbon filters that minimize memory internal fragmentation.
    ///
    /// When false, malloc_usable_size is not available, or format_version < 5, filters are
    /// generated without regard to internal fragmentation when loaded into memory (historical
    /// behavior). When true (and malloc_usable_size is available and format_version >= 5),
    /// then filters are generated to "round up" and "round down" their sizes to minimize
    /// internal fragmentation when loaded into memory, assuming the reading DB has the same
    /// memory allocation characteristics as the generating DB. This option does not break
    /// forward or backward compatibility.
    ///
    /// While individual filters will vary in bits/key and false positive rate when setting is
    /// true, the implementation attempts to maintain a weighted average FP rate for filters
    /// consistent with this option set to false.
    ///
    /// With Jemalloc for example, this setting is expected to save about 10% of the memory
    /// footprint and block cache charge of filters, while increasing disk usage of filters by
    /// about 1-2% due to encoding efficiency losses with variance in bits/key.
    ///
    /// NOTE: Because some memory counted by block cache might be unmapped pages within
    /// internal fragmentation, this option can increase observed RSS memory usage. With
    /// cache_index_and_filter_blocks=true, this option makes the block cache better at using
    /// space it is allowed. (These issues should not arise with partitioned filters.)
    ///
    /// NOTE: Set to false if you do not trust malloc_usable_size. When set to true, RocksDB
    /// might access an allocated memory object beyond its original size if malloc_usable_size
    /// says it is safe to do so. While this can be considered bad practice, it should not
    /// produce undefined behavior unless malloc_usable_size is buggy or broken.
    pub fn get_optimize_filters_for_memory(&self) -> bool {
        unsafe { ffi::rocksdb_block_based_options_get_optimize_filters_for_memory(self.inner) != 0 }
    }

    /// Note: currently this option requires kTwoLevelIndexSearch to be set as well.
    /// TODO(myabandeh): remove the note above once the limitation is lifted Use partitioned
    /// full filters for each SST file. This option is incompatible with block-based filters.
    /// Filter partition blocks use block cache even when cache_index_and_filter_blocks=false.
    pub fn get_partition_filters(&self) -> bool {
        unsafe { ffi::rocksdb_block_based_options_get_partition_filters(self.inner) != 0 }
    }

    /// DEPRECATED: This option will be removed in a future version. For now, this option
    /// still takes effect by updating each of the following variables that has the default
    /// value, `PinningTier::kFallback`:
    ///
    /// - `MetadataCacheOptions::partition_pinning`
    /// - `MetadataCacheOptions::unpartitioned_pinning`
    ///
    /// The updated value is chosen as follows:
    ///
    /// - `pin_l0_filter_and_index_blocks_in_cache == false` -> `PinningTier::kNone`
    /// - `pin_l0_filter_and_index_blocks_in_cache == true` ->
    ///   `PinningTier::kFlushedAndSimilar`
    ///
    /// To migrate away from this flag, explicitly configure `MetadataCacheOptions` as
    /// described above.
    ///
    /// if cache_index_and_filter_blocks is true and the below is true, then filter and index
    /// blocks are stored in the cache, but a reference is held in the "table reader" object
    /// so the blocks are pinned and only evicted from cache when the table reader is freed.
    pub fn get_pin_l0_filter_and_index_blocks_in_cache(&self) -> bool {
        unsafe {
            ffi::rocksdb_block_based_options_get_pin_l0_filter_and_index_blocks_in_cache(self.inner)
                != 0
        }
    }

    /// DEPRECATED: This option will be removed in a future version. For now, this option
    /// still takes effect by updating `MetadataCacheOptions::top_level_index_pinning` when it
    /// has the default value, `PinningTier::kFallback`.
    ///
    /// The updated value is chosen as follows:
    ///
    /// - `pin_top_level_index_and_filter == false` -> `PinningTier::kNone`
    /// - `pin_top_level_index_and_filter == true` -> `PinningTier::kAll`
    ///
    /// To migrate away from this flag, explicitly configure `MetadataCacheOptions` as
    /// described above.
    ///
    /// If cache_index_and_filter_blocks is true and the below is true, then the top-level
    /// index of partitioned filter and index blocks are stored in the cache, but a reference
    /// is held in the "table reader" object so the blocks are pinned and only evicted from
    /// cache when the table reader is freed. This is not limited to l0 in LSM tree.
    pub fn get_pin_top_level_index_and_filter(&self) -> bool {
        unsafe {
            ffi::rocksdb_block_based_options_get_pin_top_level_index_and_filter(self.inner) != 0
        }
    }

    /// Sets the `prepopulate_block_cache` option.
    pub fn set_prepopulate_block_cache(&mut self, val: c_int) {
        unsafe {
            ffi::rocksdb_block_based_options_set_prepopulate_block_cache(self.inner, val);
        }
    }

    /// Returns the value of the `prepopulate_block_cache` option.
    pub fn get_prepopulate_block_cache(&self) -> c_int {
        unsafe { ffi::rocksdb_block_based_options_get_prepopulate_block_cache(self.inner) }
    }

    /// If used, For every data block we load into memory, we will create a bitmap of size
    /// ((block_size / `read_amp_bytes_per_bit`) / 8) bytes. This bitmap will be used to
    /// figure out the percentage we actually read of the blocks.
    ///
    /// When this feature is used Tickers::READ_AMP_ESTIMATE_USEFUL_BYTES and
    /// Tickers::READ_AMP_TOTAL_READ_BYTES can be used to calculate the read amplification
    /// using this formula (READ_AMP_TOTAL_READ_BYTES / READ_AMP_ESTIMATE_USEFUL_BYTES)
    ///
    /// value  =>  memory usage (percentage of loaded blocks memory) 1      =>  12.50 % 2
    /// =>  06.25 % 4      =>  03.12 % 8      =>  01.56 % 16     =>  00.78 %
    ///
    /// Note: This number must be a power of 2, if not it will be sanitized to be the next
    /// lowest power of 2, for example a value of 7 will be treated as 4, a value of 19 will
    /// be treated as 16.
    ///
    /// Default: 0 (disabled)
    pub fn set_read_amp_bytes_per_bit(&mut self, val: u32) {
        unsafe {
            ffi::rocksdb_block_based_options_set_read_amp_bytes_per_bit(self.inner, val);
        }
    }

    /// Returns the value of the `read_amp_bytes_per_bit` option.
    pub fn get_read_amp_bytes_per_bit(&self) -> u32 {
        unsafe { ffi::rocksdb_block_based_options_get_read_amp_bytes_per_bit(self.inner) }
    }

    /// When true, data blocks store keys and values separately. Keys are stored at the
    /// beginning of the block, followed by values at the end. This can improve read
    /// performance at a cost of a varint per restart interval (~1 bit per key by default), in
    /// addition to improving compression. Small values or low block_restart_interval may
    /// prefer to set this as false.
    ///
    /// Default: false
    pub fn get_separate_key_value_in_data_block(&self) -> bool {
        unsafe {
            ffi::rocksdb_block_based_options_get_separate_key_value_in_data_block(self.inner) != 0
        }
    }

    /// Align data blocks on super block alignment. Avoid a data block split across super
    /// block boundaries. Works with/without compression.
    ///
    /// Here a "super block" refers to an aligned unit of underlying Filesystem storage for
    /// which there is an extra cost when a random read involves two such super blocks instead
    /// of just one. Configuring that size here suggests inserting padding in the SST file to
    /// avoid a single SST block splitting across two super blocks. Only power-of-two sizes
    /// are supported. See also super_block_alignment_space_overhead_ratio. Default to 0,
    /// which means super block alignment is disabled.
    ///
    /// Super block alignment size. Default to 0, which means super block alignment is
    /// disabled. If it is enabled, it needs to be a power of 2 and higher than block size.
    pub fn set_super_block_alignment_size(&mut self, val: usize) {
        unsafe {
            ffi::rocksdb_block_based_options_set_super_block_alignment_size(self.inner, val);
        }
    }

    /// Returns the value of the `super_block_alignment_size` option.
    pub fn get_super_block_alignment_size(&self) -> usize {
        unsafe { ffi::rocksdb_block_based_options_get_super_block_alignment_size(self.inner) }
    }

    /// This option constrols the storage space overhead of super block alignment. It is used
    /// to calculate the max padding size allowed for super block alignment. It is calculated
    /// in this way. If super_block_alignment_size is 2MB, and
    /// super_block_alignment_overhead_ratio is 128, then the max padding size allowed for
    /// super block alignment is 2MB / 128 = 16KB. Note that, when it is set to 0, super block
    /// alignment is disabled.
    pub fn set_super_block_alignment_space_overhead_ratio(&mut self, val: usize) {
        unsafe {
            ffi::rocksdb_block_based_options_set_super_block_alignment_space_overhead_ratio(
                self.inner, val,
            );
        }
    }

    /// Returns the value of the `super_block_alignment_space_overhead_ratio` option.
    pub fn get_super_block_alignment_space_overhead_ratio(&self) -> usize {
        unsafe {
            ffi::rocksdb_block_based_options_get_super_block_alignment_space_overhead_ratio(
                self.inner,
            )
        }
    }

    /// Coefficient of variation (CV) threshold used to determine if keys in an index block
    /// are uniformly distributed. Lower CV means more "uniform", and the more likely
    /// interpolation search will outperform binary search.
    ///
    /// On the write path, if the CV of key gaps in an index block is less than this
    /// threshold, the "is_uniform" hint is set in that block's footer. To disable (i.e.
    /// always have "is_uniform=false"), set value to -1.
    ///
    /// On the read path, if `BlockSearchType::kAuto` is set, then it will use the is_uniform
    /// hint to select an appropriate search algorithm for the block.
    ///
    /// NOTE: Currently only supports index blocks. May update to include data blocks in the
    /// future.
    pub fn get_uniform_cv_threshold(&self) -> f64 {
        unsafe { ffi::rocksdb_block_based_options_get_uniform_cv_threshold(self.inner) }
    }

    /// Use delta encoding to compress keys in blocks. ReadOptions::pin_data requires this
    /// option to be disabled.
    ///
    /// Default: true
    pub fn get_use_delta_encoding(&self) -> bool {
        unsafe { ffi::rocksdb_block_based_options_get_use_delta_encoding(self.inner) != 0 }
    }

    /// EXPERIMENTAL
    ///
    /// When true and user_defined_index_factory is set, the UDI becomes the primary index for
    /// reads. All reads (including internal operations like compaction and VerifyChecksum)
    /// automatically route through the UDI without needing ReadOptions::table_index_factory.
    ///
    /// Both the standard binary search index and the UDI are always fully built. The standard
    /// index serves as a safety fallback (e.g., for backup/restore or rollback to a non-UDI
    /// configuration). A future refactor will extract the index abstraction to allow skipping
    /// the standard index build when the UDI is primary.
    ///
    /// When the UDI is primary:
    /// - All reads automatically use the UDI (ReadOptions::table_index_factory does not
    ///   need to be set)
    /// - Partitioned index (kTwoLevelIndexSearch) and partitioned filters are incompatible
    ///   with this option
    /// - fail_if_no_udi_on_open is automatically enforced to prevent silent data loss if
    ///   these SSTs are opened without UDI support
    ///
    /// Recommended migration path:
    ///
    /// - Deploy with user_defined_index_factory set but use_udi_as_primary_index=false
    ///   (secondary mode). New SSTs are written with both indexes. Reads use the standard
    ///   index by default.
    ///
    /// - Validate reads through the UDI by setting ReadOptions::table_index_factory on a
    ///   subset of reads.
    ///
    /// - Compact the entire DB to rewrite all pre-existing SSTs with both indexes. All SSTs
    ///   must have a UDI block before proceeding.
    ///
    /// - Enable use_udi_as_primary_index=true. All reads use the UDI.
    ///
    /// Rollback: set use_udi_as_primary_index=false. Since the standard index is always fully
    /// populated, SSTs are immediately readable through the standard index. No compaction is
    /// required. All reads immediately revert to the standard index path.
    ///
    /// Backup/restore: the user_defined_index_factory is a shared_ptr that cannot survive
    /// Options serialization (e.g., GetStringFromDBOptions). Since the standard index is
    /// always fully populated, a restored DB can be opened and read without the factory
    /// (reads fall back to the standard index). Set the factory when opening the restored DB
    /// to resume using the UDI.
    ///
    /// Default: false (UDI is built alongside the standard index as a secondary)
    pub fn set_use_udi_as_primary_index(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_block_based_options_set_use_udi_as_primary_index(
                self.inner,
                c_uchar::from(val),
            );
        }
    }

    /// Returns the value of the `use_udi_as_primary_index` option.
    pub fn get_use_udi_as_primary_index(&self) -> bool {
        unsafe { ffi::rocksdb_block_based_options_get_use_udi_as_primary_index(self.inner) != 0 }
    }

    /// EXPERIMENTAL
    ///
    /// Builds a user defined index into every new SST file, using the factory named by
    /// `value`.
    ///
    /// `value` goes through the `UserDefinedIndexFactory` object registry, so it is either a
    /// registered id on its own or an id followed by that factory's own settings, in the
    /// usual `id=name; option=value; ...` form. `trie_index` is the only factory RocksDB
    /// registers itself.
    ///
    /// The factory replaces any set earlier. Reads still go through the standard index unless
    /// [`Self::set_use_udi_as_primary_index`] is on or
    /// [`ReadOptions::set_table_index_factory_from_string`] selects the UDI for that read.
    ///
    /// # Errors
    ///
    /// Returns an error if `value` names no registered factory, or carries settings that
    /// factory rejects. Either way the previously configured factory is cleared first.
    pub fn set_user_defined_index_factory_from_string(
        &mut self,
        value: impl AsRef<str>,
    ) -> Result<(), Error> {
        let value = value.as_ref();
        unsafe {
            ffi_try!(
                ffi::rocksdb_block_based_options_set_user_defined_index_factory_from_string(
                    self.inner,
                    value.as_ptr().cast::<c_char>(),
                    value.len(),
                )
            );
        }
        Ok(())
    }

    /// Name of the configured user defined index factory, or `None` when there is none.
    ///
    /// This is the factory's registered id, not the full string passed to
    /// [`Self::set_user_defined_index_factory_from_string`].
    pub fn get_user_defined_index_factory_name(&self) -> Option<String> {
        let mut len: size_t = 0;
        let name = unsafe {
            ffi::rocksdb_block_based_options_get_user_defined_index_factory_name(
                self.inner.cast_const(),
                &raw mut len,
            )
        };
        if name.is_null() {
            return None;
        }
        Some(unsafe { borrowed_string(name, len) })
    }

    /// Drops the user defined index factory, so new SST files carry only the standard index.
    ///
    /// Files already written keep their UDI block, and stay readable through the standard
    /// index.
    pub fn clear_user_defined_index_factory(&mut self) {
        unsafe {
            ffi::rocksdb_block_based_options_clear_user_defined_index_factory(self.inner);
        }
    }

    /// Verify that decompressing the compressed block gives back the input. This is a
    /// verification mode that we use to detect bugs in compression algorithms.
    pub fn set_verify_compression(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_block_based_options_set_verify_compression(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `verify_compression` option.
    pub fn get_verify_compression(&self) -> bool {
        unsafe { ffi::rocksdb_block_based_options_get_verify_compression(self.inner) != 0 }
    }

    /// If true, place whole keys in the filter (not just prefixes). This must generally be
    /// true for gets to be efficient.
    pub fn get_whole_key_filtering(&self) -> bool {
        unsafe { ffi::rocksdb_block_based_options_get_whole_key_filtering(self.inner) != 0 }
    }

    /// Align data blocks on lesser of page size and block size.
    pub fn set_block_align(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_block_based_options_set_block_align(self.inner, c_uchar::from(val));
        }
    }

    /// This is used to close a block before it reaches the configured 'block_size'. If the
    /// percentage of free space in the current block is less than this specified number and
    /// adding a new record to the block will exceed the configured block size, then this
    /// block will be closed and the new record will be written to the next block.
    pub fn set_block_size_deviation(&mut self, val: c_int) {
        unsafe {
            ffi::rocksdb_block_based_options_set_block_size_deviation(self.inner, val);
        }
    }

    /// When true, data blocks store keys and values separately. Keys are stored at the
    /// beginning of the block, followed by values at the end. This can improve read
    /// performance at a cost of a varint per restart interval (~1 bit per key by default), in
    /// addition to improving compression. Small values or low block_restart_interval may
    /// prefer to set this as false.
    ///
    /// Default: false.
    pub fn set_separate_key_value_in_data_block(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_block_based_options_set_separate_key_value_in_data_block(
                self.inner,
                c_uchar::from(val),
            );
        }
    }
}

impl Default for BlockBasedOptions {
    fn default() -> Self {
        let block_opts = unsafe { ffi::rocksdb_block_based_options_create() };
        assert!(
            !block_opts.is_null(),
            "Could not create RocksDB block based options"
        );

        Self {
            inner: block_opts,
            outlive: BlockBasedOptionsMustOutliveDB::default(),
        }
    }
}

impl CuckooTableOptions {
    /// Determines the utilization of hash tables. Smaller values
    /// result in larger hash tables with fewer collisions.
    /// Default: 0.9
    pub fn set_hash_ratio(&mut self, ratio: f64) {
        unsafe {
            ffi::rocksdb_cuckoo_options_set_hash_ratio(self.inner, ratio);
        }
    }

    /// A property used by builder to determine the depth to go to
    /// to search for a path to displace elements in case of
    /// collision. See Builder.MakeSpaceForKey method. Higher
    /// values result in more efficient hash tables with fewer
    /// lookups but take more time to build.
    /// Default: 100
    pub fn set_max_search_depth(&mut self, depth: u32) {
        unsafe {
            ffi::rocksdb_cuckoo_options_set_max_search_depth(self.inner, depth);
        }
    }

    /// In case of collision while inserting, the builder
    /// attempts to insert in the next cuckoo_block_size
    /// locations before skipping over to the next Cuckoo hash
    /// function. This makes lookups more cache friendly in case
    /// of collisions.
    /// Default: 5
    pub fn set_cuckoo_block_size(&mut self, size: u32) {
        unsafe {
            ffi::rocksdb_cuckoo_options_set_cuckoo_block_size(self.inner, size);
        }
    }

    /// If this option is enabled, user key is treated as uint64_t and its value
    /// is used as hash value directly. This option changes builder's behavior.
    /// Reader ignore this option and behave according to what specified in
    /// table property.
    /// Default: false
    pub fn set_identity_as_first_hash(&mut self, flag: bool) {
        unsafe {
            ffi::rocksdb_cuckoo_options_set_identity_as_first_hash(self.inner, c_uchar::from(flag));
        }
    }

    /// If this option is set to true, module is used during hash calculation.
    /// This often yields better space efficiency at the cost of performance.
    /// If this option is set to false, # of entries in table is constrained to
    /// be power of two, and bit and is used to calculate hash, which is faster in general.
    /// Default: true
    pub fn set_use_module_hash(&mut self, flag: bool) {
        unsafe {
            ffi::rocksdb_cuckoo_options_set_use_module_hash(self.inner, c_uchar::from(flag));
        }
    }

    /// In case of collision while inserting, the builder attempts to insert in the next
    /// cuckoo_block_size locations before skipping over to the next Cuckoo hash function.
    /// This makes lookups more cache friendly in case of collisions.
    pub fn get_cuckoo_block_size(&self) -> u32 {
        unsafe { ffi::rocksdb_cuckoo_options_get_cuckoo_block_size(self.inner) }
    }

    /// @hash_table_ratio: the desired utilization of the hash table used for prefix hashing.
    /// hash_table_ratio = number of prefixes / #buckets in the hash table
    pub fn set_hash_table_ratio(&mut self, val: f64) {
        unsafe {
            ffi::rocksdb_cuckoo_options_set_hash_table_ratio(self.inner, val);
        }
    }

    /// Returns the value of the `hash_table_ratio` option.
    pub fn get_hash_table_ratio(&self) -> f64 {
        unsafe { ffi::rocksdb_cuckoo_options_get_hash_table_ratio(self.inner) }
    }

    /// If this option is enabled, user key is treated as uint64_t and its value is used as
    /// hash value directly. This option changes builder's behavior. Reader ignore this option
    /// and behave according to what specified in table property.
    pub fn get_identity_as_first_hash(&self) -> bool {
        unsafe { ffi::rocksdb_cuckoo_options_get_identity_as_first_hash(self.inner) != 0 }
    }

    /// A property used by builder to determine the depth to go to to search for a path to
    /// displace elements in case of collision. See Builder.MakeSpaceForKey method. Higher
    /// values result in more efficient hash tables with fewer lookups but take more time to
    /// build.
    pub fn get_max_search_depth(&self) -> u32 {
        unsafe { ffi::rocksdb_cuckoo_options_get_max_search_depth(self.inner) }
    }

    /// If this option is set to true, module is used during hash calculation. This often
    /// yields better space efficiency at the cost of performance. If this option is set to
    /// false, # of entries in table is constrained to be power of two, and bit and is used to
    /// calculate hash, which is faster in general.
    pub fn get_use_module_hash(&self) -> bool {
        unsafe { ffi::rocksdb_cuckoo_options_get_use_module_hash(self.inner) != 0 }
    }
}

impl Default for CuckooTableOptions {
    fn default() -> Self {
        let opts = unsafe { ffi::rocksdb_cuckoo_options_create() };
        assert!(!opts.is_null(), "Could not create RocksDB cuckoo options");

        Self { inner: opts }
    }
}

// Verbosity of the LOG.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[repr(i32)]
pub enum LogLevel {
    Debug = 0,
    Info,
    Warn,
    Error,
    Fatal,
    Header,
}

impl LogLevel {
    pub(crate) fn try_from_raw(raw: i32) -> Option<Self> {
        match raw {
            n if n == LogLevel::Debug as i32 => Some(LogLevel::Debug),
            n if n == LogLevel::Info as i32 => Some(LogLevel::Info),
            n if n == LogLevel::Warn as i32 => Some(LogLevel::Warn),
            n if n == LogLevel::Error as i32 => Some(LogLevel::Error),
            n if n == LogLevel::Fatal as i32 => Some(LogLevel::Fatal),
            n if n == LogLevel::Header as i32 => Some(LogLevel::Header),
            _ => None,
        }
    }
}

impl Options {
    /// Constructs the DBOptions and ColumnFamilyDescriptors by loading the
    /// latest RocksDB options file stored in the specified rocksdb database.
    ///
    /// *IMPORTANT*:
    /// ROCKSDB DOES NOT STORE cf ttl in the options file. If you have set it via
    /// [`ColumnFamilyDescriptor::new_with_ttl`] then you need to set it again after loading the options file.
    /// Tll will be set to [`ColumnFamilyTtl::Disabled`] for all column families for your safety.
    pub fn load_latest<P: AsRef<Path>>(
        path: P,
        env: Env,
        ignore_unknown_options: bool,
        cache: Cache,
    ) -> Result<(Options, Vec<ColumnFamilyDescriptor>), Error> {
        let path = to_cpath(path)?;
        let mut db_options: *mut ffi::rocksdb_options_t = null_mut();
        let mut num_column_families: usize = 0;
        let mut column_family_names: *mut *mut c_char = null_mut();
        let mut column_family_options: *mut *mut ffi::rocksdb_options_t = null_mut();
        unsafe {
            ffi_try!(ffi::rocksdb_load_latest_options(
                path.as_ptr(),
                env.0.inner,
                ignore_unknown_options,
                cache.0.inner.as_ptr(),
                &raw mut db_options,
                &raw mut num_column_families,
                &raw mut column_family_names,
                &raw mut column_family_options,
            ));
        }
        let options = Options {
            inner: db_options,
            outlive: OptionsMustOutliveDB::default(),
        };
        // read_column_descriptors frees column_family_names and the column_family_options array.
        // We can't call rocksdb_load_latest_options_destroy because it also frees options, and
        // the individual `column_family_options` pointers. We want to return them.
        let column_families = unsafe {
            Options::read_column_descriptors(
                num_column_families,
                column_family_names,
                column_family_options,
            )
        };
        Ok((options, column_families))
    }

    /// Constructs a new `DBOptions` from `self` and a string `opts_str` with the syntax detailed in the blogpost
    /// [Reading RocksDB options from a file](https://rocksdb.org/blog/2015/02/24/reading-rocksdb-options-from-a-file.html)
    pub fn get_options_from_string<S: AsRef<str>>(
        &mut self,
        opts_str: S,
    ) -> Result<Options, Error> {
        // create the rocksdb_options_t and immediately wrap it so we don't forget to free it
        let options = Options {
            inner: unsafe { ffi::rocksdb_options_create() },
            outlive: OptionsMustOutliveDB::default(),
        };

        let opts_cstr = opts_str.as_ref().into_c_string().map_err(|e| {
            Error::new(format!(
                "options string must not contain NUL (0x00) bytes: {e}"
            ))
        })?;
        unsafe {
            ffi_try!(ffi::rocksdb_get_options_from_string(
                self.inner.cast_const(),
                opts_cstr.as_ptr(),
                options.inner,
            ));
        }
        Ok(options)
    }

    /// Reads column descriptors from C pointers. This frees the `column_family_names` and
    /// `column_family_options` arrays, and the strings contained in `column_family_names`. It does
    /// *not* free the `rocksdb_options_t*` pointers contained in `column_family_options`.
    #[inline]
    unsafe fn read_column_descriptors(
        num_column_families: usize,
        column_family_names: *mut *mut c_char,
        column_family_options: *mut *mut ffi::rocksdb_options_t,
    ) -> Vec<ColumnFamilyDescriptor> {
        let column_family_names_iter = unsafe {
            slice::from_raw_parts(column_family_names, num_column_families)
                .iter()
                .map(|ptr| from_cstr_and_free(*ptr))
        };
        let column_family_options_iter = unsafe {
            slice::from_raw_parts(column_family_options, num_column_families)
                .iter()
                .map(|ptr| Options {
                    inner: *ptr,
                    outlive: OptionsMustOutliveDB::default(),
                })
        };
        let column_descriptors = column_family_names_iter
            .zip(column_family_options_iter)
            .map(|(name, options)| ColumnFamilyDescriptor {
                name,
                options,
                ttl: ColumnFamilyTtl::Disabled,
            })
            .collect::<Vec<_>>();

        // free the arrays
        unsafe {
            // we freed each string in the column_family_names array using from_cstr_and_free
            ffi::rocksdb_free(column_family_names as *mut c_void);
            // we don't want to free the contents of this array because we return it
            ffi::rocksdb_free(column_family_options as *mut c_void);
            column_descriptors
        }
    }

    /// By default, RocksDB uses only one background thread for flush and
    /// compaction. Calling this function will set it up such that total of
    /// `total_threads` is used. Good value for `total_threads` is the number of
    /// cores. You almost definitely want to call this function if your system is
    /// bottlenecked by RocksDB.
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// opts.increase_parallelism(3);
    /// ```
    pub fn increase_parallelism(&mut self, parallelism: i32) {
        unsafe {
            ffi::rocksdb_options_increase_parallelism(self.inner, parallelism);
        }
    }

    /// Optimize level style compaction.
    ///
    /// Default values for some parameters in `Options` are not optimized for heavy
    /// workloads and big datasets, which means you might observe write stalls under
    /// some conditions.
    ///
    /// This can be used as one of the starting points for tuning RocksDB options in
    /// such cases.
    ///
    /// Internally, it sets `write_buffer_size`, `min_write_buffer_number_to_merge`,
    /// `max_write_buffer_number`, `level0_file_num_compaction_trigger`,
    /// `target_file_size_base`, `max_bytes_for_level_base`, so it can override if those
    /// parameters were set before.
    ///
    /// It sets buffer sizes so that memory consumption would be constrained by
    /// `memtable_memory_budget`.
    pub fn optimize_level_style_compaction(&mut self, memtable_memory_budget: usize) {
        unsafe {
            ffi::rocksdb_options_optimize_level_style_compaction(
                self.inner,
                memtable_memory_budget as u64,
            );
        }
    }

    /// Optimize universal style compaction.
    ///
    /// Default values for some parameters in `Options` are not optimized for heavy
    /// workloads and big datasets, which means you might observe write stalls under
    /// some conditions.
    ///
    /// This can be used as one of the starting points for tuning RocksDB options in
    /// such cases.
    ///
    /// Internally, it sets `write_buffer_size`, `min_write_buffer_number_to_merge`,
    /// `max_write_buffer_number`, `level0_file_num_compaction_trigger`,
    /// `target_file_size_base`, `max_bytes_for_level_base`, so it can override if those
    /// parameters were set before.
    ///
    /// It sets buffer sizes so that memory consumption would be constrained by
    /// `memtable_memory_budget`.
    pub fn optimize_universal_style_compaction(&mut self, memtable_memory_budget: usize) {
        unsafe {
            ffi::rocksdb_options_optimize_universal_style_compaction(
                self.inner,
                memtable_memory_budget as u64,
            );
        }
    }

    /// If true, the database will be created if it is missing.
    ///
    /// Default: `false`
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// opts.create_if_missing(true);
    /// ```
    pub fn create_if_missing(&mut self, create_if_missing: bool) {
        unsafe {
            ffi::rocksdb_options_set_create_if_missing(
                self.inner,
                c_uchar::from(create_if_missing),
            );
        }
    }

    /// If true, any column families that didn't exist when opening the database
    /// will be created.
    ///
    /// Default: `false`
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// opts.create_missing_column_families(true);
    /// ```
    pub fn create_missing_column_families(&mut self, create_missing_cfs: bool) {
        unsafe {
            ffi::rocksdb_options_set_create_missing_column_families(
                self.inner,
                c_uchar::from(create_missing_cfs),
            );
        }
    }

    /// Specifies whether an error should be raised if the database already exists.
    ///
    /// Default: false
    pub fn set_error_if_exists(&mut self, enabled: bool) {
        unsafe {
            ffi::rocksdb_options_set_error_if_exists(self.inner, c_uchar::from(enabled));
        }
    }

    /// Enable/disable paranoid checks.
    ///
    /// If true, the implementation will do aggressive checking of the
    /// data it is processing and will stop early if it detects any
    /// errors. This may have unforeseen ramifications: for example, a
    /// corruption of one DB entry may cause a large number of entries to
    /// become unreadable or for the entire DB to become unopenable.
    /// If any of the  writes to the database fails (Put, Delete, Merge, Write),
    /// the database will switch to read-only mode and fail all other
    /// Write operations.
    ///
    /// Default: true
    pub fn set_paranoid_checks(&mut self, enabled: bool) {
        unsafe {
            ffi::rocksdb_options_set_paranoid_checks(self.inner, c_uchar::from(enabled));
        }
    }

    /// A list of paths where SST files can be put into, with its target size.
    /// Newer data is placed into paths specified earlier in the vector while
    /// older data gradually moves to paths specified later in the vector.
    ///
    /// For example, you have a flash device with 10GB allocated for the DB,
    /// as well as a hard drive of 2TB, you should config it to be:
    ///   [{"/flash_path", 10GB}, {"/hard_drive", 2TB}]
    ///
    /// The system will try to guarantee data under each path is close to but
    /// not larger than the target size. But current and future file sizes used
    /// by determining where to place a file are based on best-effort estimation,
    /// which means there is a chance that the actual size under the directory
    /// is slightly more than target size under some workloads. User should give
    /// some buffer room for those cases.
    ///
    /// If none of the paths has sufficient room to place a file, the file will
    /// be placed to the last path anyway, despite to the target size.
    ///
    /// Placing newer data to earlier paths is also best-efforts. User should
    /// expect user files to be placed in higher levels in some extreme cases.
    ///
    /// If left empty, only one path will be used, which is `path` passed when
    /// opening the DB.
    ///
    /// Default: empty
    pub fn set_db_paths(&mut self, paths: &[DBPath]) {
        let mut paths: Vec<_> = paths.iter().map(|path| path.inner.cast_const()).collect();
        let num_paths = paths.len();
        unsafe {
            ffi::rocksdb_options_set_db_paths(self.inner, paths.as_mut_ptr(), num_paths);
        }
    }

    /// The same list of sized paths as [`Self::set_db_paths`], but for one column family
    /// rather than the whole DB.
    ///
    /// When set, this wins over `db_paths` for the SST files of that column family, and
    /// `db_paths` keeps covering everything else. Set it on the [`Options`] you pass in the
    /// [`ColumnFamilyDescriptor`], not on the DB-wide options.
    ///
    /// More than one entry is only supported under level and universal compaction, and it
    /// forces `level_compaction_dynamic_level_bytes` off because RocksDB cannot combine the
    /// two. A path shared by several column families holds the files and counts the size of
    /// all of them against its target, so size it for the total.
    ///
    /// Default: empty, meaning the column family follows `db_paths`.
    pub fn set_cf_paths(&mut self, paths: &[DBPath]) {
        let mut paths: Vec<_> = paths.iter().map(|path| path.inner.cast_const()).collect();
        let num_paths = paths.len();
        unsafe {
            ffi::rocksdb_options_set_cf_paths(self.inner, paths.as_mut_ptr(), num_paths);
        }
    }

    /// Use the specified object to interact with the environment,
    /// e.g. to read/write files, schedule background work, etc. In the near
    /// future, support for doing storage operations such as read/write files
    /// through env will be deprecated in favor of file_system.
    ///
    /// Default: Env::default()
    pub fn set_env(&mut self, env: &Env) {
        unsafe {
            ffi::rocksdb_options_set_env(self.inner, env.0.inner);
        }
        self.outlive.env = Some(env.clone());
    }

    /// Sets the compression algorithm that will be used for compressing blocks.
    ///
    /// Default: `DBCompressionType::Lz4`, falling back to
    /// `DBCompressionType::Snappy` and then `DBCompressionType::None` when the
    /// preceding one is not compiled in. RocksDB 11.5.0 changed this from
    /// Snappy; it affects only column families that never set `compression`,
    /// and only newly written SST files. Existing data stays readable, since
    /// the decompressor is selected per block.
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::{Options, DBCompressionType};
    ///
    /// let mut opts = Options::default();
    /// opts.set_compression_type(DBCompressionType::Snappy);
    /// ```
    pub fn set_compression_type(&mut self, t: DBCompressionType) {
        unsafe {
            ffi::rocksdb_options_set_compression(self.inner, t as c_int);
        }
    }

    /// The compression algorithm used for new blocks.
    ///
    /// `None` covers a compression type this crate does not name: xpress, which is Windows
    /// only, and the custom compression range a `CompressionManager` can hand out.
    pub fn get_compression_type(&self) -> Option<DBCompressionType> {
        let raw = unsafe { ffi::rocksdb_options_get_compression(self.inner) };
        DBCompressionType::try_from_raw(raw)
    }

    /// Number of threads for parallel compression.
    /// Parallel compression is enabled only if threads > 1.
    /// THE FEATURE IS STILL EXPERIMENTAL
    ///
    /// See [code](https://github.com/facebook/rocksdb/blob/v8.6.7/include/rocksdb/advanced_options.h#L116-L127)
    /// for more information.
    ///
    /// Default: 1
    ///
    /// Examples
    ///
    /// ```
    /// use rust_rocksdb::{Options, DBCompressionType};
    ///
    /// let mut opts = Options::default();
    /// opts.set_compression_type(DBCompressionType::Zstd);
    /// opts.set_compression_options_parallel_threads(3);
    /// ```
    pub fn set_compression_options_parallel_threads(&mut self, num: i32) {
        unsafe {
            ffi::rocksdb_options_set_compression_options_parallel_threads(self.inner, num);
        }
    }

    /// Sets the compression algorithm that will be used for compressing WAL.
    ///
    /// At present, only ZSTD compression is supported!
    ///
    /// Default: `DBCompressionType::None`
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::{Options, DBCompressionType};
    ///
    /// let mut opts = Options::default();
    /// opts.set_wal_compression_type(DBCompressionType::Zstd);
    /// // Or None to disable it
    /// opts.set_wal_compression_type(DBCompressionType::None);
    /// ```
    pub fn set_wal_compression_type(&mut self, t: DBCompressionType) {
        match t {
            DBCompressionType::None | DBCompressionType::Zstd => unsafe {
                ffi::rocksdb_options_set_wal_compression(self.inner, t as c_int);
            },
            other => unimplemented!("{:?} is not supported for WAL compression", other),
        }
    }

    /// The compression algorithm used for the WAL, `DBCompressionType::None` when disabled.
    ///
    /// `None` covers a compression type this crate does not name. Only ZSTD can reach here
    /// through [`Self::set_wal_compression_type`], but an options string can set anything.
    pub fn get_wal_compression_type(&self) -> Option<DBCompressionType> {
        let raw = unsafe { ffi::rocksdb_options_get_wal_compression(self.inner) };
        DBCompressionType::try_from_raw(raw)
    }

    /// Sets the bottom-most compression algorithm that will be used for
    /// compressing blocks at the bottom-most level.
    ///
    /// Note that to actually enable bottom-most compression configuration after
    /// setting the compression type, it needs to be enabled by calling
    /// [`set_bottommost_compression_options`](#method.set_bottommost_compression_options) or
    /// [`set_bottommost_zstd_max_train_bytes`](#method.set_bottommost_zstd_max_train_bytes) method with `enabled` argument
    /// set to `true`.
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::{Options, DBCompressionType};
    ///
    /// let mut opts = Options::default();
    /// opts.set_bottommost_compression_type(DBCompressionType::Zstd);
    /// opts.set_bottommost_zstd_max_train_bytes(0, true);
    /// ```
    pub fn set_bottommost_compression_type(&mut self, t: DBCompressionType) {
        unsafe {
            ffi::rocksdb_options_set_bottommost_compression(self.inner, t as c_int);
        }
    }

    /// The compression algorithm set for the bottom-most level.
    ///
    /// The default is the `kDisableCompressionOption` sentinel, which this crate does not
    /// name, so an untouched `Options` reads back as `None`. That sentinel means the
    /// bottom-most level follows [`Self::set_compression_type`] like every other level.
    pub fn get_bottommost_compression_type(&self) -> Option<DBCompressionType> {
        let raw = unsafe { ffi::rocksdb_options_get_bottommost_compression(self.inner) };
        DBCompressionType::try_from_raw(raw)
    }

    /// Different levels can have different compression policies. There
    /// are cases where most lower levels would like to use quick compression
    /// algorithms while the higher levels (which have more data) use
    /// compression algorithms that have better compression but could
    /// be slower. This array, if non-empty, should have an entry for
    /// each level of the database; these override the value specified in
    /// the previous field 'compression'.
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::{Options, DBCompressionType};
    ///
    /// let mut opts = Options::default();
    /// opts.set_compression_per_level(&[
    ///     DBCompressionType::None,
    ///     DBCompressionType::None,
    ///     DBCompressionType::Snappy,
    ///     DBCompressionType::Snappy,
    ///     DBCompressionType::Snappy
    /// ]);
    /// ```
    pub fn set_compression_per_level(&mut self, level_types: &[DBCompressionType]) {
        unsafe {
            let mut level_types: Vec<_> = level_types.iter().map(|&t| t as c_int).collect();
            ffi::rocksdb_options_set_compression_per_level(
                self.inner,
                level_types.as_mut_ptr(),
                level_types.len() as size_t,
            );
        }
    }

    /// Maximum size of dictionaries used to prime the compression library.
    /// Enabling dictionary can improve compression ratios when there are
    /// repetitions across data blocks.
    ///
    /// The dictionary is created by sampling the SST file data. If
    /// `zstd_max_train_bytes` is nonzero, the samples are passed through zstd's
    /// dictionary generator. Otherwise, the random samples are used directly as
    /// the dictionary.
    ///
    /// When compression dictionary is disabled, we compress and write each block
    /// before buffering data for the next one. When compression dictionary is
    /// enabled, we buffer all SST file data in-memory so we can sample it, as data
    /// can only be compressed and written after the dictionary has been finalized.
    /// So users of this feature may see increased memory usage.
    ///
    /// Default: `0`
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// opts.set_compression_options(4, 5, 6, 7);
    /// ```
    pub fn set_compression_options(
        &mut self,
        w_bits: c_int,
        level: c_int,
        strategy: c_int,
        max_dict_bytes: c_int,
    ) {
        unsafe {
            ffi::rocksdb_options_set_compression_options(
                self.inner,
                w_bits,
                level,
                strategy,
                max_dict_bytes,
            );
        }
    }

    /// Sets compression options for blocks at the bottom-most level.  Meaning
    /// of all settings is the same as in [`set_compression_options`](#method.set_compression_options) method but
    /// affect only the bottom-most compression which is set using
    /// [`set_bottommost_compression_type`](#method.set_bottommost_compression_type) method.
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::{Options, DBCompressionType};
    ///
    /// let mut opts = Options::default();
    /// opts.set_bottommost_compression_type(DBCompressionType::Zstd);
    /// opts.set_bottommost_compression_options(4, 5, 6, 7, true);
    /// ```
    pub fn set_bottommost_compression_options(
        &mut self,
        w_bits: c_int,
        level: c_int,
        strategy: c_int,
        max_dict_bytes: c_int,
        enabled: bool,
    ) {
        unsafe {
            ffi::rocksdb_options_set_bottommost_compression_options(
                self.inner,
                w_bits,
                level,
                strategy,
                max_dict_bytes,
                c_uchar::from(enabled),
            );
        }
    }

    /// Sets maximum size of training data passed to zstd's dictionary trainer. Using zstd's
    /// dictionary trainer can achieve even better compression ratio improvements than using
    /// `max_dict_bytes` alone.
    ///
    /// The training data will be used to generate a dictionary of max_dict_bytes.
    ///
    /// Default: 0.
    pub fn set_zstd_max_train_bytes(&mut self, value: c_int) {
        unsafe {
            ffi::rocksdb_options_set_compression_options_zstd_max_train_bytes(self.inner, value);
        }
    }

    /// Sets maximum size of training data passed to zstd's dictionary trainer
    /// when compressing the bottom-most level. Using zstd's dictionary trainer
    /// can achieve even better compression ratio improvements than using
    /// `max_dict_bytes` alone.
    ///
    /// The training data will be used to generate a dictionary of
    /// `max_dict_bytes`.
    ///
    /// Default: 0.
    pub fn set_bottommost_zstd_max_train_bytes(&mut self, value: c_int, enabled: bool) {
        unsafe {
            ffi::rocksdb_options_set_bottommost_compression_options_zstd_max_train_bytes(
                self.inner,
                value,
                c_uchar::from(enabled),
            );
        }
    }

    /// If non-zero, we perform bigger reads when doing compaction. If you're
    /// running RocksDB on spinning disks, you should set this to at least 2MB.
    /// That way RocksDB's compaction is doing sequential instead of random reads.
    ///
    /// Default: 2 * 1024 * 1024 (2 MB)
    pub fn set_compaction_readahead_size(&mut self, compaction_readahead_size: usize) {
        unsafe {
            ffi::rocksdb_options_compaction_readahead_size(self.inner, compaction_readahead_size);
        }
    }

    /// Allow RocksDB to pick dynamic base of bytes for levels.
    /// With this feature turned on, RocksDB will automatically adjust max bytes for each level.
    /// The goal of this feature is to have lower bound on size amplification.
    ///
    /// Default: true.
    pub fn set_level_compaction_dynamic_level_bytes(&mut self, v: bool) {
        unsafe {
            ffi::rocksdb_options_set_level_compaction_dynamic_level_bytes(
                self.inner,
                c_uchar::from(v),
            );
        }
    }

    /// This option has different meanings for different compaction styles:
    ///
    /// Leveled: files older than `periodic_compaction_seconds` will be picked up
    /// for compaction and will be re-written to the same level as they were
    /// before if level_compaction_dynamic_level_bytes is disabled. Otherwise,
    /// it will rewrite files to the next level except for the last level files
    /// to the same level.
    ///
    /// FIFO: not supported. Setting this option has no effect for FIFO compaction.
    ///
    /// Universal: when there are files older than `periodic_compaction_seconds`,
    /// rocksdb will try to do as large a compaction as possible including the
    /// last level. Such compaction is only skipped if only last level is to
    /// be compacted and no file in last level is older than
    /// `periodic_compaction_seconds`. See more in
    /// UniversalCompactionBuilder::PickPeriodicCompaction().
    /// For backward compatibility, the effective value of this option takes
    /// into account the value of option `ttl`. The logic is as follows:
    ///
    /// - both options are set to 30 days if they have the default value.
    /// - if both options are zero, zero is picked. Otherwise, we take the min
    ///   value among non-zero options values (i.e. takes the stricter limit).
    ///
    /// One main use of the feature is to make sure a file goes through compaction
    /// filters periodically. Users can also use the feature to clear up SST
    /// files using old format.
    ///
    /// A file's age is computed by looking at file_creation_time or creation_time
    /// table properties in order, if they have valid non-zero values; if not, the
    /// age is based on the file's last modified time (given by the underlying
    /// Env).
    ///
    /// This option only supports block based table format for any compaction
    /// style.
    ///
    /// unit: seconds. Ex: 7 days = 7 * 24 * 60 * 60
    ///
    /// Values:
    /// 0: Turn off Periodic compactions.
    /// UINT64_MAX - 1 (0xfffffffffffffffe) is special flag to allow RocksDB to
    /// pick default.
    ///
    /// Default: 30 days if using block based table format + compaction filter +
    /// leveled compaction or block based table format + universal compaction.
    /// 0 (disabled) otherwise.
    ///
    pub fn set_periodic_compaction_seconds(&mut self, secs: u64) {
        unsafe {
            ffi::rocksdb_options_set_periodic_compaction_seconds(self.inner, secs);
        }
    }

    /// When an iterator scans this number of invisible entries (tombstones or
    /// hidden puts) from the active memtable during a single iterator operation,
    /// we will attempt to flush the memtable. Currently only forward scans are
    /// supported (SeekToFirst(), Seek() and Next()).
    /// This option helps to reduce the overhead of scanning through a
    /// large number of entries in memtable.
    /// Users should consider enable deletion-triggered-compaction (see
    /// CompactOnDeletionCollectorFactory) together with this option to compact
    /// away tombstones after the memtable is flushed.
    ///
    /// Default: 0 (disabled)
    /// Dynamically changeable through the SetOptions() API.
    pub fn set_memtable_op_scan_flush_trigger(&mut self, num: u32) {
        unsafe {
            ffi::rocksdb_options_set_memtable_op_scan_flush_trigger(self.inner, num);
        }
    }

    /// Similar to `memtable_op_scan_flush_trigger`, but this option applies to
    /// Next() calls between Seeks or until iterator destruction. If the average
    /// of the number of invisible entries scanned from the active memtable, the
    /// memtable will be marked for flush.
    /// Note that to avoid the case where the window between Seeks is too small,
    /// the option only takes effect if the total number of hidden entries scanned
    /// within a window is at least `memtable_op_scan_flush_trigger`. So this
    /// option is only effective when `memtable_op_scan_flush_trigger` is set.
    ///
    /// This option should be set to a lower value than
    /// `memtable_op_scan_flush_trigger`. It covers the case where an iterator
    /// scans through an expensive key range with many invisible entries from the
    /// active memtable, but the number of invisible entries per operation does not
    /// exceed `memtable_op_scan_flush_trigger`.
    ///
    /// Default: 0 (disabled)
    /// Dynamically changeable through the SetOptions() API.
    pub fn set_memtable_avg_op_scan_flush_trigger(&mut self, num: u32) {
        unsafe {
            ffi::rocksdb_options_set_memtable_avg_op_scan_flush_trigger(self.inner, num);
        }
    }

    /// This option has different meanings for different compaction styles:
    ///
    /// Leveled: Non-bottom-level files with all keys older than TTL will go
    ///    through the compaction process. This usually happens in a cascading
    ///    way so that those entries will be compacted to bottommost level/file.
    ///    The feature is used to remove stale entries that have been deleted or
    ///    updated from the file system.
    ///
    /// FIFO: Files with all keys older than TTL will be deleted. TTL is only
    ///    supported if option max_open_files is set to -1.
    ///
    /// Universal: users should only set the option `periodic_compaction_seconds`
    ///    instead. For backward compatibility, this option has the same
    ///    meaning as `periodic_compaction_seconds`. See more in comments for
    ///    `periodic_compaction_seconds` on the interaction between these two
    ///    options.
    ///
    /// This option only supports block based table format for any compaction
    /// style.
    ///
    /// unit: seconds. Ex: 1 day = 1 * 24 * 60 * 60
    /// 0 means disabling.
    /// UINT64_MAX - 1 (0xfffffffffffffffe) is special flag to allow RocksDB to
    /// pick default.
    ///
    /// Default: 30 days if using block based table. 0 (disable) otherwise.
    ///
    /// Dynamically changeable
    /// Note that dynamically changing this option only works for leveled and FIFO
    /// compaction. For universal compaction, dynamically changing this option has
    /// no effect, users should dynamically change `periodic_compaction_seconds`
    /// instead.
    pub fn set_ttl(&mut self, secs: u64) {
        unsafe {
            ffi::rocksdb_options_set_ttl(self.inner, secs);
        }
    }

    pub fn set_merge_operator_associative<F: MergeFn + Clone>(
        &mut self,
        name: impl CStrLike,
        full_merge_fn: F,
    ) {
        let cb = Box::new(MergeOperatorCallback {
            name: name.into_c_string().unwrap(),
            full_merge_fn: full_merge_fn.clone(),
            partial_merge_fn: full_merge_fn,
        });

        unsafe {
            let mo = ffi::rocksdb_mergeoperator_create(
                Box::into_raw(cb).cast::<c_void>(),
                Some(merge_operator::destructor_callback::<F, F>),
                Some(full_merge_callback::<F, F>),
                Some(partial_merge_callback::<F, F>),
                Some(merge_operator::delete_callback),
                Some(merge_operator::name_callback::<F, F>),
            );
            ffi::rocksdb_options_set_merge_operator(self.inner, mo);
        }
    }

    pub fn set_merge_operator<F: MergeFn, PF: MergeFn>(
        &mut self,
        name: impl CStrLike,
        full_merge_fn: F,
        partial_merge_fn: PF,
    ) {
        let cb = Box::new(MergeOperatorCallback {
            name: name.into_c_string().unwrap(),
            full_merge_fn,
            partial_merge_fn,
        });

        unsafe {
            let mo = ffi::rocksdb_mergeoperator_create(
                Box::into_raw(cb).cast::<c_void>(),
                Some(merge_operator::destructor_callback::<F, PF>),
                Some(full_merge_callback::<F, PF>),
                Some(partial_merge_callback::<F, PF>),
                Some(merge_operator::delete_callback),
                Some(merge_operator::name_callback::<F, PF>),
            );
            ffi::rocksdb_options_set_merge_operator(self.inner, mo);
        }
    }

    #[deprecated(
        since = "0.5.0",
        note = "add_merge_operator has been renamed to set_merge_operator"
    )]
    pub fn add_merge_operator<F: MergeFn + Clone>(&mut self, name: &str, merge_fn: F) {
        self.set_merge_operator_associative(name, merge_fn);
    }

    /// Sets a compaction filter used to determine if entries should be kept, changed,
    /// or removed during compaction.
    ///
    /// An example use case is to remove entries with an expired TTL.
    ///
    /// If you take a snapshot of the database, only values written since the last
    /// snapshot will be passed through the compaction filter.
    ///
    /// If multi-threaded compaction is used, `filter_fn` may be called multiple times
    /// simultaneously.
    pub fn set_compaction_filter<F>(&mut self, name: impl CStrLike, filter_fn: F)
    where
        F: CompactionFilterFn + Send + 'static,
    {
        let cb = Box::new(CompactionFilterCallback {
            name: name.into_c_string().unwrap(),
            filter_fn,
        });

        let filter = unsafe {
            let cf = ffi::rocksdb_compactionfilter_create(
                Box::into_raw(cb).cast::<c_void>(),
                Some(compaction_filter::destructor_callback::<CompactionFilterCallback<F>>),
                Some(compaction_filter::filter_callback::<CompactionFilterCallback<F>>),
                Some(compaction_filter::name_callback::<CompactionFilterCallback<F>>),
            );
            ffi::rocksdb_options_set_compaction_filter(self.inner, cf);

            OwnedCompactionFilter::new(NonNull::new(cf).unwrap())
        };
        self.outlive.compaction_filter = Some(Arc::new(filter));
    }

    pub fn add_event_listener<L: EventListener>(&mut self, l: L) {
        let handle = new_event_listener(l);
        unsafe { ffi::rust_rocksdb_options_add_eventlistener(self.inner, handle.inner) }
    }

    /// This is a factory that provides compaction filter objects which allow
    /// an application to modify/delete a key-value during background compaction.
    ///
    /// A new filter will be created on each compaction run.  If multithreaded
    /// compaction is being used, each created CompactionFilter will only be used
    /// from a single thread and so does not need to be thread-safe.
    ///
    /// Default: nullptr
    pub fn set_compaction_filter_factory<F>(&mut self, factory: F)
    where
        F: CompactionFilterFactory + 'static,
    {
        let factory = Box::new(factory);

        unsafe {
            let cff = ffi::rocksdb_compactionfilterfactory_create(
                Box::into_raw(factory).cast::<c_void>(),
                Some(compaction_filter_factory::destructor_callback::<F>),
                Some(compaction_filter_factory::create_compaction_filter_callback::<F>),
                Some(compaction_filter_factory::name_callback::<F>),
            );

            ffi::rocksdb_options_set_compaction_filter_factory(self.inner, cff);
        }
    }

    /// Makes compaction cut its output files on the boundaries this factory
    /// reports, so a key prefix stays inside a single SST.
    ///
    /// See the [`sst_partitioner`](crate::sst_partitioner) module for what that
    /// buys and what it does not. Only files written by later compactions are
    /// partitioned, so setting this on an existing DB takes effect gradually.
    ///
    /// Marked experimental upstream. Default: no partitioner.
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::{Options, SstPartitionerFactory};
    ///
    /// let mut opts = Options::default();
    /// opts.set_sst_partitioner_factory(&SstPartitionerFactory::fixed_prefix(8));
    /// ```
    pub fn set_sst_partitioner_factory(&mut self, factory: &SstPartitionerFactory) {
        // `rocksdb_options_set_sst_partitioner_factory` assigns `factory->rep`
        // into `Options::sst_partitioner_factory` (c.cc:6142), copying the
        // `shared_ptr`. The options object holds its own reference from here
        // on, so the caller's handle is free to drop at any time.
        unsafe {
            ffi::rocksdb_options_set_sst_partitioner_factory(self.inner, factory.as_ptr());
        }
    }

    /// Makes RocksDB compute a checksum over each SST file it writes and record
    /// it in the manifest.
    ///
    /// Nothing verifies file checksums until this is set, and files already on
    /// disk stay without one until a compaction rewrites them. See the
    /// [`file_checksum`](crate::file_checksum) module for how this differs from
    /// the per-block checksum on [`BlockBasedOptions::set_checksum_type`].
    ///
    /// Default: none, so no file checksums are produced or checked.
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::{FileChecksumGenFactory, Options};
    ///
    /// let mut opts = Options::default();
    /// opts.set_file_checksum_gen_factory(&FileChecksumGenFactory::crc32c());
    /// ```
    pub fn set_file_checksum_gen_factory(&mut self, factory: &FileChecksumGenFactory) {
        // `rocksdb_options_set_file_checksum_gen_factory` assigns
        // `factory->rep` into `Options::file_checksum_gen_factory` (c.cc:6067),
        // copying the `shared_ptr`. The options object holds its own reference
        // from here on, so the caller's handle is free to drop at any time.
        unsafe {
            ffi::rocksdb_options_set_file_checksum_gen_factory(self.inner, factory.as_ptr());
        }
    }

    /// Sends this DB's compactions to `service` instead of running them
    /// locally.
    ///
    /// RocksDB serializes each compaction, hands it to
    /// [`schedule`](CompactionService::schedule), and blocks in
    /// [`wait`](CompactionService::wait) until the worker returns a result. See
    /// the [`compaction_service`](crate::compaction_service) module for the
    /// worker half and for the panic and threading rules the service methods
    /// run under.
    ///
    /// Upstream marks this experimental and reserves the right to change it
    /// without compatibility guarantees.
    ///
    /// Replaces any service set earlier. Default: none.
    pub fn set_compaction_service<S>(&mut self, service: S)
    where
        S: CompactionService + 'static,
    {
        // `rocksdb_options_set_compaction_service` adopts the pointer into a
        // fresh `std::shared_ptr<CompactionService>` (c.cc:1361), so RocksDB
        // owns the service and the boxed implementation behind it from here on.
        // Nothing goes in `OptionsMustOutliveDB`: cloning the options copies
        // the `shared_ptr`, and the last copy to drop frees the service.
        unsafe {
            ffi::rocksdb_options_set_compaction_service(
                self.inner,
                new_compaction_service(service).into_ptr(),
            );
        }
    }

    /// Installs a filter that sees every WAL record replayed during recovery
    /// and decides what to do with it.
    ///
    /// The filter runs inside [`DB::open`](crate::DB::open) and is never
    /// consulted again once the DB is up. See the
    /// [`wal_filter`](crate::wal_filter) module for the decisions it can make
    /// and for the panic and threading rules its methods run under.
    ///
    /// This is a DB-wide option. Setting it on a column family's `Options` has
    /// no effect.
    ///
    /// Replaces any filter set earlier. Default: none.
    pub fn set_wal_filter<F>(&mut self, filter: F)
    where
        F: WalFilter + 'static,
    {
        // `rocksdb_options_set_wal_filter` stores the bare pointer in
        // `DBOptions::wal_filter` (c.cc:5843). RocksDB never copies or frees
        // it, so the filter has to outlive the options and every DB opened
        // from them, which is what `OptionsMustOutliveDB` is for.
        let handle = new_wal_filter(filter);
        unsafe {
            ffi::rocksdb_options_set_wal_filter(self.inner, handle.as_ptr());
        }
        self.outlive.wal_filter = Some(Arc::new(handle));
    }

    /// Removes the filter set by [`Self::set_wal_filter`], so recovery replays
    /// every WAL record as written.
    ///
    /// This only clears these `Options`. A DB already opened from them keeps
    /// the filter it was opened with, and so does any `Options` cloned before
    /// this call.
    pub fn clear_wal_filter(&mut self) {
        unsafe {
            ffi::rocksdb_options_clear_wal_filter(self.inner);
        }
        self.outlive.wal_filter = None;
    }

    /// Sets the comparator used to define the order of keys in the table.
    /// Default: a comparator that uses lexicographic byte-wise ordering
    ///
    /// The client must ensure that the comparator supplied here has the same
    /// name and orders keys *exactly* the same as the comparator provided to
    /// previous open calls on the same DB.
    pub fn set_comparator(&mut self, name: impl CStrLike, compare_fn: Box<CompareFn>) {
        let cb = Box::new(ComparatorCallback {
            name: name.into_c_string().unwrap(),
            compare_fn,
        });

        let cmp = unsafe {
            let cmp = ffi::rocksdb_comparator_create(
                Box::into_raw(cb).cast::<c_void>(),
                Some(ComparatorCallback::destructor_callback),
                Some(ComparatorCallback::compare_callback),
                Some(ComparatorCallback::name_callback),
            );
            ffi::rocksdb_options_set_comparator(self.inner, cmp);
            Comparator::from_raw(NonNull::new(cmp).unwrap())
        };
        self.outlive.comparator = Some(Arc::new(cmp));
    }

    /// Sets the comparator that are timestamp-aware, used to define the order of keys in the table,
    /// taking timestamp into consideration.
    /// Find more information on timestamp-aware comparator on [here](https://github.com/facebook/rocksdb/wiki/User-defined-Timestamp)
    ///
    /// The client must ensure that the comparator supplied here has the same
    /// name and orders keys *exactly* the same as the comparator provided to
    /// previous open calls on the same DB.
    pub fn set_comparator_with_ts(
        &mut self,
        name: impl CStrLike,
        timestamp_size: usize,
        compare_fn: Box<CompareFn>,
        compare_ts_fn: Box<CompareTsFn>,
        compare_without_ts_fn: Box<CompareWithoutTsFn>,
    ) {
        let cb = Box::new(ComparatorWithTsCallback {
            name: name.into_c_string().unwrap(),
            compare_fn,
            compare_ts_fn,
            compare_without_ts_fn,
        });

        let cmp = unsafe {
            let cmp = ffi::rocksdb_comparator_with_ts_create(
                Box::into_raw(cb).cast::<c_void>(),
                Some(ComparatorWithTsCallback::destructor_callback),
                Some(ComparatorWithTsCallback::compare_callback),
                Some(ComparatorWithTsCallback::compare_ts_callback),
                Some(ComparatorWithTsCallback::compare_without_ts_callback),
                Some(ComparatorWithTsCallback::name_callback),
                timestamp_size,
            );
            ffi::rocksdb_options_set_comparator(self.inner, cmp);
            Comparator::from_raw(NonNull::new(cmp).unwrap())
        };
        self.outlive.comparator = Some(Arc::new(cmp));
    }

    pub fn set_prefix_extractor(&mut self, prefix_extractor: SliceTransform) {
        unsafe {
            ffi::rocksdb_options_set_prefix_extractor(self.inner, prefix_extractor.inner);
        }
    }

    // Use this if you don't need to keep the data sorted, i.e. you'll never use
    // an iterator, only Put() and Get() API calls
    //
    pub fn optimize_for_point_lookup(&mut self, block_cache_size_mb: u64) {
        unsafe {
            ffi::rocksdb_options_optimize_for_point_lookup(self.inner, block_cache_size_mb);
        }
    }

    /// Sets the optimize_filters_for_hits flag
    ///
    /// Default: `false`
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// opts.set_optimize_filters_for_hits(true);
    /// ```
    pub fn set_optimize_filters_for_hits(&mut self, optimize_for_hits: bool) {
        unsafe {
            ffi::rocksdb_options_set_optimize_filters_for_hits(
                self.inner,
                c_int::from(optimize_for_hits),
            );
        }
    }

    /// Sets the periodicity when obsolete files get deleted.
    ///
    /// The files that get out of scope by compaction
    /// process will still get automatically delete on every compaction,
    /// regardless of this setting.
    ///
    /// Default: 6 hours
    pub fn set_delete_obsolete_files_period_micros(&mut self, micros: u64) {
        unsafe {
            ffi::rocksdb_options_set_delete_obsolete_files_period_micros(self.inner, micros);
        }
    }

    /// Prepare the DB for bulk loading.
    ///
    /// All data will be in level 0 without any automatic compaction.
    /// It's recommended to manually call CompactRange(NULL, NULL) before reading
    /// from the database, because otherwise the read can be very slow.
    pub fn prepare_for_bulk_load(&mut self) {
        unsafe {
            ffi::rocksdb_options_prepare_for_bulk_load(self.inner);
        }
    }

    /// Sets the number of open files that can be used by the DB. You may need to
    /// increase this if your database has a large working set. Value `-1` means
    /// files opened are always kept open. You can estimate number of files based
    /// on target_file_size_base and target_file_size_multiplier for level-based
    /// compaction. For universal-style compaction, you can usually set it to `-1`.
    ///
    /// Default: `-1`
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// opts.set_max_open_files(10);
    /// ```
    pub fn set_max_open_files(&mut self, nfiles: c_int) {
        unsafe {
            ffi::rocksdb_options_set_max_open_files(self.inner, nfiles);
        }
    }

    /// If max_open_files is -1, DB will open all files on DB::Open(). You can
    /// use this option to increase the number of threads used to open the files.
    /// Default: 16
    pub fn set_max_file_opening_threads(&mut self, nthreads: c_int) {
        unsafe {
            ffi::rocksdb_options_set_max_file_opening_threads(self.inner, nthreads);
        }
    }

    /// By default, writes to stable storage use fdatasync (on platforms
    /// where this function is available). If this option is true,
    /// fsync is used instead.
    ///
    /// fsync and fdatasync are equally safe for our purposes and fdatasync is
    /// faster, so it is rarely necessary to set this option. It is provided
    /// as a workaround for kernel/filesystem bugs, such as one that affected
    /// fdatasync with ext4 in kernel versions prior to 3.7.
    ///
    /// Default: `false`
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// opts.set_use_fsync(true);
    /// ```
    pub fn set_use_fsync(&mut self, useit: bool) {
        unsafe {
            ffi::rocksdb_options_set_use_fsync(self.inner, c_int::from(useit));
        }
    }

    /// Returns the value of the `use_fsync` option.
    pub fn get_use_fsync(&self) -> bool {
        let val = unsafe { ffi::rocksdb_options_get_use_fsync(self.inner) };
        val != 0
    }

    /// Specifies the absolute info LOG dir.
    ///
    /// If it is empty, the log files will be in the same dir as data.
    /// If it is non empty, the log files will be in the specified dir,
    /// and the db data dir's absolute path will be used as the log file
    /// name's prefix.
    ///
    /// Default: empty
    pub fn set_db_log_dir<P: AsRef<Path>>(&mut self, path: P) {
        let p = to_cpath(path).unwrap();
        unsafe {
            ffi::rocksdb_options_set_db_log_dir(self.inner, p.as_ptr());
        }
    }

    /// The info LOG dir set by [`Self::set_db_log_dir`], empty when logs go next to the data.
    pub fn get_db_log_dir(&self) -> String {
        let mut len: size_t = 0;
        let path = unsafe { ffi::rocksdb_options_get_db_log_dir(self.inner, &raw mut len) };
        unsafe { borrowed_string(path, len) }
    }

    /// Specifies the log level.
    /// Consider the `LogLevel` enum for a list of possible levels.
    ///
    /// Default: Info
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::{Options, LogLevel};
    ///
    /// let mut opts = Options::default();
    /// opts.set_log_level(LogLevel::Warn);
    /// ```
    pub fn set_log_level(&mut self, level: LogLevel) {
        unsafe {
            ffi::rocksdb_options_set_info_log_level(self.inner, level as c_int);
        }
    }

    /// The verbosity set by [`Self::set_log_level`].
    ///
    /// `None` covers a level this crate does not name, which today only means RocksDB's
    /// `NUM_INFO_LOG_LEVELS` sentinel.
    pub fn get_log_level(&self) -> Option<LogLevel> {
        let raw = unsafe { ffi::rocksdb_options_get_info_log_level(self.inner) };
        LogLevel::try_from_raw(raw)
    }

    /// Allows OS to incrementally sync files to disk while they are being
    /// written, asynchronously, in the background. This operation can be used
    /// to smooth out write I/Os over time. Users shouldn't rely on it for
    /// persistency guarantee.
    /// Issue one request for every bytes_per_sync written. `0` turns it off.
    ///
    /// Default: `0`
    ///
    /// You may consider using rate_limiter to regulate write rate to device.
    /// When rate limiter is enabled, it automatically enables bytes_per_sync
    /// to 1MB.
    ///
    /// This option applies to table files
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// opts.set_bytes_per_sync(1024 * 1024);
    /// ```
    pub fn set_bytes_per_sync(&mut self, nbytes: u64) {
        unsafe {
            ffi::rocksdb_options_set_bytes_per_sync(self.inner, nbytes);
        }
    }

    /// Same as bytes_per_sync, but applies to WAL files.
    ///
    /// Default: 0, turned off
    ///
    /// Dynamically changeable through SetDBOptions() API.
    pub fn set_wal_bytes_per_sync(&mut self, nbytes: u64) {
        unsafe {
            ffi::rocksdb_options_set_wal_bytes_per_sync(self.inner, nbytes);
        }
    }

    /// Sets the maximum buffer size that is used by WritableFileWriter.
    ///
    /// On Windows, we need to maintain an aligned buffer for writes.
    /// We allow the buffer to grow until it's size hits the limit in buffered
    /// IO and fix the buffer size when using direct IO to ensure alignment of
    /// write requests if the logical sector size is unusual
    ///
    /// Default: 1024 * 1024 (1 MB)
    ///
    /// Dynamically changeable through SetDBOptions() API.
    pub fn set_writable_file_max_buffer_size(&mut self, nbytes: u64) {
        unsafe {
            ffi::rocksdb_options_set_writable_file_max_buffer_size(self.inner, nbytes);
        }
    }

    /// If true, allow multi-writers to update mem tables in parallel.
    /// Only some memtable_factory-s support concurrent writes; currently it
    /// is implemented only for SkipListFactory.  Concurrent memtable writes
    /// are not compatible with inplace_update_support or filter_deletes.
    /// It is strongly recommended to set enable_write_thread_adaptive_yield
    /// if you are going to use this feature.
    ///
    /// Default: true
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// opts.set_allow_concurrent_memtable_write(false);
    /// ```
    pub fn set_allow_concurrent_memtable_write(&mut self, allow: bool) {
        unsafe {
            ffi::rocksdb_options_set_allow_concurrent_memtable_write(
                self.inner,
                c_uchar::from(allow),
            );
        }
    }

    /// If true, threads synchronizing with the write batch group leader will wait for up to
    /// write_thread_max_yield_usec before blocking on a mutex. This can substantially improve
    /// throughput for concurrent workloads, regardless of whether allow_concurrent_memtable_write
    /// is enabled.
    ///
    /// Default: true
    pub fn set_enable_write_thread_adaptive_yield(&mut self, enabled: bool) {
        unsafe {
            ffi::rocksdb_options_set_enable_write_thread_adaptive_yield(
                self.inner,
                c_uchar::from(enabled),
            );
        }
    }

    /// Specifies whether an iteration->Next() sequentially skips over keys with the same user-key or not.
    ///
    /// This number specifies the number of keys (with the same userkey)
    /// that will be sequentially skipped before a reseek is issued.
    ///
    /// Default: 8
    pub fn set_max_sequential_skip_in_iterations(&mut self, num: u64) {
        unsafe {
            ffi::rocksdb_options_set_max_sequential_skip_in_iterations(self.inner, num);
        }
    }

    /// Enable direct I/O mode for reading
    /// they may or may not improve performance depending on the use case
    ///
    /// Files will be opened in "direct I/O" mode
    /// which means that data read from the disk will not be cached or
    /// buffered. The hardware buffer of the devices may however still
    /// be used. Memory mapped files are not impacted by these parameters.
    ///
    /// Default: false
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// opts.set_use_direct_reads(true);
    /// ```
    pub fn set_use_direct_reads(&mut self, enabled: bool) {
        unsafe {
            ffi::rocksdb_options_set_use_direct_reads(self.inner, c_uchar::from(enabled));
        }
    }

    /// Enable direct I/O mode for flush and compaction
    ///
    /// Files will be opened in "direct I/O" mode
    /// which means that data written to the disk will not be cached or
    /// buffered. The hardware buffer of the devices may however still
    /// be used. Memory mapped files are not impacted by these parameters.
    /// they may or may not improve performance depending on the use case
    ///
    /// Default: false
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// opts.set_use_direct_io_for_flush_and_compaction(true);
    /// ```
    pub fn set_use_direct_io_for_flush_and_compaction(&mut self, enabled: bool) {
        unsafe {
            ffi::rocksdb_options_set_use_direct_io_for_flush_and_compaction(
                self.inner,
                c_uchar::from(enabled),
            );
        }
    }

    /// Enable/disable child process inherit open files.
    ///
    /// Default: true
    pub fn set_is_fd_close_on_exec(&mut self, enabled: bool) {
        unsafe {
            ffi::rocksdb_options_set_is_fd_close_on_exec(self.inner, c_uchar::from(enabled));
        }
    }

    /// Hints to the OS that it should not buffer disk I/O. Enabling this
    /// parameter may improve performance but increases pressure on the
    /// system cache.
    ///
    /// The exact behavior of this parameter is platform dependent.
    ///
    /// On POSIX systems, after RocksDB reads data from disk it will
    /// mark the pages as "unneeded". The operating system may or may not
    /// evict these pages from memory, reducing pressure on the system
    /// cache. If the disk block is requested again this can result in
    /// additional disk I/O.
    ///
    /// On WINDOWS systems, files will be opened in "unbuffered I/O" mode
    /// which means that data read from the disk will not be cached or
    /// bufferized. The hardware buffer of the devices may however still
    /// be used. Memory mapped files are not impacted by this parameter.
    ///
    /// Default: true
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// #[allow(deprecated)]
    /// opts.set_allow_os_buffer(false);
    /// ```
    #[deprecated(
        since = "0.7.0",
        note = "replaced with set_use_direct_reads/set_use_direct_io_for_flush_and_compaction methods"
    )]
    pub fn set_allow_os_buffer(&mut self, is_allow: bool) {
        self.set_use_direct_reads(!is_allow);
        self.set_use_direct_io_for_flush_and_compaction(!is_allow);
    }

    /// Sets the number of shards used for table cache.
    ///
    /// Default: `6`
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// opts.set_table_cache_num_shard_bits(4);
    /// ```
    pub fn set_table_cache_num_shard_bits(&mut self, nbits: c_int) {
        unsafe {
            ffi::rocksdb_options_set_table_cache_numshardbits(self.inner, nbits);
        }
    }

    /// By default target_file_size_multiplier is 1, which means
    /// by default files in different levels will have similar size.
    ///
    /// Dynamically changeable through SetOptions() API
    pub fn set_target_file_size_multiplier(&mut self, multiplier: i32) {
        unsafe {
            ffi::rocksdb_options_set_target_file_size_multiplier(self.inner, multiplier as c_int);
        }
    }

    /// Sets the minimum number of write buffers that will be merged
    /// before writing to storage.  If set to `1`, then
    /// all write buffers are flushed to L0 as individual files and this increases
    /// read amplification because a get request has to check in all of these
    /// files. Also, an in-memory merge may result in writing lesser
    /// data to storage if there are duplicate records in each of these
    /// individual write buffers.
    ///
    /// Default: `1`
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// opts.set_min_write_buffer_number(2);
    /// ```
    pub fn set_min_write_buffer_number(&mut self, nbuf: c_int) {
        unsafe {
            ffi::rocksdb_options_set_min_write_buffer_number_to_merge(self.inner, nbuf);
        }
    }

    /// Sets the maximum number of write buffers that are built up in memory.
    /// The default and the minimum number is 2, so that when 1 write buffer
    /// is being flushed to storage, new writes can continue to the other
    /// write buffer.
    /// If max_write_buffer_number > 3, writing will be slowed down to
    /// options.delayed_write_rate if we are writing to the last write buffer
    /// allowed.
    ///
    /// Default: `2`
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// opts.set_max_write_buffer_number(4);
    /// ```
    pub fn set_max_write_buffer_number(&mut self, nbuf: c_int) {
        unsafe {
            ffi::rocksdb_options_set_max_write_buffer_number(self.inner, nbuf);
        }
    }

    /// Sets the amount of data to build up in memory (backed by an unsorted log
    /// on disk) before converting to a sorted on-disk file.
    ///
    /// Larger values increase performance, especially during bulk loads.
    /// Up to max_write_buffer_number write buffers may be held in memory
    /// at the same time,
    /// so you may wish to adjust this parameter to control memory usage.
    /// Also, a larger write buffer will result in a longer recovery time
    /// the next time the database is opened.
    ///
    /// Note that write_buffer_size is enforced per column family.
    /// See db_write_buffer_size for sharing memory across column families.
    ///
    /// Default: `0x4000000` (64MiB)
    ///
    /// Dynamically changeable through SetOptions() API
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// opts.set_write_buffer_size(128 * 1024 * 1024);
    /// ```
    pub fn set_write_buffer_size(&mut self, size: usize) {
        unsafe {
            ffi::rocksdb_options_set_write_buffer_size(self.inner, size);
        }
    }

    /// Amount of data to build up in memtables across all column
    /// families before writing to disk.
    ///
    /// This is distinct from write_buffer_size, which enforces a limit
    /// for a single memtable.
    ///
    /// This feature is disabled by default. Specify a non-zero value
    /// to enable it.
    ///
    /// Default: 0 (disabled)
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// opts.set_db_write_buffer_size(128 * 1024 * 1024);
    /// ```
    pub fn set_db_write_buffer_size(&mut self, size: usize) {
        unsafe {
            ffi::rocksdb_options_set_db_write_buffer_size(self.inner, size);
        }
    }

    /// Control maximum total data size for a level.
    /// max_bytes_for_level_base is the max total for level-1.
    /// Maximum number of bytes for level L can be calculated as
    /// (max_bytes_for_level_base) * (max_bytes_for_level_multiplier ^ (L-1))
    /// For example, if max_bytes_for_level_base is 200MB, and if
    /// max_bytes_for_level_multiplier is 10, total data size for level-1
    /// will be 200MB, total file size for level-2 will be 2GB,
    /// and total file size for level-3 will be 20GB.
    ///
    /// Default: `0x10000000` (256MiB).
    ///
    /// Dynamically changeable through SetOptions() API
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// opts.set_max_bytes_for_level_base(512 * 1024 * 1024);
    /// ```
    pub fn set_max_bytes_for_level_base(&mut self, size: u64) {
        unsafe {
            ffi::rocksdb_options_set_max_bytes_for_level_base(self.inner, size);
        }
    }

    /// Default: `10`
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// opts.set_max_bytes_for_level_multiplier(4.0);
    /// ```
    pub fn set_max_bytes_for_level_multiplier(&mut self, mul: f64) {
        unsafe {
            ffi::rocksdb_options_set_max_bytes_for_level_multiplier(self.inner, mul);
        }
    }

    /// Sets a lower bound on the auto-tuned MANIFEST size limit. The MANIFEST
    /// is rolled over on reaching the limit and the older one is deleted.
    ///
    /// This used to be a hard limit. RocksDB now auto-tunes the real limit and
    /// treats this as a minimum, so setting it small does not keep the MANIFEST
    /// small. Batches written in the foreground get a 25% higher limit.
    ///
    /// Default: 1 GiB.
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// opts.set_max_manifest_file_size(20 * 1024 * 1024);
    /// ```
    pub fn set_max_manifest_file_size(&mut self, size: usize) {
        unsafe {
            ffi::rocksdb_options_set_max_manifest_file_size(self.inner, size);
        }
    }

    /// Sets the target file size for compaction.
    /// target_file_size_base is per-file size for level-1.
    /// Target file size for level L can be calculated by
    /// target_file_size_base * (target_file_size_multiplier ^ (L-1))
    /// For example, if target_file_size_base is 2MB and
    /// target_file_size_multiplier is 10, then each file on level-1 will
    /// be 2MB, and each file on level 2 will be 20MB,
    /// and each file on level-3 will be 200MB.
    ///
    /// Default: `0x4000000` (64MiB)
    ///
    /// Dynamically changeable through SetOptions() API
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// opts.set_target_file_size_base(128 * 1024 * 1024);
    /// ```
    pub fn set_target_file_size_base(&mut self, size: u64) {
        unsafe {
            ffi::rocksdb_options_set_target_file_size_base(self.inner, size);
        }
    }

    /// Sets the minimum number of write buffers that will be merged together
    /// before writing to storage.  If set to `1`, then
    /// all write buffers are flushed to L0 as individual files and this increases
    /// read amplification because a get request has to check in all of these
    /// files. Also, an in-memory merge may result in writing lesser
    /// data to storage if there are duplicate records in each of these
    /// individual write buffers.
    ///
    /// Default: `1`
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// opts.set_min_write_buffer_number_to_merge(2);
    /// ```
    pub fn set_min_write_buffer_number_to_merge(&mut self, to_merge: c_int) {
        unsafe {
            ffi::rocksdb_options_set_min_write_buffer_number_to_merge(self.inner, to_merge);
        }
    }

    /// Sets the number of files to trigger level-0 compaction. A value < `0` means that
    /// level-0 compaction will not be triggered by number of files at all.
    ///
    /// Default: `4`
    ///
    /// Dynamically changeable through SetOptions() API
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// opts.set_level_zero_file_num_compaction_trigger(8);
    /// ```
    pub fn set_level_zero_file_num_compaction_trigger(&mut self, n: c_int) {
        unsafe {
            ffi::rocksdb_options_set_level0_file_num_compaction_trigger(self.inner, n);
        }
    }

    /// Sets the soft limit on number of level-0 files. We start slowing down writes at this
    /// point. A value < `0` means that no writing slowdown will be triggered by
    /// number of files in level-0.
    ///
    /// Default: `20`
    ///
    /// Dynamically changeable through SetOptions() API
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// opts.set_level_zero_slowdown_writes_trigger(10);
    /// ```
    pub fn set_level_zero_slowdown_writes_trigger(&mut self, n: c_int) {
        unsafe {
            ffi::rocksdb_options_set_level0_slowdown_writes_trigger(self.inner, n);
        }
    }

    /// Sets the maximum number of level-0 files.  We stop writes at this point.
    ///
    /// Default: `36`
    ///
    /// Dynamically changeable through SetOptions() API
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// opts.set_level_zero_stop_writes_trigger(48);
    /// ```
    pub fn set_level_zero_stop_writes_trigger(&mut self, n: c_int) {
        unsafe {
            ffi::rocksdb_options_set_level0_stop_writes_trigger(self.inner, n);
        }
    }

    /// Sets the compaction style.
    ///
    /// Default: DBCompactionStyle::Level
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::{Options, DBCompactionStyle};
    ///
    /// let mut opts = Options::default();
    /// opts.set_compaction_style(DBCompactionStyle::Universal);
    /// ```
    pub fn set_compaction_style(&mut self, style: DBCompactionStyle) {
        unsafe {
            ffi::rocksdb_options_set_compaction_style(self.inner, style as c_int);
        }
    }

    /// The compaction style set by [`Self::set_compaction_style`].
    ///
    /// `None` means `kCompactionStyleNone`, which this crate does not name. That style turns
    /// background compaction off entirely and only runs work submitted through
    /// `CompactFiles`.
    pub fn get_compaction_style(&self) -> Option<DBCompactionStyle> {
        let raw = unsafe { ffi::rocksdb_options_get_compaction_style(self.inner) };
        DBCompactionStyle::try_from_raw(raw)
    }

    /// Sets the options needed to support Universal Style compactions.
    pub fn set_universal_compaction_options(&mut self, uco: &UniversalCompactOptions) {
        unsafe {
            ffi::rocksdb_options_set_universal_compaction_options(self.inner, uco.inner);
        }
    }

    /// Sets the options for FIFO compaction style.
    pub fn set_fifo_compaction_options(&mut self, fco: &FifoCompactOptions) {
        unsafe {
            ffi::rocksdb_options_set_fifo_compaction_options(self.inner, fco.inner);
        }
    }

    /// Sets unordered_write to true trades higher write throughput with
    /// relaxing the immutability guarantee of snapshots. This violates the
    /// repeatability one expects from ::Get from a snapshot, as well as
    /// ::MultiGet and Iterator's consistent-point-in-time view property.
    /// If the application cannot tolerate the relaxed guarantees, it can implement
    /// its own mechanisms to work around that and yet benefit from the higher
    /// throughput. Using TransactionDB with WRITE_PREPARED write policy and
    /// two_write_queues=true is one way to achieve immutable snapshots despite
    /// unordered_write.
    ///
    /// By default, i.e., when it is false, rocksdb does not advance the sequence
    /// number for new snapshots unless all the writes with lower sequence numbers
    /// are already finished. This provides the immutability that we expect from
    /// snapshots. Moreover, since Iterator and MultiGet internally depend on
    /// snapshots, the snapshot immutability results into Iterator and MultiGet
    /// offering consistent-point-in-time view. If set to true, although
    /// Read-Your-Own-Write property is still provided, the snapshot immutability
    /// property is relaxed: the writes issued after the snapshot is obtained (with
    /// larger sequence numbers) will be still not visible to the reads from that
    /// snapshot, however, there still might be pending writes (with lower sequence
    /// number) that will change the state visible to the snapshot after they are
    /// landed to the memtable.
    ///
    /// Default: false
    pub fn set_unordered_write(&mut self, unordered: bool) {
        unsafe {
            ffi::rocksdb_options_set_unordered_write(self.inner, c_uchar::from(unordered));
        }
    }

    /// Sets maximum number of threads that will
    /// concurrently perform a compaction job by breaking it into multiple,
    /// smaller ones that are run simultaneously.
    ///
    /// Default: 1 (i.e. no subcompactions)
    pub fn set_max_subcompactions(&mut self, num: u32) {
        unsafe {
            ffi::rocksdb_options_set_max_subcompactions(self.inner, num);
        }
    }

    /// Sets maximum number of concurrent background jobs
    /// (compactions and flushes).
    ///
    /// Default: 2
    ///
    /// Dynamically changeable through SetDBOptions() API.
    pub fn set_max_background_jobs(&mut self, jobs: c_int) {
        unsafe {
            ffi::rocksdb_options_set_max_background_jobs(self.inner, jobs);
        }
    }

    /// Sets the maximum number of concurrent background compaction jobs, submitted to
    /// the default LOW priority thread pool.
    /// We first try to schedule compactions based on
    /// `base_background_compactions`. If the compaction cannot catch up , we
    /// will increase number of compaction threads up to
    /// `max_background_compactions`.
    ///
    /// If you're increasing this, also consider increasing number of threads in
    /// LOW priority thread pool. For more information, see
    /// Env::SetBackgroundThreads
    ///
    /// Default: `-1`, meaning RocksDB derives it from `max_background_jobs`.
    /// Setting either this or `max_background_flushes` opts into the old
    /// behaviour, where the unset one of the pair counts as `1`.
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// #[allow(deprecated)]
    /// opts.set_max_background_compactions(2);
    /// ```
    #[deprecated(
        since = "0.15.0",
        note = "RocksDB automatically decides this based on the value of max_background_jobs"
    )]
    pub fn set_max_background_compactions(&mut self, n: c_int) {
        unsafe {
            ffi::rocksdb_options_set_max_background_compactions(self.inner, n);
        }
    }

    /// The raw `max_background_compactions` field, `-1` while it is unset.
    ///
    /// Deprecated upstream in favour of `max_background_jobs`, so this is the value someone
    /// passed to [`Self::set_max_background_compactions`], not the concurrency RocksDB will
    /// actually run. While it is `-1` the real limit comes from
    /// [`Self::get_max_background_jobs`], unless `max_background_flushes` is set, in which
    /// case this half of the pair counts as `1`. RocksDB resolves that on a copy when the DB
    /// opens and never writes it back here.
    pub fn get_max_background_compactions(&self) -> c_int {
        unsafe { ffi::rocksdb_options_get_max_background_compactions(self.inner) }
    }

    /// Sets the maximum number of concurrent background memtable flush jobs, submitted to
    /// the HIGH priority thread pool.
    ///
    /// By default, all background jobs (major compaction and memtable flush) go
    /// to the LOW priority pool. If this option is set to a positive number,
    /// memtable flush jobs will be submitted to the HIGH priority pool.
    /// It is important when the same Env is shared by multiple db instances.
    /// Without a separate pool, long running major compaction jobs could
    /// potentially block memtable flush jobs of other db instances, leading to
    /// unnecessary Put stalls.
    ///
    /// If you're increasing this, also consider increasing number of threads in
    /// HIGH priority thread pool. For more information, see
    /// Env::SetBackgroundThreads
    ///
    /// Default: `-1`, meaning RocksDB derives it from `max_background_jobs`.
    /// Setting either this or `max_background_compactions` opts into the old
    /// behaviour, where the unset one of the pair counts as `1`.
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// #[allow(deprecated)]
    /// opts.set_max_background_flushes(2);
    /// ```
    #[deprecated(
        since = "0.15.0",
        note = "RocksDB automatically decides this based on the value of max_background_jobs"
    )]
    pub fn set_max_background_flushes(&mut self, n: c_int) {
        unsafe {
            ffi::rocksdb_options_set_max_background_flushes(self.inner, n);
        }
    }

    /// The raw `max_background_flushes` field, `-1` while it is unset.
    ///
    /// Deprecated upstream in favour of `max_background_jobs`, so this is the value someone
    /// passed to [`Self::set_max_background_flushes`], not the concurrency RocksDB will
    /// actually run. While it is `-1` the real limit comes from
    /// [`Self::get_max_background_jobs`], unless `max_background_compactions` is set, in
    /// which case this half of the pair counts as `1`. RocksDB resolves that on a copy when
    /// the DB opens and never writes it back here.
    pub fn get_max_background_flushes(&self) -> c_int {
        unsafe { ffi::rocksdb_options_get_max_background_flushes(self.inner) }
    }

    /// Disables automatic compactions. Manual compactions can still
    /// be issued on this column family
    ///
    /// Default: `false`
    ///
    /// Dynamically changeable through SetOptions() API
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// opts.set_disable_auto_compactions(true);
    /// ```
    pub fn set_disable_auto_compactions(&mut self, disable: bool) {
        unsafe {
            ffi::rocksdb_options_set_disable_auto_compactions(self.inner, c_int::from(disable));
        }
    }

    /// SetMemtableHugePageSize sets the page size for huge page for
    /// arena used by the memtable.
    /// If <=0, it won't allocate from huge page but from malloc.
    /// Users are responsible to reserve huge pages for it to be allocated. For
    /// example:
    ///      sysctl -w vm.nr_hugepages=20
    /// See linux doc Documentation/vm/hugetlbpage.txt
    /// If there isn't enough free huge page available, it will fall back to
    /// malloc.
    ///
    /// Dynamically changeable through SetOptions() API
    pub fn set_memtable_huge_page_size(&mut self, size: size_t) {
        unsafe {
            ffi::rocksdb_options_set_memtable_huge_page_size(self.inner, size);
        }
    }

    /// Enables the skip-list memtable's batch-lookup optimization for
    /// `MultiGet`.
    ///
    /// When enabled, the search path is cached between consecutive keys in a
    /// `MultiGet`, reducing per-key cost from `O(log N)` to `O(log d)` where
    /// `d` is the distance between consecutive keys. The optimization
    /// exploits the fact that `MultiGet` keys are sorted.
    ///
    /// Applies only to the default skip-list memtable (the one used when no
    /// memtable factory is set via [`Self::set_memtable_factory`]). The
    /// `MemtableFactory::Vector`, `HashSkipList`, and `HashLinkList` variants
    /// all fall back to per-key lookups regardless of this flag.
    ///
    /// This option is immutable on the C++ side: it must be set before the
    /// column family is opened and cannot be changed via `SetOptions`.
    ///
    /// Default: `false`
    pub fn set_memtable_batch_lookup_optimization(&mut self, enable: bool) {
        unsafe {
            ffi::rocksdb_options_set_memtable_batch_lookup_optimization(
                self.inner,
                c_uchar::from(enable),
            );
        }
    }

    /// Returns the current value of
    /// [`Self::set_memtable_batch_lookup_optimization`].
    ///
    /// Provided primarily for tests that want to confirm the setter is wired
    /// through to the underlying C++ `AdvancedColumnFamilyOptions`.
    pub fn get_memtable_batch_lookup_optimization(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_memtable_batch_lookup_optimization(self.inner) != 0 }
    }

    /// Sets the maximum number of successive merge operations on a key in the memtable.
    ///
    /// When a merge operation is added to the memtable and the maximum number of
    /// successive merges is reached, the value of the key will be calculated and
    /// inserted into the memtable instead of the merge operation. This will
    /// ensure that there are never more than max_successive_merges merge
    /// operations in the memtable.
    ///
    /// Default: 0 (disabled)
    pub fn set_max_successive_merges(&mut self, num: usize) {
        unsafe {
            ffi::rocksdb_options_set_max_successive_merges(self.inner, num);
        }
    }

    /// Control locality of bloom filter probes to improve cache miss rate.
    /// This option only applies to memtable prefix bloom and plaintable
    /// prefix bloom. It essentially limits the max number of cache lines each
    /// bloom filter check can touch.
    ///
    /// This optimization is turned off when set to 0. The number should never
    /// be greater than number of probes. This option can boost performance
    /// for in-memory workload but should use with care since it can cause
    /// higher false positive rate.
    ///
    /// Default: 0
    pub fn set_bloom_locality(&mut self, v: u32) {
        unsafe {
            ffi::rocksdb_options_set_bloom_locality(self.inner, v);
        }
    }

    /// Enable/disable thread-safe inplace updates.
    ///
    /// Requires updates if
    /// * key exists in current memtable
    /// * new sizeof(new_value) <= sizeof(old_value)
    /// * old_value for that key is a put i.e. kTypeValue
    ///
    /// Default: false.
    pub fn set_inplace_update_support(&mut self, enabled: bool) {
        unsafe {
            ffi::rocksdb_options_set_inplace_update_support(self.inner, c_uchar::from(enabled));
        }
    }

    /// Sets the number of locks used for inplace update.
    ///
    /// Default: 10000 when inplace_update_support = true, otherwise 0.
    pub fn set_inplace_update_locks(&mut self, num: usize) {
        unsafe {
            ffi::rocksdb_options_set_inplace_update_num_locks(self.inner, num);
        }
    }

    /// Different max-size multipliers for different levels.
    /// These are multiplied by max_bytes_for_level_multiplier to arrive
    /// at the max-size of each level.
    ///
    /// Default: 1
    ///
    /// Dynamically changeable through SetOptions() API
    pub fn set_max_bytes_for_level_multiplier_additional(&mut self, level_values: &[i32]) {
        let count = level_values.len();
        unsafe {
            ffi::rocksdb_options_set_max_bytes_for_level_multiplier_additional(
                self.inner,
                level_values.as_ptr().cast_mut(),
                count,
            );
        }
    }

    /// The total maximum size(bytes) of write buffers to maintain in memory
    /// including copies of buffers that have already been flushed. This parameter
    /// only affects trimming of flushed buffers and does not affect flushing.
    /// This controls the maximum amount of write history that will be available
    /// in memory for conflict checking when Transactions are used. The actual
    /// size of write history (flushed Memtables) might be higher than this limit
    /// if further trimming will reduce write history total size below this
    /// limit. For example, if max_write_buffer_size_to_maintain is set to 64MB,
    /// and there are three flushed Memtables, with sizes of 32MB, 20MB, 20MB.
    /// Because trimming the next Memtable of size 20MB will reduce total memory
    /// usage to 52MB which is below the limit, RocksDB will stop trimming.
    ///
    /// When using an OptimisticTransactionDB:
    /// If this value is too low, some transactions may fail at commit time due
    /// to not being able to determine whether there were any write conflicts.
    ///
    /// When using a TransactionDB:
    /// If Transaction::SetSnapshot is used, TransactionDB will read either
    /// in-memory write buffers or SST files to do write-conflict checking.
    /// Increasing this value can reduce the number of reads to SST files
    /// done for conflict detection.
    ///
    /// Setting this value to 0 will cause write buffers to be freed immediately
    /// after they are flushed. If this value is set to -1,
    /// 'max_write_buffer_number * write_buffer_size' will be used.
    ///
    /// Default:
    /// If using a TransactionDB/OptimisticTransactionDB, the default value will
    /// be set to the value of 'max_write_buffer_number * write_buffer_size'
    /// if it is not explicitly set by the user.  Otherwise, the default is 0.
    pub fn set_max_write_buffer_size_to_maintain(&mut self, size: i64) {
        unsafe {
            ffi::rocksdb_options_set_max_write_buffer_size_to_maintain(self.inner, size);
        }
    }

    /// By default, a single write thread queue is maintained. The thread gets
    /// to the head of the queue becomes write batch group leader and responsible
    /// for writing to WAL and memtable for the batch group.
    ///
    /// If enable_pipelined_write is true, separate write thread queue is
    /// maintained for WAL write and memtable write. A write thread first enter WAL
    /// writer queue and then memtable writer queue. Pending thread on the WAL
    /// writer queue thus only have to wait for previous writers to finish their
    /// WAL writing but not the memtable writing. Enabling the feature may improve
    /// write throughput and reduce latency of the prepare phase of two-phase
    /// commit.
    ///
    /// Default: false
    pub fn set_enable_pipelined_write(&mut self, value: bool) {
        unsafe {
            ffi::rocksdb_options_set_enable_pipelined_write(self.inner, c_uchar::from(value));
        }
    }

    /// Defines the underlying memtable implementation.
    /// See official [wiki](https://github.com/facebook/rocksdb/wiki/MemTable) for more information.
    /// Defaults to using a skiplist.
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::{Options, MemtableFactory};
    /// let mut opts = Options::default();
    /// let factory = MemtableFactory::HashSkipList {
    ///     bucket_count: 1_000_000,
    ///     height: 4,
    ///     branching_factor: 4,
    /// };
    ///
    /// opts.set_allow_concurrent_memtable_write(false);
    /// opts.set_memtable_factory(factory);
    /// ```
    pub fn set_memtable_factory(&mut self, factory: MemtableFactory) {
        match factory {
            MemtableFactory::Vector => unsafe {
                ffi::rocksdb_options_set_memtable_vector_rep(self.inner);
            },
            MemtableFactory::HashSkipList {
                bucket_count,
                height,
                branching_factor,
            } => unsafe {
                ffi::rocksdb_options_set_hash_skip_list_rep(
                    self.inner,
                    bucket_count,
                    height,
                    branching_factor,
                );
            },
            MemtableFactory::HashLinkList { bucket_count } => unsafe {
                ffi::rocksdb_options_set_hash_link_list_rep(self.inner, bucket_count);
            },
        }
    }

    pub fn set_block_based_table_factory(&mut self, factory: &BlockBasedOptions) {
        unsafe {
            ffi::rocksdb_options_set_block_based_table_factory(self.inner, factory.inner);
        }
        self.outlive.block_based = Some(factory.outlive.clone());
    }

    /// Sets the table factory to a CuckooTableFactory (the default table
    /// factory is a block-based table factory that provides a default
    /// implementation of TableBuilder and TableReader with default
    /// BlockBasedTableOptions).
    /// See official [wiki](https://github.com/facebook/rocksdb/wiki/CuckooTable-Format) for more information on this table format.
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::{Options, CuckooTableOptions};
    ///
    /// let mut opts = Options::default();
    /// let mut factory_opts = CuckooTableOptions::default();
    /// factory_opts.set_hash_ratio(0.8);
    /// factory_opts.set_max_search_depth(20);
    /// factory_opts.set_cuckoo_block_size(10);
    /// factory_opts.set_identity_as_first_hash(true);
    /// factory_opts.set_use_module_hash(false);
    ///
    /// opts.set_cuckoo_table_factory(&factory_opts);
    /// ```
    pub fn set_cuckoo_table_factory(&mut self, factory: &CuckooTableOptions) {
        unsafe {
            ffi::rocksdb_options_set_cuckoo_table_factory(self.inner, factory.inner);
        }
    }

    // This is a factory that provides TableFactory objects.
    // Default: a block-based table factory that provides a default
    // implementation of TableBuilder and TableReader with default
    // BlockBasedTableOptions.
    /// Sets the factory as plain table.
    /// See official [wiki](https://github.com/facebook/rocksdb/wiki/PlainTable-Format) for more
    /// information.
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::{KeyEncodingType, Options, PlainTableFactoryOptions};
    ///
    /// let mut opts = Options::default();
    /// let factory_opts = PlainTableFactoryOptions {
    ///   user_key_length: 0,
    ///   bloom_bits_per_key: 20,
    ///   hash_table_ratio: 0.75,
    ///   index_sparseness: 16,
    ///   huge_page_tlb_size: 0,
    ///   encoding_type: KeyEncodingType::Plain,
    ///   full_scan_mode: false,
    ///   store_index_in_file: false,
    /// };
    ///
    /// opts.set_plain_table_factory(&factory_opts);
    /// ```
    pub fn set_plain_table_factory(&mut self, options: &PlainTableFactoryOptions) {
        unsafe {
            ffi::rocksdb_options_set_plain_table_factory(
                self.inner,
                options.user_key_length,
                options.bloom_bits_per_key,
                options.hash_table_ratio,
                options.index_sparseness,
                options.huge_page_tlb_size,
                options.encoding_type as c_char,
                c_uchar::from(options.full_scan_mode),
                c_uchar::from(options.store_index_in_file),
            );
        }
    }

    /// Sets the start level to use compression.
    pub fn set_min_level_to_compress(&mut self, lvl: c_int) {
        unsafe {
            ffi::rocksdb_options_set_min_level_to_compress(self.inner, lvl);
        }
    }

    /// Measure IO stats in compactions and flushes, if `true`.
    ///
    /// Default: `false`
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// opts.set_report_bg_io_stats(true);
    /// ```
    pub fn set_report_bg_io_stats(&mut self, enable: bool) {
        unsafe {
            ffi::rocksdb_options_set_report_bg_io_stats(self.inner, c_int::from(enable));
        }
    }

    /// Once write-ahead logs exceed this size, we will start forcing the flush of
    /// column families whose memtables are backed by the oldest live WAL file
    /// (i.e. the ones that are causing all the space amplification).
    ///
    /// Default: `0`
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// // Set max total wal size to 1G.
    /// opts.set_max_total_wal_size(1 << 30);
    /// ```
    pub fn set_max_total_wal_size(&mut self, size: u64) {
        unsafe {
            ffi::rocksdb_options_set_max_total_wal_size(self.inner, size);
        }
    }

    /// Recovery mode to control the consistency while replaying WAL.
    ///
    /// Default: DBRecoveryMode::PointInTime
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::{Options, DBRecoveryMode};
    ///
    /// let mut opts = Options::default();
    /// opts.set_wal_recovery_mode(DBRecoveryMode::AbsoluteConsistency);
    /// ```
    pub fn set_wal_recovery_mode(&mut self, mode: DBRecoveryMode) {
        unsafe {
            ffi::rocksdb_options_set_wal_recovery_mode(self.inner, mode as c_int);
        }
    }

    /// The recovery mode set by [`Self::set_wal_recovery_mode`].
    ///
    /// [`DBRecoveryMode`] covers every mode RocksDB defines today, so `None` only shows up if
    /// a future release adds one.
    pub fn get_wal_recovery_mode(&self) -> Option<DBRecoveryMode> {
        let raw = unsafe { ffi::rocksdb_options_get_wal_recovery_mode(self.inner) };
        DBRecoveryMode::try_from_raw(raw)
    }

    /// Enables recording RocksDB statistics.
    ///
    /// The statistics in this Options object are shared between all DB instances.
    /// See [`get_statistics`](Self::get_statistics), [`get_ticker_count`](Self::get_ticker_count),
    /// and [`get_histogram_data`](Self::get_histogram_data).
    pub fn enable_statistics(&mut self) {
        unsafe {
            ffi::rocksdb_options_enable_statistics(self.inner);
        }
    }

    /// Returns a string containing RocksDB statistics if enabled using
    /// [`enable_statistics`](Self::enable_statistics).
    pub fn get_statistics(&self) -> Option<String> {
        unsafe {
            let value = ffi::rocksdb_options_statistics_get_string(self.inner);
            if value.is_null() {
                return None;
            }

            // Must have valid UTF-8 format.
            Some(from_cstr_and_free(value))
        }
    }

    /// StatsLevel can be used to reduce statistics overhead by skipping certain
    /// types of stats in the stats collection process.
    ///
    /// Only takes effect if stats are enabled first using
    /// [`enable_statistics`](Self::enable_statistics).
    pub fn set_statistics_level(&self, level: StatsLevel) {
        unsafe { ffi::rocksdb_options_set_statistics_level(self.inner, level as c_int) }
    }

    /// The level set by [`Self::set_statistics_level`].
    ///
    /// Reports [`StatsLevel::DisableAll`] when statistics were never enabled,
    /// because that is what the C API returns with no statistics object attached.
    ///
    /// Returns `None` for a value this crate has no variant for, which should not
    /// happen: RocksDB clamps the level into range on the way in.
    pub fn get_statistics_level(&self) -> Option<StatsLevel> {
        let raw = unsafe { ffi::rocksdb_options_get_statistics_level(self.inner) };
        StatsLevel::try_from_raw(raw)
    }

    /// Returns a counter if statistics are enabled using
    /// [`enable_statistics`](Self::enable_statistics).
    pub fn get_ticker_count(&self, ticker: Ticker) -> u64 {
        unsafe { ffi::rocksdb_options_statistics_get_ticker_count(self.inner, ticker as u32) }
    }

    /// Returns a histogram if statistics are enabled using
    /// [`enable_statistics`](Self::enable_statistics).
    pub fn get_histogram_data(&self, histogram: Histogram) -> HistogramData {
        unsafe {
            let data = HistogramData::default();
            ffi::rocksdb_options_statistics_get_histogram_data(
                self.inner,
                histogram as u32,
                data.inner,
            );
            data
        }
    }

    /// If not zero, dump `rocksdb.stats` to LOG every `stats_dump_period_sec`.
    ///
    /// Default: `600` (10 mins)
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// opts.set_stats_dump_period_sec(300);
    /// ```
    pub fn set_stats_dump_period_sec(&mut self, period: c_uint) {
        unsafe {
            ffi::rocksdb_options_set_stats_dump_period_sec(self.inner, period);
        }
    }

    /// If not zero, dump rocksdb.stats to RocksDB to LOG every `stats_persist_period_sec`.
    ///
    /// Default: `600` (10 mins)
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// opts.set_stats_persist_period_sec(5);
    /// ```
    pub fn set_stats_persist_period_sec(&mut self, period: c_uint) {
        unsafe {
            ffi::rocksdb_options_set_stats_persist_period_sec(self.inner, period);
        }
    }

    /// When set to true, reading SST files will opt out of the filesystem's
    /// readahead. Setting this to false may improve sequential iteration
    /// performance.
    ///
    /// Default: `true`
    pub fn set_advise_random_on_open(&mut self, advise: bool) {
        unsafe {
            ffi::rocksdb_options_set_advise_random_on_open(self.inner, c_uchar::from(advise));
        }
    }

    /// Enable/disable adaptive mutex, which spins in the user space before resorting to kernel.
    ///
    /// This could reduce context switch when the mutex is not
    /// heavily contended. However, if the mutex is hot, we could end up
    /// wasting spin time.
    ///
    /// Default: false
    pub fn set_use_adaptive_mutex(&mut self, enabled: bool) {
        unsafe {
            ffi::rocksdb_options_set_use_adaptive_mutex(self.inner, c_uchar::from(enabled));
        }
    }

    /// Sets the number of levels for this database.
    pub fn set_num_levels(&mut self, n: c_int) {
        unsafe {
            ffi::rocksdb_options_set_num_levels(self.inner, n);
        }
    }

    /// When a `prefix_extractor` is defined through `opts.set_prefix_extractor` this
    /// creates a prefix bloom filter for each memtable with the size of
    /// `write_buffer_size * memtable_prefix_bloom_ratio` (capped at 0.25).
    ///
    /// Default: `0`
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::{Options, SliceTransform};
    ///
    /// let mut opts = Options::default();
    /// let transform = SliceTransform::create_fixed_prefix(10);
    /// opts.set_prefix_extractor(transform);
    /// opts.set_memtable_prefix_bloom_ratio(0.2);
    /// ```
    pub fn set_memtable_prefix_bloom_ratio(&mut self, ratio: f64) {
        unsafe {
            ffi::rocksdb_options_set_memtable_prefix_bloom_size_ratio(self.inner, ratio);
        }
    }

    /// Sets the maximum number of bytes in all compacted files.
    /// We try to limit number of bytes in one compaction to be lower than this
    /// threshold. But it's not guaranteed.
    ///
    /// Value 0 will be sanitized.
    ///
    /// Default: target_file_size_base * 25
    pub fn set_max_compaction_bytes(&mut self, nbytes: u64) {
        unsafe {
            ffi::rocksdb_options_set_max_compaction_bytes(self.inner, nbytes);
        }
    }

    /// Specifies the absolute path of the directory the
    /// write-ahead log (WAL) should be written to.
    ///
    /// Default: same directory as the database
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut opts = Options::default();
    /// opts.set_wal_dir("/path/to/dir");
    /// ```
    pub fn set_wal_dir<P: AsRef<Path>>(&mut self, path: P) {
        let p = to_cpath(path).unwrap();
        unsafe {
            ffi::rocksdb_options_set_wal_dir(self.inner, p.as_ptr());
        }
    }

    /// The WAL directory set by [`Self::set_wal_dir`], empty when the WAL lives with the data.
    pub fn get_wal_dir(&self) -> String {
        let mut len: size_t = 0;
        let path = unsafe { ffi::rocksdb_options_get_wal_dir(self.inner, &raw mut len) };
        unsafe { borrowed_string(path, len) }
    }

    /// Sets the WAL ttl in seconds.
    ///
    /// The following two options affect how archived logs will be deleted.
    /// 1. If both set to 0, logs will be deleted asap and will not get into
    ///    the archive.
    /// 2. If wal_ttl_seconds is 0 and wal_size_limit_mb is not 0,
    ///    WAL files will be checked every 10 min and if total size is greater
    ///    then wal_size_limit_mb, they will be deleted starting with the
    ///    earliest until size_limit is met. All empty files will be deleted.
    /// 3. If wal_ttl_seconds is not 0 and wall_size_limit_mb is 0, then
    ///    WAL files will be checked every wal_ttl_seconds / 2 and those that
    ///    are older than wal_ttl_seconds will be deleted.
    /// 4. If both are not 0, WAL files will be checked every 10 min and both
    ///    checks will be performed with ttl being first.
    ///
    /// Default: 0
    pub fn set_wal_ttl_seconds(&mut self, secs: u64) {
        unsafe {
            ffi::rocksdb_options_set_WAL_ttl_seconds(self.inner, secs);
        }
    }

    /// Sets the WAL size limit in MB.
    ///
    /// If total size of WAL files is greater then wal_size_limit_mb,
    /// they will be deleted starting with the earliest until size_limit is met.
    ///
    /// Default: 0
    pub fn set_wal_size_limit_mb(&mut self, size: u64) {
        unsafe {
            ffi::rocksdb_options_set_WAL_size_limit_MB(self.inner, size);
        }
    }

    /// Sets the number of bytes to preallocate (via fallocate) the manifest files.
    ///
    /// Default is 4MB, which is reasonable to reduce random IO
    /// as well as prevent overallocation for mounts that preallocate
    /// large amounts of data (such as xfs's allocsize option).
    pub fn set_manifest_preallocation_size(&mut self, size: usize) {
        unsafe {
            ffi::rocksdb_options_set_manifest_preallocation_size(self.inner, size);
        }
    }

    /// If true, then DB::Open() will not update the statistics used to optimize
    /// compaction decision by loading table properties from many files.
    /// Turning off this feature will improve DBOpen time especially in disk environment.
    ///
    /// Default: false
    pub fn set_skip_stats_update_on_db_open(&mut self, skip: bool) {
        unsafe {
            ffi::rocksdb_options_set_skip_stats_update_on_db_open(self.inner, c_uchar::from(skip));
        }
    }

    /// Controls whether RocksDB opens and validates SST files in the background after open.
    ///
    /// Enabling this can reduce open latency for databases with many SST files
    /// or high latency storage. It is mostly useful with
    /// [`Options::set_max_open_files`] set to `-1`.
    ///
    /// This option is not compatible with FIFO compaction and requires
    /// [`Options::set_skip_stats_update_on_db_open`] to be `true`. SST open
    /// errors are no longer returned by `DB::open`; they can instead surface as
    /// background errors or from operations that access the affected file.
    ///
    /// Default: `false`
    pub fn set_open_files_async(&mut self, enabled: bool) -> Result<(), Error> {
        let supported = unsafe {
            ffi::rust_rocksdb_options_set_open_files_async(self.inner, c_uchar::from(enabled)) != 0
        };
        if !supported {
            return Err(Error::new(
                "open_files_async requires RocksDB 11.1 or newer".to_owned(),
            ));
        }
        Ok(())
    }

    /// Returns whether SST files are opened and validated in the background after open.
    pub fn get_open_files_async(&self) -> bool {
        unsafe { ffi::rust_rocksdb_options_get_open_files_async(self.inner) != 0 }
    }

    /// Returns whether the linked RocksDB supports `open_files_async`.
    pub fn supports_open_files_async() -> bool {
        unsafe { ffi::rust_rocksdb_options_open_files_async_supported() != 0 }
    }

    /// Specify the maximal number of info log files to be kept.
    ///
    /// Default: 1000
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut options = Options::default();
    /// options.set_keep_log_file_num(100);
    /// ```
    pub fn set_keep_log_file_num(&mut self, nfiles: usize) {
        unsafe {
            ffi::rocksdb_options_set_keep_log_file_num(self.inner, nfiles);
        }
    }

    /// Allow the OS to mmap file for writing.
    ///
    /// Default: false
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut options = Options::default();
    /// options.set_allow_mmap_writes(true);
    /// ```
    pub fn set_allow_mmap_writes(&mut self, is_enabled: bool) {
        unsafe {
            ffi::rocksdb_options_set_allow_mmap_writes(self.inner, c_uchar::from(is_enabled));
        }
    }

    /// Allow the OS to mmap file for reading sst tables.
    ///
    /// Default: false
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut options = Options::default();
    /// options.set_allow_mmap_reads(true);
    /// ```
    pub fn set_allow_mmap_reads(&mut self, is_enabled: bool) {
        unsafe {
            ffi::rocksdb_options_set_allow_mmap_reads(self.inner, c_uchar::from(is_enabled));
        }
    }

    /// If enabled, WAL is not flushed automatically after each write. Instead it
    /// relies on manual invocation of `DB::flush_wal()` to write the WAL buffer
    /// to its file.
    ///
    /// Default: false
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut options = Options::default();
    /// options.set_manual_wal_flush(true);
    /// ```
    pub fn set_manual_wal_flush(&mut self, is_enabled: bool) {
        unsafe {
            ffi::rocksdb_options_set_manual_wal_flush(self.inner, c_uchar::from(is_enabled));
        }
    }

    /// Guarantee that all column families are flushed together atomically.
    /// This option applies to both manual flushes (`db.flush()`) and automatic
    /// background flushes caused when memtables are filled.
    ///
    /// Note that this is only useful when the WAL is disabled. When using the
    /// WAL, writes are always consistent across column families.
    ///
    /// Default: false
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut options = Options::default();
    /// options.set_atomic_flush(true);
    /// ```
    pub fn set_atomic_flush(&mut self, atomic_flush: bool) {
        unsafe {
            ffi::rocksdb_options_set_atomic_flush(self.inner, c_uchar::from(atomic_flush));
        }
    }

    /// Sets global cache for table-level rows.
    ///
    /// Default: null (disabled)
    /// Not supported in ROCKSDB_LITE mode!
    pub fn set_row_cache(&mut self, cache: &Cache) {
        unsafe {
            ffi::rocksdb_options_set_row_cache(self.inner, cache.0.inner.as_ptr());
        }
        self.outlive.row_cache = Some(cache.clone());
    }

    /// Use to control write rate of flush and compaction. Flush has higher
    /// priority than compaction.
    /// If rate limiter is enabled, bytes_per_sync is set to 1MB by default.
    ///
    /// Default: disable
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut options = Options::default();
    /// options.set_ratelimiter(1024 * 1024, 100 * 1000, 10);
    /// ```
    pub fn set_ratelimiter(
        &mut self,
        rate_bytes_per_sec: i64,
        refill_period_us: i64,
        fairness: i32,
    ) {
        unsafe {
            let ratelimiter =
                ffi::rocksdb_ratelimiter_create(rate_bytes_per_sec, refill_period_us, fairness);
            ffi::rocksdb_options_set_ratelimiter(self.inner, ratelimiter);
            ffi::rocksdb_ratelimiter_destroy(ratelimiter);
        }
    }

    /// Use to control write rate of flush and compaction. Flush has higher
    /// priority than compaction.
    /// If rate limiter is enabled, bytes_per_sync is set to 1MB by default.
    ///
    /// Default: disable
    pub fn set_auto_tuned_ratelimiter(
        &mut self,
        rate_bytes_per_sec: i64,
        refill_period_us: i64,
        fairness: i32,
    ) {
        unsafe {
            let ratelimiter = ffi::rocksdb_ratelimiter_create_auto_tuned(
                rate_bytes_per_sec,
                refill_period_us,
                fairness,
            );
            ffi::rocksdb_options_set_ratelimiter(self.inner, ratelimiter);
            ffi::rocksdb_ratelimiter_destroy(ratelimiter);
        }
    }

    /// Create a RateLimiter object, which can be shared among RocksDB instances to
    /// control write rate of flush and compaction.
    ///
    /// rate_bytes_per_sec: this is the only parameter you want to set most of the
    /// time. It controls the total write rate of compaction and flush in bytes per
    /// second. Currently, RocksDB does not enforce rate limit for anything other
    /// than flush and compaction, e.g. write to WAL.
    ///
    /// refill_period_us: this controls how often tokens are refilled. For example,
    /// when rate_bytes_per_sec is set to 10MB/s and refill_period_us is set to
    /// 100ms, then 1MB is refilled every 100ms internally. Larger value can lead to
    /// burstier writes while smaller value introduces more CPU overhead.
    /// The default should work for most cases.
    ///
    /// fairness: RateLimiter accepts high-pri requests and low-pri requests.
    /// A low-pri request is usually blocked in favor of hi-pri request. Currently,
    /// RocksDB assigns low-pri to request from compaction and high-pri to request
    /// from flush. Low-pri requests can get blocked if flush requests come in
    /// continuously. This fairness parameter grants low-pri requests permission by
    /// 1/fairness chance even though high-pri requests exist to avoid starvation.
    /// You should be good by leaving it at default 10.
    ///
    /// mode: Mode indicates which types of operations count against the limit.
    ///
    /// auto_tuned: Enables dynamic adjustment of rate limit within the range
    ///              `[rate_bytes_per_sec / 20, rate_bytes_per_sec]`, according to
    ///              the recent demand for background I/O.
    pub fn set_ratelimiter_with_mode(
        &mut self,
        rate_bytes_per_sec: i64,
        refill_period_us: i64,
        fairness: i32,
        mode: RateLimiterMode,
        auto_tuned: bool,
    ) {
        unsafe {
            let ratelimiter = ffi::rocksdb_ratelimiter_create_with_mode(
                rate_bytes_per_sec,
                refill_period_us,
                fairness,
                mode as c_int,
                auto_tuned,
            );
            ffi::rocksdb_options_set_ratelimiter(self.inner, ratelimiter);
            ffi::rocksdb_ratelimiter_destroy(ratelimiter);
        }
    }

    /// Sets the maximal size of the info log file.
    ///
    /// If the log file is larger than `max_log_file_size`, a new info log file
    /// will be created. If `max_log_file_size` is equal to zero, all logs will
    /// be written to one log file.
    ///
    /// Default: 0
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut options = Options::default();
    /// options.set_max_log_file_size(0);
    /// ```
    pub fn set_max_log_file_size(&mut self, size: usize) {
        unsafe {
            ffi::rocksdb_options_set_max_log_file_size(self.inner, size);
        }
    }

    /// Sets the time for the info log file to roll (in seconds).
    ///
    /// If specified with non-zero value, log file will be rolled
    /// if it has been active longer than `log_file_time_to_roll`.
    /// Default: 0 (disabled)
    pub fn set_log_file_time_to_roll(&mut self, secs: usize) {
        unsafe {
            ffi::rocksdb_options_set_log_file_time_to_roll(self.inner, secs);
        }
    }

    /// Controls the recycling of log files.
    ///
    /// If non-zero, previously written log files will be reused for new logs,
    /// overwriting the old data. The value indicates how many such files we will
    /// keep around at any point in time for later use. This is more efficient
    /// because the blocks are already allocated and fdatasync does not need to
    /// update the inode after each write.
    ///
    /// Default: 0
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::Options;
    ///
    /// let mut options = Options::default();
    /// options.set_recycle_log_file_num(5);
    /// ```
    pub fn set_recycle_log_file_num(&mut self, num: usize) {
        unsafe {
            ffi::rocksdb_options_set_recycle_log_file_num(self.inner, num);
        }
    }

    /// Prints logs to stderr for faster debugging
    /// See official [wiki](https://github.com/facebook/rocksdb/wiki/Logger) for more information.
    pub fn set_stderr_logger(&mut self, log_level: LogLevel, prefix: impl CStrLike) {
        let p = prefix.into_c_string().unwrap();

        unsafe {
            let logger = ffi::rocksdb_logger_create_stderr_logger(log_level as c_int, p.as_ptr());
            ffi::rocksdb_options_set_info_log(self.inner, logger);
            ffi::rocksdb_logger_destroy(logger);
        }
    }

    /// Invokes `callback` with RocksDB log messages with level >= `log_level`.
    ///
    /// The callback can be called concurrently by multiple RocksDB threads.
    ///
    /// # Examples
    /// ```
    /// use rust_rocksdb::{LogLevel, Options};
    ///
    /// let mut options = Options::default();
    /// options.set_callback_logger(LogLevel::Debug, move |level, msg| println!("{level:?} {msg}"));
    /// ```
    pub fn set_callback_logger(
        &mut self,
        log_level: LogLevel,
        callback: impl Fn(LogLevel, &str) + 'static + Send + Sync,
    ) {
        // store the closure in an Arc so it can be shared across multiple Option/DBs
        let holder = Arc::new(LogCallback {
            callback: Box::new(callback),
        });
        let holder_ptr = std::ptr::from_ref::<LogCallback>(holder.as_ref());
        let holder_cvoid = holder_ptr.cast::<c_void>().cast_mut();

        unsafe {
            let logger = ffi::rocksdb_logger_create_callback_logger(
                log_level as c_int,
                Some(Self::logger_callback),
                holder_cvoid,
            );
            ffi::rocksdb_options_set_info_log(self.inner, logger);
            ffi::rocksdb_logger_destroy(logger);
        }

        self.outlive.log_callback = Some(holder);
    }

    extern "C" fn logger_callback(func: *mut c_void, level: u32, msg: *mut c_char, len: usize) {
        use std::process;

        // Neither argument can be trusted:
        //
        //  * `LogLevel` is `#[repr(i32)]`, and `level` is whatever
        //    `InfoLogLevel` the C layer cast to an unsigned, so transmuting it
        //    could materialise an invalid discriminant.
        //  * `msg` is raw `vsnprintf` output. Log lines routinely embed
        //    filesystem paths and `Status::ToString()` text, and paths reach
        //    RocksDB via `OsStr::as_bytes()`, which is not UTF-8 validated, so
        //    `from_utf8_unchecked` was unsound.
        //
        // `from_utf8_lossy` returns `Cow::Borrowed` for valid UTF-8, so the
        // common path still does not allocate.
        let level = LogLevel::try_from_raw(level as i32).unwrap_or(LogLevel::Info);
        let slice = if len == 0 {
            &[][..]
        } else {
            unsafe { slice::from_raw_parts(msg.cast_const().cast::<u8>(), len) }
        };
        let msg = String::from_utf8_lossy(slice);

        // Shared reference, not `&mut`: RocksDB logs from several background
        // threads at once, so a `&mut` here would alias. `LogCallbackFn` is a
        // `dyn Fn`, so a shared reference is all it needs.
        let holder = unsafe { &*func.cast::<LogCallback>() };
        let callback_in_catch_unwind = AssertUnwindSafe(&holder.callback);
        if catch_unwind(move || callback_in_catch_unwind(level, &msg)).is_err() {
            process::abort();
        }
    }

    /// Sets the threshold at which all writes will be slowed down to at least delayed_write_rate if estimated
    /// bytes needed to be compaction exceed this threshold.
    ///
    /// Default: 64GB
    pub fn set_soft_pending_compaction_bytes_limit(&mut self, limit: usize) {
        unsafe {
            ffi::rocksdb_options_set_soft_pending_compaction_bytes_limit(self.inner, limit);
        }
    }

    /// Sets the bytes threshold at which all writes are stopped if estimated bytes needed to be compaction exceed
    /// this threshold.
    ///
    /// Default: 256GB
    pub fn set_hard_pending_compaction_bytes_limit(&mut self, limit: usize) {
        unsafe {
            ffi::rocksdb_options_set_hard_pending_compaction_bytes_limit(self.inner, limit);
        }
    }

    /// Sets the size of one block in arena memory allocation.
    ///
    /// If <= 0, a proper value is automatically calculated (usually 1/10 of
    /// writer_buffer_size).
    ///
    /// Default: 0
    pub fn set_arena_block_size(&mut self, size: usize) {
        unsafe {
            ffi::rocksdb_options_set_arena_block_size(self.inner, size);
        }
    }

    /// If true, then print malloc stats together with rocksdb.stats when printing to LOG.
    ///
    /// Default: false
    pub fn set_dump_malloc_stats(&mut self, enabled: bool) {
        unsafe {
            ffi::rocksdb_options_set_dump_malloc_stats(self.inner, c_uchar::from(enabled));
        }
    }

    /// Enable whole key bloom filter in memtable. Note this will only take effect
    /// if memtable_prefix_bloom_size_ratio is not 0. Enabling whole key filtering
    /// can potentially reduce CPU usage for point-look-ups.
    ///
    /// Default: false (disable)
    ///
    /// Dynamically changeable through SetOptions() API
    pub fn set_memtable_whole_key_filtering(&mut self, whole_key_filter: bool) {
        unsafe {
            ffi::rocksdb_options_set_memtable_whole_key_filtering(
                self.inner,
                c_uchar::from(whole_key_filter),
            );
        }
    }

    /// Enable the use of key-value separation.
    ///
    /// More details can be found here: [Integrated BlobDB](http://rocksdb.org/blog/2021/05/26/integrated-blob-db.html).
    ///
    /// Default: false (disable)
    ///
    /// Dynamically changeable through SetOptions() API
    pub fn set_enable_blob_files(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_enable_blob_files(self.inner, u8::from(val));
        }
    }

    /// Sets the minimum threshold value at or above which will be written
    /// to blob files during flush or compaction.
    ///
    /// Dynamically changeable through SetOptions() API
    pub fn set_min_blob_size(&mut self, val: u64) {
        unsafe {
            ffi::rocksdb_options_set_min_blob_size(self.inner, val);
        }
    }

    /// Sets the size limit for blob files.
    ///
    /// Dynamically changeable through SetOptions() API
    pub fn set_blob_file_size(&mut self, val: u64) {
        unsafe {
            ffi::rocksdb_options_set_blob_file_size(self.inner, val);
        }
    }

    /// Sets the blob compression type. All blob files use the same
    /// compression type.
    ///
    /// Dynamically changeable through SetOptions() API
    pub fn set_blob_compression_type(&mut self, val: DBCompressionType) {
        unsafe {
            ffi::rocksdb_options_set_blob_compression_type(self.inner, val as _);
        }
    }

    /// The compression algorithm used for blob files.
    ///
    /// `None` covers a compression type this crate does not name.
    pub fn get_blob_compression_type(&self) -> Option<DBCompressionType> {
        let raw = unsafe { ffi::rocksdb_options_get_blob_compression_type(self.inner) };
        DBCompressionType::try_from_raw(raw)
    }

    /// If this is set to true RocksDB will actively relocate valid blobs from the oldest blob files
    /// as they are encountered during compaction.
    ///
    /// Dynamically changeable through SetOptions() API
    pub fn set_enable_blob_gc(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_enable_blob_gc(self.inner, u8::from(val));
        }
    }

    /// Sets the threshold that the GC logic uses to determine which blob files should be considered “old.”
    ///
    /// For example, the default value of 0.25 signals to RocksDB that blobs residing in the
    /// oldest 25% of blob files should be relocated by GC. This parameter can be tuned to adjust
    /// the trade-off between write amplification and space amplification.
    ///
    /// Dynamically changeable through SetOptions() API
    pub fn set_blob_gc_age_cutoff(&mut self, val: c_double) {
        unsafe {
            ffi::rocksdb_options_set_blob_gc_age_cutoff(self.inner, val);
        }
    }

    /// Sets the blob GC force threshold.
    ///
    /// Dynamically changeable through SetOptions() API
    pub fn set_blob_gc_force_threshold(&mut self, val: c_double) {
        unsafe {
            ffi::rocksdb_options_set_blob_gc_force_threshold(self.inner, val);
        }
    }

    /// Sets the blob compaction read ahead size.
    ///
    /// Dynamically changeable through SetOptions() API
    pub fn set_blob_compaction_readahead_size(&mut self, val: u64) {
        unsafe {
            ffi::rocksdb_options_set_blob_compaction_readahead_size(self.inner, val);
        }
    }

    /// Sets the blob cache.
    ///
    /// Using a dedicated object for blobs and using the same object for the block and blob caches
    /// are both supported. In the latter case, note that blobs are less valuable from a caching
    /// perspective than SST blocks, and some cache implementations have configuration options that
    /// can be used to prioritize items accordingly (see Cache::Priority and
    /// LRUCacheOptions::{high,low}_pri_pool_ratio).
    ///
    /// Default: disabled
    pub fn set_blob_cache(&mut self, cache: &Cache) {
        unsafe {
            ffi::rocksdb_options_set_blob_cache(self.inner, cache.0.inner.as_ptr());
        }
        self.outlive.blob_cache = Some(cache.clone());
    }

    /// Whether newly written blobs go straight into the blob cache.
    ///
    /// [`PrepopulateBlobCache::FlushOnly`] pays off when reading a blob back is expensive,
    /// with direct I/O or remote storage, or when the workload has strong temporal locality.
    /// It needs [`Self::set_blob_cache`] to have been called to have any effect.
    ///
    /// Default: [`PrepopulateBlobCache::Disable`]
    ///
    /// Dynamically changeable through SetOptions() API
    pub fn set_prepopulate_blob_cache(&mut self, val: PrepopulateBlobCache) {
        unsafe {
            ffi::rocksdb_options_set_prepopulate_blob_cache(self.inner, val as c_int);
        }
    }

    /// The setting from [`Self::set_prepopulate_blob_cache`].
    ///
    /// `None` covers a value this crate does not name, which RocksDB has none of today.
    pub fn get_prepopulate_blob_cache(&self) -> Option<PrepopulateBlobCache> {
        let raw = unsafe { ffi::rocksdb_options_get_prepopulate_blob_cache(self.inner) };
        PrepopulateBlobCache::try_from_raw(raw)
    }

    /// Set this option to true during creation of database if you want
    /// to be able to ingest behind (call IngestExternalFile() skipping keys
    /// that already exist, rather than overwriting matching keys).
    /// Setting this option to true has the following effects:
    ///
    /// 1. Disable some internal optimizations around SST file compression.
    /// 2. Reserve the last level for ingested files only.
    /// 3. Compaction will not include any file from the last level.
    ///
    /// Note that only Universal Compaction supports allow_ingest_behind.
    /// `num_levels` should be >= 3 if this option is turned on.
    ///
    /// DEFAULT: false
    /// Immutable.
    pub fn set_allow_ingest_behind(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_allow_ingest_behind(self.inner, c_uchar::from(val));
        }
    }

    // A factory of a table property collector that marks an SST
    // file as need-compaction when it observe at least "D" deletion
    // entries in any "N" consecutive entries, or the ratio of tombstone
    // entries >= deletion_ratio.
    //
    // `window_size`: is the sliding window size "N"
    // `num_dels_trigger`: is the deletion trigger "D"
    // `deletion_ratio`: if <= 0 or > 1, disable triggering compaction based on
    // deletion ratio.
    pub fn add_compact_on_deletion_collector_factory(
        &mut self,
        window_size: size_t,
        num_dels_trigger: size_t,
        deletion_ratio: f64,
    ) {
        unsafe {
            ffi::rocksdb_options_add_compact_on_deletion_collector_factory_del_ratio(
                self.inner,
                window_size,
                num_dels_trigger,
                deletion_ratio,
            );
        }
    }

    /// Like [`Self::add_compact_on_deletion_collector_factory`], but with the ratio trigger
    /// off, so a file is only marked once `num_dels_trigger` deletions land inside a window
    /// of `window_size` consecutive entries.
    ///
    /// `window_size` is rounded up to a multiple of 128. `num_dels_trigger` is used as given
    /// and is not rescaled when `window_size` changes.
    ///
    /// This appends another collector factory to the column family's list, it does not
    /// replace the ones already there. Calling it twice registers the collector twice.
    pub fn add_compact_on_deletion_collector_factory_count_only(
        &mut self,
        window_size: size_t,
        num_dels_trigger: size_t,
    ) {
        unsafe {
            ffi::rocksdb_options_add_compact_on_deletion_collector_factory(
                self.inner,
                window_size,
                num_dels_trigger,
            );
        }
    }

    /// Like [`Self::add_compact_on_deletion_collector_factory`], but only triggers
    /// compaction if the SST file size is at least `min_file_size` bytes.
    pub fn add_compact_on_deletion_collector_factory_min_file_size(
        &mut self,
        window_size: size_t,
        num_dels_trigger: size_t,
        deletion_ratio: f64,
        min_file_size: u64,
    ) {
        unsafe {
            ffi::rocksdb_options_add_compact_on_deletion_collector_factory_min_file_size(
                self.inner,
                window_size,
                num_dels_trigger,
                deletion_ratio,
                min_file_size,
            );
        }
    }

    /// <https://github.com/facebook/rocksdb/wiki/Write-Buffer-Manager>
    /// Write buffer manager helps users control the total memory used by memtables across multiple column families and/or DB instances.
    /// Users can enable this control by 2 ways:
    ///
    /// 1- Limit the total memtable usage across multiple column families and DBs under a threshold.
    /// 2- Cost the memtable memory usage to block cache so that memory of RocksDB can be capped by the single limit.
    /// The usage of a write buffer manager is similar to rate_limiter and sst_file_manager.
    /// Users can create one write buffer manager object and pass it to all the options of column families or DBs whose memtable size they want to be controlled by this object.
    pub fn set_write_buffer_manager(&mut self, write_buffer_manager: &WriteBufferManager) {
        unsafe {
            ffi::rocksdb_options_set_write_buffer_manager(
                self.inner,
                write_buffer_manager.0.inner.as_ptr(),
            );
        }
        self.outlive.write_buffer_manager = Some(write_buffer_manager.clone());
    }

    /// Sets an `SstFileManager` for this `Options`.
    ///
    /// SstFileManager tracks and controls total SST file space usage, enabling
    /// applications to cap disk utilization and throttle deletions.
    pub fn set_sst_file_manager(&mut self, sst_file_manager: &SstFileManager) {
        unsafe {
            ffi::rocksdb_options_set_sst_file_manager(
                self.inner,
                sst_file_manager.0.inner.as_ptr(),
            );
        }
        self.outlive.sst_file_manager = Some(sst_file_manager.clone());
    }

    /// If true, working thread may avoid doing unnecessary and long-latency
    /// operation (such as deleting obsolete files directly or deleting memtable)
    /// and will instead schedule a background job to do it.
    ///
    /// Use it if you're latency-sensitive.
    ///
    /// Default: false (disabled)
    pub fn set_avoid_unnecessary_blocking_io(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_avoid_unnecessary_blocking_io(self.inner, u8::from(val));
        }
    }

    /// Activates the experimental Mempurge memtable garbage collection feature.
    ///
    /// See the upstream RocksDB option documentation:
    /// <https://github.com/facebook/rocksdb/blob/v10.7.5/include/rocksdb/advanced_options.h#L259-L274>
    ///
    /// At every flush, RocksDB estimates the useful payload ratio of the memtable
    /// and compares it with this threshold. If the ratio is below the threshold,
    /// RocksDB replaces the regular flush with a mempurge operation.
    ///
    /// Threshold values:
    ///
    /// * `0.0`: mempurge deactivated.
    /// * `1.0`: recommended threshold value.
    /// * `> 1.0`: aggressive mempurge.
    /// * `0.0 < threshold < 1.0`: mempurge only for very low useful payload ratios.
    ///
    /// Default: 0.0
    pub fn set_experimental_mempurge_threshold(&mut self, threshold: f64) {
        unsafe {
            ffi::rocksdb_options_set_experimental_mempurge_threshold(self.inner, threshold);
        }
    }

    /// Sets the compaction priority.
    ///
    /// If level compaction_style =
    /// kCompactionStyleLevel, for each level, which files are prioritized to be
    /// picked to compact.
    ///
    /// Default: `DBCompactionPri::MinOverlappingRatio`
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::{Options, DBCompactionPri};
    ///
    /// let mut opts = Options::default();
    /// opts.set_compaction_pri(DBCompactionPri::RoundRobin);
    /// ```
    pub fn set_compaction_pri(&mut self, pri: DBCompactionPri) {
        unsafe {
            ffi::rocksdb_options_set_compaction_pri(self.inner, pri as c_int);
        }
    }

    /// The file pick order set by [`Self::set_compaction_pri`].
    ///
    /// [`DBCompactionPri`] covers every value RocksDB defines today, so `None` only shows up
    /// if a future release adds one.
    pub fn get_compaction_pri(&self) -> Option<DBCompactionPri> {
        let raw = unsafe { ffi::rocksdb_options_get_compaction_pri(self.inner) };
        DBCompactionPri::try_from_raw(raw)
    }

    /// If true, the log numbers and sizes of the synced WALs are tracked
    /// in MANIFEST. During DB recovery, if a synced WAL is missing
    /// from disk, or the WAL's size does not match the recorded size in
    /// MANIFEST, an error will be reported and the recovery will be aborted.
    ///
    /// This is one additional protection against WAL corruption besides the
    /// per-WAL-entry checksum.
    ///
    /// Note that this option does not work with secondary instance.
    /// Currently, only syncing closed WALs are tracked. Calling `DB::SyncWAL()`,
    /// etc. or writing with `WriteOptions::sync=true` to sync the live WAL is not
    /// tracked for performance/efficiency reasons.
    ///
    /// See: <https://github.com/facebook/rocksdb/wiki/Track-WAL-in-MANIFEST>
    ///
    /// Default: false (disabled)
    pub fn set_track_and_verify_wals_in_manifest(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_track_and_verify_wals_in_manifest(self.inner, u8::from(val));
        }
    }

    /// Returns the value of the `track_and_verify_wals_in_manifest` option.
    pub fn get_track_and_verify_wals_in_manifest(&self) -> bool {
        let val_u8 =
            unsafe { ffi::rocksdb_options_get_track_and_verify_wals_in_manifest(self.inner) };
        val_u8 != 0
    }

    /// The DB unique ID can be saved in the DB manifest (preferred, this option)
    /// or an IDENTITY file (historical, deprecated), or both. If this option is
    /// set to false (old behavior), then `write_identity_file` must be set to true.
    /// The manifest is preferred because
    ///
    /// 1. The IDENTITY file is not checksummed, so it is not as safe against
    ///    corruption.
    /// 2. The IDENTITY file may or may not be copied with the DB (e.g. not
    ///    copied by BackupEngine), so is not reliable for the provenance of a DB.
    ///
    /// This option might eventually be obsolete and removed as Identity files
    /// are phased out.
    ///
    /// Default: true (enabled)
    pub fn set_write_dbid_to_manifest(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_write_dbid_to_manifest(self.inner, u8::from(val));
        }
    }

    /// Returns the value of the `write_dbid_to_manifest` option.
    pub fn get_write_dbid_to_manifest(&self) -> bool {
        let val_u8 = unsafe { ffi::rocksdb_options_get_write_dbid_to_manifest(self.inner) };
        val_u8 != 0
    }

    /// Sets the logger to use.
    ///
    /// By default `rocksdb` writes its internal logs to a file in the database
    /// directory; this can be changed to a custom callback with the
    /// [`InfoLogger::new_callback_logger`] constructor.
    pub fn set_info_logger(&mut self, mut logger: InfoLogger) {
        // Move the callback so it can be shared across database instances
        self.outlive.logger_callback = logger.callback.take();
        unsafe {
            ffi::rocksdb_options_set_info_log(self.inner, logger.inner);
        }
    }

    /// Returns a reference to the currently configured logger.
    pub fn get_info_logger(&self) -> InfoLogger {
        let raw = unsafe { ffi::rocksdb_options_get_info_log(self.inner) };
        InfoLogger {
            inner: raw,
            callback: self.outlive.logger_callback.clone(),
        }
    }

    /// Sets the `add` option.
    pub fn set_add(&mut self, val: c_int) {
        unsafe {
            ffi::rocksdb_options_calculate_sst_write_lifetime_hint_set_add(self.inner, val);
        }
    }

    /// Empties the set of compaction styles that get SST write lifetime hints.
    ///
    /// The hints tell the filesystem how long a file is expected to live, which cuts write
    /// amplification from OS level garbage collection and SSD wear levelling. RocksDB derives
    /// them from the output level alone, so a workload whose data lifetime varies a lot
    /// inside one level can end up worse off. Clearing the set is the documented way to turn
    /// the feature off. The default set holds level compaction only.
    ///
    /// Entries go in through [`Self::set_add`] and come back out through
    /// [`Self::set_remove`], both of which take the raw `rocksdb::CompactionStyle` value.
    pub fn clear_calculate_sst_write_lifetime_hint_set(&mut self) {
        unsafe {
            ffi::rocksdb_options_calculate_sst_write_lifetime_hint_set_clear(self.inner);
        }
    }

    /// Whether `style` is in the set of compaction styles that get SST write lifetime hints.
    ///
    /// Only level and universal compaction do anything with the hints, even when another
    /// style is in the set. See [`Self::clear_calculate_sst_write_lifetime_hint_set`].
    pub fn calculate_sst_write_lifetime_hint_set_contains(&self, style: DBCompactionStyle) -> bool {
        unsafe {
            ffi::rocksdb_options_calculate_sst_write_lifetime_hint_set_contains(
                self.inner,
                style as c_int,
            ) != 0
        }
    }

    /// How many compaction styles are in the SST write lifetime hint set.
    ///
    /// See [`Self::clear_calculate_sst_write_lifetime_hint_set`].
    pub fn calculate_sst_write_lifetime_hint_set_count(&self) -> usize {
        unsafe { ffi::rocksdb_options_calculate_sst_write_lifetime_hint_set_count(self.inner) }
    }

    /// if set to false then recovery will fail when a prepared transaction is encountered in
    /// the WAL
    pub fn set_allow_2pc(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_allow_2pc(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `allow_2pc` option.
    pub fn get_allow_2pc(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_allow_2pc(self.inner) != 0 }
    }

    /// It allows user to opt-in to get error messages containing corrupted keys/values.
    /// Corrupt keys, values will be logged in the messages/logs/status that will help users
    /// with the useful information regarding affected data. By default value is set false to
    /// prevent users data to be exposed in the logs/messages etc.
    ///
    /// Default: false
    pub fn set_allow_data_in_errors(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_allow_data_in_errors(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `allow_data_in_errors` option.
    pub fn get_allow_data_in_errors(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_allow_data_in_errors(self.inner) != 0 }
    }

    /// If false, fallocate() calls are bypassed, which disables file preallocation. The file
    /// space preallocation is used to increase the file write/append performance. By default,
    /// RocksDB preallocates space for WAL, SST, Manifest files, the extra space is truncated
    /// when the file is written. Warning: if you're using btrfs, we would recommend setting
    /// `allow_fallocate=false` to disable preallocation. As on btrfs, the extra allocated
    /// space cannot be freed, which could be significant if you have lots of files. More
    /// details about this limitation:
    /// <https://github.com/btrfs/btrfs-dev-docs/blob/471c5699336e043114d4bca02adcd57d9dab9c44/data-extent-reference-counts.md>
    pub fn set_allow_fallocate(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_allow_fallocate(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `allow_fallocate` option.
    pub fn get_allow_fallocate(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_allow_fallocate(self.inner) != 0 }
    }

    /// EXPERIMENTAL: If true, RocksDB asynchronously precreates the next WAL file so
    /// foreground memtable switching can usually avoid the filesystem latency of creating a
    /// new WAL. The precreated file is only reserved empty storage; it does not become a
    /// logical WAL and is not added to WAL tracking until it is consumed by a foreground WAL
    /// rotation.
    ///
    /// The option is sanitized to false when recycle_log_file_num is non-zero.
    ///
    /// Default: false
    pub fn set_async_wal_precreate(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_async_wal_precreate(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `async_wal_precreate` option.
    pub fn get_async_wal_precreate(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_async_wal_precreate(self.inner) != 0 }
    }

    /// By default RocksDB replay WAL logs and flush them on DB open, which may create very
    /// small SST files. If this option is enabled, RocksDB will try to avoid (but not
    /// guarantee not to) flush during recovery. Also, existing WAL logs will be kept, so that
    /// if crash happened before flush, we still have logs to recover from.
    ///
    /// Note: when `enforce_write_buffer_manager_during_recovery` is also enabled, flushes may
    /// still occur during recovery to respect the WriteBufferManager's global memory limit,
    /// even if this option is true. Once any such WBM-triggered flush happens, all remaining
    /// memtables will also be flushed at the end of recovery (similar to the behavior when
    /// this option is false).
    ///
    /// DEFAULT: false
    pub fn set_avoid_flush_during_recovery(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_avoid_flush_during_recovery(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `avoid_flush_during_recovery` option.
    pub fn get_avoid_flush_during_recovery(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_avoid_flush_during_recovery(self.inner) != 0 }
    }

    /// By default RocksDB will flush all memtables on DB close if there are unpersisted data
    /// (i.e. with WAL disabled) The flush can be skip to speedup DB close. Unpersisted data
    /// WILL BE LOST.
    ///
    /// DEFAULT: false
    ///
    /// Dynamically changeable through SetDBOptions() API.
    pub fn set_avoid_flush_during_shutdown(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_avoid_flush_during_shutdown(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `avoid_flush_during_shutdown` option.
    pub fn get_avoid_flush_during_shutdown(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_avoid_flush_during_shutdown(self.inner) != 0 }
    }

    /// Set to true to re-instate an old behavior of keeping complete, synced WAL files open
    /// for write until they are collected for deletion by a background thread. This should
    /// not be needed unless there is a performance issue with file Close(), but setting it to
    /// true means that Checkpoint might call LinkFile on a WAL still open for write, which
    /// might be unsupported on some FileSystem implementations. As this is intended as a
    /// temporary kill switch, it is already DEPRECATED.
    pub fn set_background_close_inactive_wals(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_background_close_inactive_wals(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `background_close_inactive_wals` option.
    pub fn get_background_close_inactive_wals(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_background_close_inactive_wals(self.inner) != 0 }
    }

    /// By default, RocksDB will attempt to detect any data losses or corruptions in DB files
    /// and return an error to the user, either at DB::Open time or later during DB operation.
    /// The exception to this policy is the WAL file, whose recovery is controlled by the
    /// wal_recovery_mode option.
    ///
    /// Best-efforts recovery (this option set to true) signals a preference for opening the
    /// DB to any point-in-time valid state for each column family, including the empty/new
    /// state, versus the default of returning non-WAL data losses to the user as errors. In
    /// terms of RocksDB user data, this is like applying
    /// WALRecoveryMode::kPointInTimeRecovery to each column family rather than just the WAL.
    ///
    /// The behavior changes in the presence of "AtomicGroup"s in the MANIFEST, which is
    /// currently only the case when `atomic_flush == true`. In that case, all pre-existing
    /// CFs must recover the atomic group in order for that group to be applied in an
    /// all-or-nothing manner. This means that unused/inactive CF(s) with invalid filesystem
    /// state can block recovery of all other CFs at an atomic group.
    ///
    /// Best-efforts recovery (BER) is specifically designed to recover a DB with files that
    /// are missing or truncated to some smaller size, such as the result of an incomplete DB
    /// "physical" (FileSystem) copy. BER can also detect when an SST file has been replaced
    /// with a different one of the same size (assuming SST unique IDs are tracked in DB
    /// manifest). BER is not yet designed to produce a usable DB from other corruptions to DB
    /// files (which should generally be detectable by DB::VerifyChecksum()), and BER does not
    /// yet attempt to recover any WAL files.
    ///
    /// For example, if an SST or blob file referenced by the MANIFEST is missing, BER might
    /// be able to find a set of files corresponding to an old "point in time" version of the
    /// column family, possibly from an older MANIFEST file. Besides complete "point in time"
    /// version, an incomplete version with only a suffix of L0 files missing can also be
    /// recovered to if the versioning history doesn't include an atomic flush.  From the
    /// users' perspective, missing a suffix of L0 files means missing the user's most
    /// recently written data. So the remaining available files still presents a valid point
    /// in time view, although for some previous time. It's not done for atomic flush because
    /// that guarantees a consistent view across column families. We cannot guarantee that if
    /// recovering an incomplete version. Some other kinds of DB files (e.g. CURRENT, LOCK,
    /// IDENTITY) are either ignored or replaced with BER, or quietly fixed regardless of BER
    /// setting. BER does require at least one valid MANIFEST to recover to a non-trivial DB
    /// state, unlike `ldb repair`.
    ///
    /// Default: false
    pub fn set_best_efforts_recovery(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_best_efforts_recovery(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `best_efforts_recovery` option.
    pub fn get_best_efforts_recovery(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_best_efforts_recovery(self.inner) != 0 }
    }

    /// If max_bgerror_resume_count is >= 2, db resume is called multiple times. This option
    /// decides how long to wait to retry the next resume if the previous resume fails and
    /// satisfy redo resume conditions.
    ///
    /// Default: 1000000 (microseconds).
    pub fn set_bgerror_resume_retry_interval(&mut self, val: u64) {
        unsafe {
            ffi::rocksdb_options_set_bgerror_resume_retry_interval(self.inner, val);
        }
    }

    /// Returns the value of the `bgerror_resume_retry_interval` option.
    pub fn get_bgerror_resume_retry_interval(&self) -> u64 {
        unsafe { ffi::rocksdb_options_get_bgerror_resume_retry_interval(self.inner) }
    }

    /// Number of direct-write blob partitions for this column family. Requires
    /// enable_blob_direct_write = true.
    ///
    /// If blob_direct_write_partition_strategy is null, partition selection uses the default
    /// round-robin strategy.
    ///
    /// Default: 1
    ///
    /// Not dynamically changeable through the SetOptions() API.
    pub fn set_blob_direct_write_partitions(&mut self, val: u32) {
        unsafe {
            ffi::rocksdb_options_set_blob_direct_write_partitions(self.inner, val);
        }
    }

    /// Returns the value of the `blob_direct_write_partitions` option.
    pub fn get_blob_direct_write_partitions(&self) -> u32 {
        unsafe { ffi::rocksdb_options_get_blob_direct_write_partitions(self.inner) }
    }

    /// Enable/disable per key-value checksum protection for in memory blocks.
    ///
    /// Checksum is constructed when a block is loaded into memory and verification is done
    /// for each key read from the block. This is useful for detecting in-memory data
    /// corruption. Note that this feature has a non-trivial negative impact on read
    /// performance. Different values of the option have similar performance impact, but
    /// different memory cost and corruption detection probability (e.g. 1 byte gives 255/256
    /// chance for detecting a corruption).
    ///
    /// Default: 0 (no protection) Supported values: 0, 1, 2, 4, 8. Dynamically changeable
    /// through the SetOptions() API.
    pub fn set_block_protection_bytes_per_key(&mut self, val: u8) {
        unsafe {
            ffi::rocksdb_options_set_block_protection_bytes_per_key(self.inner, val);
        }
    }

    /// Returns the value of the `block_protection_bytes_per_key` option.
    pub fn get_block_protection_bytes_per_key(&self) -> u8 {
        unsafe { ffi::rocksdb_options_get_block_protection_bytes_per_key(self.inner) }
    }

    /// For leveled compaction, RocksDB may compact a file at the bottommost level if it can
    /// compact away data that were protected by some snapshot. The compaction reason in LOG
    /// for this kind of compactions is "BottommostFiles". Usually such compaction can happen
    /// as soon as a relevant snapshot is released. This option allows user to delay such
    /// compactions. A file is qualified for "BottommostFiles" compaction if it is at least
    /// "bottommost_file_compaction_delay" seconds old.
    ///
    /// Default: 0 (no delay) Dynamically changeable through the SetOptions() API.
    pub fn set_bottommost_file_compaction_delay(&mut self, val: u32) {
        unsafe {
            ffi::rocksdb_options_set_bottommost_file_compaction_delay(self.inner, val);
        }
    }

    /// Returns the value of the `bottommost_file_compaction_delay` option.
    pub fn get_bottommost_file_compaction_delay(&self) -> u32 {
        unsafe { ffi::rocksdb_options_get_bottommost_file_compaction_delay(self.inner) }
    }

    /// If either DBOptions::allow_ingest_behind or this option is set to true, this column
    /// family will prepare for ingesting files to the last level (IngestExternalFiles() with
    /// ingest_behind=true). Users should set only this option since
    /// DBOptions::allow_ingest_behind is deprecated.
    ///
    /// Specifically, preparing a column family for ingesting files to the last level has the
    /// following effects:
    /// - Disables some internal optimizations around SST file compression.
    /// - Reserves the last level for ingested files only.
    /// - Compaction will not include any file from the last level.
    /// - Compaction will preserve necessary tombstones that can apply on top of ingested
    ///   files.
    ///
    /// Note that only Universal Compaction supports cf_allow_ingest_behind. `num_levels`
    /// should be >= 3 if this option is turned on.
    ///
    /// Note that this option needs to be set to true before any write to the CF. It's
    /// recommended to set the option to true since CF creation. Otherwise, ingestion with
    /// ingest_behind = true might fail. Once file ingestions are done, the option should be
    /// flipped to false. Flipping this option to false allows the CF to disable the behavior
    /// changes detailed above and resume more efficient operation.
    ///
    /// Default: false Immutable.
    pub fn set_cf_allow_ingest_behind(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_cf_allow_ingest_behind(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `cf_allow_ingest_behind` option.
    pub fn get_cf_allow_ingest_behind(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_cf_allow_ingest_behind(self.inner) != 0 }
    }

    /// Turns on checksum handoff for `file_type`, so RocksDB passes the crc32c it already
    /// computed down to the `FileSystem` instead of relying on the storage layer to protect
    /// the write on its own.
    ///
    /// Only enable this for a `FileSystem` that verifies crc32c. RocksDB generates nothing
    /// else, so a filesystem expecting a different checksum will reject the writes.
    ///
    /// RocksDB honours the set for [`FileType::WalFile`], [`FileType::TableFile`], and
    /// [`FileType::DescriptorFile`]. Other types can be added but are never consulted.
    /// [`FileType::CompactionProgressFile`] and [`FileType::Unknown`] fall outside the range
    /// RocksDB's file type set can hold and are ignored.
    ///
    /// Default: empty.
    pub fn add_checksum_handoff_file_type(&mut self, file_type: FileType) {
        let Some(raw) = checksum_handoff_file_type_raw(file_type) else {
            return;
        };
        unsafe {
            ffi::rocksdb_options_checksum_handoff_file_types_add(self.inner, raw);
        }
    }

    /// Turns checksum handoff back off for `file_type`.
    ///
    /// Removing a type that is not in the set does nothing. See
    /// [`Self::add_checksum_handoff_file_type`].
    pub fn remove_checksum_handoff_file_type(&mut self, file_type: FileType) {
        let Some(raw) = checksum_handoff_file_type_raw(file_type) else {
            return;
        };
        unsafe {
            ffi::rocksdb_options_checksum_handoff_file_types_remove(self.inner, raw);
        }
    }

    /// Turns checksum handoff off for every file type.
    ///
    /// See [`Self::add_checksum_handoff_file_type`].
    pub fn clear_checksum_handoff_file_types(&mut self) {
        unsafe {
            ffi::rocksdb_options_checksum_handoff_file_types_clear(self.inner);
        }
    }

    /// Whether checksum handoff is on for `file_type`.
    ///
    /// Always false for the two types the set cannot hold, see
    /// [`Self::add_checksum_handoff_file_type`].
    pub fn contains_checksum_handoff_file_type(&self, file_type: FileType) -> bool {
        let Some(raw) = checksum_handoff_file_type_raw(file_type) else {
            return false;
        };
        unsafe { ffi::rocksdb_options_checksum_handoff_file_types_contains(self.inner, raw) != 0 }
    }

    /// How many file types have checksum handoff turned on.
    ///
    /// See [`Self::add_checksum_handoff_file_type`].
    pub fn checksum_handoff_file_type_count(&self) -> usize {
        unsafe { ffi::rocksdb_options_checksum_handoff_file_types_count(self.inner) }
    }

    /// DEPRECATED: This option might be removed in a future release.
    ///
    /// If true, during compaction, RocksDB will count the number of entries read and compare
    /// it against the number of entries in the compaction input files. This is intended to
    /// add protection against corruption during compaction. Note that
    /// - this verification is not done for compactions during which a compaction filter
    ///   returns kRemoveAndSkipUntil, and
    /// - the number of range deletions is not verified.
    ///
    /// The option is here to turn the feature off in case this new validation feature has a
    /// bug. The option may be removed in the future once the feature is stable.
    ///
    /// Default: true
    pub fn set_compaction_verify_record_count(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_compaction_verify_record_count(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `compaction_verify_record_count` option.
    pub fn get_compaction_verify_record_count(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_compaction_verify_record_count(self.inner) != 0 }
    }

    /// Declares a daily window of low read and write activity, in UTC, so RocksDB can pull
    /// low priority work such as TTL compaction into it instead of letting it land in the
    /// middle of a busy period.
    ///
    /// The format is `HH:mm-HH:mm`, inclusive on both ends, with hours in `00` to `23` and
    /// minutes in `00` to `59`. A start later than the end wraps past midnight, so
    /// `23:30-04:00` is a valid overnight window. `0:00-23:59` marks the whole day off-peak,
    /// and an empty string, the default, means there is no off-peak period.
    ///
    /// A string that does not parse is not reported here. RocksDB rejects it when the DB is
    /// opened, and `SetDBOptions` rejects it at runtime.
    ///
    /// # Errors
    ///
    /// Returns an error if `v` contains an interior NUL byte.
    pub fn set_daily_offpeak_time_utc(&mut self, v: impl CStrLike) -> Result<(), Error> {
        let v = v
            .bake()
            .map_err(|e| Error::new(format!("daily offpeak time must not contain NUL: {e}")))?;
        unsafe {
            ffi::rocksdb_options_set_daily_offpeak_time_utc(self.inner, v.as_ptr());
        }
        Ok(())
    }

    /// The off-peak window set by [`Self::set_daily_offpeak_time_utc`], empty when there is
    /// none.
    pub fn get_daily_offpeak_time_utc(&self) -> String {
        let mut len: size_t = 0;
        let window =
            unsafe { ffi::rocksdb_options_get_daily_offpeak_time_utc(self.inner, &raw mut len) };
        unsafe { borrowed_string(window, len) }
    }

    /// Names the machine hosting the DB. RocksDB writes it as a property into every SST file
    /// it produces, including files from `SstFileWriter` and `RepairDB`.
    ///
    /// It exists to trace memory corruption back to the host that wrote the file. Corruption
    /// that happens before RocksDB checksums the data is invisible to the checksum, so the
    /// host id is the only thing left pointing at the culprit.
    ///
    /// RocksDB substitutes the real hostname when this is left at its default. Setting it to
    /// an empty string leaves the property out of the SST file entirely.
    ///
    /// # Errors
    ///
    /// Returns an error if `v` contains an interior NUL byte.
    pub fn set_db_host_id(&mut self, v: impl CStrLike) -> Result<(), Error> {
        let v = v
            .bake()
            .map_err(|e| Error::new(format!("db host id must not contain NUL: {e}")))?;
        unsafe {
            ffi::rocksdb_options_set_db_host_id(self.inner, v.as_ptr());
        }
        Ok(())
    }

    /// The host id set by [`Self::set_db_host_id`].
    ///
    /// An untouched `Options` returns the `__hostname__` placeholder rather than the real
    /// hostname, because RocksDB only resolves it while writing a file.
    pub fn get_db_host_id(&self) -> String {
        let mut len: size_t = 0;
        let host_id = unsafe { ffi::rocksdb_options_get_db_host_id(self.inner, &raw mut len) };
        unsafe { borrowed_string(host_id, len) }
    }

    /// EXPERIMENTAL When this field is set, all SST files without an explicitly set
    /// temperature will be treated as if they have this temperature for file reading
    /// accounting purpose, such as io statistics, io perf context.
    ///
    /// Not dynamically changeable; change requires DB restart.
    pub fn set_default_temperature(&mut self, val: c_int) {
        unsafe {
            ffi::rocksdb_options_set_default_temperature(self.inner, val);
        }
    }

    /// Returns the value of the `default_temperature` option.
    pub fn get_default_temperature(&self) -> c_int {
        unsafe { ffi::rocksdb_options_get_default_temperature(self.inner) }
    }

    /// EXPERIMENTAL When no other option such as last_level_temperature determines the
    /// temperature of a new SST file, it will be written with this temperature, which can be
    /// set differently for each column family.
    ///
    /// Dynamically changeable through the SetOptions() API
    pub fn set_default_write_temperature(&mut self, val: c_int) {
        unsafe {
            ffi::rocksdb_options_set_default_write_temperature(self.inner, val);
        }
    }

    /// Returns the value of the `default_write_temperature` option.
    pub fn get_default_write_temperature(&self) -> c_int {
        unsafe { ffi::rocksdb_options_get_default_write_temperature(self.inner) }
    }

    /// The limited write rate to DB if soft_pending_compaction_bytes_limit or
    /// level0_slowdown_writes_trigger is triggered, or we are writing to the last mem table
    /// allowed and we allow more than 3 mem tables. It is calculated using size of user write
    /// requests before compression. RocksDB may decide to slow down more if the compaction
    /// still gets behind further. If the value is 0, we will infer a value from
    /// `rater_limiter` value if it is not empty, or 16MB if `rater_limiter` is empty. Note
    /// that if users change the rate in `rate_limiter` after DB is opened,
    /// `delayed_write_rate` won't be adjusted.
    ///
    /// Unit: byte per second.
    ///
    /// Default: 0
    ///
    /// Dynamically changeable through SetDBOptions() API.
    pub fn set_delayed_write_rate(&mut self, val: u64) {
        unsafe {
            ffi::rocksdb_options_set_delayed_write_rate(self.inner, val);
        }
    }

    /// Returns the value of the `delayed_write_rate` option.
    pub fn get_delayed_write_rate(&self) -> u64 {
        unsafe { ffi::rocksdb_options_get_delayed_write_rate(self.inner) }
    }

    /// Setting this option to true disallows ordinary writes to the column family and it can
    /// only be populated through import and ingestion. It is intended to protect "ingestion
    /// only" column families. This option is not currently supported on the default column
    /// family because of error handling challenges analogous to
    /// <https://github.com/facebook/rocksdb/issues/13429>
    ///
    /// This option is not mutable with SetOptions(). It can be changed between DB::Open()
    /// calls, but open will fail if recovering WAL writes to a CF with this option set.
    pub fn set_disallow_memtable_writes(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_disallow_memtable_writes(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `disallow_memtable_writes` option.
    pub fn get_disallow_memtable_writes(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_disallow_memtable_writes(self.inner) != 0 }
    }

    /// If true, then print malloc stats together with rocksdb.stats when printing to LOG.
    /// DEFAULT: false
    pub fn get_dump_malloc_stats(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_dump_malloc_stats(self.inner) != 0 }
    }

    /// When enabled, values >= min_blob_size are written directly to blob files during the
    /// write path and replaced in WAL and memtable with BlobIndex references.
    ///
    /// Requires enable_blob_files = true. Experimental reduced-scope v1 restrictions. These
    /// limitations keep the v1 implementation intentionally small; follow-up PRs are expected
    /// to improve feature compatibility over time:
    /// - only supports the ordered single-memtable-writer path; unordered, pipelined,
    ///   two_write_queues, and allow_concurrent_memtable_write are not supported.
    /// - crash recovery only supports blob files that were already made manifest-visible by
    ///   flush/SST creation; WAL replay of active direct-write blob files is not currently
    ///   supported.
    /// - checkpoint/backup/live-files enumeration must flush pending direct-write state
    ///   first; APIs that intentionally skip the flush, or run while WAL is locked, can
    ///   return NotSupported.
    /// - not compatible with MemPurge or user-defined timestamps.
    /// - DB::IngestWriteBatchWithIndex() is not supported while any live column family
    ///   enables this option.
    /// - read-only and secondary opens can read flushed/manifest-visible blob files, but do
    ///   not resolve still-active direct-write blob files.
    ///
    /// Default: false
    ///
    /// Not dynamically changeable through the SetOptions() API.
    pub fn set_enable_blob_direct_write(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_enable_blob_direct_write(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `enable_blob_direct_write` option.
    pub fn get_enable_blob_direct_write(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_enable_blob_direct_write(self.inner) != 0 }
    }

    /// If true, then the status of the threads involved in this DB will be tracked and
    /// available via GetThreadList() API.
    ///
    /// Default: false
    pub fn set_enable_thread_tracking(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_enable_thread_tracking(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `enable_thread_tracking` option.
    pub fn get_enable_thread_tracking(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_enable_thread_tracking(self.inner) != 0 }
    }

    /// DEPRECATED: This option might be removed in a future release.
    ///
    /// If set to false, when compaction or flush sees a SingleDelete followed by a Delete for
    /// the same user key, compaction job will not fail. Otherwise, compaction job will fail.
    /// This is a temporary option to help existing use cases migrate, and will be removed in
    /// a future release. Warning: do not set to false unless you are trying to migrate
    /// existing data in which the contract of single delete
    /// (<https://github.com/facebook/rocksdb/wiki/Single-Delete>) is not enforced, thus has
    /// Delete mixed with SingleDelete for the same user key. Violation of the contract leads
    /// to undefined behaviors with high possibility of data inconsistency, e.g. deleted old
    /// data become visible again, etc.
    pub fn set_enforce_single_del_contracts(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_enforce_single_del_contracts(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `enforce_single_del_contracts` option.
    pub fn get_enforce_single_del_contracts(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_enforce_single_del_contracts(self.inner) != 0 }
    }

    /// If true and a WriteBufferManager is configured, RocksDB will check
    /// WriteBufferManager::ShouldFlush() during WAL recovery and schedule flushes when
    /// needed. This prevents OOM when multiple RocksDB instances share a WriteBufferManager
    /// and one instance is recovering from WAL.
    ///
    /// When triggered, all column families with non-empty memtables are scheduled for flush,
    /// which may produce smaller L0 files in some column families. This also overrides
    /// `avoid_flush_during_recovery`: once a WBM-triggered flush occurs mid-recovery, all
    /// remaining non-empty memtables will be flushed at the end of recovery as well.
    ///
    /// DEFAULT: true
    pub fn set_enforce_write_buffer_manager_during_recovery(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_enforce_write_buffer_manager_during_recovery(
                self.inner,
                c_uchar::from(val),
            );
        }
    }

    /// Returns the value of the `enforce_write_buffer_manager_during_recovery` option.
    pub fn get_enforce_write_buffer_manager_during_recovery(&self) -> bool {
        unsafe {
            ffi::rocksdb_options_get_enforce_write_buffer_manager_during_recovery(self.inner) != 0
        }
    }

    /// EXPERIMENTAL When this is true, save file system metadata (if supported by the FS) for
    /// SST files added to the DB in the MANIFEST, and use it to accelerate re-opening of
    /// those files on DB open. This will help cut down DB open latency on remote storage
    /// systems.
    pub fn set_fast_sst_open(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_fast_sst_open(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `fast_sst_open` option.
    pub fn get_fast_sst_open(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_fast_sst_open(self.inner) != 0 }
    }

    /// DEPRECATED: This option might be removed in a future release.
    ///
    /// If true, during memtable flush, RocksDB will validate total entries read in flush,
    /// total entries written in the SST and compare them with counter of keys added.
    ///
    /// The option is here to turn the feature off in case this new validation feature has a
    /// bug. The option may be removed in the future once the feature is stable.
    ///
    /// Default: true
    pub fn set_flush_verify_memtable_count(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_flush_verify_memtable_count(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `flush_verify_memtable_count` option.
    pub fn get_flush_verify_memtable_count(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_flush_verify_memtable_count(self.inner) != 0 }
    }

    /// For a given catch up attempt, this option specifies the number of times to tail the
    /// MANIFEST and try to install a new, consistent  version before giving up. Though it
    /// should be extremely rare, the catch up may fail if the leader is mutating the LSM at a
    /// very high rate and the follower is unable to get a consistent view. Default to 10
    /// attempts
    pub fn set_follower_catchup_retry_count(&mut self, val: u64) {
        unsafe {
            ffi::rocksdb_options_set_follower_catchup_retry_count(self.inner, val);
        }
    }

    /// Returns the value of the `follower_catchup_retry_count` option.
    pub fn get_follower_catchup_retry_count(&self) -> u64 {
        unsafe { ffi::rocksdb_options_get_follower_catchup_retry_count(self.inner) }
    }

    /// Time to wait between consecutive catch up attempts Default 100ms
    pub fn set_follower_catchup_retry_wait_ms(&mut self, val: u64) {
        unsafe {
            ffi::rocksdb_options_set_follower_catchup_retry_wait_ms(self.inner, val);
        }
    }

    /// Returns the value of the `follower_catchup_retry_wait_ms` option.
    pub fn get_follower_catchup_retry_wait_ms(&self) -> u64 {
        unsafe { ffi::rocksdb_options_get_follower_catchup_retry_wait_ms(self.inner) }
    }

    /// When a RocksDB database is opened in follower mode, this option is set by the user to
    /// request the frequency of the follower attempting to refresh its view of the leader.
    /// RocksDB may choose to trigger catch ups more frequently if it detects any changes in
    /// the database state. Default every 10s.
    pub fn set_follower_refresh_catchup_period_ms(&mut self, val: u64) {
        unsafe {
            ffi::rocksdb_options_set_follower_refresh_catchup_period_ms(self.inner, val);
        }
    }

    /// Returns the value of the `follower_refresh_catchup_period_ms` option.
    pub fn get_follower_refresh_catchup_period_ms(&self) -> u64 {
        unsafe { ffi::rocksdb_options_get_follower_refresh_catchup_period_ms(self.inner) }
    }

    /// In debug mode, RocksDB runs consistency checks on the LSM every time the LSM changes
    /// (Flush, Compaction, AddFile). When this option is true, these checks are also enabled
    /// in release mode. These checks were historically disabled in release mode, but are now
    /// enabled by default for proactive corruption detection. The CPU overhead is negligible
    /// for normal mixed operations but can slow down saturated writing. See
    /// Options::DisableExtraChecks(). Default: true
    pub fn set_force_consistency_checks(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_force_consistency_checks(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `force_consistency_checks` option.
    pub fn get_force_consistency_checks(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_force_consistency_checks(self.inner) != 0 }
    }

    /// EXPERIMENTAL If this option is set, when creating the last level files, pass this
    /// temperature to FileSystem used. Should be no-op for default FileSystem and users need
    /// to plug in their own FileSystem to take advantage of it. Currently only compatible
    /// with universal compaction.
    ///
    /// Dynamically changeable through the SetOptions() API
    pub fn set_last_level_temperature(&mut self, val: c_int) {
        unsafe {
            ffi::rocksdb_options_set_last_level_temperature(self.inner, val);
        }
    }

    /// Returns the value of the `last_level_temperature` option.
    pub fn get_last_level_temperature(&self) -> c_int {
        unsafe { ffi::rocksdb_options_get_last_level_temperature(self.inner) }
    }

    /// The number of bytes to prefetch when reading the DB manifest and WAL files during
    /// DB::Open (and variants). This is mostly useful for reading a remotely located log, as
    /// it can save the number of round-trips. If 0, then the prefetching is disabled.
    ///
    /// Default: 0
    pub fn set_log_readahead_size(&mut self, val: usize) {
        unsafe {
            ffi::rocksdb_options_set_log_readahead_size(self.inner, val);
        }
    }

    /// Returns the value of the `log_readahead_size` option.
    pub fn get_log_readahead_size(&self) -> usize {
        unsafe { ffi::rocksdb_options_get_log_readahead_size(self.inner) }
    }

    /// It indicates, which lowest cache tier we want to use for a certain DB. Currently we
    /// support volatile_tier and non_volatile_tier. They are layered. By setting it to
    /// kVolatileTier, only the block cache (current implemented volatile_tier) is used. So
    /// cache entries will not spill to secondary cache (current implemented
    /// non_volatile_tier), and block cache lookup misses will not lookup in the secondary
    /// cache. When kNonVolatileBlockTier is used, we use both block cache and secondary
    /// cache.
    ///
    /// Default: kNonVolatileBlockTier
    pub fn set_lowest_used_cache_tier(&mut self, val: c_int) {
        unsafe {
            ffi::rocksdb_options_set_lowest_used_cache_tier(self.inner, val);
        }
    }

    /// Returns the value of the `lowest_used_cache_tier` option.
    pub fn get_lowest_used_cache_tier(&self) -> c_int {
        unsafe { ffi::rocksdb_options_get_lowest_used_cache_tier(self.inner) }
    }

    /// It defines how many times DB::Resume() is called by a separate thread when background
    /// retryable IO Error happens. When background retryable IO Error happens, SetBGError is
    /// called to deal with the error. If the error can be auto-recovered (e.g., retryable IO
    /// Error during Flush or WAL write), then db resume is called in background to recover
    /// from the error. If this value is 0 or negative, DB::Resume() will not be called
    /// automatically.
    ///
    /// Default: INT_MAX
    pub fn set_max_bgerror_resume_count(&mut self, val: c_int) {
        unsafe {
            ffi::rocksdb_options_set_max_bgerror_resume_count(self.inner, val);
        }
    }

    /// Returns the value of the `max_bgerror_resume_count` option.
    pub fn get_max_bgerror_resume_count(&self) -> c_int {
        unsafe { ffi::rocksdb_options_get_max_bgerror_resume_count(self.inner) }
    }

    /// Maximum interval in seconds between periodic compaction trigger checks. The periodic
    /// trigger re-evaluates compaction scores for all column families, which is necessary for
    /// features like read-triggered compaction and time-based compaction to work on a "quiet"
    /// DB with no writes.
    ///
    /// This is an upper bound: the actual check interval may be reduced to align with
    /// stats_dump_period_sec, stats_persist_period_sec, or per-CF time-based compaction
    /// intervals (periodic_compaction_seconds, ttl, etc.).
    ///
    /// Note: this option controls how often RocksDB *checks* whether compaction is needed. It
    /// is different from the CF option `periodic_compaction_seconds` which controls the *age
    /// threshold* at which SST files become eligible for periodic compaction.
    ///
    /// The minimum effective period is 1 second (values below 1 are clamped to 1). Setting
    /// this to 0 results in the most aggressive 1-second polling.
    ///
    /// Default: 43200 (12 hours)
    ///
    /// Dynamically changeable through SetDBOptions() API.
    pub fn set_max_compaction_trigger_wakeup_seconds(&mut self, val: u64) {
        unsafe {
            ffi::rocksdb_options_set_max_compaction_trigger_wakeup_seconds(self.inner, val);
        }
    }

    /// Returns the value of the `max_compaction_trigger_wakeup_seconds` option.
    pub fn get_max_compaction_trigger_wakeup_seconds(&self) -> u64 {
        unsafe { ffi::rocksdb_options_get_max_compaction_trigger_wakeup_seconds(self.inner) }
    }

    /// This option mostly replaces max_manifest_file_size to control an auto-tuned balance of
    /// manifest write amplification and space amplification. A new manifest file is created
    /// with the "compacted" contents of the old one when current_manifest_size >
    /// max(max_manifest_file_size, est_compacted_manifest_size * (1 +
    /// max_manifest_space_amp_pct/100))
    ///
    /// where est_compacted_manifest_size is an estimate of how big a new compacted version of
    /// the current manifest would be. Currently, the estimate used is the last newly-written
    /// manifest, in its "compacted" form.
    ///
    /// Space amplification in the manifest file might be less of a concern for primary
    /// storage space and more of a concern for DB recover time and size of backup files that
    /// aren't incremental between backups. To minimize manifest churn on initial DB
    /// population, setting max_manifest_file_size to something not too small, like 1MB,
    /// should suffice. Similarly, write amp on the manifest file is likely not a direct
    /// concern but completed compactions and flushes cannot (currently) be committed while
    /// the (relatively small) manifest file is being compacted. Manifest compactions should
    /// not interfere with user write latency or throughput unless the DB is chronically
    /// stalling or close to stalling writes already.
    ///
    /// For this option to have a meaningful effect, it is recommended to set
    /// max_manifest_file_size to something modest like 1MB. Then we can interpret values for
    /// this option as follows, starting with minimum space amp and maximum write amp:
    /// - 0 - Every manifest write (flush, compaction, etc.) generates a whole new manifest.
    ///   Only useful for testing.
    /// - very small - Doesn't take many manifest writes to generate a whole new manifest.
    /// - 100 - In a DB with pretty consistent number of SST files, etc., achieves about 1.0
    ///   write amp (writing about 2x the theoretical minimum) and a max of about 1.0 space
    ///   amp (manifest up to 2x the compacted size).
    /// - 500 - Recommended and default: 0.2 write amp and up to roughly 5.0 space amp.
    /// - 10000 - 0.01 write amp and up to 100 space amp on the manifest.
    ///
    /// This option is mutable with SetDBOptions(), taking effect on the next manifest write
    /// (e.g. completed DB compaction or flush).
    pub fn set_max_manifest_space_amp_pct(&mut self, val: c_int) {
        unsafe {
            ffi::rocksdb_options_set_max_manifest_space_amp_pct(self.inner, val);
        }
    }

    /// Returns the value of the `max_manifest_space_amp_pct` option.
    pub fn get_max_manifest_space_amp_pct(&self) -> c_int {
        unsafe { ffi::rocksdb_options_get_max_manifest_space_amp_pct(self.inner) }
    }

    /// The maximum limit of number of bytes that are written in a single batch of WAL or
    /// memtable write. It is followed when the leader write size is larger than 1/8 of this
    /// limit.
    ///
    /// Default: 1 MB
    pub fn set_max_write_batch_group_size_bytes(&mut self, val: u64) {
        unsafe {
            ffi::rocksdb_options_set_max_write_batch_group_size_bytes(self.inner, val);
        }
    }

    /// Returns the value of the `max_write_batch_group_size_bytes` option.
    pub fn get_max_write_batch_group_size_bytes(&self) -> u64 {
        unsafe { ffi::rocksdb_options_get_max_write_batch_group_size_bytes(self.inner) }
    }

    /// RocksDB will try to flush the current memtable after the number of range deletions is
    /// \>= this limit. For workloads with many range deletions, limiting the number of range
    /// deletions in memtable can help prevent performance degradation and/or OOM caused by
    /// too many range tombstones in a single memtable.
    ///
    /// Default: 0 (disabled)
    ///
    /// Dynamically changeable through SetOptions() API
    pub fn set_memtable_max_range_deletions(&mut self, val: u32) {
        unsafe {
            ffi::rocksdb_options_set_memtable_max_range_deletions(self.inner, val);
        }
    }

    /// Returns the value of the `memtable_max_range_deletions` option.
    pub fn get_memtable_max_range_deletions(&self) -> u32 {
        unsafe { ffi::rocksdb_options_get_memtable_max_range_deletions(self.inner) }
    }

    /// Enable memtable per key-value checksum protection.
    ///
    /// Each entry in memtable will be suffixed by a per key-value checksum. This options
    /// determines the size of such checksums.
    ///
    /// It is suggested to turn on write batch per key-value checksum protection together with
    /// this option, so that the checksum computation is done outside of writer threads
    /// (memtable kv checksum can be computed from write batch checksum) See
    /// WriteOptions::protection_bytes_per_key for more detail.
    ///
    /// Default: 0 (no protection) Supported values: 0, 1, 2, 4, 8. Dynamically changeable
    /// through the SetOptions() API.
    pub fn set_memtable_protection_bytes_per_key(&mut self, val: u32) {
        unsafe {
            ffi::rocksdb_options_set_memtable_protection_bytes_per_key(self.inner, val);
        }
    }

    /// Returns the value of the `memtable_protection_bytes_per_key` option.
    pub fn get_memtable_protection_bytes_per_key(&self) -> u32 {
        unsafe { ffi::rocksdb_options_get_memtable_protection_bytes_per_key(self.inner) }
    }

    /// Enables additional integrity checks during seek. Specifically, for skiplist-based
    /// memtables, key checksum validation could be enabled during seek optionally. This is
    /// helpful to detect corrupted memtable keys during reads. Enabling this feature incurs a
    /// performance overhead due to additional key checksum validation during memtable seek
    /// operation. This option depends on memtable_protection_bytes_per_key to be non zero. If
    /// memtable_protection_bytes_per_key is zero, no validation is performed.
    pub fn set_memtable_verify_per_key_checksum_on_seek(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_memtable_verify_per_key_checksum_on_seek(
                self.inner,
                c_uchar::from(val),
            );
        }
    }

    /// Returns the value of the `memtable_verify_per_key_checksum_on_seek` option.
    pub fn get_memtable_verify_per_key_checksum_on_seek(&self) -> bool {
        unsafe {
            ffi::rocksdb_options_get_memtable_verify_per_key_checksum_on_seek(self.inner) != 0
        }
    }

    /// Enable whole key bloom filter in memtable. Note this will only take effect if
    /// memtable_prefix_bloom_size_ratio is not 0. Enabling whole key filtering can
    /// potentially reduce CPU usage for point-look-ups.
    ///
    /// Default: false (disabled)
    ///
    /// Dynamically changeable through SetOptions() API
    pub fn get_memtable_whole_key_filtering(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_memtable_whole_key_filtering(self.inner) != 0 }
    }

    /// When DB files other than SST, blob and WAL files are created, use this filesystem
    /// temperature. (See also `wal_write_temperature` and various `*_temperature` CF
    /// options.) When not `kUnknown`, this overrides any temperature set by
    /// OptimizeForManifestWrite functions.
    pub fn set_metadata_write_temperature(&mut self, val: c_int) {
        unsafe {
            ffi::rocksdb_options_set_metadata_write_temperature(self.inner, val);
        }
    }

    /// Returns the value of the `metadata_write_temperature` option.
    pub fn get_metadata_write_temperature(&self) -> c_int {
        unsafe { ffi::rocksdb_options_get_metadata_write_temperature(self.inner) }
    }

    /// EXPERIMENTAL
    ///
    /// During forward or reverse iteration, when this many or more strictly contiguous point
    /// tombstones (kTypeDeletion, kTypeDeletionWithTimestamp, kTypeSingleDeletion) are
    /// encountered with no live keys between them, a range tombstone [first_tombstone_key,
    /// next_live_key) is inserted into the current mutable memtable (only if memtable is not
    /// empty). This is a logically redundant entry that does not change any data, but
    /// optimizes future iterators by potentially skipping a large number of tombstone scans.
    ///
    /// This optimization is best-effort and is currently disabled for iterator configurations
    /// that may not expose all interior live keys, including:
    /// - user-defined timestamp reads without full visibility (for example,
    ///   ReadOptions::iter_start_ts or a non-max ReadOptions::timestamp)
    /// - prefix extractor reads that are neither total-order (ReadOptions::total_order_seek
    ///   / ReadOptions::auto_prefix_mode) nor bounded by ReadOptions::prefix_same_as_start
    ///
    /// Even if the above restrictions are met, there are still scenarios where a converted
    /// range tombstone may be discarded:
    /// - The snapshot's active mutable memtable has already become immutable.
    /// - The iterator's snapshot seq is below the active memtable's earliest sequence
    ///   number.
    /// - A range tombstone covering [first_tombstone_key, next_live_key) is already present
    ///   in the memtable.
    /// - A WritePrepared/WriteUnprepared transaction read callback is in use and the
    ///   snapshot seq is at or above its min uncommitted seq.
    /// - An IngestExternalFile call is currently in flight on this column family OR the
    ///   inserted range tombstone seqno would be lower than the ingested file seqno.
    ///
    /// Read-write iterators using ReadOptions::table_filter are rejected while this option is
    /// enabled, see more details in ReadOptions::table_filter comments.
    ///
    /// Set to 0 to disable.
    ///
    /// Dynamically changeable through SetOptions() API
    pub fn set_min_tombstones_for_range_conversion(&mut self, val: u32) {
        unsafe {
            ffi::rocksdb_options_set_min_tombstones_for_range_conversion(self.inner, val);
        }
    }

    /// Returns the value of the `min_tombstones_for_range_conversion` option.
    pub fn get_min_tombstones_for_range_conversion(&self) -> u32 {
        unsafe { ffi::rocksdb_options_get_min_tombstones_for_range_conversion(self.inner) }
    }

    /// EXPERIMENTAL: If true, RocksDB can reduce recovery work after a clean shutdown, which
    /// may reduce DB::Open latency on warm reopens, especially on storage where metadata
    /// appends are expensive.
    ///
    /// Best-effort optimization: if it is disabled or unavailable, RocksDB falls back to the
    /// standard recovery path.
    ///
    /// Temporary rollout / kill switch for an optimization that is intended to be correct and
    /// eventually always enabled. Mutable via SetDBOptions().
    pub fn set_optimize_manifest_for_recovery(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_optimize_manifest_for_recovery(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `optimize_manifest_for_recovery` option.
    pub fn get_optimize_manifest_for_recovery(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_optimize_manifest_for_recovery(self.inner) != 0 }
    }

    /// After writing every SST file, reopen it and read all the keys. Checks the hash of all
    /// of the keys and values written versus the keys in the file and signals a corruption if
    /// they do not match
    ///
    /// Default: false
    ///
    /// Dynamically changeable through SetOptions() API
    pub fn set_paranoid_file_checks(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_paranoid_file_checks(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `paranoid_file_checks` option.
    pub fn get_paranoid_file_checks(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_paranoid_file_checks(self.inner) != 0 }
    }

    /// Enables additional integrity checks during reads/scans. Specifically, for
    /// skiplist-based memtables, key ordering validation could be enabled optionally. This is
    /// helpful to detect corrupted memtable keys during reads. Enabling this feature incurs a
    /// performance overhead due to additional comparison during memtable lookup.
    pub fn set_paranoid_memory_checks(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_paranoid_memory_checks(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `paranoid_memory_checks` option.
    pub fn get_paranoid_memory_checks(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_paranoid_memory_checks(self.inner) != 0 }
    }

    /// If true, automatically persist stats to a hidden column family (column family name:
    /// ___rocksdb_stats_history___) every stats_persist_period_sec seconds; otherwise, write
    /// to an in-memory struct. User can query through `GetStatsHistory` API. If user attempts
    /// to create a column family with the same name on a DB which have previously set
    /// persist_stats_to_disk to true, the column family creation will fail, but the hidden
    /// column family will survive, as well as the previously persisted statistics. When
    /// peristing stats to disk, the stat name will be limited at 100 bytes. Default: false
    pub fn set_persist_stats_to_disk(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_persist_stats_to_disk(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `persist_stats_to_disk` option.
    pub fn get_persist_stats_to_disk(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_persist_stats_to_disk(self.inner) != 0 }
    }

    /// UNDER CONSTRUCTION -- DO NOT USE When the user-defined timestamp feature is enabled,
    /// this flag controls whether the user-defined timestamps will be persisted.
    ///
    /// When it's false, the user-defined timestamps will be removed from the user keys when
    /// data is flushed from memtables to SST files. Other places that user keys can be
    /// persisted like file boundaries in file metadata and blob files go through a similar
    /// process. There are two major motivations for this flag:
    /// - backward compatibility: if the user later decides to disable the user-defined
    ///   timestamp feature for the column family, these SST files can be handled by a user
    ///   comparator that is not aware of user-defined timestamps.
    /// - enable user-defined timestamp feature for an existing column family while set this
    ///   flag to be `false`: user keys in the newly generated SST files are of the same
    ///   format as the existing SST files.
    ///
    /// Currently only user comparator that formats user-defined timesamps as uint64_t via
    /// using one of the RocksDB provided comparator `ComparatorWithU64TsImpl` are supported.
    ///
    /// When setting this flag to `false`, users should also call
    /// `DB::IncreaseFullHistoryTsLow` to set a cutoff timestamp for flush. RocksDB refrains
    /// from flushing a memtable with data still above the cutoff timestamp with best effort.
    /// One limitation of this best effort is that when `max_write_buffer_number` is equal to
    /// or smaller than 2, RocksDB will not attempt to retain user-defined timestamps, all
    /// flush jobs continue normally.
    ///
    /// Users can do user-defined multi-versioned read above the cutoff timestamp. When users
    /// try to read below the cutoff timestamp, an error will be returned.
    ///
    /// Note that if WAL is enabled, unlike SST files, user-defined timestamps are persisted
    /// to WAL even if this flag is set to `false`. The benefit of this is that user-defined
    /// timestamps can be recovered with the caveat that users should flush all memtables so
    /// there is no active WAL files before doing a downgrade. In order to use WAL to recover
    /// user-defined timestamps, users of this feature would want to set both
    /// `avoid_flush_during_shutdown` and `avoid_flush_during_recovery` to be true.
    ///
    /// Note that setting this flag to false is not supported in combination with atomic
    /// flush, or concurrent memtable write enabled by `allow_concurrent_memtable_write`.
    ///
    /// Default: true (user-defined timestamps are persisted) Not dynamically changeable,
    /// change it requires db restart and only compatible changes are allowed.
    pub fn set_persist_user_defined_timestamps(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_persist_user_defined_timestamps(
                self.inner,
                c_uchar::from(val),
            );
        }
    }

    /// Returns the value of the `persist_user_defined_timestamps` option.
    pub fn get_persist_user_defined_timestamps(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_persist_user_defined_timestamps(self.inner) != 0 }
    }

    /// EXPERIMENTAL The feature is still in development and is incomplete. If this option is
    /// set, when data insert time is within this time range, it will be precluded from the
    /// last level. 0 means no key will be precluded from the last level.
    ///
    /// Note: when enabled, universal size amplification (controlled by option
    /// `compaction_options_universal.max_size_amplification_percent`) calculation will
    /// exclude the last level. As the feature is designed for tiered storage and a typical
    /// setting is the last level is cold tier which is likely not size constrained, the size
    /// amp is going to be only for non-last levels.
    ///
    /// Default: 0 (disable the feature)
    ///
    /// Dynamically changeable through the SetOptions() API
    pub fn set_preclude_last_level_data_seconds(&mut self, val: u64) {
        unsafe {
            ffi::rocksdb_options_set_preclude_last_level_data_seconds(self.inner, val);
        }
    }

    /// Returns the value of the `preclude_last_level_data_seconds` option.
    pub fn get_preclude_last_level_data_seconds(&self) -> u64 {
        unsafe { ffi::rocksdb_options_get_preclude_last_level_data_seconds(self.inner) }
    }

    /// Historically, when prefix_extractor != nullptr, iterators have an unfortunate default
    /// semantics of *possibly* only returning data within the same prefix. To avoid "spooky
    /// action at a distance," iterator bounds should come from the instantiation or seeking
    /// of the iterator, not from a mutable column family option.
    ///
    /// When set to true, it is as if every iterator is created with total_order_seek=true and
    /// only auto_prefix_mode=true and prefix_same_as_start=true can take advantage of prefix
    /// seek optimizations.
    pub fn set_prefix_seek_opt_in_only(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_prefix_seek_opt_in_only(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `prefix_seek_opt_in_only` option.
    pub fn get_prefix_seek_opt_in_only(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_prefix_seek_opt_in_only(self.inner) != 0 }
    }

    /// EXPERIMENTAL If this option is set, it will preserve the internal time information
    /// about the data until it's older than the specified time here. Internally the time
    /// information is a map between sequence number and time, which is the same as
    /// `preclude_last_level_data_seconds`. But it won't preclude the data from the last level
    /// and the data in the last level won't have the sequence number zeroed out. Internally,
    /// rocksdb would sample the sequence number to time pair and store that in SST property
    /// "rocksdb.seqno.time.map". The information is currently only used for tiered storage
    /// compaction (option `preclude_last_level_data_seconds`).
    ///
    /// Note: if both `preclude_last_level_data_seconds` and this option is set, it will
    /// preserve the max time of the 2 options and compaction still preclude the data based on
    /// `preclude_last_level_data_seconds`. The higher the preserve_time is, the less the
    /// sampling frequency will be ( which means less accuracy of the time estimation).
    ///
    /// Default: 0 (disable the feature)
    ///
    /// Dynamically changeable through the SetOptions() API
    pub fn set_preserve_internal_time_seconds(&mut self, val: u64) {
        unsafe {
            ffi::rocksdb_options_set_preserve_internal_time_seconds(self.inner, val);
        }
    }

    /// Returns the value of the `preserve_internal_time_seconds` option.
    pub fn get_preserve_internal_time_seconds(&self) -> u64 {
        unsafe { ffi::rocksdb_options_get_preserve_internal_time_seconds(self.inner) }
    }

    /// Requested maximum number of threads in the shared read I/O executor. A DB open can
    /// increase the executor to this size but cannot reduce it. Used exclusively for
    /// asynchronous read requests (e.g. GetAsync, MultiGetAsync).
    pub fn set_read_io_executor_threads(&mut self, val: c_int) {
        unsafe {
            ffi::rocksdb_options_set_read_io_executor_threads(self.inner, val);
        }
    }

    /// Returns the value of the `read_io_executor_threads` option.
    pub fn get_read_io_executor_threads(&self) -> c_int {
        unsafe { ffi::rocksdb_options_get_read_io_executor_threads(self.inner) }
    }

    /// When set to a positive value, enables read-triggered compaction. An SST file is marked
    /// for compaction when its estimated read frequency (estimated_reads / file_size) exceeds
    /// this threshold. This helps reduce read amplification for hot keys by compacting
    /// frequently-read files.
    ///
    /// Only "collapsible" reads are counted -- lookups that return NotFound (bloom filter
    /// false positive), Delete/SingleDeletion (tombstone), or Merge (partial result). These
    /// are reads where the file contributed no final value and compaction would eliminate the
    /// wasted work.
    ///
    /// Choosing a value: the threshold balances read IO saved against the write amplification
    /// (WA) of an extra compaction. This assumes the block-based table format is being used,
    ///
    /// Break-even derivation (no block cache): Let r = estimated_reads / file_size  (the
    /// threshold) S = file_size B = block_size             (typically 4 KB) F = level fanout
    /// (typically ~10)
    ///
    /// Each collapsible read wastes one data-block read = B bytes of IO. Total wasted read IO
    /// for a file = r * S * B.
    ///
    /// Compaction cost: one level-L file overlaps ~F files in level L+1, so we read (1 + F)
    /// files and write (1 + F) files. Total compaction IO = 2 * (1 + F) * S.
    ///
    /// Break-even when wasted read IO equals compaction IO: r * S * B = 2 * (1 + F) * S r = 2
    /// * (1 + F) / B
    ///
    /// With F = 10, B = 4096:  r = 22 / 4096 ~= 0.005.
    ///
    /// With a block-cache hit rate h (0 <= h < 1), each collapsible read only costs (1 - h) *
    /// B bytes of actual disk IO, so: r = 2 * (1 + F) / ((1 - h) * B)
    ///
    /// h = 0   -> r ~= 0.005 h = 0.5 -> r ~= 0.01 h = 0.9 -> r ~= 0.05
    ///
    /// A recommended starting point is 0.01, which avoids triggering compactions that cost
    /// more IO than they save for most cache-friendly workloads, while still being responsive
    /// enough to compact files with significant wasted reads.
    ///
    /// For this feature to take effect on a "quiet" DB (no writes), the DB-level option
    /// `max_compaction_trigger_wakeup_seconds` must also be set to a non-zero value so the
    /// periodic background job can re-evaluate files.
    ///
    /// Valid range: >= 0.0 (must be finite). Use 0.0 to disable.
    ///
    /// Dynamically changeable through SetOptions() API
    pub fn set_read_triggered_compaction_threshold(&mut self, val: f64) {
        unsafe {
            ffi::rocksdb_options_set_read_triggered_compaction_threshold(self.inner, val);
        }
    }

    /// Returns the value of the `read_triggered_compaction_threshold` option.
    pub fn get_read_triggered_compaction_threshold(&self) -> f64 {
        unsafe { ffi::rocksdb_options_get_read_triggered_compaction_threshold(self.inner) }
    }

    /// Sets the `remove` option.
    pub fn set_remove(&mut self, val: c_int) {
        unsafe {
            ffi::rocksdb_options_calculate_sst_write_lifetime_hint_set_remove(self.inner, val);
        }
    }

    /// EXPERIMENTAL: If true, DB::Open can try to reuse the existing MANIFEST for the first
    /// post-open metadata update instead of creating a fresh one. This can reduce warm-open
    /// latency for DBs whose MANIFEST is expensive to rebuild.
    ///
    /// Best-effort optimization: even when enabled, RocksDB may still create a fresh MANIFEST
    /// if the FileSystem does not support reopening the existing MANIFEST for append, or if
    /// RocksDB decides reuse is unsafe. That fallback is normal behavior.
    ///
    /// With very small `max_manifest_file_size` settings, the reused MANIFEST can still
    /// rotate earlier than expected after open, because RocksDB may keep a conservative
    /// auto-tuned rotation threshold until it later refreshes its compacted-size estimate.
    ///
    /// Temporary rollout / kill switch while this optimization is being validated.
    pub fn set_reuse_manifest_on_open(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_reuse_manifest_on_open(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `reuse_manifest_on_open` option.
    pub fn get_reuse_manifest_on_open(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_reuse_manifest_on_open(self.inner) != 0 }
    }

    /// If this option is set then 1 in N blocks are compressed using a fast (lz4) and slow
    /// (zstd) compression algorithm. The compressibility is reported as stats and the stored
    /// data is left uncompressed (unless compression is also requested).
    pub fn set_sample_for_compression(&mut self, val: u64) {
        unsafe {
            ffi::rocksdb_options_set_sample_for_compression(self.inner, val);
        }
    }

    /// Returns the value of the `sample_for_compression` option.
    pub fn get_sample_for_compression(&self) -> u64 {
        unsafe { ffi::rocksdb_options_get_sample_for_compression(self.inner) }
    }

    /// if not zero, periodically take stats snapshots and store in memory, the memory size
    /// for stats snapshots is capped at stats_history_buffer_size Default: 1MB
    pub fn set_stats_history_buffer_size(&mut self, val: usize) {
        unsafe {
            ffi::rocksdb_options_set_stats_history_buffer_size(self.inner, val);
        }
    }

    /// Returns the value of the `stats_history_buffer_size` option.
    pub fn get_stats_history_buffer_size(&self) -> usize {
        unsafe { ffi::rocksdb_options_get_stats_history_buffer_size(self.inner) }
    }

    /// When true, guarantees WAL files have at most `wal_bytes_per_sync` bytes submitted for
    /// writeback at any given time, and SST files have at most `bytes_per_sync` bytes pending
    /// writeback at any given time. This can be used to handle cases where processing speed
    /// exceeds I/O speed during file generation, which can lead to a huge sync when the file
    /// is finished, even with `bytes_per_sync` / `wal_bytes_per_sync` properly configured.
    ///
    /// - If `sync_file_range` is supported it achieves this by waiting for any prior
    ///   `sync_file_range`s to finish before proceeding. In this way, processing
    ///   (compression, etc.) can proceed uninhibited in the gap between `sync_file_range`s,
    ///   and we block only when I/O falls behind.
    /// - Otherwise the `WritableFile::Sync` method is used. Note this mechanism always
    ///   blocks, thus preventing the interleaving of I/O and processing.
    ///
    /// Note: Enabling this option does not provide any additional persistence guarantees, as
    /// it may use `sync_file_range`, which does not write out metadata.
    ///
    /// Default: false
    pub fn set_strict_bytes_per_sync(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_strict_bytes_per_sync(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `strict_bytes_per_sync` option.
    pub fn get_strict_bytes_per_sync(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_strict_bytes_per_sync(self.inner) != 0 }
    }

    /// Whether to allow filesystem reads to stay under the `max_successive_merges` limit.
    /// When true, this can lead to merge writes blocking the write path waiting on filesystem
    /// reads.
    ///
    /// This option is temporary in case the recent change to disallow filesystem reads during
    /// merge writes has a problem and users need to undo it quickly.
    ///
    /// Default: false
    pub fn set_strict_max_successive_merges(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_strict_max_successive_merges(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `strict_max_successive_merges` option.
    pub fn get_strict_max_successive_merges(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_strict_max_successive_merges(self.inner) != 0 }
    }

    /// If true, RocksDB will consider the estimated tail size (filter + index + meta blocks)
    /// when deciding whether to cut a compaction output file. This helps prevent output files
    /// from exceeding the target_file_size_base due to large tail blocks. When disabled, only
    /// the data block size is considered, which may result in SST files exceeding the
    /// target_file_size_base.
    ///
    /// Default: false
    ///
    /// Dynamically changeable through SetOptions() API
    pub fn set_target_file_size_is_upper_bound(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_target_file_size_is_upper_bound(
                self.inner,
                c_uchar::from(val),
            );
        }
    }

    /// Returns the value of the `target_file_size_is_upper_bound` option.
    pub fn get_target_file_size_is_upper_bound(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_target_file_size_is_upper_bound(self.inner) != 0 }
    }

    /// EXPERIMENTAL
    ///
    /// If true, each new WAL will record various information about its predecessor WAL for
    /// verification on the predecessor WAL during WAL recovery.
    ///
    /// It verifies the following:
    /// - There exists at least some WAL in the DB
    /// - It's not compatible with `RepairDB()` since this option imposes a stricter
    ///   requirement on WAL than the DB went through `RepariDB()` can normally meet
    /// - There exists no WAL hole where new WAL data presents while some old WAL data not
    ///   yet obsolete is missing. The DB manifest indicates which WALs are obsolete.
    ///
    /// This is intended to be a better replacement to `track_and_verify_wals_in_manifest`.
    ///
    /// Default: false
    pub fn set_track_and_verify_wals(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_track_and_verify_wals(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `track_and_verify_wals` option.
    pub fn get_track_and_verify_wals(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_track_and_verify_wals(self.inner) != 0 }
    }

    /// If enabled it uses two queues for writes, one for the ones with disable_memtable and
    /// one for the ones that also write to memtable. This allows the memtable writes not to
    /// lag behind other writes. It can be used to optimize MySQL 2PC in which only the
    /// commits, which are serial, write to memtable.
    pub fn set_two_write_queues(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_two_write_queues(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `two_write_queues` option.
    pub fn get_two_write_queues(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_two_write_queues(self.inner) != 0 }
    }

    /// EXPERIMENTAL When > 0, RocksDB attempts to erase some block cache entries for files
    /// that have become obsolete, which means they are about to be deleted. To avoid
    /// excessive tracking, this "uncaching" process is iterative and speculative, meaning it
    /// could incur extra background CPU effort if the file's blocks are generally not cached.
    /// A larger number indicates more willingness to spend CPU time to maximize block cache
    /// hit rates by erasing known-obsolete entries.
    ///
    /// When uncache_aggressiveness=1, block cache entries for an obsolete file are only
    /// erased until any attempted erase operation fails because the block is not cached. Then
    /// no further attempts are made to erase cached blocks for that file.
    ///
    /// For larger values, erasure is attempted until evidence incidates that the chance of
    /// success is < 0.99^(a-1), where a = uncache_aggressiveness. For example: 2 -> Attempt
    /// only while expecting >= 99% successful/useful erasure 11 -> 90% 69 -> 50% 110 -> 33%
    /// 230 -> 10% 460 -> 1% 690 -> 0.1% 1000 -> 1 in 23000 10000 -> Always (for all practical
    /// purposes) NOTE: UINT32_MAX and nearby values could take additional special meanings in
    /// the future.
    ///
    /// Pinned cache entries (guaranteed present) are always erased if uncache_aggressiveness
    /// \> 0, but are not used in predicting the chances of successful erasure of non-pinned
    /// entries.
    ///
    /// NOTE: In the case of copied DBs (such as Checkpoints) sharing a block cache, it is
    /// possible that a file becoming obsolete doesn't mean its block cache entries (shared
    /// among copies) are obsolete. Such a scenerio is the best case for
    /// uncache_aggressiveness = 0.
    ///
    /// When using allow_mmap_reads=true, this option is ignored (no un-caching).
    ///
    /// Once validated in production, the default will likely change to something around 300.
    pub fn set_uncache_aggressiveness(&mut self, val: u32) {
        unsafe {
            ffi::rocksdb_options_set_uncache_aggressiveness(self.inner, val);
        }
    }

    /// Returns the value of the `uncache_aggressiveness` option.
    pub fn get_uncache_aggressiveness(&self) -> u32 {
        unsafe { ffi::rocksdb_options_get_uncache_aggressiveness(self.inner) }
    }

    /// Use O_DIRECT for compaction-input SST reads only, leaving user reads buffered. Useful
    /// when sequential compaction reads would otherwise evict the hot user-read working set
    /// from the OS page cache. When this is true and use_direct_reads is false, compaction
    /// opens short-lived O_DIRECT readers for its input files instead of reusing the buffered
    /// readers cached for user reads. This is the read-side analogue of
    /// use_direct_io_for_flush_and_compaction, and the two are often paired on write-heavy
    /// workloads.
    ///
    /// Scope and limits:
    /// - DBOption scope (applies to all column families); no per-CF setting.
    /// - Covers compaction inputs only. Blob-file reads and compaction-output verification
    ///   (paranoid_file_checks) still use the buffered path.
    /// - The ephemeral readers bypass the TableCache and are not counted against
    ///   max_open_files. Non-L0 levels keep one reader open at a time; L0 opens all of a
    ///   subcompaction's overlapping inputs at once, so with large L0 fan-in and many
    ///   subcompactions, watch RLIMIT_NOFILE.
    /// - Every input file is reopened per compaction, so NO_FILE_OPENS and
    ///   TABLE_OPEN_IO_MICROS rise while this is enabled.
    ///
    /// The same SST can be open through both a buffered handle (user reads) and an O_DIRECT
    /// handle (the compaction scan) at once; modern Linux handles this fine. The flag is
    /// neutral or slightly negative for in-memory DBs or uniform random reads, so measure
    /// before enabling.
    ///
    /// Has no effect when use_direct_reads is true (all reads are already O_DIRECT). Rejected
    /// at DB::Open when allow_mmap_reads is set.
    ///
    /// On a filesystem without O_DIRECT support (e.g. tmpfs), DB::Open fails: it probes by
    /// opening the MANIFEST with O_DIRECT. The probe only checks the filesystem holding the
    /// DB directory, so if SST files live elsewhere (via db_paths/cf_paths) without O_DIRECT,
    /// Open succeeds and the first compaction fails instead.
    ///
    /// Default: false
    pub fn set_use_direct_io_for_compaction_reads(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_use_direct_io_for_compaction_reads(
                self.inner,
                c_uchar::from(val),
            );
        }
    }

    /// Returns the value of the `use_direct_io_for_compaction_reads` option.
    pub fn get_use_direct_io_for_compaction_reads(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_use_direct_io_for_compaction_reads(self.inner) != 0 }
    }

    /// If true, on DB close, read back the entire MANIFEST file and validate CRC checksums
    /// and logical record content. If corruption is detected, a fresh MANIFEST is written
    /// from in-memory state before closing.
    ///
    /// This option is mutable with SetDBOptions().
    pub fn set_verify_manifest_content_on_close(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_verify_manifest_content_on_close(
                self.inner,
                c_uchar::from(val),
            );
        }
    }

    /// Returns the value of the `verify_manifest_content_on_close` option.
    pub fn get_verify_manifest_content_on_close(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_verify_manifest_content_on_close(self.inner) != 0 }
    }

    /// Bitmask enum for output verification option.
    ///
    /// Default: 0 (kVerifyNone)
    ///
    /// Dynamically changeable (as a uint32_t) through SetOptions() API.
    pub fn set_verify_output_flags(&mut self, val: c_int) {
        unsafe {
            ffi::rocksdb_options_set_verify_output_flags(self.inner, val);
        }
    }

    /// Returns the value of the `verify_output_flags` option.
    pub fn get_verify_output_flags(&self) -> c_int {
        unsafe { ffi::rocksdb_options_get_verify_output_flags(self.inner) }
    }

    /// If true, verifies the SST unique id between MANIFEST and actual file each time an SST
    /// file is opened. This check ensures an SST file is not overwritten or misplaced. A
    /// corruption error will be reported if mismatch detected, but only when MANIFEST tracks
    /// the unique id, which starts from RocksDB version 7.3. Although the tracked internal
    /// unique id is related to the one returned by GetUniqueIdFromTableProperties, that is
    /// subject to change. NOTE: verification is currently only done on SST files using
    /// block-based table format.
    ///
    /// Setting to false should only be needed in case of unexpected problems.
    ///
    /// Although an early version of this option opened all SST files for verification on
    /// DB::Open, that is no longer guaranteed. However, as documented in an above option, if
    /// max_open_files is -1, DB will open all files on DB::Open().
    ///
    /// Default: true
    pub fn set_verify_sst_unique_id_in_manifest(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_verify_sst_unique_id_in_manifest(
                self.inner,
                c_uchar::from(val),
            );
        }
    }

    /// Returns the value of the `verify_sst_unique_id_in_manifest` option.
    pub fn get_verify_sst_unique_id_in_manifest(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_verify_sst_unique_id_in_manifest(self.inner) != 0 }
    }

    /// Use this filesystem temperature when creating WAL files. When not `kUnknown`, this
    /// overrides any temperature set by OptimizeForLogWrite functions.
    pub fn set_wal_write_temperature(&mut self, val: c_int) {
        unsafe {
            ffi::rocksdb_options_set_wal_write_temperature(self.inner, val);
        }
    }

    /// Returns the value of the `wal_write_temperature` option.
    pub fn get_wal_write_temperature(&self) -> c_int {
        unsafe { ffi::rocksdb_options_get_wal_write_temperature(self.inner) }
    }

    /// The maximum number of microseconds that a write operation will use a yielding spin
    /// loop to coordinate with other write threads before blocking on a mutex.  (Assuming
    /// write_thread_slow_yield_usec is set properly) increasing this value is likely to
    /// increase RocksDB throughput at the expense of increased CPU usage.
    ///
    /// Default: 100
    pub fn set_write_thread_max_yield_usec(&mut self, val: u64) {
        unsafe {
            ffi::rocksdb_options_set_write_thread_max_yield_usec(self.inner, val);
        }
    }

    /// Returns the value of the `write_thread_max_yield_usec` option.
    pub fn get_write_thread_max_yield_usec(&self) -> u64 {
        unsafe { ffi::rocksdb_options_get_write_thread_max_yield_usec(self.inner) }
    }

    /// The latency in microseconds after which a std::this_thread::yield call (sched_yield on
    /// Linux) is considered to be a signal that other processes or threads would like to use
    /// the current core. Increasing this makes writer threads more likely to take CPU by
    /// spinning, which will show up as an increase in the number of involuntary context
    /// switches.
    ///
    /// Default: 3
    pub fn set_write_thread_slow_yield_usec(&mut self, val: u64) {
        unsafe {
            ffi::rocksdb_options_set_write_thread_slow_yield_usec(self.inner, val);
        }
    }

    /// Returns the value of the `write_thread_slow_yield_usec` option.
    pub fn get_write_thread_slow_yield_usec(&self) -> u64 {
        unsafe { ffi::rocksdb_options_get_write_thread_slow_yield_usec(self.inner) }
    }

    /// Returns the current `advise_random_on_open` setting.
    ///
    /// See [`Self::set_advise_random_on_open`] for what this controls.
    pub fn get_advise_random_on_open(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_advise_random_on_open(self.inner) != 0 }
    }

    /// Returns the current `allow_concurrent_memtable_write` setting.
    ///
    /// See [`Self::set_allow_concurrent_memtable_write`] for what this controls.
    pub fn get_allow_concurrent_memtable_write(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_allow_concurrent_memtable_write(self.inner) != 0 }
    }

    /// Returns the current `allow_ingest_behind` setting.
    ///
    /// See [`Self::set_allow_ingest_behind`] for what this controls.
    pub fn get_allow_ingest_behind(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_allow_ingest_behind(self.inner) != 0 }
    }

    /// Returns the current `allow_mmap_reads` setting.
    ///
    /// See [`Self::set_allow_mmap_reads`] for what this controls.
    pub fn get_allow_mmap_reads(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_allow_mmap_reads(self.inner) != 0 }
    }

    /// Returns the current `allow_mmap_writes` setting.
    ///
    /// See [`Self::set_allow_mmap_writes`] for what this controls.
    pub fn get_allow_mmap_writes(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_allow_mmap_writes(self.inner) != 0 }
    }

    /// Returns the current `arena_block_size` setting.
    ///
    /// See [`Self::set_arena_block_size`] for what this controls.
    pub fn get_arena_block_size(&self) -> usize {
        unsafe { ffi::rocksdb_options_get_arena_block_size(self.inner) }
    }

    /// Returns the current `atomic_flush` setting.
    ///
    /// See [`Self::set_atomic_flush`] for what this controls.
    pub fn get_atomic_flush(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_atomic_flush(self.inner) != 0 }
    }

    /// Returns the current `avoid_unnecessary_blocking_io` setting.
    ///
    /// See [`Self::set_avoid_unnecessary_blocking_io`] for what this controls.
    pub fn get_avoid_unnecessary_blocking_io(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_avoid_unnecessary_blocking_io(self.inner) != 0 }
    }

    /// Returns the current `blob_compaction_readahead_size` setting.
    ///
    /// See [`Self::set_blob_compaction_readahead_size`] for what this controls.
    pub fn get_blob_compaction_readahead_size(&self) -> u64 {
        unsafe { ffi::rocksdb_options_get_blob_compaction_readahead_size(self.inner) }
    }

    /// Returns the current `blob_file_size` setting.
    ///
    /// See [`Self::set_blob_file_size`] for what this controls.
    pub fn get_blob_file_size(&self) -> u64 {
        unsafe { ffi::rocksdb_options_get_blob_file_size(self.inner) }
    }

    /// Returns the current `blob_file_starting_level` setting.
    ///
    /// See [`Self::set_blob_file_starting_level`] for what this controls.
    pub fn get_blob_file_starting_level(&self) -> c_int {
        unsafe { ffi::rocksdb_options_get_blob_file_starting_level(self.inner) }
    }

    /// Returns the current `blob_gc_age_cutoff` setting.
    ///
    /// See [`Self::set_blob_gc_age_cutoff`] for what this controls.
    pub fn get_blob_gc_age_cutoff(&self) -> f64 {
        unsafe { ffi::rocksdb_options_get_blob_gc_age_cutoff(self.inner) }
    }

    /// Returns the current `blob_gc_force_threshold` setting.
    ///
    /// See [`Self::set_blob_gc_force_threshold`] for what this controls.
    pub fn get_blob_gc_force_threshold(&self) -> f64 {
        unsafe { ffi::rocksdb_options_get_blob_gc_force_threshold(self.inner) }
    }

    /// Returns the current `bloom_locality` setting.
    ///
    /// See [`Self::set_bloom_locality`] for what this controls.
    pub fn get_bloom_locality(&self) -> u32 {
        unsafe { ffi::rocksdb_options_get_bloom_locality(self.inner) }
    }

    /// Returns the current `bottommost_compression_options_use_zstd_dict_trainer` setting.
    ///
    /// See [`Self::set_bottommost_compression_options_use_zstd_dict_trainer`] for what this controls.
    pub fn get_bottommost_compression_options_use_zstd_dict_trainer(&self) -> bool {
        unsafe {
            ffi::rocksdb_options_get_bottommost_compression_options_use_zstd_dict_trainer(
                self.inner,
            ) != 0
        }
    }

    /// Returns the current `bytes_per_sync` setting.
    ///
    /// See [`Self::set_bytes_per_sync`] for what this controls.
    pub fn get_bytes_per_sync(&self) -> u64 {
        unsafe { ffi::rocksdb_options_get_bytes_per_sync(self.inner) }
    }

    /// Returns the current `compaction_readahead_size` setting.
    ///
    /// See [`Self::set_compaction_readahead_size`] for what this controls.
    pub fn get_compaction_readahead_size(&self) -> usize {
        unsafe { ffi::rocksdb_options_get_compaction_readahead_size(self.inner) }
    }

    /// Returns the current `compression_options_max_dict_buffer_bytes` setting.
    ///
    /// See [`Self::set_compression_options_max_dict_buffer_bytes`] for what this controls.
    pub fn get_compression_options_max_dict_buffer_bytes(&self) -> u64 {
        unsafe { ffi::rocksdb_options_get_compression_options_max_dict_buffer_bytes(self.inner) }
    }

    /// Returns the current `compression_options_parallel_threads` setting.
    ///
    /// See [`Self::set_compression_options_parallel_threads`] for what this controls.
    pub fn get_compression_options_parallel_threads(&self) -> c_int {
        unsafe { ffi::rocksdb_options_get_compression_options_parallel_threads(self.inner) }
    }

    /// Returns the current `compression_options_use_zstd_dict_trainer` setting.
    ///
    /// See [`Self::set_compression_options_use_zstd_dict_trainer`] for what this controls.
    pub fn get_compression_options_use_zstd_dict_trainer(&self) -> bool {
        unsafe {
            ffi::rocksdb_options_get_compression_options_use_zstd_dict_trainer(self.inner) != 0
        }
    }

    /// Returns the maximum size of training data passed to zstd's dictionary trainer.
    pub fn get_compression_options_zstd_max_train_bytes(&self) -> c_int {
        unsafe { ffi::rocksdb_options_get_compression_options_zstd_max_train_bytes(self.inner) }
    }

    /// Returns the current `create_if_missing` setting.
    ///
    /// See [`Self::create_if_missing`] for what this controls.
    pub fn get_create_if_missing(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_create_if_missing(self.inner) != 0 }
    }

    /// Returns the current `create_missing_column_families` setting.
    ///
    /// See [`Self::create_missing_column_families`] for what this controls.
    pub fn get_create_missing_column_families(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_create_missing_column_families(self.inner) != 0 }
    }

    /// Returns the current `db_write_buffer_size` setting.
    ///
    /// See [`Self::set_db_write_buffer_size`] for what this controls.
    pub fn get_db_write_buffer_size(&self) -> usize {
        unsafe { ffi::rocksdb_options_get_db_write_buffer_size(self.inner) }
    }

    /// Returns the current `delete_obsolete_files_period_micros` setting.
    ///
    /// See [`Self::set_delete_obsolete_files_period_micros`] for what this controls.
    pub fn get_delete_obsolete_files_period_micros(&self) -> u64 {
        unsafe { ffi::rocksdb_options_get_delete_obsolete_files_period_micros(self.inner) }
    }

    /// Returns the current `disable_auto_compactions` setting.
    ///
    /// See [`Self::set_disable_auto_compactions`] for what this controls.
    pub fn get_disable_auto_compactions(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_disable_auto_compactions(self.inner) != 0 }
    }

    /// Returns the current `enable_blob_files` setting.
    ///
    /// See [`Self::set_enable_blob_files`] for what this controls.
    pub fn get_enable_blob_files(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_enable_blob_files(self.inner) != 0 }
    }

    /// Returns the current `enable_blob_gc` setting.
    ///
    /// See [`Self::set_enable_blob_gc`] for what this controls.
    pub fn get_enable_blob_gc(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_enable_blob_gc(self.inner) != 0 }
    }

    /// Returns the current `enable_pipelined_write` setting.
    ///
    /// See [`Self::set_enable_pipelined_write`] for what this controls.
    pub fn get_enable_pipelined_write(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_enable_pipelined_write(self.inner) != 0 }
    }

    /// Returns the current `enable_write_thread_adaptive_yield` setting.
    ///
    /// See [`Self::set_enable_write_thread_adaptive_yield`] for what this controls.
    pub fn get_enable_write_thread_adaptive_yield(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_enable_write_thread_adaptive_yield(self.inner) != 0 }
    }

    /// Returns the current `error_if_exists` setting.
    ///
    /// See [`Self::set_error_if_exists`] for what this controls.
    pub fn get_error_if_exists(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_error_if_exists(self.inner) != 0 }
    }

    /// Returns the current `experimental_mempurge_threshold` setting.
    ///
    /// See [`Self::set_experimental_mempurge_threshold`] for what this controls.
    pub fn get_experimental_mempurge_threshold(&self) -> f64 {
        unsafe { ffi::rocksdb_options_get_experimental_mempurge_threshold(self.inner) }
    }

    /// Returns the current `hard_pending_compaction_bytes_limit` setting.
    ///
    /// See [`Self::set_hard_pending_compaction_bytes_limit`] for what this controls.
    pub fn get_hard_pending_compaction_bytes_limit(&self) -> usize {
        unsafe { ffi::rocksdb_options_get_hard_pending_compaction_bytes_limit(self.inner) }
    }

    /// Number of locks used for inplace update Default: 10000, if inplace_update_support =
    /// true, else 0.
    ///
    /// Dynamically changeable through SetOptions() API.
    pub fn get_inplace_update_num_locks(&self) -> usize {
        unsafe { ffi::rocksdb_options_get_inplace_update_num_locks(self.inner) }
    }

    /// Returns the current `inplace_update_support` setting.
    ///
    /// See [`Self::set_inplace_update_support`] for what this controls.
    pub fn get_inplace_update_support(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_inplace_update_support(self.inner) != 0 }
    }

    /// Returns the current `is_fd_close_on_exec` setting.
    ///
    /// See [`Self::set_is_fd_close_on_exec`] for what this controls.
    pub fn get_is_fd_close_on_exec(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_is_fd_close_on_exec(self.inner) != 0 }
    }

    /// Returns the current `keep_log_file_num` setting.
    ///
    /// See [`Self::set_keep_log_file_num`] for what this controls.
    pub fn get_keep_log_file_num(&self) -> usize {
        unsafe { ffi::rocksdb_options_get_keep_log_file_num(self.inner) }
    }

    /// Number of files to trigger level-0 compaction. A value <0 means that level-0
    /// compaction will not be triggered by number of files at all.
    ///
    /// Universal compaction: RocksDB will try to keep the number of sorted runs no more than
    /// this number. If CompactionOptionsUniversal::max_read_amp is set, then this option will
    /// be used only as a trigger to look for compaction.
    /// CompactionOptionsUniversal::max_read_amp will be the limit on the number of sorted
    /// runs.
    ///
    /// Default: 4
    ///
    /// Dynamically changeable through SetOptions() API.
    pub fn get_level0_file_num_compaction_trigger(&self) -> c_int {
        unsafe { ffi::rocksdb_options_get_level0_file_num_compaction_trigger(self.inner) }
    }

    /// Soft limit on number of level-0 files. We start slowing down writes at this point. A
    /// value <0 means that no writing slow down will be triggered by number of files in
    /// level-0.
    ///
    /// Default: 20
    ///
    /// Dynamically changeable through SetOptions() API.
    pub fn get_level0_slowdown_writes_trigger(&self) -> c_int {
        unsafe { ffi::rocksdb_options_get_level0_slowdown_writes_trigger(self.inner) }
    }

    /// Maximum number of level-0 files.  We stop writes at this point.
    ///
    /// Default: 36
    ///
    /// Dynamically changeable through SetOptions() API.
    pub fn get_level0_stop_writes_trigger(&self) -> c_int {
        unsafe { ffi::rocksdb_options_get_level0_stop_writes_trigger(self.inner) }
    }

    /// Returns the current `level_compaction_dynamic_level_bytes` setting.
    ///
    /// See [`Self::set_level_compaction_dynamic_level_bytes`] for what this controls.
    pub fn get_level_compaction_dynamic_level_bytes(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_level_compaction_dynamic_level_bytes(self.inner) != 0 }
    }

    /// Returns the current `log_file_time_to_roll` setting.
    ///
    /// See [`Self::set_log_file_time_to_roll`] for what this controls.
    pub fn get_log_file_time_to_roll(&self) -> usize {
        unsafe { ffi::rocksdb_options_get_log_file_time_to_roll(self.inner) }
    }

    /// Returns the current `manifest_preallocation_size` setting.
    ///
    /// See [`Self::set_manifest_preallocation_size`] for what this controls.
    pub fn get_manifest_preallocation_size(&self) -> usize {
        unsafe { ffi::rocksdb_options_get_manifest_preallocation_size(self.inner) }
    }

    /// Returns the current `manual_wal_flush` setting.
    ///
    /// See [`Self::set_manual_wal_flush`] for what this controls.
    pub fn get_manual_wal_flush(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_manual_wal_flush(self.inner) != 0 }
    }

    /// Returns the current `max_background_jobs` setting.
    ///
    /// See [`Self::set_max_background_jobs`] for what this controls.
    pub fn get_max_background_jobs(&self) -> c_int {
        unsafe { ffi::rocksdb_options_get_max_background_jobs(self.inner) }
    }

    /// Returns the current `max_bytes_for_level_base` setting.
    ///
    /// See [`Self::set_max_bytes_for_level_base`] for what this controls.
    pub fn get_max_bytes_for_level_base(&self) -> u64 {
        unsafe { ffi::rocksdb_options_get_max_bytes_for_level_base(self.inner) }
    }

    /// Returns the current `max_bytes_for_level_multiplier` setting.
    ///
    /// See [`Self::set_max_bytes_for_level_multiplier`] for what this controls.
    pub fn get_max_bytes_for_level_multiplier(&self) -> f64 {
        unsafe { ffi::rocksdb_options_get_max_bytes_for_level_multiplier(self.inner) }
    }

    /// Returns the current `max_compaction_bytes` setting.
    ///
    /// See [`Self::set_max_compaction_bytes`] for what this controls.
    pub fn get_max_compaction_bytes(&self) -> u64 {
        unsafe { ffi::rocksdb_options_get_max_compaction_bytes(self.inner) }
    }

    /// Returns the current `max_file_opening_threads` setting.
    ///
    /// See [`Self::set_max_file_opening_threads`] for what this controls.
    pub fn get_max_file_opening_threads(&self) -> c_int {
        unsafe { ffi::rocksdb_options_get_max_file_opening_threads(self.inner) }
    }

    /// Returns the current `max_log_file_size` setting.
    ///
    /// See [`Self::set_max_log_file_size`] for what this controls.
    pub fn get_max_log_file_size(&self) -> usize {
        unsafe { ffi::rocksdb_options_get_max_log_file_size(self.inner) }
    }

    /// Returns the current `max_manifest_file_size` setting.
    ///
    /// See [`Self::set_max_manifest_file_size`] for what this controls.
    pub fn get_max_manifest_file_size(&self) -> usize {
        unsafe { ffi::rocksdb_options_get_max_manifest_file_size(self.inner) }
    }

    /// Returns the current `max_open_files` setting.
    ///
    /// See [`Self::set_max_open_files`] for what this controls.
    pub fn get_max_open_files(&self) -> c_int {
        unsafe { ffi::rocksdb_options_get_max_open_files(self.inner) }
    }

    /// Returns the current `max_sequential_skip_in_iterations` setting.
    ///
    /// See [`Self::set_max_sequential_skip_in_iterations`] for what this controls.
    pub fn get_max_sequential_skip_in_iterations(&self) -> u64 {
        unsafe { ffi::rocksdb_options_get_max_sequential_skip_in_iterations(self.inner) }
    }

    /// Returns the current `max_subcompactions` setting.
    ///
    /// See [`Self::set_max_subcompactions`] for what this controls.
    pub fn get_max_subcompactions(&self) -> u32 {
        unsafe { ffi::rocksdb_options_get_max_subcompactions(self.inner) }
    }

    /// Returns the current `max_successive_merges` setting.
    ///
    /// See [`Self::set_max_successive_merges`] for what this controls.
    pub fn get_max_successive_merges(&self) -> usize {
        unsafe { ffi::rocksdb_options_get_max_successive_merges(self.inner) }
    }

    /// Returns the current `max_total_wal_size` setting.
    ///
    /// See [`Self::set_max_total_wal_size`] for what this controls.
    pub fn get_max_total_wal_size(&self) -> u64 {
        unsafe { ffi::rocksdb_options_get_max_total_wal_size(self.inner) }
    }

    /// Returns the current `max_write_buffer_number` setting.
    ///
    /// See [`Self::set_max_write_buffer_number`] for what this controls.
    pub fn get_max_write_buffer_number(&self) -> c_int {
        unsafe { ffi::rocksdb_options_get_max_write_buffer_number(self.inner) }
    }

    /// Returns the current `max_write_buffer_size_to_maintain` setting.
    ///
    /// See [`Self::set_max_write_buffer_size_to_maintain`] for what this controls.
    pub fn get_max_write_buffer_size_to_maintain(&self) -> i64 {
        unsafe { ffi::rocksdb_options_get_max_write_buffer_size_to_maintain(self.inner) }
    }

    /// Returns the current `memtable_avg_op_scan_flush_trigger` setting.
    ///
    /// See [`Self::set_memtable_avg_op_scan_flush_trigger`] for what this controls.
    pub fn get_memtable_avg_op_scan_flush_trigger(&self) -> u32 {
        unsafe { ffi::rocksdb_options_get_memtable_avg_op_scan_flush_trigger(self.inner) }
    }

    /// Returns the current `memtable_huge_page_size` setting.
    ///
    /// See [`Self::set_memtable_huge_page_size`] for what this controls.
    pub fn get_memtable_huge_page_size(&self) -> usize {
        unsafe { ffi::rocksdb_options_get_memtable_huge_page_size(self.inner) }
    }

    /// Returns the current `memtable_op_scan_flush_trigger` setting.
    ///
    /// See [`Self::set_memtable_op_scan_flush_trigger`] for what this controls.
    pub fn get_memtable_op_scan_flush_trigger(&self) -> u32 {
        unsafe { ffi::rocksdb_options_get_memtable_op_scan_flush_trigger(self.inner) }
    }

    /// Should really be called `memtable_bloom_size_ratio`. Enables a dynamic Bloom filter in
    /// memtable to optimize many queries that must go beyond the memtable. The size in bytes
    /// of the filter is write_buffer_size * memtable_prefix_bloom_size_ratio.
    /// - If prefix_extractor is set, the filter includes prefixes.
    /// - If memtable_whole_key_filtering, the filter includes whole keys.
    /// - If both, the filter includes both.
    /// - If neither, the feature is disabled.
    ///
    /// If this value is larger than 0.25, it is sanitized to 0.25.
    ///
    /// Default: 0 (disabled)
    ///
    /// Dynamically changeable through SetOptions() API.
    pub fn get_memtable_prefix_bloom_size_ratio(&self) -> f64 {
        unsafe { ffi::rocksdb_options_get_memtable_prefix_bloom_size_ratio(self.inner) }
    }

    /// Returns the current `min_blob_size` setting.
    ///
    /// See [`Self::set_min_blob_size`] for what this controls.
    pub fn get_min_blob_size(&self) -> u64 {
        unsafe { ffi::rocksdb_options_get_min_blob_size(self.inner) }
    }

    /// Returns the current `min_write_buffer_number_to_merge` setting.
    ///
    /// See [`Self::set_min_write_buffer_number_to_merge`] for what this controls.
    pub fn get_min_write_buffer_number_to_merge(&self) -> c_int {
        unsafe { ffi::rocksdb_options_get_min_write_buffer_number_to_merge(self.inner) }
    }

    /// Returns the current `num_levels` setting.
    ///
    /// See [`Self::set_num_levels`] for what this controls.
    pub fn get_num_levels(&self) -> c_int {
        unsafe { ffi::rocksdb_options_get_num_levels(self.inner) }
    }

    /// Returns the current `optimize_filters_for_hits` setting.
    ///
    /// See [`Self::set_optimize_filters_for_hits`] for what this controls.
    pub fn get_optimize_filters_for_hits(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_optimize_filters_for_hits(self.inner) != 0 }
    }

    /// Returns the current `paranoid_checks` setting.
    ///
    /// See [`Self::set_paranoid_checks`] for what this controls.
    pub fn get_paranoid_checks(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_paranoid_checks(self.inner) != 0 }
    }

    /// Returns the current `periodic_compaction_seconds` setting.
    ///
    /// See [`Self::set_periodic_compaction_seconds`] for what this controls.
    pub fn get_periodic_compaction_seconds(&self) -> u64 {
        unsafe { ffi::rocksdb_options_get_periodic_compaction_seconds(self.inner) }
    }

    /// Returns the current `recycle_log_file_num` setting.
    ///
    /// See [`Self::set_recycle_log_file_num`] for what this controls.
    pub fn get_recycle_log_file_num(&self) -> usize {
        unsafe { ffi::rocksdb_options_get_recycle_log_file_num(self.inner) }
    }

    /// Returns the current `report_bg_io_stats` setting.
    ///
    /// See [`Self::set_report_bg_io_stats`] for what this controls.
    pub fn get_report_bg_io_stats(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_report_bg_io_stats(self.inner) != 0 }
    }

    /// Returns the current `skip_stats_update_on_db_open` setting.
    ///
    /// See [`Self::set_skip_stats_update_on_db_open`] for what this controls.
    pub fn get_skip_stats_update_on_db_open(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_skip_stats_update_on_db_open(self.inner) != 0 }
    }

    /// Returns the current `soft_pending_compaction_bytes_limit` setting.
    ///
    /// See [`Self::set_soft_pending_compaction_bytes_limit`] for what this controls.
    pub fn get_soft_pending_compaction_bytes_limit(&self) -> usize {
        unsafe { ffi::rocksdb_options_get_soft_pending_compaction_bytes_limit(self.inner) }
    }

    /// Returns the current `stats_dump_period_sec` setting.
    ///
    /// See [`Self::set_stats_dump_period_sec`] for what this controls.
    pub fn get_stats_dump_period_sec(&self) -> u32 {
        unsafe { ffi::rocksdb_options_get_stats_dump_period_sec(self.inner) }
    }

    /// Returns the current `stats_persist_period_sec` setting.
    ///
    /// See [`Self::set_stats_persist_period_sec`] for what this controls.
    pub fn get_stats_persist_period_sec(&self) -> u32 {
        unsafe { ffi::rocksdb_options_get_stats_persist_period_sec(self.inner) }
    }

    /// Number of shards used for table cache.
    pub fn get_table_cache_numshardbits(&self) -> c_int {
        unsafe { ffi::rocksdb_options_get_table_cache_numshardbits(self.inner) }
    }

    /// Returns the current `target_file_size_base` setting.
    ///
    /// See [`Self::set_target_file_size_base`] for what this controls.
    pub fn get_target_file_size_base(&self) -> u64 {
        unsafe { ffi::rocksdb_options_get_target_file_size_base(self.inner) }
    }

    /// Returns the current `target_file_size_multiplier` setting.
    ///
    /// See [`Self::set_target_file_size_multiplier`] for what this controls.
    pub fn get_target_file_size_multiplier(&self) -> c_int {
        unsafe { ffi::rocksdb_options_get_target_file_size_multiplier(self.inner) }
    }

    /// Returns the current `ttl` setting.
    ///
    /// See [`Self::set_ttl`] for what this controls.
    pub fn get_ttl(&self) -> u64 {
        unsafe { ffi::rocksdb_options_get_ttl(self.inner) }
    }

    /// Returns the current `unordered_write` setting.
    ///
    /// See [`Self::set_unordered_write`] for what this controls.
    pub fn get_unordered_write(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_unordered_write(self.inner) != 0 }
    }

    /// Returns the current `use_adaptive_mutex` setting.
    ///
    /// See [`Self::set_use_adaptive_mutex`] for what this controls.
    pub fn get_use_adaptive_mutex(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_use_adaptive_mutex(self.inner) != 0 }
    }

    /// Returns the current `use_direct_io_for_flush_and_compaction` setting.
    ///
    /// See [`Self::set_use_direct_io_for_flush_and_compaction`] for what this controls.
    pub fn get_use_direct_io_for_flush_and_compaction(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_use_direct_io_for_flush_and_compaction(self.inner) != 0 }
    }

    /// Returns the current `use_direct_reads` setting.
    ///
    /// See [`Self::set_use_direct_reads`] for what this controls.
    pub fn get_use_direct_reads(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_use_direct_reads(self.inner) != 0 }
    }

    /// Returns the current `wal_bytes_per_sync` setting.
    ///
    /// See [`Self::set_wal_bytes_per_sync`] for what this controls.
    pub fn get_wal_bytes_per_sync(&self) -> u64 {
        unsafe { ffi::rocksdb_options_get_wal_bytes_per_sync(self.inner) }
    }

    /// Returns the current `wal_size_limit_mb` setting.
    ///
    /// See [`Self::set_wal_size_limit_mb`] for what this controls.
    pub fn get_wal_size_limit_mb(&self) -> u64 {
        unsafe { ffi::rocksdb_options_get_WAL_size_limit_MB(self.inner) }
    }

    /// Returns the current `wal_ttl_seconds` setting.
    ///
    /// See [`Self::set_wal_ttl_seconds`] for what this controls.
    pub fn get_wal_ttl_seconds(&self) -> u64 {
        unsafe { ffi::rocksdb_options_get_WAL_ttl_seconds(self.inner) }
    }

    /// Returns the current `writable_file_max_buffer_size` setting.
    ///
    /// See [`Self::set_writable_file_max_buffer_size`] for what this controls.
    pub fn get_writable_file_max_buffer_size(&self) -> u64 {
        unsafe { ffi::rocksdb_options_get_writable_file_max_buffer_size(self.inner) }
    }

    /// Returns the current `write_buffer_size` setting.
    ///
    /// See [`Self::set_write_buffer_size`] for what this controls.
    pub fn get_write_buffer_size(&self) -> usize {
        unsafe { ffi::rocksdb_options_get_write_buffer_size(self.inner) }
    }

    /// Returns the current `write_identity_file` setting.
    ///
    /// See [`Self::set_write_identity_file`] for what this controls.
    pub fn get_write_identity_file(&self) -> bool {
        unsafe { ffi::rocksdb_options_get_write_identity_file(self.inner) != 0 }
    }

    /// Enable blob files starting from a certain LSM tree level.
    ///
    /// For certain use cases that have a mix of short-lived and long-lived values, it might
    /// make sense to support extracting large values only during compactions whose output
    /// level is greater than or equal to a specified LSM tree level (e.g. compactions into
    /// L1/L2/... or above). This could reduce the space amplification caused by large values
    /// that are turned into garbage shortly after being written at the price of some write
    /// amplification incurred by long-lived values whose extraction to blob files is delayed.
    ///
    /// Default: 0
    ///
    /// Dynamically changeable through the SetOptions() API.
    pub fn set_blob_file_starting_level(&mut self, val: c_int) {
        unsafe {
            ffi::rocksdb_options_set_blob_file_starting_level(self.inner, val);
        }
    }

    /// Bottommost-level counterpart of
    /// [`Self::set_compression_options_max_dict_buffer_bytes`].
    ///
    /// `enabled` must be true for the bottommost setting to take effect; otherwise
    /// the non-bottommost compression options apply.
    pub fn set_bottommost_compression_options_max_dict_buffer_bytes(
        &mut self,
        max_dict_buffer_bytes: u64,
        enabled: bool,
    ) {
        unsafe {
            ffi::rocksdb_options_set_bottommost_compression_options_max_dict_buffer_bytes(
                self.inner,
                max_dict_buffer_bytes,
                c_uchar::from(enabled),
            );
        }
    }

    /// Bottommost-level counterpart of
    /// [`Self::set_compression_options_use_zstd_dict_trainer`].
    ///
    /// `enabled` must be true for the bottommost setting to take effect; otherwise
    /// the non-bottommost compression options apply.
    pub fn set_bottommost_compression_options_use_zstd_dict_trainer(
        &mut self,
        use_zstd_dict_trainer: bool,
        enabled: bool,
    ) {
        unsafe {
            ffi::rocksdb_options_set_bottommost_compression_options_use_zstd_dict_trainer(
                self.inner,
                c_uchar::from(use_zstd_dict_trainer),
                c_uchar::from(enabled),
            );
        }
    }

    /// Limits the max buffered data used to build the compression dictionary.
    ///
    /// Limiting too strictly may harm dictionary effectiveness, because it forces
    /// RocksDB to pick samples from the start of the output SST, which may not
    /// represent the whole file. Setting it below `zstd_max_train_bytes` restricts
    /// how many samples reach the dictionary trainer, and setting it below
    /// `max_dict_bytes` restricts the size of the final dictionary.
    ///
    /// Default: `0`
    pub fn set_compression_options_max_dict_buffer_bytes(&mut self, val: u64) {
        unsafe {
            ffi::rocksdb_options_set_compression_options_max_dict_buffer_bytes(self.inner, val);
        }
    }

    /// Selects how zstd dictionaries are generated.
    ///
    /// When true, buffered data is passed to zstd's dictionary trainer. When false,
    /// zstd's `ZDICT_finalizeDictionary()` is called instead, which saves CPU during
    /// training but usually gives a worse compression ratio.
    ///
    /// Default: `true`
    pub fn set_compression_options_use_zstd_dict_trainer(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_compression_options_use_zstd_dict_trainer(
                self.inner,
                c_uchar::from(val),
            );
        }
    }

    /// Installs the built-in merge operator that adds 64-bit counters.
    ///
    /// Values are RocksDB fixed-width 64-bit integers, and a value that is not
    /// exactly that width is treated as 0 rather than failing the merge.
    pub fn set_uint64add_merge_operator(&mut self) {
        unsafe {
            ffi::rocksdb_options_set_uint64add_merge_operator(self.inner);
        }
    }

    /// It is expected that the Identity file will be obsoleted by recording DB ID in the
    /// manifest (see write_dbid_to_manifest). Setting this to true maintains the historical
    /// behavior of writing an Identity file, while setting to false is expected to be the
    /// future default. This option might eventually be obsolete and removed as Identity files
    /// are phased out.
    pub fn set_write_identity_file(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_options_set_write_identity_file(self.inner, c_uchar::from(val));
        }
    }
}

impl Default for Options {
    fn default() -> Self {
        unsafe {
            let opts = ffi::rocksdb_options_create();
            assert!(!opts.is_null(), "Could not create RocksDB options");

            Self {
                inner: opts,
                outlive: OptionsMustOutliveDB::default(),
            }
        }
    }
}

impl FlushOptions {
    pub fn new() -> FlushOptions {
        FlushOptions::default()
    }

    /// Waits until the flush is done.
    ///
    /// Default: true
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_rocksdb::FlushOptions;
    ///
    /// let mut options = FlushOptions::default();
    /// options.set_wait(false);
    /// ```
    pub fn set_wait(&mut self, wait: bool) {
        unsafe {
            ffi::rocksdb_flushoptions_set_wait(self.inner, c_uchar::from(wait));
        }
    }

    /// If true, the flush would proceed immediately even it means writes will stall for the
    /// duration of the flush; if false the operation will wait until it's possible to do
    /// flush w/o causing stall or until required flush is performed by someone else
    /// (foreground call or background thread). Default: false
    pub fn set_allow_write_stall(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_flushoptions_set_allow_write_stall(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `allow_write_stall` option.
    pub fn get_allow_write_stall(&self) -> bool {
        unsafe { ffi::rocksdb_flushoptions_get_allow_write_stall(self.inner) != 0 }
    }

    /// If true, use atomic flush to flush all column families atomically, regardless of the
    /// DBOptions::atomic_flush setting. When used with DB::Flush() or internally via
    /// GetLiveFilesStorageInfo(), this forces all column families to be flushed in a single
    /// atomic operation. Default: false (uses DBOptions::atomic_flush setting).
    pub fn set_force_atomic_flush(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_flushoptions_set_force_atomic_flush(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `force_atomic_flush` option.
    pub fn get_force_atomic_flush(&self) -> bool {
        unsafe { ffi::rocksdb_flushoptions_get_force_atomic_flush(self.inner) != 0 }
    }

    /// If true (and `wait` is also true), Flush() will not return until the registered
    /// EventListener::OnFlushCompleted callbacks for the flushed memtables have finished
    /// running. By default (false), Flush(wait=true) may return as soon as the flush result
    /// is committed, which can be before (or while) the OnFlushCompleted callbacks execute on
    /// the background flush thread. Set this to true when the caller needs to observe the
    /// effects of its OnFlushCompleted listener(s) immediately after Flush() returns. Has no
    /// effect when `wait == false`. Default: false
    pub fn set_listener_wait(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_flushoptions_set_listener_wait(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `listener_wait` option.
    pub fn get_listener_wait(&self) -> bool {
        unsafe { ffi::rocksdb_flushoptions_get_listener_wait(self.inner) != 0 }
    }

    /// Returns the current `wait` setting.
    ///
    /// See [`Self::set_wait`] for what this controls.
    pub fn get_wait(&self) -> bool {
        unsafe { ffi::rocksdb_flushoptions_get_wait(self.inner) != 0 }
    }
}

impl Default for FlushOptions {
    fn default() -> Self {
        let flush_opts = unsafe { ffi::rocksdb_flushoptions_create() };
        assert!(
            !flush_opts.is_null(),
            "Could not create RocksDB flush options"
        );

        Self { inner: flush_opts }
    }
}

impl FlushWalOptions {
    #[must_use]
    pub fn new() -> FlushWalOptions {
        FlushWalOptions::default()
    }

    pub(crate) fn as_ptr(&self) -> *const ffi::rocksdb_flushwaloptions_t {
        self.inner
    }

    /// Calls `SyncWAL()` after the flush, so the writes are on durable storage
    /// rather than only handed to the operating system.
    ///
    /// Default: false
    pub fn set_sync(&mut self, sync: bool) {
        unsafe {
            ffi::rocksdb_flushwaloptions_set_sync(self.inner, c_uchar::from(sync));
        }
    }

    /// Returns the value of the `sync` option.
    pub fn get_sync(&self) -> bool {
        unsafe { ffi::rocksdb_flushwaloptions_get_sync(self.inner) != 0 }
    }

    /// Charges the IO this flush performs to the rate limiter set with
    /// [`Options::set_ratelimiter`] at the given priority, and passes the
    /// priority down to the file system.
    ///
    /// [`IoPriority::Total`] disables charging the rate limiter, which is the
    /// default.
    pub fn set_rate_limiter_priority(&mut self, priority: IoPriority) {
        unsafe {
            ffi::rocksdb_flushwaloptions_set_rate_limiter_priority(self.inner, priority as c_int);
        }
    }

    /// Returns the value of the `rate_limiter_priority` option.
    ///
    /// Returns `None` if RocksDB reports a priority this crate has no variant
    /// for, which should not happen.
    pub fn get_rate_limiter_priority(&self) -> Option<IoPriority> {
        let raw = unsafe { ffi::rocksdb_flushwaloptions_get_rate_limiter_priority(self.inner) };
        IoPriority::try_from_raw(raw)
    }
}

impl Default for FlushWalOptions {
    fn default() -> Self {
        let opts = unsafe { ffi::rocksdb_flushwaloptions_create() };
        assert!(
            !opts.is_null(),
            "Could not create RocksDB flush WAL options"
        );

        Self { inner: opts }
    }
}

impl SizeApproximationOptions {
    #[must_use]
    pub fn new() -> SizeApproximationOptions {
        SizeApproximationOptions::default()
    }

    pub(crate) fn as_ptr(&self) -> *const ffi::rocksdb_size_approximation_options_t {
        self.inner
    }

    /// Counts data still sitting in the memtables.
    ///
    /// Default: false
    pub fn set_include_memtables(&mut self, include: bool) {
        unsafe {
            ffi::rocksdb_size_approximation_options_set_include_memtables(
                self.inner,
                c_uchar::from(include),
            );
        }
    }

    /// Returns the value of the `include_memtables` option.
    pub fn get_include_memtables(&self) -> bool {
        unsafe { ffi::rocksdb_size_approximation_options_get_include_memtables(self.inner) != 0 }
    }

    /// Counts data written out to SST files.
    ///
    /// Default: true
    pub fn set_include_files(&mut self, include: bool) {
        unsafe {
            ffi::rocksdb_size_approximation_options_set_include_files(
                self.inner,
                c_uchar::from(include),
            );
        }
    }

    /// Returns the value of the `include_files` option.
    pub fn get_include_files(&self) -> bool {
        unsafe { ffi::rocksdb_size_approximation_options_get_include_files(self.inner) != 0 }
    }

    /// Counts a share of the blob files, prorated by how much of the SST data
    /// falls in the range:
    ///
    /// ```text
    /// blob_size_in_range ~= total_blob_size * (sst_in_range / total_sst)
    /// ```
    ///
    /// That assumes blob values are spread evenly across keys, so it skews when
    /// value sizes vary a lot. It also reports zero blob bytes when every key is
    /// still in a memtable, because there is no SST data to prorate against.
    ///
    /// Default: false
    pub fn set_include_blob_files(&mut self, include: bool) {
        unsafe {
            ffi::rocksdb_size_approximation_options_set_include_blob_files(
                self.inner,
                c_uchar::from(include),
            );
        }
    }

    /// Returns the value of the `include_blob_files` option.
    pub fn get_include_blob_files(&self) -> bool {
        unsafe { ffi::rocksdb_size_approximation_options_get_include_blob_files(self.inner) != 0 }
    }

    /// Lets the file-size estimate be off by up to
    /// `total_files_size * margin` in exchange for doing less work, so 0.1
    /// allows a 10% error.
    ///
    /// Zero or negative asks for the precise and more CPU intensive walk.
    pub fn set_files_size_error_margin(&mut self, margin: f64) {
        unsafe {
            ffi::rocksdb_size_approximation_options_set_files_size_error_margin(self.inner, margin);
        }
    }

    /// Returns the value of the `files_size_error_margin` option.
    pub fn get_files_size_error_margin(&self) -> f64 {
        unsafe { ffi::rocksdb_size_approximation_options_get_files_size_error_margin(self.inner) }
    }
}

impl Default for SizeApproximationOptions {
    fn default() -> Self {
        let opts = unsafe { ffi::rocksdb_size_approximation_options_create() };
        assert!(
            !opts.is_null(),
            "Could not create RocksDB size approximation options"
        );

        Self { inner: opts }
    }
}

impl WriteOptions {
    pub fn new() -> WriteOptions {
        WriteOptions::default()
    }

    /// Sets the sync mode. If true, the write will be flushed
    /// from the operating system buffer cache before the write is considered complete.
    /// If this flag is true, writes will be slower.
    ///
    /// Default: false
    pub fn set_sync(&mut self, sync: bool) {
        unsafe {
            ffi::rocksdb_writeoptions_set_sync(self.inner, c_uchar::from(sync));
        }
    }

    /// Sets whether WAL should be active or not.
    /// If true, writes will not first go to the write ahead log,
    /// and the write may got lost after a crash.
    ///
    /// Default: false
    pub fn disable_wal(&mut self, disable: bool) {
        unsafe {
            ffi::rocksdb_writeoptions_disable_WAL(self.inner, c_int::from(disable));
        }
    }

    /// If true and if user is trying to write to column families that don't exist (they were dropped),
    /// ignore the write (don't return an error). If there are multiple writes in a WriteBatch,
    /// other writes will succeed.
    ///
    /// Default: false
    pub fn set_ignore_missing_column_families(&mut self, ignore: bool) {
        unsafe {
            ffi::rocksdb_writeoptions_set_ignore_missing_column_families(
                self.inner,
                c_uchar::from(ignore),
            );
        }
    }

    /// If true and we need to wait or sleep for the write request, fails
    /// immediately with Status::Incomplete().
    ///
    /// Default: false
    pub fn set_no_slowdown(&mut self, no_slowdown: bool) {
        unsafe {
            ffi::rocksdb_writeoptions_set_no_slowdown(self.inner, c_uchar::from(no_slowdown));
        }
    }

    /// If true, this write request is of lower priority if compaction is
    /// behind. In this case, no_slowdown = true, the request will be cancelled
    /// immediately with Status::Incomplete() returned. Otherwise, it will be
    /// slowed down. The slowdown value is determined by RocksDB to guarantee
    /// it introduces minimum impacts to high priority writes.
    ///
    /// Default: false
    pub fn set_low_pri(&mut self, v: bool) {
        unsafe {
            ffi::rocksdb_writeoptions_set_low_pri(self.inner, c_uchar::from(v));
        }
    }

    /// If true, writebatch will maintain the last insert positions of each
    /// memtable as hints in concurrent write. It can improve write performance
    /// in concurrent writes if keys in one writebatch are sequential. In
    /// non-concurrent writes (when concurrent_memtable_writes is false) this
    /// option will be ignored.
    ///
    /// Default: false
    pub fn set_memtable_insert_hint_per_batch(&mut self, v: bool) {
        unsafe {
            ffi::rocksdb_writeoptions_set_memtable_insert_hint_per_batch(
                self.inner,
                c_uchar::from(v),
            );
        }
    }

    /// EXPERIMENTAL
    pub fn set_io_activity(&mut self, val: c_int) {
        unsafe {
            ffi::rocksdb_writeoptions_set_io_activity(self.inner, val);
        }
    }

    /// Returns the value of the `io_activity` option.
    pub fn get_io_activity(&self) -> c_int {
        unsafe { ffi::rocksdb_writeoptions_get_io_activity(self.inner) }
    }

    /// `protection_bytes_per_key` is the number of bytes used to store protection information
    /// for each key entry. Currently supported values are zero (disabled) and eight.
    ///
    /// Default: zero (disabled).
    pub fn set_protection_bytes_per_key(&mut self, val: usize) {
        unsafe {
            ffi::rocksdb_writeoptions_set_protection_bytes_per_key(self.inner, val);
        }
    }

    /// Returns the value of the `protection_bytes_per_key` option.
    pub fn get_protection_bytes_per_key(&self) -> usize {
        unsafe { ffi::rocksdb_writeoptions_get_protection_bytes_per_key(self.inner) }
    }

    /// For file reads associated with this option, charge the internal rate limiter (see
    /// `DBOptions::rate_limiter`) at the specified priority. The special value
    /// `Env::IO_TOTAL` disables charging the rate limiter.
    ///
    /// The rate limiting is bypassed no matter this option's value for file reads on plain
    /// tables (these can exist when `ColumnFamilyOptions::table_factory` is a
    /// `PlainTableFactory`) and cuckoo tables (these can exist when
    /// `ColumnFamilyOptions::table_factory` is a `CuckooTableFactory`).
    ///
    /// The bytes charged to rate limiter may not exactly match the file read bytes since
    /// there are some seemingly insignificant reads, like for file headers/footers, that we
    /// currently do not charge to rate limiter.
    pub fn set_rate_limiter_priority(&mut self, val: c_int) {
        unsafe {
            ffi::rocksdb_writeoptions_set_rate_limiter_priority(self.inner, val);
        }
    }

    /// Returns the value of the `rate_limiter_priority` option.
    pub fn get_rate_limiter_priority(&self) -> c_int {
        unsafe { ffi::rocksdb_writeoptions_get_rate_limiter_priority(self.inner) }
    }

    /// Returns the current `disable_wal` setting.
    ///
    /// See [`Self::disable_wal`] for what this controls.
    pub fn get_disable_wal(&self) -> bool {
        unsafe { ffi::rocksdb_writeoptions_get_disable_WAL(self.inner) != 0 }
    }

    /// Returns the current `ignore_missing_column_families` setting.
    ///
    /// See [`Self::set_ignore_missing_column_families`] for what this controls.
    pub fn get_ignore_missing_column_families(&self) -> bool {
        unsafe { ffi::rocksdb_writeoptions_get_ignore_missing_column_families(self.inner) != 0 }
    }

    /// Returns the current `low_pri` setting.
    ///
    /// See [`Self::set_low_pri`] for what this controls.
    pub fn get_low_pri(&self) -> bool {
        unsafe { ffi::rocksdb_writeoptions_get_low_pri(self.inner) != 0 }
    }

    /// Returns the current `memtable_insert_hint_per_batch` setting.
    ///
    /// See [`Self::set_memtable_insert_hint_per_batch`] for what this controls.
    pub fn get_memtable_insert_hint_per_batch(&self) -> bool {
        unsafe { ffi::rocksdb_writeoptions_get_memtable_insert_hint_per_batch(self.inner) != 0 }
    }

    /// Returns the current `no_slowdown` setting.
    ///
    /// See [`Self::set_no_slowdown`] for what this controls.
    pub fn get_no_slowdown(&self) -> bool {
        unsafe { ffi::rocksdb_writeoptions_get_no_slowdown(self.inner) != 0 }
    }

    /// Returns the current `sync` setting.
    ///
    /// See [`Self::set_sync`] for what this controls.
    pub fn get_sync(&self) -> bool {
        unsafe { ffi::rocksdb_writeoptions_get_sync(self.inner) != 0 }
    }
}

impl Default for WriteOptions {
    fn default() -> Self {
        let write_opts = unsafe { ffi::rocksdb_writeoptions_create() };
        assert!(
            !write_opts.is_null(),
            "Could not create RocksDB write options"
        );

        Self { inner: write_opts }
    }
}

impl LruCacheOptions {
    /// Capacity of the cache, in the same units as the `charge` of each entry.
    /// This is typically measured in bytes, but can be a different unit if using
    /// kDontChargeCacheMetadata.
    pub fn set_capacity(&mut self, cap: usize) {
        unsafe {
            ffi::rocksdb_lru_cache_options_set_capacity(self.inner, cap);
        }
    }

    /// Cache is sharded into 2^num_shard_bits shards, by hash of key.
    /// If < 0, a good default is chosen based on the capacity and the
    /// implementation. (Mutex-based implementations are much more reliant
    /// on many shards for parallel scalability.)
    pub fn set_num_shard_bits(&mut self, val: c_int) {
        unsafe {
            ffi::rocksdb_lru_cache_options_set_num_shard_bits(self.inner, val);
        }
    }

    /// Allocates cache block memory through `allocator` instead of the system
    /// allocator.
    ///
    /// These options do not borrow the allocator. The C setter copies the
    /// `shared_ptr<MemoryAllocator>` out of the handle, so the allocator stays
    /// alive through the options and the caches built from them even after the
    /// [`MemoryAllocator`] here is dropped.
    pub fn set_memory_allocator(&mut self, allocator: &MemoryAllocator) {
        unsafe {
            ffi::rocksdb_lru_cache_options_set_memory_allocator(self.inner, allocator.as_ptr());
        }
    }
}

impl Default for LruCacheOptions {
    fn default() -> Self {
        let inner = unsafe { ffi::rocksdb_lru_cache_options_create() };
        assert!(
            !inner.is_null(),
            "Could not create RocksDB LRU cache options"
        );

        Self { inner }
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde1", derive(serde::Serialize, serde::Deserialize))]
#[repr(i32)]
pub enum ReadTier {
    /// Reads data in memtable, block cache, OS cache or storage.
    All = 0,
    /// Reads data in memtable or block cache.
    BlockCache,
    /// Reads persisted data. When WAL is disabled, this option will skip data in memtable.
    Persisted,
    /// Reads data in memtable. Used for memtable only iterators.
    Memtable,
}

impl ReadTier {
    /// Decodes a raw `rocksdb::ReadTier`.
    ///
    /// This covers every tier RocksDB defines today, so `None` only means a future release
    /// added one.
    pub(crate) fn try_from_raw(raw: c_int) -> Option<Self> {
        match raw {
            n if n == ReadTier::All as c_int => Some(ReadTier::All),
            n if n == ReadTier::BlockCache as c_int => Some(ReadTier::BlockCache),
            n if n == ReadTier::Persisted as c_int => Some(ReadTier::Persisted),
            n if n == ReadTier::Memtable as c_int => Some(ReadTier::Memtable),
            _ => None,
        }
    }
}

impl ReadOptions {
    // TODO add snapshot setting here
    // TODO add snapshot wrapper structs with proper destructors;
    // that struct needs an "iterator" impl too.

    /// Specify whether the "data block"/"index block"/"filter block"
    /// read for this iteration should be cached in memory?
    /// Callers may wish to set this field to false for bulk scans.
    ///
    /// Default: true
    pub fn fill_cache(&mut self, v: bool) {
        unsafe {
            ffi::rocksdb_readoptions_set_fill_cache(self.inner, c_uchar::from(v));
        }
    }

    /// Sets the snapshot which should be used for the read.
    /// The snapshot must belong to the DB that is being read and must
    /// not have been released.
    pub fn set_snapshot<D: DBAccess>(&mut self, snapshot: &SnapshotWithThreadMode<D>) {
        unsafe {
            ffi::rocksdb_readoptions_set_snapshot(self.inner, snapshot.inner);
        }
    }

    /// Sets the lower bound for an iterator.
    pub fn set_iterate_lower_bound<K: Into<Vec<u8>>>(&mut self, key: K) {
        self.set_lower_bound_impl(Some(key.into()));
    }

    /// Sets the upper bound for an iterator.
    /// The upper bound itself is not included on the iteration result.
    pub fn set_iterate_upper_bound<K: Into<Vec<u8>>>(&mut self, key: K) {
        self.set_upper_bound_impl(Some(key.into()));
    }

    /// Sets lower and upper bounds based on the provided range.  This is
    /// similar to setting lower and upper bounds separately except that it also
    /// allows either bound to be reset.
    ///
    /// The argument can be a regular Rust range, e.g. `lower..upper`.  However,
    /// since RocksDB upper bound is always excluded (i.e. range can never be
    /// fully closed) inclusive ranges (`lower..=upper` and `..=upper`) are not
    /// supported.  For example:
    ///
    /// ```
    /// let mut options = rust_rocksdb::ReadOptions::default();
    /// options.set_iterate_range("xy".as_bytes().."xz".as_bytes());
    /// ```
    ///
    /// In addition, [`crate::PrefixRange`] can be used to specify a range of
    /// keys with a given prefix.  In particular, the above example is
    /// equivalent to:
    ///
    /// ```
    /// let mut options = rust_rocksdb::ReadOptions::default();
    /// options.set_iterate_range(rust_rocksdb::PrefixRange("xy".as_bytes()));
    /// ```
    ///
    /// Note that setting range using this method is separate to using prefix
    /// iterators.  Prefix iterators use prefix extractor configured for
    /// a column family.  Setting bounds via [`crate::PrefixRange`] is more akin
    /// to using manual prefix.
    ///
    /// Using this method clears any previously set bounds.  In other words, the
    /// bounds can be reset by setting the range to `..` as in:
    ///
    /// ```
    /// let mut options = rust_rocksdb::ReadOptions::default();
    /// options.set_iterate_range(..);
    /// ```
    pub fn set_iterate_range(&mut self, range: impl crate::IterateBounds) {
        let (lower, upper) = range.into_bounds();
        self.set_lower_bound_impl(lower);
        self.set_upper_bound_impl(upper);
    }

    /// Equivalent to `set_iterate_range(PrefixRange(prefix))`, but writes into
    /// the already-allocated bound buffers instead of building two fresh
    /// `Vec<u8>`s and dropping the old ones.
    ///
    /// `set_iterate_range` has to allocate because `IterateBounds::into_bounds`
    /// hands back owned `Vec`s. That is fine for one-off configuration, but the
    /// hot prefix-probe path reuses a cached `ReadOptions` specifically to avoid
    /// per-call allocation, and then threw that away by reallocating both bounds
    /// on every call. Reusing the buffers makes the steady state allocation-free.
    pub(crate) fn set_prefix_range_in_place(&mut self, prefix: &[u8]) {
        // An empty prefix covers the full keyspace, i.e. no bounds at all.
        if prefix.is_empty() {
            self.set_lower_bound_impl(None);
            self.set_upper_bound_impl(None);
            return;
        }

        // Lower bound is the prefix itself. The buffer can be reallocated by
        // `extend_from_slice`, so the pointer has to be handed to RocksDB again
        // even when the bound was already set.
        let (ptr, len) = {
            let lower = self.iterate_lower_bound.get_or_insert_with(Vec::new);
            lower.clear();
            lower.extend_from_slice(prefix);
            (lower.as_ptr() as *const c_char, lower.len())
        };
        unsafe {
            ffi::rocksdb_readoptions_set_iterate_lower_bound(self.inner, ptr, len);
        }

        // Upper bound is the successor of the prefix: strip trailing 0xff bytes,
        // then increment the last remaining one. A prefix that is entirely 0xff
        // has no successor, so it is an unbounded scan. This mirrors
        // `iter_range::next_prefix`.
        let ffs = prefix
            .iter()
            .rev()
            .take_while(|&&byte| byte == u8::MAX)
            .count();
        let head = &prefix[..prefix.len() - ffs];
        if head.is_empty() {
            self.set_upper_bound_impl(None);
            return;
        }
        let (ptr, len) = {
            let upper = self.iterate_upper_bound.get_or_insert_with(Vec::new);
            upper.clear();
            upper.extend_from_slice(head);
            // `head` is non-empty and its last byte is not 0xff, so this cannot
            // overflow.
            *upper.last_mut().unwrap() += 1;
            (upper.as_ptr() as *const c_char, upper.len())
        };
        unsafe {
            ffi::rocksdb_readoptions_set_iterate_upper_bound(self.inner, ptr, len);
        }
    }

    fn set_lower_bound_impl(&mut self, bound: Option<Vec<u8>>) {
        let (ptr, len) = if let Some(ref bound) = bound {
            (bound.as_ptr() as *const c_char, bound.len())
        } else if self.iterate_lower_bound.is_some() {
            (std::ptr::null(), 0)
        } else {
            return;
        };
        self.iterate_lower_bound = bound;
        unsafe {
            ffi::rocksdb_readoptions_set_iterate_lower_bound(self.inner, ptr, len);
        }
    }

    fn set_upper_bound_impl(&mut self, bound: Option<Vec<u8>>) {
        let (ptr, len) = if let Some(ref bound) = bound {
            (bound.as_ptr() as *const c_char, bound.len())
        } else if self.iterate_upper_bound.is_some() {
            (std::ptr::null(), 0)
        } else {
            return;
        };
        self.iterate_upper_bound = bound;
        unsafe {
            ffi::rocksdb_readoptions_set_iterate_upper_bound(self.inner, ptr, len);
        }
    }

    /// Specify if this read request should process data that ALREADY
    /// resides on a particular cache. If the required data is not
    /// found at the specified cache, then Status::Incomplete is returned.
    ///
    /// Default: ::All
    pub fn set_read_tier(&mut self, tier: ReadTier) {
        unsafe {
            ffi::rocksdb_readoptions_set_read_tier(self.inner, tier as c_int);
        }
    }

    /// The tier set by [`Self::set_read_tier`].
    ///
    /// [`ReadTier`] covers every tier RocksDB defines today, so `None` only shows up if a
    /// future release adds one.
    pub fn get_read_tier(&self) -> Option<ReadTier> {
        let raw = unsafe { ffi::rocksdb_readoptions_get_read_tier(self.inner) };
        ReadTier::try_from_raw(raw)
    }

    /// Enforce that the iterator only iterates over the same
    /// prefix as the seek.
    /// This option is effective only for prefix seeks, i.e. prefix_extractor is
    /// non-null for the column family and total_order_seek is false.  Unlike
    /// iterate_upper_bound, prefix_same_as_start only works within a prefix
    /// but in both directions.
    ///
    /// Default: false
    pub fn set_prefix_same_as_start(&mut self, v: bool) {
        unsafe {
            ffi::rocksdb_readoptions_set_prefix_same_as_start(self.inner, c_uchar::from(v));
        }
    }

    /// Enable a total order seek regardless of index format (e.g. hash index)
    /// used in the table. Some table format (e.g. plain table) may not support
    /// this option.
    ///
    /// If true when calling Get(), we also skip prefix bloom when reading from
    /// block based table. It provides a way to read existing data after
    /// changing implementation of prefix extractor.
    pub fn set_total_order_seek(&mut self, v: bool) {
        unsafe {
            ffi::rocksdb_readoptions_set_total_order_seek(self.inner, c_uchar::from(v));
        }
    }

    /// Sets a threshold for the number of keys that can be skipped
    /// before failing an iterator seek as incomplete. The default value of 0 should be used to
    /// never fail a request as incomplete, even on skipping too many keys.
    ///
    /// Default: 0
    pub fn set_max_skippable_internal_keys(&mut self, num: u64) {
        unsafe {
            ffi::rocksdb_readoptions_set_max_skippable_internal_keys(self.inner, num);
        }
    }

    /// If true, when PurgeObsoleteFile is called in CleanupIteratorState, we schedule a background job
    /// in the flush job queue and delete obsolete files in background.
    ///
    /// Default: false
    pub fn set_background_purge_on_iterator_cleanup(&mut self, v: bool) {
        unsafe {
            ffi::rocksdb_readoptions_set_background_purge_on_iterator_cleanup(
                self.inner,
                c_uchar::from(v),
            );
        }
    }

    /// If true, keys deleted using the DeleteRange() API will be visible to
    /// readers until they are naturally deleted during compaction.
    ///
    /// Default: false
    #[deprecated(
        note = "deprecated in RocksDB 10.2.1: no performance impact if DeleteRange is not used"
    )]
    pub fn set_ignore_range_deletions(&mut self, v: bool) {
        unsafe {
            ffi::rocksdb_readoptions_set_ignore_range_deletions(self.inner, c_uchar::from(v));
        }
    }

    /// Returns the value of the `ignore_range_deletions` option.
    ///
    /// Deprecated in RocksDB 10.2.1 along with its setter: there is no performance impact if
    /// `DeleteRange` is not used.
    pub fn get_ignore_range_deletions(&self) -> bool {
        unsafe { ffi::rocksdb_readoptions_get_ignore_range_deletions(self.inner) != 0 }
    }

    /// If true, all data read from underlying storage will be
    /// verified against corresponding checksums.
    ///
    /// Default: true
    pub fn set_verify_checksums(&mut self, v: bool) {
        unsafe {
            ffi::rocksdb_readoptions_set_verify_checksums(self.inner, c_uchar::from(v));
        }
    }

    /// If non-zero, an iterator will create a new table reader which
    /// performs reads of the given size. Using a large size (> 2MB) can
    /// improve the performance of forward iteration on spinning disks.
    /// Default: 0
    ///
    /// ```
    /// use rust_rocksdb::{ReadOptions};
    ///
    /// let mut opts = ReadOptions::default();
    /// opts.set_readahead_size(4_194_304); // 4mb
    /// ```
    pub fn set_readahead_size(&mut self, v: usize) {
        unsafe {
            ffi::rocksdb_readoptions_set_readahead_size(self.inner, v as size_t);
        }
    }

    /// If auto_readahead_size is set to true, it will auto tune the readahead_size
    /// during scans internally.
    /// For this feature to be enabled, iterate_upper_bound must also be specified.
    ///
    /// NOTE: - Recommended for forward Scans only.
    ///       - If there is a backward scans, this option will be
    ///         disabled internally and won't be enabled again if the forward scan
    ///         is issued again.
    ///
    /// Default: true
    pub fn set_auto_readahead_size(&mut self, v: bool) {
        unsafe {
            ffi::rocksdb_readoptions_set_auto_readahead_size(self.inner, c_uchar::from(v));
        }
    }

    /// If true, create a tailing iterator. Note that tailing iterators
    /// only support moving in the forward direction. Iterating in reverse
    /// or seek_to_last are not supported.
    pub fn set_tailing(&mut self, v: bool) {
        unsafe {
            ffi::rocksdb_readoptions_set_tailing(self.inner, c_uchar::from(v));
        }
    }

    /// Specifies the value of "pin_data". If true, it keeps the blocks
    /// loaded by the iterator pinned in memory as long as the iterator is not deleted,
    /// If used when reading from tables created with
    /// BlockBasedTableOptions::use_delta_encoding = false,
    /// Iterator's property "rocksdb.iterator.is-key-pinned" is guaranteed to
    /// return 1.
    ///
    /// Default: false
    pub fn set_pin_data(&mut self, v: bool) {
        unsafe {
            ffi::rocksdb_readoptions_set_pin_data(self.inner, c_uchar::from(v));
        }
    }

    /// Asynchronously prefetch some data.
    ///
    /// Used for sequential reads and internal automatic prefetching.
    ///
    /// Default: `false`
    pub fn set_async_io(&mut self, v: bool) {
        unsafe {
            ffi::rocksdb_readoptions_set_async_io(self.inner, c_uchar::from(v));
        }
    }

    /// Selects the multi-level vs single-level parallel `MultiGet` path when
    /// the library is built with `USE_COROUTINES` (the `coroutines` cargo
    /// feature) and `set_async_io(true)` has been called.
    ///
    /// When `true` (the C++ default), `MultiGet` parallelises reads across
    /// LSM levels, giving the lowest latency at the cost of higher CPU and
    /// coroutine scheduling overhead. When `false`, parallelism is limited
    /// to within a single level, trading some latency for CPU savings.
    ///
    /// Has no effect outside of `USE_COROUTINES` builds with `async_io=true`.
    /// With either condition unmet, both code paths in `db/version_set.cc`
    /// fall through to the synchronous per-file lookup regardless of this
    /// flag's value.
    ///
    /// See the RocksDB ["Asynchronous IO in RocksDB" blog
    /// post](https://rocksdb.org/blog/2022/10/07/asynchronous-io-in-rocksdb.html)
    /// for the qualitative tradeoff: `optimize_multiget_for_io=true`
    /// (multi-level) is the lowest-latency configuration but costs the most
    /// CPU; `optimize_multiget_for_io=false` (single-level, with `async_io`
    /// still on) retains most of the latency win at meaningfully lower CPU.
    ///
    /// Default: `true`
    pub fn set_optimize_multiget_for_io(&mut self, v: bool) {
        unsafe {
            ffi::rocksdb_readoptions_set_optimize_multiget_for_io(self.inner, c_uchar::from(v));
        }
    }

    /// Returns the current value of [`Self::set_optimize_multiget_for_io`].
    ///
    /// Provided primarily for tests that want to confirm the setter is wired
    /// through to the underlying C++ `ReadOptions`. Reads through to the C
    /// API getter without exposing the underlying `c_uchar` representation.
    pub fn get_optimize_multiget_for_io(&self) -> bool {
        unsafe { ffi::rocksdb_readoptions_get_optimize_multiget_for_io(self.inner) != 0 }
    }

    /// Deadline for completing an API call (Get/MultiGet/Seek/Next for now)
    /// in microseconds.
    /// It should be set to microseconds since epoch, i.e, gettimeofday or
    /// equivalent plus allowed duration in microseconds.
    /// This is best effort. The call may exceed the deadline if there is IO
    /// involved and the file system doesn't support deadlines, or due to
    /// checking for deadline periodically rather than for every key if
    /// processing a batch
    pub fn set_deadline(&mut self, microseconds: u64) {
        unsafe {
            ffi::rocksdb_readoptions_set_deadline(self.inner, microseconds);
        }
    }

    /// A timeout in microseconds to be passed to the underlying FileSystem for
    /// reads. As opposed to deadline, this determines the timeout for each
    /// individual file read request. If a MultiGet/Get/Seek/Next etc call
    /// results in multiple reads, each read can last up to io_timeout us.
    pub fn set_io_timeout(&mut self, microseconds: u64) {
        unsafe {
            ffi::rocksdb_readoptions_set_io_timeout(self.inner, microseconds);
        }
    }

    /// Timestamp of operation. Read should return the latest data visible to the
    /// specified timestamp. All timestamps of the same database must be of the
    /// same length and format. The user is responsible for providing a customized
    /// compare function via Comparator to order <key, timestamp> tuples.
    /// For iterator, iter_start_ts is the lower bound (older) and timestamp
    /// serves as the upper bound. Versions of the same record that fall in
    /// the timestamp range will be returned. If iter_start_ts is nullptr,
    /// only the most recent version visible to timestamp is returned.
    /// The user-specified timestamp feature is still under active development,
    /// and the API is subject to change.
    pub fn set_timestamp<S: Into<Vec<u8>>>(&mut self, ts: S) {
        self.set_timestamp_impl(Some(ts.into()));
    }

    fn set_timestamp_impl(&mut self, ts: Option<Vec<u8>>) {
        let (ptr, len) = if let Some(ref ts) = ts {
            (ts.as_ptr() as *const c_char, ts.len())
        } else if self.timestamp.is_some() {
            // The stored timestamp is a `Some` but we're updating it to a `None`.
            // This means to cancel a previously set timestamp.
            // To do this, use a null pointer and zero length.
            (std::ptr::null(), 0)
        } else {
            return;
        };
        self.timestamp = ts;
        unsafe {
            ffi::rocksdb_readoptions_set_timestamp(self.inner, ptr, len);
        }
    }

    /// See `set_timestamp`
    pub fn set_iter_start_ts<S: Into<Vec<u8>>>(&mut self, ts: S) {
        self.set_iter_start_ts_impl(Some(ts.into()));
    }

    fn set_iter_start_ts_impl(&mut self, ts: Option<Vec<u8>>) {
        let (ptr, len) = if let Some(ref ts) = ts {
            (ts.as_ptr() as *const c_char, ts.len())
        } else if self.timestamp.is_some() {
            (std::ptr::null(), 0)
        } else {
            return;
        };
        self.iter_start_ts = ts;
        unsafe {
            ffi::rocksdb_readoptions_set_iter_start_ts(self.inner, ptr, len);
        }
    }

    /// For iterators, RocksDB does auto-readahead on noticing more than two sequential reads
    /// for a table file if user doesn't provide readahead_size. The readahead starts at 8KB
    /// and doubles on every additional read upto max_auto_readahead_size only when reads are
    /// sequential. However at each level, if iterator moves over next file, readahead_size
    /// starts again from 8KB.
    ///
    /// By enabling this option, RocksDB will do some enhancements for prefetching the data.
    pub fn set_adaptive_readahead(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_readoptions_set_adaptive_readahead(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `adaptive_readahead` option.
    pub fn get_adaptive_readahead(&self) -> bool {
        unsafe { ffi::rocksdb_readoptions_get_adaptive_readahead(self.inner) != 0 }
    }

    /// When set, the iterator may defer loading and/or preparing the value when moving to a
    /// different entry (i.e. during SeekToFirst/SeekToLast/Seek/ SeekForPrev/Next/Prev
    /// operations). This can be used to save on I/O and/or CPU when the values associated
    /// with certain keys may not be used by the application. See also
    /// IteratorBase::PrepareValue().
    ///
    /// Note: this option currently only applies to 1) large values stored in blob files using
    /// BlobDB and 2) multi-column-family iterators (CoalescingIterator and
    /// AttributeGroupIterator). Otherwise, it has no effect.
    ///
    /// Default: false
    pub fn set_allow_unprepared_value(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_readoptions_set_allow_unprepared_value(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `allow_unprepared_value` option.
    pub fn get_allow_unprepared_value(&self) -> bool {
        unsafe { ffi::rocksdb_readoptions_get_allow_unprepared_value(self.inner) != 0 }
    }

    /// When true, by default use total_order_seek = true, and RocksDB can selectively enable
    /// prefix seek mode if won't generate a different result from total_order_seek, based on
    /// seek key, and iterator upper bound. BUG: Using
    /// Comparator::IsSameLengthImmediateSuccessor and SliceTransform::FullLengthEnabled to
    /// enable prefix mode in cases where prefix of upper bound differs from prefix of seek
    /// key has a flaw. If present in the DB, "short keys" (shorter than "full length" prefix)
    /// can be omitted from auto_prefix_mode iteration when they would be present in
    /// total_order_seek iteration, regardless of whether the short keys are "in domain" of
    /// the prefix extractor. This is not an issue if no short keys are added to DB or are not
    /// expected to be returned by such iterators. (We are also assuming the new condition on
    /// IsSameLengthImmediateSuccessor is satisfied; see its BUG section). A bug example is in
    /// DBTest2::AutoPrefixMode1, search for "BUG".
    pub fn set_auto_prefix_mode(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_readoptions_set_auto_prefix_mode(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `auto_prefix_mode` option.
    pub fn get_auto_prefix_mode(&self) -> bool {
        unsafe { ffi::rocksdb_readoptions_get_auto_prefix_mode(self.inner) != 0 }
    }

    /// If auto_readahead_size is set to true, it will auto tune the readahead_size during
    /// scans internally based on block cache data when block cache is enabled, iteration
    /// upper bound when `iterate_upper_bound != nullptr` and prefix when
    /// `prefix_same_as_start == true`
    ///
    /// Besides enabling block cache, it also requires `iterate_upper_bound != nullptr` or
    /// `prefix_same_as_start == true` for this option to take effect
    ///
    /// To be specific, it does the following: (1) When `iterate_upper_bound` is specified,
    /// trim the readahead so the readahead does not exceed iteration upper bound (2) When
    /// `prefix_same_as_start` is set to true, trim the readahead so data blocks containing
    /// keys that are not in the same prefix as the seek key in `Seek()` are not prefetched
    /// - Limition: `Seek(key)` instead of `SeekToFirst()` needs to be called in order for
    ///   this trimming to take effect
    ///
    /// NOTE: - Used for forward Scans only.
    /// - If there is a backward scans, this option will be disabled internally and won't be
    ///   enabled again if the forward scan is issued again.
    ///
    /// Default: true
    pub fn get_auto_readahead_size(&self) -> bool {
        unsafe { ffi::rocksdb_readoptions_get_auto_readahead_size(self.inner) != 0 }
    }

    /// EXPERIMENTAL
    ///
    /// Long-running iterators are holding onto memory and storage resources long after they
    /// are obsolete. This setting (when enabled) will fix that problem for as long as
    /// iterator periodically makes some progress and its supplied `read_options` was
    /// configured with non-nullptr `snapshot` value. The feature is engineered so that the
    /// performance impact should be negligible. We expect the default value to be true some
    /// time in the future.
    ///
    /// NOTE 1: Does not have effect on TransactionDB with WRITE_PREPARED or WRITE_UNPREPARED
    /// policies (currently incompatible).
    ///
    /// NOTE 2: True is not recommended if using user-defined timestamp with
    /// persist_user_defined_timestamps=false and non-nullptr ReadOptions::timestamp or
    /// ReadOptions::iter_start_ts, because auto-refreshing iterator will not prevent user
    /// timestamp information from being dropped during iteration. Auto-refresh might be
    /// disabled for this combination in the future.
    ///
    /// Default: false
    pub fn set_auto_refresh_iterator_with_snapshot(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_readoptions_set_auto_refresh_iterator_with_snapshot(
                self.inner,
                c_uchar::from(val),
            );
        }
    }

    /// Returns the value of the `auto_refresh_iterator_with_snapshot` option.
    pub fn get_auto_refresh_iterator_with_snapshot(&self) -> bool {
        unsafe { ffi::rocksdb_readoptions_get_auto_refresh_iterator_with_snapshot(self.inner) != 0 }
    }

    /// EXPERIMENTAL
    pub fn set_io_activity(&mut self, val: c_int) {
        unsafe {
            ffi::rocksdb_readoptions_set_io_activity(self.inner, val);
        }
    }

    /// Returns the value of the `io_activity` option.
    pub fn get_io_activity(&self) -> c_int {
        unsafe { ffi::rocksdb_readoptions_get_io_activity(self.inner) }
    }

    /// When the number of merge operands applied exceeds this threshold during a successful
    /// query, the operation will return a special OK Status with subcode
    /// kMergeOperandThresholdExceeded. Currently only applies to point lookups and is
    /// disabled by default.
    pub fn set_merge_operand_count_threshold(&mut self, val: usize) {
        unsafe {
            ffi::rocksdb_readoptions_set_merge_operand_count_threshold(self.inner, val);
        }
    }

    /// Returns the value of the `merge_operand_count_threshold` option.
    pub fn get_merge_operand_count_threshold(&self) -> usize {
        unsafe { ffi::rocksdb_readoptions_get_merge_operand_count_threshold(self.inner) }
    }

    /// For file reads associated with this option, charge the internal rate limiter (see
    /// `DBOptions::rate_limiter`) at the specified priority. The special value
    /// `Env::IO_TOTAL` disables charging the rate limiter.
    ///
    /// The rate limiting is bypassed no matter this option's value for file reads on plain
    /// tables (these can exist when `ColumnFamilyOptions::table_factory` is a
    /// `PlainTableFactory`) and cuckoo tables (these can exist when
    /// `ColumnFamilyOptions::table_factory` is a `CuckooTableFactory`).
    ///
    /// The bytes charged to rate limiter may not exactly match the file read bytes since
    /// there are some seemingly insignificant reads, like for file headers/footers, that we
    /// currently do not charge to rate limiter.
    pub fn set_rate_limiter_priority(&mut self, val: c_int) {
        unsafe {
            ffi::rocksdb_readoptions_set_rate_limiter_priority(self.inner, val);
        }
    }

    /// Returns the value of the `rate_limiter_priority` option.
    pub fn get_rate_limiter_priority(&self) -> c_int {
        unsafe { ffi::rocksdb_readoptions_get_rate_limiter_priority(self.inner) }
    }

    /// Tags this read with an application chosen id, so filesystem metrics and logs can be
    /// lined up with RocksDB and application logs for the same request.
    ///
    /// The id does not have to be unique per RocksDB call. It usually names an application
    /// level request that fans out into several of them.
    ///
    /// The `ReadOptions` owns a copy, so `id` does not have to outlive this call. Passing an
    /// empty string sets an empty id rather than removing it, use
    /// [`Self::clear_request_id`] for that.
    pub fn set_request_id(&mut self, id: impl AsRef<str>) {
        let id = id.as_ref();
        unsafe {
            ffi::rocksdb_readoptions_set_request_id(
                self.inner,
                id.as_ptr().cast::<c_char>(),
                id.len(),
            );
        }
    }

    /// The id set by [`Self::set_request_id`], or `None` when there is none.
    pub fn get_request_id(&self) -> Option<String> {
        // Borrowed: `c.cc` hands back a pointer into the `std::string` the read options own,
        // and null when no id is set. Copy it, do not free it.
        let mut len: size_t = 0;
        let id = unsafe { ffi::rocksdb_readoptions_get_request_id(self.inner, &raw mut len) };
        if id.is_null() {
            return None;
        }
        Some(unsafe { borrowed_string(id, len) })
    }

    /// Drops the request id, so this read is untagged again.
    ///
    /// See [`Self::set_request_id`].
    pub fn clear_request_id(&mut self) {
        unsafe {
            ffi::rocksdb_readoptions_clear_request_id(self.inner);
        }
    }

    /// Skips whole SST files during iteration based on their properties.
    ///
    /// `filter` runs once per table an iterator is about to open. Returning `false` skips the
    /// file, returning `true` scans it. This only affects iterators, point lookups ignore it.
    ///
    /// Creating an iterator on a read-write DB fails with `InvalidArgument` when the target
    /// column family has a non-zero `min_tombstones_for_range_conversion`, because skipping a
    /// file that holds tombstones could make deletes reappear. Turning that option off does
    /// not undo range tombstones RocksDB has already written, so account for the ones already
    /// in the memtable and SST files before relying on a filter.
    ///
    /// `filter` must be `Send + Sync` because RocksDB calls it from whichever thread drives
    /// the iterator. It replaces any filter set earlier. A panic inside it crosses a C frame,
    /// which aborts the process.
    pub fn set_table_filter<F>(&mut self, filter: F)
    where
        F: Fn(&TableProperties<'_>) -> bool + Send + Sync + 'static,
    {
        // Ownership, from `rocksdb_readoptions_t` in `db/c.cc`:
        //
        //  * `SetTableFilter` calls `ClearTableFilter` first, so setting a second filter runs
        //    the first one's destructor. Calling this twice does not leak.
        //  * `ClearTableFilter` nulls the destructor pointer after calling it, so
        //    `clear_table_filter` is idempotent.
        //  * `~rocksdb_readoptions_t` calls `ClearTableFilter` too, so dropping the
        //    `ReadOptions` reclaims the box.
        //
        // Together that is exactly one drop on every path. The C++ lambda installed into
        // `rep.table_filter` captures the state pointer raw, but `ClearTableFilter` resets
        // `rep.table_filter` before freeing the state, so the lambda can never outlive it
        // here. RocksDB copies `ReadOptions` by value when an iterator is created, and that
        // copy keeps the raw pointer, which is safe because an iterator takes ownership of
        // the whole `ReadOptions` and nothing can call these methods on it again.
        let filter: TableFilterCallback = Box::new(filter);
        let state = Box::into_raw(Box::new(filter));
        unsafe {
            ffi::rocksdb_readoptions_set_table_filter(
                self.inner,
                state.cast::<c_void>(),
                Some(table_filter_destructor),
                Some(table_filter_callback),
            );
        }
    }

    /// Drops the table filter, so iteration scans every file again.
    ///
    /// See [`Self::set_table_filter`].
    pub fn clear_table_filter(&mut self) {
        unsafe {
            ffi::rocksdb_readoptions_clear_table_filter(self.inner);
        }
    }

    /// Whether a table filter is installed.
    ///
    /// See [`Self::set_table_filter`].
    pub fn has_table_filter(&self) -> bool {
        unsafe { ffi::rocksdb_readoptions_has_table_filter(self.inner.cast_const()) != 0 }
    }

    /// Reads through the user defined index named by `value` instead of the standard
    /// block-based index.
    ///
    /// `value` goes through the `UserDefinedIndexFactory` object registry the same way
    /// [`BlockBasedOptions::set_user_defined_index_factory_from_string`] does, so it has to
    /// name the factory the SST files were written with. `trie_index` is the only factory
    /// RocksDB registers itself.
    ///
    /// Only needed while the UDI is a secondary index. With
    /// [`BlockBasedOptions::set_use_udi_as_primary_index`] on, every read already goes
    /// through the UDI and the factory from the table options wins over this one.
    ///
    /// # Errors
    ///
    /// Returns an error if `value` names no registered factory, or carries settings that
    /// factory rejects. Either way the previously configured factory is cleared first.
    pub fn set_table_index_factory_from_string(
        &mut self,
        value: impl AsRef<str>,
    ) -> Result<(), Error> {
        let value = value.as_ref();
        unsafe {
            ffi_try!(
                ffi::rocksdb_readoptions_set_table_index_factory_from_string(
                    self.inner,
                    value.as_ptr().cast::<c_char>(),
                    value.len(),
                )
            );
        }
        Ok(())
    }

    /// Name of the configured user defined index factory, or `None` when there is none.
    ///
    /// This is the factory's registered id, not the full string passed to
    /// [`Self::set_table_index_factory_from_string`].
    pub fn get_table_index_factory_name(&self) -> Option<String> {
        let mut len: size_t = 0;
        let name = unsafe {
            ffi::rocksdb_readoptions_get_table_index_factory_name(
                self.inner.cast_const(),
                &raw mut len,
            )
        };
        if name.is_null() {
            return None;
        }
        Some(unsafe { borrowed_string(name, len) })
    }

    /// Drops the user defined index factory, so reads go back to the standard index.
    ///
    /// See [`Self::set_table_index_factory_from_string`].
    pub fn clear_table_index_factory(&mut self) {
        unsafe {
            ffi::rocksdb_readoptions_clear_table_index_factory(self.inner);
        }
    }

    /// Soft limit on the cumulative value size read by a single MultiGet, to bound how much
    /// it buffers. It always makes progress: at least one key is read even if its value alone
    /// exceeds the limit. Once the returned size exceeds the limit, subsequent keys get
    /// status Aborted (so a caller can retry them, and cannot loop forever on a single value
    /// that by itself exceeds the limit).
    pub fn set_value_size_soft_limit(&mut self, val: u64) {
        unsafe {
            ffi::rocksdb_readoptions_set_value_size_soft_limit(self.inner, val);
        }
    }

    /// Returns the value of the `value_size_soft_limit` option.
    pub fn get_value_size_soft_limit(&self) -> u64 {
        unsafe { ffi::rocksdb_readoptions_get_value_size_soft_limit(self.inner) }
    }

    /// Clears the merge operand count threshold, restoring the default of no limit.
    ///
    /// See [`Self::set_merge_operand_count_threshold`].
    pub fn clear_merge_operand_count_threshold(&mut self) {
        unsafe {
            ffi::rocksdb_readoptions_clear_merge_operand_count_threshold(self.inner);
        }
    }

    /// Returns the current `async_io` setting.
    ///
    /// See [`Self::set_async_io`] for what this controls.
    pub fn get_async_io(&self) -> bool {
        unsafe { ffi::rocksdb_readoptions_get_async_io(self.inner) != 0 }
    }

    /// Returns the current `background_purge_on_iterator_cleanup` setting.
    ///
    /// See [`Self::set_background_purge_on_iterator_cleanup`] for what this controls.
    pub fn get_background_purge_on_iterator_cleanup(&self) -> bool {
        unsafe {
            ffi::rocksdb_readoptions_get_background_purge_on_iterator_cleanup(self.inner) != 0
        }
    }

    /// Returns the current `deadline` setting.
    ///
    /// See [`Self::set_deadline`] for what this controls.
    pub fn get_deadline(&self) -> u64 {
        unsafe { ffi::rocksdb_readoptions_get_deadline(self.inner) }
    }

    /// Returns the current `fill_cache` setting.
    ///
    /// See [`Self::fill_cache`] for what this controls.
    pub fn get_fill_cache(&self) -> bool {
        unsafe { ffi::rocksdb_readoptions_get_fill_cache(self.inner) != 0 }
    }

    /// Returns the current `io_timeout` setting.
    ///
    /// See [`Self::set_io_timeout`] for what this controls.
    pub fn get_io_timeout(&self) -> u64 {
        unsafe { ffi::rocksdb_readoptions_get_io_timeout(self.inner) }
    }

    /// Returns the current `max_skippable_internal_keys` setting.
    ///
    /// See [`Self::set_max_skippable_internal_keys`] for what this controls.
    pub fn get_max_skippable_internal_keys(&self) -> u64 {
        unsafe { ffi::rocksdb_readoptions_get_max_skippable_internal_keys(self.inner) }
    }

    /// Returns the current `pin_data` setting.
    ///
    /// See [`Self::set_pin_data`] for what this controls.
    pub fn get_pin_data(&self) -> bool {
        unsafe { ffi::rocksdb_readoptions_get_pin_data(self.inner) != 0 }
    }

    /// Returns the current `prefix_same_as_start` setting.
    ///
    /// See [`Self::set_prefix_same_as_start`] for what this controls.
    pub fn get_prefix_same_as_start(&self) -> bool {
        unsafe { ffi::rocksdb_readoptions_get_prefix_same_as_start(self.inner) != 0 }
    }

    /// Returns the current `readahead_size` setting.
    ///
    /// See [`Self::set_readahead_size`] for what this controls.
    pub fn get_readahead_size(&self) -> usize {
        unsafe { ffi::rocksdb_readoptions_get_readahead_size(self.inner) }
    }

    /// Returns the current `tailing` setting.
    ///
    /// See [`Self::set_tailing`] for what this controls.
    pub fn get_tailing(&self) -> bool {
        unsafe { ffi::rocksdb_readoptions_get_tailing(self.inner) != 0 }
    }

    /// Returns the current `total_order_seek` setting.
    ///
    /// See [`Self::set_total_order_seek`] for what this controls.
    pub fn get_total_order_seek(&self) -> bool {
        unsafe { ffi::rocksdb_readoptions_get_total_order_seek(self.inner) != 0 }
    }

    /// Returns the current `verify_checksums` setting.
    ///
    /// See [`Self::set_verify_checksums`] for what this controls.
    pub fn get_verify_checksums(&self) -> bool {
        unsafe { ffi::rocksdb_readoptions_get_verify_checksums(self.inner) != 0 }
    }

    /// Returns whether a merge operand count threshold is set.
    ///
    /// See [`Self::set_merge_operand_count_threshold`].
    pub fn has_merge_operand_count_threshold(&self) -> bool {
        unsafe { ffi::rocksdb_readoptions_has_merge_operand_count_threshold(self.inner) != 0 }
    }
}

impl Default for ReadOptions {
    fn default() -> Self {
        unsafe {
            Self {
                inner: ffi::rocksdb_readoptions_create(),
                timestamp: None,
                iter_start_ts: None,
                iterate_upper_bound: None,
                iterate_lower_bound: None,
            }
        }
    }
}

impl IngestExternalFileOptions {
    /// Can be set to true to move the files instead of copying them.
    pub fn set_move_files(&mut self, v: bool) {
        unsafe {
            ffi::rocksdb_ingestexternalfileoptions_set_move_files(self.inner, c_uchar::from(v));
        }
    }

    /// If set to false, an ingested file keys could appear in existing snapshots
    /// that where created before the file was ingested.
    pub fn set_snapshot_consistency(&mut self, v: bool) {
        unsafe {
            ffi::rocksdb_ingestexternalfileoptions_set_snapshot_consistency(
                self.inner,
                c_uchar::from(v),
            );
        }
    }

    /// If set to false, IngestExternalFile() will fail if the file key range
    /// overlaps with existing keys or tombstones in the DB.
    pub fn set_allow_global_seqno(&mut self, v: bool) {
        unsafe {
            ffi::rocksdb_ingestexternalfileoptions_set_allow_global_seqno(
                self.inner,
                c_uchar::from(v),
            );
        }
    }

    /// If set to false and the file key range overlaps with the memtable key range
    /// (memtable flush required), IngestExternalFile will fail.
    pub fn set_allow_blocking_flush(&mut self, v: bool) {
        unsafe {
            ffi::rocksdb_ingestexternalfileoptions_set_allow_blocking_flush(
                self.inner,
                c_uchar::from(v),
            );
        }
    }

    /// Set to true if you would like duplicate keys in the file being ingested
    /// to be skipped rather than overwriting existing data under that key.
    /// Usecase: back-fill of some historical data in the database without
    /// over-writing existing newer version of data.
    /// This option could only be used if the DB has been running
    /// with allow_ingest_behind=true since the dawn of time.
    /// All files will be ingested at the bottommost level with seqno=0.
    pub fn set_ingest_behind(&mut self, v: bool) {
        unsafe {
            ffi::rocksdb_ingestexternalfileoptions_set_ingest_behind(self.inner, c_uchar::from(v));
        }
    }

    /// Normally (true), IngestExternalFile() will trigger and block for flushing memtable(s)
    /// if there is overlap between ingested files and memtable(s). If allow_blocking_flush is
    /// set to false, IngestExternalFile() will fail if the file key range overlaps with the
    /// memtable key range (memtable flush required).
    pub fn get_allow_blocking_flush(&self) -> bool {
        unsafe { ffi::rocksdb_ingestexternalfileoptions_get_allow_blocking_flush(self.inner) != 0 }
    }

    /// EXPERIMENTAL, SUBJECT TO CHANGE
    ///
    /// Enables special mode of ingestion that allows files generated by a live DB, instead of
    /// SstFileWriter. When true:
    /// - Allows files to be ingested when their cf_id doesn't match the CF they are being
    ///   ingested into.
    /// - Allows files with any sequence numbers to be ingested.
    /// - Original sequence numbers are preserved (no reassignment).
    ///
    /// REQUIREMENTS:
    /// - Ingested files must NOT overlap with any existing data in the DB. Since no
    ///   sequence number reassignment is performed on db generated files. Ingestion will
    ///   fail if any overlap is detected. However, input files are allowed to overlap with
    ///   each other when this option is enabled. This is useful when ingesting multiple
    ///   levels of files from a CF, where levels naturally overlap with each other.
    /// - CAUTION: If input files overlap with each other, then for any given user key
    ///   appearing in multiple files, earlier files MUST have smaller sequence numbers than
    ///   later files. Later files will be placed at a higher level (smaller level number).
    ///   This is to ensure the LSM invariant where for the same key, recent updates are in
    ///   higher levels. This means that if you are ingesting files from multiple levels of
    ///   a CF, you should put files from lower levels first, and files from higher levels
    ///   later. Example for getting files from a CF for ingestion:
    ///
    /// ColumnFamilyMetaData cf_meta; from_db->GetColumnFamilyMetaData(from_cf, &cf_meta); //
    /// iterate in reverse to start from lowest level for (auto level_meta =
    /// cf_meta.levels.rbegin(); level_meta != cf_meta.levels.rend(); ++level_meta) { // L0
    /// files need to be added in reverse order so we iterate in reverse // within a level too
    /// for (auto file_meta = level_meta->files.rbegin(); file_meta !=
    /// level_meta->files.rend(); ++file_meta) { // Add file for ingestion } }
    ///
    /// WARNING: Violating the sequence number ordering requirement will cause LSM invariant
    /// violations and may lead to incorrect reads or data corruption.
    /// - If you would like to enforce that the ingested files do not overlap with each
    ///   other, you can set `fail_if_not_bottommost_level` to true. If ingested files
    ///   overlap with each other, some file will be placed above Lmax, failing the
    ///   ingestion if the option is set.
    pub fn set_allow_db_generated_files(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_ingestexternalfileoptions_set_allow_db_generated_files(
                self.inner,
                c_uchar::from(val),
            );
        }
    }

    /// Returns the value of the `allow_db_generated_files` option.
    pub fn get_allow_db_generated_files(&self) -> bool {
        unsafe {
            ffi::rocksdb_ingestexternalfileoptions_get_allow_db_generated_files(self.inner) != 0
        }
    }

    /// Enables assiging a global sequence number to each ingested file, i.e., all keys in the
    /// ingested file will be treated as having this seqno. If set to false, we will use the
    /// sequence numbers in the ingested file as is, and IngestExternalFile() will fail if the
    /// ingested key range overlaps with existing keys or tombstones or output of ongoing
    /// compaction in the CF (the conditions under which a global seqno must be assigned to
    /// the ingested file). If the ingested files overlap with each other, we need to assign
    /// global sequence to the ingested files and this option needs to be enabled. One
    /// exception to this is when ingesting DB generated SST files (see option
    /// allow_db_generated_files below). DB generated files do not support global seqno
    /// assignment and can be ingested even if they overlap with each other. This option has
    /// no effect when allow_db_generated_files is enabled.
    pub fn get_allow_global_seqno(&self) -> bool {
        unsafe { ffi::rocksdb_ingestexternalfileoptions_get_allow_global_seqno(self.inner) != 0 }
    }

    /// Set to TRUE if user wants file to be ingested to the last level. An error of
    /// Status::TryAgain() will be returned if a file cannot fit in the last level when
    /// calling DB::IngestExternalFile()/DB::IngestExternalFiles(). The user should clear the
    /// last level in the overlapping range before re-attempt.
    ///
    /// ingest_behind takes precedence over fail_if_not_bottommost_level.
    ///
    /// XXX: "bottommost" is obsolete/confusing terminology to refer to last level
    pub fn get_fail_if_not_bottommost_level(&self) -> bool {
        unsafe {
            ffi::rocksdb_ingestexternalfileoptions_get_fail_if_not_bottommost_level(self.inner) != 0
        }
    }

    /// If set to true, ingestion falls back to copy when hard linking fails. This applies to
    /// both `move_files` and `link_files`.
    pub fn set_failed_move_fall_back_to_copy(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_ingestexternalfileoptions_set_failed_move_fall_back_to_copy(
                self.inner,
                c_uchar::from(val),
            );
        }
    }

    /// Returns the value of the `failed_move_fall_back_to_copy` option.
    pub fn get_failed_move_fall_back_to_copy(&self) -> bool {
        unsafe {
            ffi::rocksdb_ingestexternalfileoptions_get_failed_move_fall_back_to_copy(self.inner)
                != 0
        }
    }

    /// Maximum number of threads used to open table readers for the files being ingested
    /// during commit, can speed up ingestion performance, when ingesting multiple files at
    /// once.
    pub fn set_file_opening_threads(&mut self, val: c_int) {
        unsafe {
            ffi::rocksdb_ingestexternalfileoptions_set_file_opening_threads(self.inner, val);
        }
    }

    /// Returns the value of the `file_opening_threads` option.
    pub fn get_file_opening_threads(&self) -> c_int {
        unsafe { ffi::rocksdb_ingestexternalfileoptions_get_file_opening_threads(self.inner) }
    }

    /// Should the "data block"/"index block" read for this iteration be placed in block
    /// cache? Callers may wish to set this field to false for bulk scans. This would help not
    /// to the change eviction order of existing items in the block cache.
    pub fn set_fill_cache(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_ingestexternalfileoptions_set_fill_cache(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `fill_cache` option.
    pub fn get_fill_cache(&self) -> bool {
        unsafe { ffi::rocksdb_ingestexternalfileoptions_get_fill_cache(self.inner) != 0 }
    }

    /// Set to true if you would like duplicate keys in the file being ingested to be skipped
    /// rather than overwriting existing data under that key. Use case: back-fill of some
    /// historical data in the database without over-writing existing newer version of data.
    /// This option could only be used if the CF has been running with
    /// cf_allow_ingest_behind=true since CF creation (or before any write). All files will be
    /// ingested at the bottommost level with seqno=0.
    pub fn get_ingest_behind(&self) -> bool {
        unsafe { ffi::rocksdb_ingestexternalfileoptions_get_ingest_behind(self.inner) != 0 }
    }

    /// Same as move_files except that input files will NOT be unlinked. Only one of
    /// `move_files` and `link_files` can be set at the same time.
    pub fn set_link_files(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_ingestexternalfileoptions_set_link_files(self.inner, c_uchar::from(val));
        }
    }

    /// Returns the value of the `link_files` option.
    pub fn get_link_files(&self) -> bool {
        unsafe { ffi::rocksdb_ingestexternalfileoptions_get_link_files(self.inner) != 0 }
    }

    /// Can be set to true to move the files instead of copying them. The input files will be
    /// unlinked after successful ingestion. The implementation depends on hard links
    /// (LinkFile) instead of traditional move (RenameFile) to maximize the chances to restore
    /// to the original state upon failure.
    pub fn get_move_files(&self) -> bool {
        unsafe { ffi::rocksdb_ingestexternalfileoptions_get_move_files(self.inner) != 0 }
    }

    /// Controls whether external file ingestion should prefetch index and filter blocks while
    /// opening table readers during commit. Setting this to false can reduce commit latency
    /// for bulk loads into Lmax when
    /// (BlockBasedTableOptions::cache_index_and_filter_blocks=true or partitioned
    /// filters/indexes are enabled).
    pub fn set_prefetch_lmax_index_and_filter_blocks(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_ingestexternalfileoptions_set_prefetch_lmax_index_and_filter_blocks(
                self.inner,
                c_uchar::from(val),
            );
        }
    }

    /// Returns the value of the `prefetch_lmax_index_and_filter_blocks` option.
    pub fn get_prefetch_lmax_index_and_filter_blocks(&self) -> bool {
        unsafe {
            ffi::rocksdb_ingestexternalfileoptions_get_prefetch_lmax_index_and_filter_blocks(
                self.inner,
            ) != 0
        }
    }

    /// If set to false, an ingested file keys could appear in existing snapshots that where
    /// created before the file was ingested.
    pub fn get_snapshot_consistency(&self) -> bool {
        unsafe { ffi::rocksdb_ingestexternalfileoptions_get_snapshot_consistency(self.inner) != 0 }
    }

    /// Set to true if you would like to verify the checksums of each block of the external
    /// SST file before ingestion. Warning: setting this to true causes slowdown in file
    /// ingestion because the external SST file has to be read.
    pub fn set_verify_checksums_before_ingest(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_ingestexternalfileoptions_set_verify_checksums_before_ingest(
                self.inner,
                c_uchar::from(val),
            );
        }
    }

    /// Returns the value of the `verify_checksums_before_ingest` option.
    pub fn get_verify_checksums_before_ingest(&self) -> bool {
        unsafe {
            ffi::rocksdb_ingestexternalfileoptions_get_verify_checksums_before_ingest(self.inner)
                != 0
        }
    }

    /// When verify_checksums_before_ingest = true, RocksDB uses default readahead setting to
    /// scan the file while verifying checksums before ingestion. Users can override the
    /// default value using this option. Using a large readahead size (> 2MB) can typically
    /// improve the performance of forward iteration on spinning disks.
    pub fn set_verify_checksums_readahead_size(&mut self, val: usize) {
        unsafe {
            ffi::rocksdb_ingestexternalfileoptions_set_verify_checksums_readahead_size(
                self.inner, val,
            );
        }
    }

    /// Returns the value of the `verify_checksums_readahead_size` option.
    pub fn get_verify_checksums_readahead_size(&self) -> usize {
        unsafe {
            ffi::rocksdb_ingestexternalfileoptions_get_verify_checksums_readahead_size(self.inner)
        }
    }

    /// Set to TRUE if user wants to verify the sst file checksum of ingested files. The DB
    /// checksum function will generate the checksum of each ingested file (if
    /// file_checksum_gen_factory is set) and compare the checksum function name and checksum
    /// with the ingested checksum information.
    ///
    /// If this option is set to True: 1) if DB does not enable checksum
    /// (file_checksum_gen_factory == nullptr), the ingested checksum information will be
    /// ignored; 2) If DB enable the checksum function, we calculate the sst file checksum
    /// after the file is moved or copied and compare the checksum and checksum name. If
    /// checksum or checksum function name does not match, ingestion will be failed. If the
    /// verification is successful, checksum and checksum function name will be stored in
    /// Manifest. If this option is set to FALSE, 1) if DB does not enable checksum, the
    /// ingested checksum information will be ignored; 2) if DB enable the checksum, we only
    /// verify the ingested checksum function name and we trust the ingested checksum. If the
    /// checksum function name matches, we store the checksum in Manifest. DB does not
    /// calculate the checksum during ingestion. However, if no checksum information is
    /// provided with the ingested files, DB will generate the checksum and store in the
    /// Manifest.
    pub fn set_verify_file_checksum(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_ingestexternalfileoptions_set_verify_file_checksum(
                self.inner,
                c_uchar::from(val),
            );
        }
    }

    /// Returns the value of the `verify_file_checksum` option.
    pub fn get_verify_file_checksum(&self) -> bool {
        unsafe { ffi::rocksdb_ingestexternalfileoptions_get_verify_file_checksum(self.inner) != 0 }
    }

    /// Set to TRUE if user wants file to be ingested to the last level. An error of
    /// Status::TryAgain() will be returned if a file cannot fit in the last level when
    /// calling DB::IngestExternalFile()/DB::IngestExternalFiles(). The user should clear the
    /// last level in the overlapping range before re-attempt.
    ///
    /// ingest_behind takes precedence over fail_if_not_bottommost_level.
    ///
    /// XXX: "bottommost" is obsolete/confusing terminology to refer to last level.
    pub fn set_fail_if_not_bottommost_level(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_ingestexternalfileoptions_set_fail_if_not_bottommost_level(
                self.inner,
                c_uchar::from(val),
            );
        }
    }
}

impl Default for IngestExternalFileOptions {
    fn default() -> Self {
        unsafe {
            Self {
                inner: ffi::rocksdb_ingestexternalfileoptions_create(),
            }
        }
    }
}

/// Used by BlockBasedOptions::set_index_type.
pub enum BlockBasedIndexType {
    /// A space efficient index block that is optimized for
    /// binary-search-based index.
    BinarySearch = ffi::rocksdb_block_based_table_index_type_binary_search as isize,

    /// The hash index, if enabled, will perform a hash lookup if
    /// a prefix extractor has been provided through Options::set_prefix_extractor.
    HashSearch = ffi::rocksdb_block_based_table_index_type_hash_search as isize,

    /// A two-level index implementation. Both levels are binary search indexes.
    TwoLevelIndexSearch = ffi::rocksdb_block_based_table_index_type_two_level_index_search as isize,
}

/// Used by BlockBasedOptions::set_data_block_index_type.
#[repr(C)]
pub enum DataBlockIndexType {
    /// Use binary search when performing point lookup for keys in data blocks.
    /// This is the default.
    BinarySearch = ffi::rocksdb_block_based_table_data_block_index_type_binary_search as isize,

    /// Appends a compact hash table to the end of the data block for efficient indexing. Backwards
    /// compatible with databases created without this feature. Once turned on, existing data will
    /// be gradually converted to the hash index format.
    BinaryAndHash =
        ffi::rocksdb_block_based_table_data_block_index_type_binary_search_and_hash as isize,
}

/// Defines the underlying memtable implementation.
/// See official [wiki](https://github.com/facebook/rocksdb/wiki/MemTable) for more information.
pub enum MemtableFactory {
    Vector,
    HashSkipList {
        bucket_count: usize,
        height: i32,
        branching_factor: i32,
    },
    HashLinkList {
        bucket_count: usize,
    },
}

/// Used by BlockBasedOptions::set_checksum_type.
pub enum ChecksumType {
    NoChecksum = 0,
    CRC32c = 1,
    XXHash = 2,
    XXHash64 = 3,
    XXH3 = 4, // Supported since RocksDB 6.27
}

/// Used in [`PlainTableFactoryOptions`].
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
pub enum KeyEncodingType {
    /// Always write full keys.
    #[default]
    Plain = 0,
    /// Find opportunities to write the same prefix for multiple rows.
    Prefix = 1,
}

/// Used with DBOptions::set_plain_table_factory.
/// See official [wiki](https://github.com/facebook/rocksdb/wiki/PlainTable-Format) for more
/// information.
///
/// Defaults:
///  user_key_length: 0 (variable length)
///  bloom_bits_per_key: 10
///  hash_table_ratio: 0.75
///  index_sparseness: 16
///  huge_page_tlb_size: 0
///  encoding_type: KeyEncodingType::Plain
///  full_scan_mode: false
///  store_index_in_file: false
pub struct PlainTableFactoryOptions {
    pub user_key_length: u32,
    pub bloom_bits_per_key: i32,
    pub hash_table_ratio: f64,
    pub index_sparseness: usize,
    pub huge_page_tlb_size: usize,
    pub encoding_type: KeyEncodingType,
    pub full_scan_mode: bool,
    pub store_index_in_file: bool,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde1", derive(serde::Serialize, serde::Deserialize))]
pub enum DBCompressionType {
    None = ffi::rocksdb_no_compression as isize,
    Snappy = ffi::rocksdb_snappy_compression as isize,
    Zlib = ffi::rocksdb_zlib_compression as isize,
    Bz2 = ffi::rocksdb_bz2_compression as isize,
    Lz4 = ffi::rocksdb_lz4_compression as isize,
    Lz4hc = ffi::rocksdb_lz4hc_compression as isize,
    Zstd = ffi::rocksdb_zstd_compression as isize,
}

impl DBCompressionType {
    /// Decodes a raw `rocksdb::CompressionType`.
    ///
    /// `None` for anything this crate does not name: xpress, which is Windows only, the
    /// `kCustomCompression*` range a `CompressionManager` can hand out, and the
    /// `kDisableCompressionOption` sentinel that `bottommost_compression` defaults to.
    pub(crate) fn try_from_raw(raw: c_int) -> Option<Self> {
        match raw {
            n if n == DBCompressionType::None as c_int => Some(DBCompressionType::None),
            n if n == DBCompressionType::Snappy as c_int => Some(DBCompressionType::Snappy),
            n if n == DBCompressionType::Zlib as c_int => Some(DBCompressionType::Zlib),
            n if n == DBCompressionType::Bz2 as c_int => Some(DBCompressionType::Bz2),
            n if n == DBCompressionType::Lz4 as c_int => Some(DBCompressionType::Lz4),
            n if n == DBCompressionType::Lz4hc as c_int => Some(DBCompressionType::Lz4hc),
            n if n == DBCompressionType::Zstd as c_int => Some(DBCompressionType::Zstd),
            _ => None,
        }
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde1", derive(serde::Serialize, serde::Deserialize))]
pub enum DBCompactionStyle {
    Level = ffi::rocksdb_level_compaction as isize,
    Universal = ffi::rocksdb_universal_compaction as isize,
    Fifo = ffi::rocksdb_fifo_compaction as isize,
}

impl DBCompactionStyle {
    /// Decodes a raw `rocksdb::CompactionStyle`.
    ///
    /// `None` for `kCompactionStyleNone`, which this crate does not name.
    pub(crate) fn try_from_raw(raw: c_int) -> Option<Self> {
        match raw {
            n if n == DBCompactionStyle::Level as c_int => Some(DBCompactionStyle::Level),
            n if n == DBCompactionStyle::Universal as c_int => Some(DBCompactionStyle::Universal),
            n if n == DBCompactionStyle::Fifo as c_int => Some(DBCompactionStyle::Fifo),
            _ => None,
        }
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde1", derive(serde::Serialize, serde::Deserialize))]
pub enum DBRecoveryMode {
    TolerateCorruptedTailRecords = ffi::rocksdb_tolerate_corrupted_tail_records_recovery as isize,
    AbsoluteConsistency = ffi::rocksdb_absolute_consistency_recovery as isize,
    PointInTime = ffi::rocksdb_point_in_time_recovery as isize,
    SkipAnyCorruptedRecord = ffi::rocksdb_skip_any_corrupted_records_recovery as isize,
}

impl DBRecoveryMode {
    /// Decodes a raw `rocksdb::WALRecoveryMode`.
    ///
    /// This covers every mode RocksDB defines today, so `None` only means a future release
    /// added one.
    pub(crate) fn try_from_raw(raw: c_int) -> Option<Self> {
        match raw {
            n if n == DBRecoveryMode::TolerateCorruptedTailRecords as c_int => {
                Some(DBRecoveryMode::TolerateCorruptedTailRecords)
            }
            n if n == DBRecoveryMode::AbsoluteConsistency as c_int => {
                Some(DBRecoveryMode::AbsoluteConsistency)
            }
            n if n == DBRecoveryMode::PointInTime as c_int => Some(DBRecoveryMode::PointInTime),
            n if n == DBRecoveryMode::SkipAnyCorruptedRecord as c_int => {
                Some(DBRecoveryMode::SkipAnyCorruptedRecord)
            }
            _ => None,
        }
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[repr(i32)]
pub enum RateLimiterMode {
    KReadsOnly = 0,
    KWritesOnly = 1,
    KAllIo = 2,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde1", derive(serde::Serialize, serde::Deserialize))]
pub enum DBCompactionPri {
    ByCompensatedSize = ffi::rocksdb_k_by_compensated_size_compaction_pri as isize,
    OldestLargestSeqFirst = ffi::rocksdb_k_oldest_largest_seq_first_compaction_pri as isize,
    OldestSmallestSeqFirst = ffi::rocksdb_k_oldest_smallest_seq_first_compaction_pri as isize,
    MinOverlappingRatio = ffi::rocksdb_k_min_overlapping_ratio_compaction_pri as isize,
    RoundRobin = ffi::rocksdb_k_round_robin_compaction_pri as isize,
}

impl DBCompactionPri {
    /// Decodes a raw `rocksdb::CompactionPri`.
    ///
    /// This covers every value RocksDB defines today, so `None` only means a future release
    /// added one.
    pub(crate) fn try_from_raw(raw: c_int) -> Option<Self> {
        match raw {
            n if n == DBCompactionPri::ByCompensatedSize as c_int => {
                Some(DBCompactionPri::ByCompensatedSize)
            }
            n if n == DBCompactionPri::OldestLargestSeqFirst as c_int => {
                Some(DBCompactionPri::OldestLargestSeqFirst)
            }
            n if n == DBCompactionPri::OldestSmallestSeqFirst as c_int => {
                Some(DBCompactionPri::OldestSmallestSeqFirst)
            }
            n if n == DBCompactionPri::MinOverlappingRatio as c_int => {
                Some(DBCompactionPri::MinOverlappingRatio)
            }
            n if n == DBCompactionPri::RoundRobin as c_int => Some(DBCompactionPri::RoundRobin),
            _ => None,
        }
    }
}

/// Whether blobs written by a flush are inserted into the blob cache right away.
///
/// Used by [`Options::set_prepopulate_blob_cache`]. Mirrors `rocksdb::PrepopulateBlobCache`
/// from `include/rocksdb/advanced_options.h`, including its discriminants.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde1", derive(serde::Serialize, serde::Deserialize))]
#[repr(i32)]
pub enum PrepopulateBlobCache {
    /// Blobs reach the cache only when something reads them. The default.
    Disable = ffi::rocksdb_prepopulate_blob_disable as i32,
    /// Blobs written by a flush go into the cache as they are written. Blobs written by
    /// compaction still do not.
    FlushOnly = ffi::rocksdb_prepopulate_blob_flush_only as i32,
}

impl PrepopulateBlobCache {
    /// Decodes a raw `rocksdb::PrepopulateBlobCache`.
    ///
    /// This covers every value RocksDB defines today, so `None` only means a future release
    /// added one.
    pub(crate) fn try_from_raw(raw: c_int) -> Option<Self> {
        match raw {
            n if n == PrepopulateBlobCache::Disable as c_int => Some(PrepopulateBlobCache::Disable),
            n if n == PrepopulateBlobCache::FlushOnly as c_int => {
                Some(PrepopulateBlobCache::FlushOnly)
            }
            _ => None,
        }
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde1", derive(serde::Serialize, serde::Deserialize))]
pub enum BlockBasedPinningTier {
    Fallback = ffi::rocksdb_block_based_k_fallback_pinning_tier as isize,
    None = ffi::rocksdb_block_based_k_none_pinning_tier as isize,
    FlushAndSimilar = ffi::rocksdb_block_based_k_flush_and_similar_pinning_tier as isize,
    All = ffi::rocksdb_block_based_k_all_pinning_tier as isize,
}

/// Index-block search algorithm selected by
/// [`BlockBasedOptions::set_index_block_search_type`].
///
/// `Auto` is only meaningful in combination with
/// [`BlockBasedOptions::set_uniform_cv_threshold`]: the threshold gates whether
/// the per-block "is_uniform" footer bit is set on the write path, and `Auto`
/// reads that bit at lookup time to choose between binary and interpolation
/// search per index block. Without setting the threshold to a non-negative
/// value, `Auto` degenerates to binary search.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde1", derive(serde::Serialize, serde::Deserialize))]
pub enum IndexBlockSearchType {
    /// Standard binary search. The default and safest choice.
    Binary = ffi::rocksdb_block_based_table_index_block_search_type_binary as isize,
    /// Interpolation search. Faster than binary search for index blocks whose
    /// keys are uniformly distributed; significantly slower when they are not.
    ///
    /// Only applicable when the byte-wise comparator is in use; with any
    /// other comparator the C++ code falls back to binary search regardless.
    ///
    /// Performance is significantly degraded when
    /// `IndexShorteningMode::kShortenSeparatorsAndSuccessor` is also set,
    /// because the shortened successor skews end-keys away from the uniform
    /// distribution that interpolation search relies on. Avoid combining the
    /// two.
    Interpolation = ffi::rocksdb_block_based_table_index_block_search_type_interpolation as isize,
    /// Per-block adaptive selection between binary and interpolation search,
    /// based on the per-block "is_uniform" footer bit. Requires
    /// `uniform_cv_threshold >= 0` on the write path; see
    /// [`BlockBasedOptions::set_uniform_cv_threshold`].
    Auto = ffi::rocksdb_block_based_table_index_block_search_type_auto as isize,
}

pub struct FifoCompactOptions {
    pub(crate) inner: *mut ffi::rocksdb_fifo_compaction_options_t,
}

impl Default for FifoCompactOptions {
    fn default() -> Self {
        let opts = unsafe { ffi::rocksdb_fifo_compaction_options_create() };
        assert!(
            !opts.is_null(),
            "Could not create RocksDB Fifo Compaction Options"
        );

        Self { inner: opts }
    }
}

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

impl FifoCompactOptions {
    /// Sets the max table file size.
    ///
    /// Once the total sum of table files reaches this, we will delete the oldest
    /// table file
    ///
    /// Default: 1GB
    pub fn set_max_table_files_size(&mut self, nbytes: u64) {
        unsafe {
            ffi::rocksdb_fifo_compaction_options_set_max_table_files_size(self.inner, nbytes);
        }
    }

    /// DEPRECATED When not 0, if the data in the file is older than this threshold, RocksDB
    /// will soon move the file to warm temperature.
    pub fn set_age_for_warm(&mut self, val: u64) {
        unsafe {
            ffi::rocksdb_fifo_compaction_options_set_age_for_warm(self.inner, val);
        }
    }

    /// Returns the value of the `age_for_warm` option.
    pub fn get_age_for_warm(&self) -> u64 {
        unsafe { ffi::rocksdb_fifo_compaction_options_get_age_for_warm(self.inner) }
    }

    /// EXPERIMENTAL If true, when compaction is picked for kChangeTemperature reason, allow
    /// the trivia copy of the sst file from source FileSystem to destination FileSystem. If
    /// false, the changeTemperature will be the non-trivial copy by iterating/appending
    /// blocks by blocks of the sst file.
    pub fn set_allow_trivial_copy_when_change_temperature(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_fifo_compaction_options_set_allow_trivial_copy_when_change_temperature(
                self.inner,
                c_uchar::from(val),
            );
        }
    }

    /// Returns the value of the `allow_trivial_copy_when_change_temperature` option.
    pub fn get_allow_trivial_copy_when_change_temperature(&self) -> bool {
        unsafe {
            ffi::rocksdb_fifo_compaction_options_get_allow_trivial_copy_when_change_temperature(
                self.inner,
            ) != 0
        }
    }

    /// EXPERIMENTAL If 'allow_trivia_copy_op_when_change_temperature=true', the tmp buffer
    /// size to copy the file from the source FileSystem to the destnation FileSystem. If
    /// 'allow_trivia_copy_op_when_change_temperature=false', this field will not be used. The
    /// minmum buffer size must be at least 4KiB
    pub fn set_trivial_copy_buffer_size(&mut self, val: u64) {
        unsafe {
            ffi::rocksdb_fifo_compaction_options_set_trivial_copy_buffer_size(self.inner, val);
        }
    }

    /// Returns the value of the `trivial_copy_buffer_size` option.
    pub fn get_trivial_copy_buffer_size(&self) -> u64 {
        unsafe { ffi::rocksdb_fifo_compaction_options_get_trivial_copy_buffer_size(self.inner) }
    }

    /// Returns the current `allow_compaction` setting.
    ///
    /// See [`Self::set_allow_compaction`] for what this controls.
    pub fn get_allow_compaction(&self) -> bool {
        unsafe { ffi::rocksdb_fifo_compaction_options_get_allow_compaction(self.inner) != 0 }
    }

    /// Returns the current `max_data_files_size` setting.
    ///
    /// See [`Self::set_max_data_files_size`] for what this controls.
    pub fn get_max_data_files_size(&self) -> u64 {
        unsafe { ffi::rocksdb_fifo_compaction_options_get_max_data_files_size(self.inner) }
    }

    /// Returns the current `max_table_files_size` setting.
    ///
    /// See [`Self::set_max_table_files_size`] for what this controls.
    pub fn get_max_table_files_size(&self) -> u64 {
        unsafe { ffi::rocksdb_fifo_compaction_options_get_max_table_files_size(self.inner) }
    }

    /// Returns the current `use_kv_ratio_compaction` setting.
    ///
    /// See [`Self::set_use_kv_ratio_compaction`] for what this controls.
    pub fn get_use_kv_ratio_compaction(&self) -> bool {
        unsafe { ffi::rocksdb_fifo_compaction_options_get_use_kv_ratio_compaction(self.inner) != 0 }
    }

    /// If true, try to do compaction to compact smaller files into larger ones. Minimum files
    /// to compact follows options.level0_file_num_compaction_trigger and compaction won't
    /// trigger if average compact bytes per del file is larger than
    /// options.write_buffer_size. This is to protect large files from being compacted again.
    /// Default: false;
    pub fn set_allow_compaction(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_fifo_compaction_options_set_allow_compaction(
                self.inner,
                c_uchar::from(val),
            );
        }
    }

    /// When non-zero, FIFO compaction uses the combined size of SST files and blob files for
    /// size-based trimming decisions. When the total data size (SST + blob) exceeds this
    /// limit, the oldest SST files are dropped along with their associated blob files.
    ///
    /// When non-zero, this takes precedence over max_table_files_size for all FIFO compaction
    /// decisions: size-based dropping, TTL threshold checks, and compaction score
    /// computation. max_table_files_size is ignored.
    ///
    /// When zero (default), FIFO compaction uses max_table_files_size which only considers
    /// SST file sizes, maintaining backward compatibility.
    ///
    /// This option is primarily intended for use with integrated BlobDB where blob files can
    /// represent a significant portion of the total data.
    ///
    /// Dynamically changeable through SetOptions() API. Default: 0 (use max_table_files_size
    /// behavior).
    pub fn set_max_data_files_size(&mut self, val: u64) {
        unsafe {
            ffi::rocksdb_fifo_compaction_options_set_max_data_files_size(self.inner, val);
        }
    }

    /// When true, enables a capacity-derived intra-L0 compaction strategy optimized for
    /// BlobDB workloads where SST files are much smaller than write_buffer_size. Uses the
    /// observed key/value size ratio (SST vs blob file sizes) to compute a target compacted
    /// file size, producing uniform files for predictable FIFO trimming.
    ///
    /// Uses level0_file_num_compaction_trigger as the target max L0 file count.
    ///
    /// When max_compaction_bytes is 0, the target is auto-calculated from the data capacity
    /// and observed SST/blob ratio. When max_compaction_bytes is explicitly set to a non-zero
    /// value, it overrides the auto-calculated target.
    ///
    /// Recommends:
    /// - allow_compaction = true (master switch for intra-L0 compaction)
    /// - max_data_files_size > 0 (needed to compute the target file size) If these are not
    ///   met, kv_ratio compaction is skipped and the old cost-based intra-L0 compaction
    ///   algorithm is used as a fallback.
    ///
    /// When false, the old intra-L0 strategy is used if allow_compaction is true
    /// (PickCostBasedIntraL0Compaction with 1.1 * write_buffer_size guard).
    ///
    /// Dynamically changeable through SetOptions() API. Default: false.
    pub fn set_use_kv_ratio_compaction(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_fifo_compaction_options_set_use_kv_ratio_compaction(
                self.inner,
                c_uchar::from(val),
            );
        }
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde1", derive(serde::Serialize, serde::Deserialize))]
pub enum UniversalCompactionStopStyle {
    Similar = ffi::rocksdb_similar_size_compaction_stop_style as isize,
    Total = ffi::rocksdb_total_size_compaction_stop_style as isize,
}

impl UniversalCompactionStopStyle {
    /// Decodes a raw `rocksdb::CompactionStopStyle`.
    pub(crate) fn try_from_raw(raw: c_int) -> Option<Self> {
        match raw {
            n if n == UniversalCompactionStopStyle::Similar as c_int => {
                Some(UniversalCompactionStopStyle::Similar)
            }
            n if n == UniversalCompactionStopStyle::Total as c_int => {
                Some(UniversalCompactionStopStyle::Total)
            }
            _ => None,
        }
    }
}

pub struct UniversalCompactOptions {
    pub(crate) inner: *mut ffi::rocksdb_universal_compaction_options_t,
}

impl Default for UniversalCompactOptions {
    fn default() -> Self {
        let opts = unsafe { ffi::rocksdb_universal_compaction_options_create() };
        assert!(
            !opts.is_null(),
            "Could not create RocksDB Universal Compaction Options"
        );

        Self { inner: opts }
    }
}

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

impl UniversalCompactOptions {
    /// Sets the percentage flexibility while comparing file size.
    /// If the candidate file(s) size is 1% smaller than the next file's size,
    /// then include next file into this candidate set.
    ///
    /// Default: 1
    pub fn set_size_ratio(&mut self, ratio: c_int) {
        unsafe {
            ffi::rocksdb_universal_compaction_options_set_size_ratio(self.inner, ratio);
        }
    }

    /// Sets the minimum number of files in a single compaction run.
    ///
    /// Default: 2
    pub fn set_min_merge_width(&mut self, num: c_int) {
        unsafe {
            ffi::rocksdb_universal_compaction_options_set_min_merge_width(self.inner, num);
        }
    }

    /// Sets the maximum number of files in a single compaction run.
    ///
    /// Default: UINT_MAX
    pub fn set_max_merge_width(&mut self, num: c_int) {
        unsafe {
            ffi::rocksdb_universal_compaction_options_set_max_merge_width(self.inner, num);
        }
    }

    /// sets the size amplification.
    ///
    /// It is defined as the amount (in percentage) of
    /// additional storage needed to store a single byte of data in the database.
    /// For example, a size amplification of 2% means that a database that
    /// contains 100 bytes of user-data may occupy upto 102 bytes of
    /// physical storage. By this definition, a fully compacted database has
    /// a size amplification of 0%. Rocksdb uses the following heuristic
    /// to calculate size amplification: it assumes that all files excluding
    /// the earliest file contribute to the size amplification.
    ///
    /// Default: 200, which means that a 100 byte database could require upto 300 bytes of storage.
    pub fn set_max_size_amplification_percent(&mut self, v: c_int) {
        unsafe {
            ffi::rocksdb_universal_compaction_options_set_max_size_amplification_percent(
                self.inner, v,
            );
        }
    }

    /// Sets the percentage of compression size.
    ///
    /// If this option is set to be -1, all the output files
    /// will follow compression type specified.
    ///
    /// If this option is not negative, we will try to make sure compressed
    /// size is just above this value. In normal cases, at least this percentage
    /// of data will be compressed.
    /// When we are compacting to a new file, here is the criteria whether
    /// it needs to be compressed: assuming here are the list of files sorted
    /// by generation time:
    ///    A1...An B1...Bm C1...Ct
    /// where A1 is the newest and Ct is the oldest, and we are going to compact
    /// B1...Bm, we calculate the total size of all the files as total_size, as
    /// well as  the total size of C1...Ct as total_C, the compaction output file
    /// will be compressed iff
    ///   total_C / total_size < this percentage
    ///
    /// Default: -1
    pub fn set_compression_size_percent(&mut self, v: c_int) {
        unsafe {
            ffi::rocksdb_universal_compaction_options_set_compression_size_percent(self.inner, v);
        }
    }

    /// Sets the algorithm used to stop picking files into a single compaction run.
    ///
    /// Default: ::Total
    pub fn set_stop_style(&mut self, style: UniversalCompactionStopStyle) {
        unsafe {
            ffi::rocksdb_universal_compaction_options_set_stop_style(self.inner, style as c_int);
        }
    }

    /// The stop style set by [`Self::set_stop_style`].
    ///
    /// [`UniversalCompactionStopStyle`] covers both styles RocksDB defines
    /// today, so `None` only shows up if a future release adds one.
    pub fn get_stop_style(&self) -> Option<UniversalCompactionStopStyle> {
        let raw = unsafe { ffi::rocksdb_universal_compaction_options_get_stop_style(self.inner) };
        UniversalCompactionStopStyle::try_from_raw(raw)
    }

    /// Option to optimize the manual compaction by enabling trivial move for non overlapping
    /// files. Default: false
    pub fn set_allow_trivial_move(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_universal_compaction_options_set_allow_trivial_move(
                self.inner,
                c_uchar::from(val),
            );
        }
    }

    /// Returns the value of the `allow_trivial_move` option.
    pub fn get_allow_trivial_move(&self) -> bool {
        unsafe { ffi::rocksdb_universal_compaction_options_get_allow_trivial_move(self.inner) != 0 }
    }

    /// EXPERIMENTAL If true, try to limit compaction size under max_compaction_bytes. This
    /// might cause higher write amplification, but can prevent some problem caused by large
    /// compactions. Default: false
    pub fn set_incremental(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_universal_compaction_options_set_incremental(
                self.inner,
                c_uchar::from(val),
            );
        }
    }

    /// Returns the value of the `incremental` option.
    pub fn get_incremental(&self) -> bool {
        unsafe { ffi::rocksdb_universal_compaction_options_get_incremental(self.inner) != 0 }
    }

    /// The limit on the number of sorted runs. RocksDB will try to keep the number of sorted
    /// runs at most this number. While compactions are running, the number of sorted runs may
    /// be temporarily higher than this number.
    ///
    /// Since universal compaction checks if there is compaction to do when the number of
    /// sorted runs is at least level0_file_num_compaction_trigger, it is suggested to set
    /// level0_file_num_compaction_trigger to be no larger than max_read_amp.
    ///
    /// Values: -1: special flag to let RocksDB pick default. Currently, RocksDB will fall
    /// back to the behavior before this option is introduced, which is to use
    /// level0_file_num_compaction_trigger as the limit. This may change in the future to
    /// behave as 0 below. 0: Let RocksDB auto-tune. Currently, we determine the max number of
    /// sorted runs based on the current DB size, size_ratio and write_buffer_size. Note that
    /// this is only supported for the default stop_style kCompactionStopStyleTotalSize. For
    /// kCompactionStopStyleSimilarSize, this behaves as if -1 is configured. N > 0: limit the
    /// number of sorted runs to be at most N. N should be at least the compaction trigger
    /// specified by level0_file_num_compaction_trigger. If 0 < max_read_amp <
    /// level0_file_num_compaction_trigger, Status::NotSupported() will be returned during DB
    /// open. N < -1: Status::NotSupported() will be returned during DB open.
    ///
    /// Default: -1
    pub fn set_max_read_amp(&mut self, val: c_int) {
        unsafe {
            ffi::rocksdb_universal_compaction_options_set_max_read_amp(self.inner, val);
        }
    }

    /// Returns the value of the `max_read_amp` option.
    pub fn get_max_read_amp(&self) -> c_int {
        unsafe { ffi::rocksdb_universal_compaction_options_get_max_read_amp(self.inner) }
    }

    /// If true, auto universal compaction picking will adjust to minimize locking of input
    /// files when bottom priority compactions are waiting to run. This can increase the
    /// likelihood of existing L0s being selected for compaction, thereby improving write
    /// stall and reducing read regression. It may increase the overrall write amplification
    /// and compaction load on low priority threads.
    ///
    /// Default: true (enabled)
    ///
    /// This options does not apply to manual compactions.
    ///
    /// This option is temporary in case turning on this feature causes problems and users
    /// need to undo it quickly. This option is planned for removal in the near future with
    /// default value set to true.
    ///
    /// Dynamically changeable through the SetOptions() API.
    pub fn set_reduce_file_locking(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_universal_compaction_options_set_reduce_file_locking(
                self.inner,
                c_uchar::from(val),
            );
        }
    }

    /// Returns the value of the `reduce_file_locking` option.
    pub fn get_reduce_file_locking(&self) -> bool {
        unsafe {
            ffi::rocksdb_universal_compaction_options_get_reduce_file_locking(self.inner) != 0
        }
    }

    /// Returns the current `compression_size_percent` setting.
    ///
    /// See [`Self::set_compression_size_percent`] for what this controls.
    pub fn get_compression_size_percent(&self) -> c_int {
        unsafe {
            ffi::rocksdb_universal_compaction_options_get_compression_size_percent(self.inner)
        }
    }

    /// Returns the current `max_merge_width` setting.
    ///
    /// See [`Self::set_max_merge_width`] for what this controls.
    pub fn get_max_merge_width(&self) -> c_int {
        unsafe { ffi::rocksdb_universal_compaction_options_get_max_merge_width(self.inner) }
    }

    /// Returns the current `max_size_amplification_percent` setting.
    ///
    /// See [`Self::set_max_size_amplification_percent`] for what this controls.
    pub fn get_max_size_amplification_percent(&self) -> c_int {
        unsafe {
            ffi::rocksdb_universal_compaction_options_get_max_size_amplification_percent(self.inner)
        }
    }

    /// Returns the current `min_merge_width` setting.
    ///
    /// See [`Self::set_min_merge_width`] for what this controls.
    pub fn get_min_merge_width(&self) -> c_int {
        unsafe { ffi::rocksdb_universal_compaction_options_get_min_merge_width(self.inner) }
    }

    /// Returns the current `size_ratio` setting.
    ///
    /// See [`Self::set_size_ratio`] for what this controls.
    pub fn get_size_ratio(&self) -> c_int {
        unsafe { ffi::rocksdb_universal_compaction_options_get_size_ratio(self.inner) }
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde1", derive(serde::Serialize, serde::Deserialize))]
#[repr(u8)]
pub enum BottommostLevelCompaction {
    /// Skip bottommost level compaction
    Skip = 0,
    /// Only compact bottommost level if there is a compaction filter
    /// This is the default option
    IfHaveCompactionFilter,
    /// Always compact bottommost level
    Force,
    /// Always compact bottommost level but in bottommost level avoid
    /// double-compacting files created in the same compaction
    ForceOptimized,
}

pub struct CompactOptions {
    pub(crate) inner: *mut ffi::rocksdb_compactoptions_t,
    full_history_ts_low: Option<Vec<u8>>,
}

impl Default for CompactOptions {
    fn default() -> Self {
        let opts = unsafe { ffi::rocksdb_compactoptions_create() };
        assert!(!opts.is_null(), "Could not create RocksDB Compact Options");

        Self {
            inner: opts,
            full_history_ts_low: None,
        }
    }
}

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

impl CompactOptions {
    /// If more than one thread calls manual compaction,
    /// only one will actually schedule it while the other threads will simply wait
    /// for the scheduled manual compaction to complete. If exclusive_manual_compaction
    /// is set to true, the call will disable scheduling of automatic compaction jobs
    /// and wait for existing automatic compaction jobs to finish.
    pub fn set_exclusive_manual_compaction(&mut self, v: bool) {
        unsafe {
            ffi::rocksdb_compactoptions_set_exclusive_manual_compaction(
                self.inner,
                c_uchar::from(v),
            );
        }
    }

    /// Sets bottommost level compaction.
    pub fn set_bottommost_level_compaction(&mut self, lvl: BottommostLevelCompaction) {
        unsafe {
            ffi::rocksdb_compactoptions_set_bottommost_level_compaction(self.inner, lvl as c_uchar);
        }
    }

    /// If true, compacted files will be moved to the minimum level capable
    /// of holding the data or given level (specified non-negative target_level).
    pub fn set_change_level(&mut self, v: bool) {
        unsafe {
            ffi::rocksdb_compactoptions_set_change_level(self.inner, c_uchar::from(v));
        }
    }

    /// If change_level is true and target_level have non-negative value, compacted
    /// files will be moved to target_level.
    pub fn set_target_level(&mut self, lvl: c_int) {
        unsafe {
            ffi::rocksdb_compactoptions_set_target_level(self.inner, lvl);
        }
    }

    /// Set user-defined timestamp low bound, the data with older timestamp than
    /// low bound maybe GCed by compaction. Default: nullptr
    pub fn set_full_history_ts_low<S: Into<Vec<u8>>>(&mut self, ts: S) {
        self.set_full_history_ts_low_impl(Some(ts.into()));
    }

    fn set_full_history_ts_low_impl(&mut self, ts: Option<Vec<u8>>) {
        let (ptr, len) = if let Some(ref ts) = ts {
            (ts.as_ptr().cast_mut().cast::<c_char>(), ts.len())
        } else if self.full_history_ts_low.is_some() {
            (std::ptr::null::<Vec<u8>>() as *mut c_char, 0)
        } else {
            return;
        };
        self.full_history_ts_low = ts;
        unsafe {
            ffi::rocksdb_compactoptions_set_full_history_ts_low(self.inner, ptr, len);
        }
    }

    /// Override `CompactRangeOptions::blob_garbage_collection_age_cutoff` for a
    /// single manual compaction.
    ///
    /// If set to `< 0` or `> 1`, RocksDB leaves the
    /// `blob_garbage_collection_age_cutoff` from `ColumnFamilyOptions` in
    /// effect (this is the default, `-1`). Otherwise, it overrides the
    /// user-provided setting for the duration of this compaction. This
    /// enables callers to selectively override the age cutoff per
    /// `compact_range` call.
    ///
    /// See [`Options::set_blob_gc_age_cutoff`] for the CF-level setter that
    /// this value overrides.
    pub fn set_blob_garbage_collection_age_cutoff(&mut self, v: c_double) {
        unsafe {
            ffi::rocksdb_compactoptions_set_blob_garbage_collection_age_cutoff(self.inner, v);
        }
    }

    /// If set to < 0 or > 1, RocksDB leaves blob_garbage_collection_age_cutoff from
    /// ColumnFamilyOptions in effect. Otherwise, it will override the user-provided setting.
    /// This enables customers to selectively override the age cutoff.
    pub fn get_blob_garbage_collection_age_cutoff(&self) -> f64 {
        unsafe { ffi::rocksdb_compactoptions_get_blob_garbage_collection_age_cutoff(self.inner) }
    }

    /// If set to kForce, RocksDB will override enable_blob_file_garbage_collection to true;
    /// if set to kDisable, RocksDB will override it to false, and kUseDefault leaves the
    /// setting in effect. This enables customers to both force-enable and force-disable GC
    /// when calling CompactRange.
    pub fn set_blob_garbage_collection_policy(&mut self, val: c_int) {
        unsafe {
            ffi::rocksdb_compactoptions_set_blob_garbage_collection_policy(self.inner, val);
        }
    }

    /// Returns the value of the `blob_garbage_collection_policy` option.
    pub fn get_blob_garbage_collection_policy(&self) -> c_int {
        unsafe { ffi::rocksdb_compactoptions_get_blob_garbage_collection_policy(self.inner) }
    }

    /// Returns the current `allow_write_stall` setting.
    ///
    /// See [`Self::set_allow_write_stall`] for what this controls.
    pub fn get_allow_write_stall(&self) -> bool {
        unsafe { ffi::rocksdb_compactoptions_get_allow_write_stall(self.inner) != 0 }
    }

    /// Returns the current `bottommost_level_compaction` setting.
    ///
    /// See [`Self::set_bottommost_level_compaction`] for what this controls.
    pub fn get_bottommost_level_compaction(&self) -> bool {
        unsafe { ffi::rocksdb_compactoptions_get_bottommost_level_compaction(self.inner) != 0 }
    }

    /// Returns the current `change_level` setting.
    ///
    /// See [`Self::set_change_level`] for what this controls.
    pub fn get_change_level(&self) -> bool {
        unsafe { ffi::rocksdb_compactoptions_get_change_level(self.inner) != 0 }
    }

    /// Returns the current `exclusive_manual_compaction` setting.
    ///
    /// See [`Self::set_exclusive_manual_compaction`] for what this controls.
    pub fn get_exclusive_manual_compaction(&self) -> bool {
        unsafe { ffi::rocksdb_compactoptions_get_exclusive_manual_compaction(self.inner) != 0 }
    }

    /// Returns the current `max_subcompactions` setting.
    ///
    /// See [`Self::set_max_subcompactions`] for what this controls.
    pub fn get_max_subcompactions(&self) -> c_int {
        unsafe { ffi::rocksdb_compactoptions_get_max_subcompactions(self.inner) }
    }

    /// Returns the current `target_level` setting.
    ///
    /// See [`Self::set_target_level`] for what this controls.
    pub fn get_target_level(&self) -> c_int {
        unsafe { ffi::rocksdb_compactoptions_get_target_level(self.inner) }
    }

    /// Returns the current `target_path_id` setting.
    ///
    /// See [`Self::set_target_path_id`] for what this controls.
    pub fn get_target_path_id(&self) -> c_int {
        unsafe { ffi::rocksdb_compactoptions_get_target_path_id(self.inner) }
    }

    /// If true, the flush would proceed immediately even it means writes will stall for the
    /// duration of the flush; if false the operation will wait until it's possible to do
    /// flush w/o causing stall or until required flush is performed by someone else
    /// (foreground call or background thread). Default: false.
    pub fn set_allow_write_stall(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_compactoptions_set_allow_write_stall(self.inner, c_uchar::from(val));
        }
    }

    /// This value represents the maximum number of threads that will concurrently perform a
    /// compaction job by breaking it into multiple, smaller ones that are run simultaneously.
    /// Default: 1 (i.e. no subcompactions)
    ///
    /// Dynamically changeable through SetDBOptions() API.
    pub fn set_max_subcompactions(&mut self, val: c_int) {
        unsafe {
            ffi::rocksdb_compactoptions_set_max_subcompactions(self.inner, val);
        }
    }

    /// Compaction outputs will be placed in options.db_paths\[target_path_id\]. Behavior is
    /// undefined if target_path_id is out of range.
    pub fn set_target_path_id(&mut self, val: c_int) {
        unsafe {
            ffi::rocksdb_compactoptions_set_target_path_id(self.inner, val);
        }
    }
}

pub struct WaitForCompactOptions {
    pub(crate) inner: *mut ffi::rocksdb_wait_for_compact_options_t,
}

impl Default for WaitForCompactOptions {
    fn default() -> Self {
        let opts = unsafe { ffi::rocksdb_wait_for_compact_options_create() };
        assert!(
            !opts.is_null(),
            "Could not create RocksDB Wait For Compact Options"
        );

        Self { inner: opts }
    }
}

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

impl WaitForCompactOptions {
    /// If true, abort waiting if background jobs are paused. If false,
    /// ContinueBackgroundWork() must be called to resume the background jobs.
    /// Otherwise, jobs that were queued, but not scheduled yet may never finish
    /// and WaitForCompact() may wait indefinitely (if timeout is set, it will
    /// abort after the timeout).
    ///
    /// Default: false
    pub fn set_abort_on_pause(&mut self, v: bool) {
        unsafe {
            ffi::rocksdb_wait_for_compact_options_set_abort_on_pause(self.inner, c_uchar::from(v));
        }
    }

    /// If true, flush all column families before starting to wait.
    ///
    /// Default: false
    pub fn set_flush(&mut self, v: bool) {
        unsafe {
            ffi::rocksdb_wait_for_compact_options_set_flush(self.inner, c_uchar::from(v));
        }
    }

    /// Timeout in microseconds for waiting for compaction to complete.
    /// when timeout == 0, WaitForCompact() will wait as long as there's background
    /// work to finish.
    ///
    /// Default: 0
    pub fn set_timeout(&mut self, microseconds: u64) {
        unsafe {
            ffi::rocksdb_wait_for_compact_options_set_timeout(self.inner, microseconds);
        }
    }

    /// A boolean to wait for purge to complete
    pub fn set_wait_for_purge(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_wait_for_compact_options_set_wait_for_purge(
                self.inner,
                c_uchar::from(val),
            );
        }
    }

    /// Returns the value of the `wait_for_purge` option.
    pub fn get_wait_for_purge(&self) -> bool {
        unsafe { ffi::rocksdb_wait_for_compact_options_get_wait_for_purge(self.inner) != 0 }
    }

    /// Returns the current `abort_on_pause` setting.
    ///
    /// See [`Self::set_abort_on_pause`] for what this controls.
    pub fn get_abort_on_pause(&self) -> bool {
        unsafe { ffi::rocksdb_wait_for_compact_options_get_abort_on_pause(self.inner) != 0 }
    }

    /// Returns the current `close_db` setting.
    ///
    /// See [`Self::set_close_db`] for what this controls.
    pub fn get_close_db(&self) -> bool {
        unsafe { ffi::rocksdb_wait_for_compact_options_get_close_db(self.inner) != 0 }
    }

    /// Returns the current `flush` setting.
    ///
    /// See [`Self::set_flush`] for what this controls.
    pub fn get_flush(&self) -> bool {
        unsafe { ffi::rocksdb_wait_for_compact_options_get_flush(self.inner) != 0 }
    }

    /// Returns the current `timeout` setting.
    ///
    /// See [`Self::set_timeout`] for what this controls.
    pub fn get_timeout(&self) -> u64 {
        unsafe { ffi::rocksdb_wait_for_compact_options_get_timeout(self.inner) }
    }

    /// A boolean to call Close() after waiting is done. By the time Close() is called here,
    /// there should be no background jobs in progress and no new background jobs should be
    /// added. DB may not have been closed if Close() returned Aborted status due to
    /// unreleased snapshots in the system. See comments in DB::Close() for details.
    pub fn set_close_db(&mut self, val: bool) {
        unsafe {
            ffi::rocksdb_wait_for_compact_options_set_close_db(self.inner, c_uchar::from(val));
        }
    }
}

/// Represents a path where sst files can be put into
pub struct DBPath {
    pub(crate) inner: *mut ffi::rocksdb_dbpath_t,
}

impl DBPath {
    /// Create a new path
    pub fn new<P: AsRef<Path>>(path: P, target_size: u64) -> Result<Self, Error> {
        let p = to_cpath(path.as_ref()).unwrap();
        let dbpath = unsafe { ffi::rocksdb_dbpath_create(p.as_ptr(), target_size) };
        if dbpath.is_null() {
            Err(Error::new(format!(
                "Could not create path for storing sst files at location: {}",
                path.as_ref().display()
            )))
        } else {
            Ok(DBPath { inner: dbpath })
        }
    }
}

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

pub struct InfoLogger {
    pub(crate) inner: *mut ffi::rocksdb_logger_t,
    callback: Option<Arc<LoggerCallback>>,
}

impl InfoLogger {
    /// Creates a new logger that redirects logs to `STDERR` with an optional
    /// prefix.
    pub fn new_stderr_logger<S: AsRef<str>>(log_level: LogLevel, prefix: Option<S>) -> Self {
        let prefix = prefix.map(|s| {
            s.as_ref()
                .into_c_string()
                .expect("cannot have NULL in prefix")
        });
        let prefix_ptr = match prefix.as_ref() {
            Some(s) => s.as_ptr(),
            None => std::ptr::null(),
        };
        let inner =
            unsafe { ffi::rocksdb_logger_create_stderr_logger(log_level as i32, prefix_ptr) };
        Self {
            inner,
            // no Rust callback: RocksDB implements this
            callback: None,
        }
    }

    /// Creates a new logger that redirects logs to a custom callback.
    pub fn new_callback_logger<F: Fn(LogLevel, &str) + Sync + Send + 'static>(
        level: LogLevel,
        cb: F,
    ) -> Self {
        // use an Arc<Box<...>> so we can reference count, and still pass a thin pointer to C
        let arc_cb: Arc<LoggerCallback> = Arc::new(Box::new(cb));
        let raw_cb: LoggerCallbackPtr = Arc::as_ptr(&arc_cb);
        let inner = unsafe {
            ffi::rocksdb_logger_create_callback_logger(
                level as i32,
                Some(logger_callback),
                raw_cb as *mut c_void,
            )
        };
        Self {
            inner,
            callback: Some(arc_cb),
        }
    }
}

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

/// Options for importing column families. See
/// [DB::create_column_family_with_import](crate::DB::create_column_family_with_import).
pub struct ImportColumnFamilyOptions {
    pub(crate) inner: *mut ffi::rocksdb_import_column_family_options_t,
}

impl ImportColumnFamilyOptions {
    pub fn new() -> Self {
        let inner = unsafe { ffi::rocksdb_import_column_family_options_create() };
        ImportColumnFamilyOptions { inner }
    }

    /// Determines whether to move the provided set of files on import. The default
    /// behavior is to copy the external files on import. Setting `move_files` to `true`
    /// will move the files instead of copying them. See
    /// [DB::create_column_family_with_import](crate::DB::create_column_family_with_import)
    /// for more information.
    pub fn set_move_files(&mut self, move_files: bool) {
        unsafe {
            ffi::rocksdb_import_column_family_options_set_move_files(
                self.inner,
                c_uchar::from(move_files),
            );
        }
    }

    /// Returns the current `move_files` setting.
    ///
    /// See [`Self::set_move_files`] for what this controls.
    pub fn get_move_files(&self) -> bool {
        unsafe { ffi::rocksdb_import_column_family_options_get_move_files(self.inner) != 0 }
    }
}

impl Default for ImportColumnFamilyOptions {
    fn default() -> Self {
        Self::new()
    }
}

impl Drop for ImportColumnFamilyOptions {
    fn drop(&mut self) {
        unsafe { ffi::rocksdb_import_column_family_options_destroy(self.inner) }
    }
}

/// Ensures the unsafe casts use the same type.
type LoggerCallbackPtr = *const LoggerCallback;

/// The closure behind [`ReadOptions::set_table_filter`], boxed twice so the `state` handed to
/// the C API is a thin pointer.
type TableFilterCallback = Box<dyn Fn(&TableProperties<'_>) -> bool + Send + Sync>;

/// Reclaims the box installed by [`ReadOptions::set_table_filter`].
///
/// RocksDB calls this exactly once per filter, from `ClearTableFilter`, which runs when a new
/// filter replaces this one, when the filter is cleared, and when the read options are
/// destroyed.
unsafe extern "C" fn table_filter_destructor(state: *mut c_void) {
    drop(unsafe { Box::from_raw(state.cast::<TableFilterCallback>()) });
}

unsafe extern "C" fn table_filter_callback(
    state: *mut c_void,
    table_properties: *const ffi::rocksdb_table_properties_t,
) -> c_uchar {
    // Shared reference, not `&mut`: several iterator threads can hold the same `ReadOptions`.
    let filter = unsafe { &*state.cast::<TableFilterCallback>() };
    // RocksDB passes a reference to a `TableProperties` that only lives for this call, and
    // the `Fn(&TableProperties<'_>)` bound is higher ranked, so the borrow cannot escape.
    let properties = unsafe { TableProperties::from_ptr(table_properties) };
    c_uchar::from(filter(&properties))
}

unsafe extern "C" fn logger_callback(
    raw_cb: *mut c_void,
    level: c_uint,
    msg: *mut c_char,
    len: size_t,
) {
    let rust_callback: &LoggerCallback = unsafe { &*(raw_cb as LoggerCallbackPtr) };
    let raw_msg = if len == 0 {
        &[][..]
    } else {
        unsafe { std::slice::from_raw_parts(msg.cast_const().cast::<u8>(), len) }
    };
    let msg = String::from_utf8_lossy(raw_msg);
    // Don't panic on an unexpected level: this runs in an `extern "C"` frame,
    // where unwinding aborts the process. Losing the exact level of one log
    // line is not worth taking the process down for.
    let level = LogLevel::try_from_raw(level as i32).unwrap_or(LogLevel::Info);
    (rust_callback)(level, &msg);
}

#[cfg(test)]
mod tests {
    use crate::cache::Cache;
    use crate::db_options::{DBCompactionPri, InfoLogger, WriteBufferManager};
    use crate::{MemtableFactory, Options};

    /// `set_prefix_range_in_place` is an allocation-free reimplementation of
    /// `set_iterate_range(PrefixRange(..))`. It has to produce byte-identical
    /// bounds, including for the awkward cases: empty prefixes, trailing 0xff
    /// bytes, and all-0xff prefixes (which have no successor).
    #[test]
    fn prefix_range_in_place_matches_prefix_range() {
        let cases: &[&[u8]] = &[
            b"",
            b"a",
            b"foo",
            b"\x00",
            b"\xff",
            b"\xff\xff",
            b"a\xff",
            b"a\xff\xff",
            b"\xfe\xff",
            b"prefix\x00\xff",
        ];

        for prefix in cases {
            let mut expected = crate::ReadOptions::default();
            expected.set_iterate_range(crate::PrefixRange(*prefix));

            let mut actual = crate::ReadOptions::default();
            actual.set_prefix_range_in_place(prefix);

            assert_eq!(
                actual.iterate_lower_bound, expected.iterate_lower_bound,
                "lower bound mismatch for prefix {prefix:?}"
            );
            assert_eq!(
                actual.iterate_upper_bound, expected.iterate_upper_bound,
                "upper bound mismatch for prefix {prefix:?}"
            );
        }
    }

    /// The whole point of the in-place setter is that a reused `ReadOptions`
    /// stops reallocating, so overwriting the bounds repeatedly must keep the
    /// results correct rather than leaving stale bytes behind.
    #[test]
    fn prefix_range_in_place_is_reusable() {
        let mut opts = crate::ReadOptions::default();

        opts.set_prefix_range_in_place(b"aaaa");
        assert_eq!(opts.iterate_lower_bound.as_deref(), Some(&b"aaaa"[..]));
        assert_eq!(opts.iterate_upper_bound.as_deref(), Some(&b"aaab"[..]));

        // Shorter prefix must truncate, not leave the tail of the previous one.
        opts.set_prefix_range_in_place(b"b");
        assert_eq!(opts.iterate_lower_bound.as_deref(), Some(&b"b"[..]));
        assert_eq!(opts.iterate_upper_bound.as_deref(), Some(&b"c"[..]));

        // An all-0xff prefix has no successor: the upper bound must be cleared.
        opts.set_prefix_range_in_place(b"\xff");
        assert_eq!(opts.iterate_lower_bound.as_deref(), Some(&b"\xff"[..]));
        assert_eq!(opts.iterate_upper_bound, None);

        // An empty prefix is the full range: both bounds cleared.
        opts.set_prefix_range_in_place(b"");
        assert_eq!(opts.iterate_lower_bound, None);
        assert_eq!(opts.iterate_upper_bound, None);
    }

    #[test]
    fn test_enable_statistics() {
        let mut opts = Options::default();
        assert_eq!(None, opts.get_statistics());
        opts.enable_statistics();
        opts.set_stats_dump_period_sec(60);
        assert!(opts.get_statistics().is_some());

        let opts = Options::default();
        assert!(opts.get_statistics().is_none());
    }

    #[test]
    fn test_set_memtable_factory() {
        let mut opts = Options::default();
        opts.set_memtable_factory(MemtableFactory::Vector);
        opts.set_memtable_factory(MemtableFactory::HashLinkList { bucket_count: 100 });
        opts.set_memtable_factory(MemtableFactory::HashSkipList {
            bucket_count: 100,
            height: 4,
            branching_factor: 4,
        });
    }

    #[test]
    fn test_use_fsync() {
        let mut opts = Options::default();
        assert!(!opts.get_use_fsync());
        opts.set_use_fsync(true);
        assert!(opts.get_use_fsync());
    }

    #[test]
    fn test_set_stats_persist_period_sec() {
        let mut opts = Options::default();
        opts.enable_statistics();
        opts.set_stats_persist_period_sec(5);
        assert!(opts.get_statistics().is_some());

        let opts = Options::default();
        assert!(opts.get_statistics().is_none());
    }

    #[test]
    fn test_set_write_buffer_manager() {
        let mut opts = Options::default();
        let lrucache = Cache::new_lru_cache(100);
        let write_buffer_manager =
            WriteBufferManager::new_write_buffer_manager_with_cache(100, false, lrucache);
        assert_eq!(write_buffer_manager.get_buffer_size(), 100);
        assert_eq!(write_buffer_manager.get_usage(), 0);
        assert!(write_buffer_manager.enabled());

        opts.set_write_buffer_manager(&write_buffer_manager);
        drop(opts);

        // WriteBufferManager outlives options
        assert!(write_buffer_manager.enabled());
    }

    #[test]
    fn compaction_pri() {
        let mut opts = Options::default();
        opts.set_compaction_pri(DBCompactionPri::RoundRobin);
        opts.create_if_missing(true);
        let tmp = tempfile::tempdir().unwrap();
        let _db = crate::DB::open(&opts, tmp.path()).unwrap();

        let options = std::fs::read_dir(tmp.path())
            .unwrap()
            .find_map(|x| {
                let x = x.ok()?;
                x.file_name()
                    .into_string()
                    .unwrap()
                    .contains("OPTIONS")
                    .then_some(x.path())
            })
            .map(std::fs::read_to_string)
            .unwrap()
            .unwrap();

        assert!(options.contains("compaction_pri=kRoundRobin"));
    }

    #[test]
    fn test_callback_logger() {
        let (log_snd, log_rcv) = std::sync::mpsc::channel();
        let callback = move |level, msg: &str| {
            log_snd.send((level, msg.to_string())).ok();
        };

        let mut opts = Options::default();
        opts.create_if_missing(true);
        opts.set_info_logger(InfoLogger::new_callback_logger(
            super::LogLevel::Debug,
            callback,
        ));

        // create 2 DBs with the options then drop the options to ensure it is reference counted
        let tmp = tempfile::tempdir().unwrap();
        let db = crate::DB::open(&opts, tmp.path()).unwrap();
        db.put(b"testkey", b"testvalue").unwrap();
        db.flush().unwrap();
        db.delete(b"testkey").unwrap();
        db.flush().unwrap();
        db.compact_range(Some(b"a"), Some(b"z"));
        assert!(log_rcv.try_recv().is_ok());
        drop(db);

        let tmp2 = tempfile::tempdir().unwrap();
        let db2 = crate::DB::open(&opts, tmp2.path()).unwrap();

        // get the configured logger before dropping the options
        let logger = opts.get_info_logger();
        drop(opts);

        // clear the logs and make sure the callback is called by db2
        while log_rcv.try_recv().is_ok() {}
        assert!(log_rcv.try_recv().is_err());

        db2.put(b"testkey2", b"testvalue2").unwrap();
        db2.flush().unwrap();
        db2.delete(b"testkey2").unwrap();
        db2.flush().unwrap();
        db2.compact_range(Some(b"a"), Some(b"z"));

        drop(db2);
        assert!(log_rcv.try_recv().is_ok());

        // clear the logs
        while log_rcv.try_recv().is_ok() {}
        assert!(log_rcv.try_recv().is_err());

        // create a db with the copied logger to check lifetimes
        let tmp3 = tempfile::tempdir().unwrap();
        let mut opts2 = Options::default();
        opts2.create_if_missing(true);
        opts2.set_info_logger(logger);
        let db3 = crate::DB::open(&opts2, tmp3.path()).unwrap();
        drop(opts2);
        db3.put(b"testkey3", b"testvalue3").unwrap();
        db3.flush().unwrap();
        db3.delete(b"testkey3").unwrap();
        db3.flush().unwrap();
        db3.compact_range(Some(b"a"), Some(b"z"));
        assert!(log_rcv.try_recv().is_ok());
        drop(db3);
    }
}