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
// Copyright 2014 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 crocksdb_ffi::{
    self, DBBackupEngine, DBCFHandle, DBCache, DBCompressionType, DBEnv, DBInstance, DBMapProperty,
    DBPinnableSlice, DBSequentialFile, DBStatisticsHistogramType, DBStatisticsTickerType,
    DBTablePropertiesCollection, DBTitanDBOptions, DBWriteBatch,
};
use libc::{self, c_char, c_int, c_void, size_t};
use librocksdb_sys::DBMemoryAllocator;
use metadata::ColumnFamilyMetaData;
use rocksdb_options::{
    CColumnFamilyDescriptor, ColumnFamilyDescriptor, ColumnFamilyOptions, CompactOptions,
    CompactionOptions, DBOptions, EnvOptions, FlushOptions, HistogramData,
    IngestExternalFileOptions, LRUCacheOptions, ReadOptions, RestoreOptions, UnsafeSnap,
    WriteOptions,
};
use std::collections::BTreeMap;
use std::ffi::{CStr, CString};
use std::fmt::{self, Debug, Formatter};
use std::io;
use std::mem;
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::str::from_utf8;
use std::sync::Arc;
use std::{fs, ptr, slice};

#[cfg(feature = "encryption")]
use encryption::{DBEncryptionKeyManager, EncryptionKeyManager};
use file_system::{DBFileSystemInspector, FileSystemInspector};
use table_properties::{TableProperties, TablePropertiesCollection};
use table_properties_rc::TablePropertiesCollection as RcTablePropertiesCollection;
use titan::TitanDBOptions;
use write_batch::WriteBatch;

pub struct CFHandle {
    inner: *mut DBCFHandle,
}

impl CFHandle {
    pub fn id(&self) -> u32 {
        unsafe { crocksdb_ffi::crocksdb_column_family_handle_id(self.inner) }
    }
}

impl Drop for CFHandle {
    fn drop(&mut self) {
        unsafe {
            crocksdb_ffi::crocksdb_column_family_handle_destroy(self.inner);
        }
    }
}

fn ensure_default_cf_exists<'a>(
    list: &mut Vec<ColumnFamilyDescriptor<'a>>,
    ttls: &mut Vec<i32>,
    is_titan: bool,
) {
    let contains = list.iter().any(|ref cf| cf.is_default());
    if !contains {
        let mut desc = ColumnFamilyDescriptor::default();
        if is_titan {
            desc.options.set_titandb_options(&TitanDBOptions::new());
        }
        list.push(desc);
        if ttls.len() > 0 {
            ttls.push(0);
        }
    }
}

fn split_descriptors(
    list: Vec<ColumnFamilyDescriptor>,
    is_titan: bool,
) -> (Vec<&str>, Vec<ColumnFamilyOptions>) {
    let mut v1 = Vec::with_capacity(list.len());
    let mut v2 = Vec::with_capacity(list.len());
    for mut d in list {
        v1.push(d.name);
        if is_titan && d.options.titan_inner.is_null() {
            d.options.set_titandb_options(&TitanDBOptions::new());
        }
        v2.push(d.options);
    }
    (v1, v2)
}

fn build_cstring_list(str_list: &[&str]) -> Vec<CString> {
    str_list
        .iter()
        .map(|s| CString::new(s.as_bytes()).unwrap())
        .collect()
}

pub struct MapProperty {
    inner: *mut DBMapProperty,
}

impl Drop for MapProperty {
    fn drop(&mut self) {
        unsafe {
            crocksdb_ffi::crocksdb_destroy_map_property(self.inner);
        }
    }
}

impl MapProperty {
    pub fn new() -> MapProperty {
        unsafe {
            MapProperty {
                inner: crocksdb_ffi::crocksdb_create_map_property(),
            }
        }
    }

    pub fn get_property_value(&self, property: &str) -> String {
        let propname = CString::new(property.as_bytes()).unwrap();
        unsafe {
            let value = crocksdb_ffi::crocksdb_map_property_value(self.inner, propname.as_ptr());
            return CStr::from_ptr(value).to_str().unwrap().to_owned();
        }
    }

    pub fn get_property_int_value(&self, property: &str) -> u64 {
        let propname = CString::new(property.as_bytes()).unwrap();
        unsafe {
            let value =
                crocksdb_ffi::crocksdb_map_property_int_value(self.inner, propname.as_ptr());
            return value as u64;
        }
    }
}

pub struct DB {
    inner: *mut DBInstance,
    cfs_by_name: BTreeMap<String, usize>,
    cfs: Vec<Option<(String, CFHandle)>>,
    path: String,
    opts: DBOptions,
    _cf_opts: Vec<ColumnFamilyOptions>,
    readonly: bool,
}

impl Debug for DB {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "Db [path={}]", self.path)
    }
}

unsafe impl Send for DB {}
unsafe impl Sync for DB {}

impl DB {
    pub fn is_titan(&self) -> bool {
        !self.opts.titan_inner.is_null()
    }
}

pub struct Snapshot<D: Deref<Target = DB>> {
    db: D,
    snap: UnsafeSnap,
}

pub struct DBIterator<D> {
    _db: D,
    _readopts: ReadOptions,
    inner: *mut crocksdb_ffi::DBIterator,
}

pub enum SeekKey<'a> {
    Start,
    End,
    Key(&'a [u8]),
}

impl<'a> From<&'a [u8]> for SeekKey<'a> {
    fn from(bs: &'a [u8]) -> SeekKey {
        SeekKey::Key(bs)
    }
}

impl<D: Deref<Target = DB>> DBIterator<D> {
    pub fn new(db: D, readopts: ReadOptions) -> DBIterator<D> {
        unsafe {
            let iterator = if db.is_titan() {
                crocksdb_ffi::ctitandb_create_iterator(
                    db.inner,
                    readopts.get_inner(),
                    readopts.get_titan_inner(),
                )
            } else {
                crocksdb_ffi::crocksdb_create_iterator(db.inner, readopts.get_inner())
            };

            DBIterator {
                _db: db,
                _readopts: readopts,
                inner: iterator,
            }
        }
    }

    pub fn new_cf(db: D, cf_handle: &CFHandle, readopts: ReadOptions) -> DBIterator<D> {
        unsafe {
            let iterator = if db.is_titan() {
                crocksdb_ffi::ctitandb_create_iterator_cf(
                    db.inner,
                    readopts.get_inner(),
                    readopts.get_titan_inner(),
                    cf_handle.inner,
                )
            } else {
                crocksdb_ffi::crocksdb_create_iterator_cf(
                    db.inner,
                    readopts.get_inner(),
                    cf_handle.inner,
                )
            };
            DBIterator {
                _db: db,
                _readopts: readopts,
                inner: iterator,
            }
        }
    }
}

impl<D> DBIterator<D> {
    pub fn seek(&mut self, key: SeekKey) -> Result<bool, String> {
        unsafe {
            match key {
                SeekKey::Start => crocksdb_ffi::crocksdb_iter_seek_to_first(self.inner),
                SeekKey::End => crocksdb_ffi::crocksdb_iter_seek_to_last(self.inner),
                SeekKey::Key(key) => {
                    crocksdb_ffi::crocksdb_iter_seek(self.inner, key.as_ptr(), key.len() as size_t)
                }
            }
        }
        self.valid()
    }

    pub fn seek_for_prev(&mut self, key: SeekKey) -> Result<bool, String> {
        unsafe {
            match key {
                SeekKey::Start => crocksdb_ffi::crocksdb_iter_seek_to_first(self.inner),
                SeekKey::End => crocksdb_ffi::crocksdb_iter_seek_to_last(self.inner),
                SeekKey::Key(key) => crocksdb_ffi::crocksdb_iter_seek_for_prev(
                    self.inner,
                    key.as_ptr(),
                    key.len() as size_t,
                ),
            }
        }
        self.valid()
    }

    pub fn prev(&mut self) -> Result<bool, String> {
        unsafe {
            crocksdb_ffi::crocksdb_iter_prev(self.inner);
        }
        self.valid()
    }

    #[allow(clippy::should_implement_trait)]
    pub fn next(&mut self) -> Result<bool, String> {
        unsafe {
            crocksdb_ffi::crocksdb_iter_next(self.inner);
        }
        self.valid()
    }

    /// Get the key pointed by the iterator. Must be called when `self.valid() == Ok(true)`.
    pub fn key(&self) -> &[u8] {
        debug_assert_eq!(self.valid(), Ok(true));
        let mut key_len: size_t = 0;
        let key_len_ptr: *mut size_t = &mut key_len;
        unsafe {
            let key_ptr = crocksdb_ffi::crocksdb_iter_key(self.inner, key_len_ptr);
            slice::from_raw_parts(key_ptr, key_len as usize)
        }
    }

    /// Get the value pointed by the iterator. Must be called when `self.valid() == Ok(true)`.
    pub fn value(&self) -> &[u8] {
        debug_assert_eq!(self.valid(), Ok(true));
        let mut val_len: size_t = 0;
        let val_len_ptr: *mut size_t = &mut val_len;
        unsafe {
            let val_ptr = crocksdb_ffi::crocksdb_iter_value(self.inner, val_len_ptr);
            slice::from_raw_parts(val_ptr, val_len as usize)
        }
    }

    pub fn sequence(&self) -> Option<u64> {
        debug_assert_eq!(self.valid(), Ok(true));
        unsafe {
            let mut seqno = 0;
            if crocksdb_ffi::crocksdb_iter_seqno(self.inner, &mut seqno) {
                return Some(seqno);
            }
            None
        }
    }

    #[deprecated]
    pub fn kv(&self) -> Option<(Vec<u8>, Vec<u8>)> {
        if self.valid().unwrap() {
            Some((self.key().to_vec(), self.value().to_vec()))
        } else {
            None
        }
    }

    pub fn valid(&self) -> Result<bool, String> {
        let valid = unsafe { crocksdb_ffi::crocksdb_iter_valid(self.inner) };
        if !valid {
            self.status()?;
        }
        Ok(valid)
    }

    fn status(&self) -> Result<(), String> {
        unsafe {
            ffi_try!(crocksdb_iter_get_error(self.inner));
        }
        Ok(())
    }
}

#[deprecated]
pub type Kv = (Vec<u8>, Vec<u8>);

impl<'b, D> Iterator for &'b mut DBIterator<D> {
    #[allow(deprecated)]
    type Item = Kv;

    fn next(&mut self) -> Option<Self::Item> {
        match self.valid() {
            Ok(true) => {}
            Ok(false) => return None,
            Err(e) => panic!("invalid iterator: {}", e),
        }
        let k = self.key().to_vec();
        let v = self.value().to_vec();
        let _ = DBIterator::next(self);
        Some((k, v))
    }
}

impl<D> Drop for DBIterator<D> {
    fn drop(&mut self) {
        unsafe {
            crocksdb_ffi::crocksdb_iter_destroy(self.inner);
        }
    }
}

unsafe impl<D: Send> Send for DBIterator<D> {}

unsafe impl<D: Deref<Target = DB> + Send + Sync> Send for Snapshot<D> {}

unsafe impl<D: Deref<Target = DB> + Send + Sync> Sync for Snapshot<D> {}

impl<D: Deref<Target = DB> + Clone> Snapshot<D> {
    /// Create an iterator and clone the inner db.
    ///
    /// Please note that, the snapshot struct could be dropped before the iterator
    /// if use improperly, which seems safe though.
    pub fn iter_opt_clone(&self, mut opt: ReadOptions) -> DBIterator<D> {
        unsafe {
            opt.set_snapshot(&self.snap);
        }
        DBIterator::new(self.db.clone(), opt)
    }
}

impl<D: Deref<Target = DB>> Snapshot<D> {
    pub fn new(db: D) -> Snapshot<D> {
        unsafe {
            Snapshot {
                snap: db.unsafe_snap(),
                db: db,
            }
        }
    }

    pub fn iter(&self) -> DBIterator<&DB> {
        let readopts = ReadOptions::new();
        self.iter_opt(readopts)
    }

    pub fn iter_opt(&self, mut opt: ReadOptions) -> DBIterator<&DB> {
        unsafe {
            opt.set_snapshot(&self.snap);
        }
        DBIterator::new(&self.db, opt)
    }

    pub fn iter_cf(&self, cf_handle: &CFHandle, mut opt: ReadOptions) -> DBIterator<&DB> {
        unsafe {
            opt.set_snapshot(&self.snap);
        }
        DBIterator::new_cf(&self.db, cf_handle, opt)
    }

    pub fn get(&self, key: &[u8]) -> Result<Option<DBVector>, String> {
        let mut readopts = ReadOptions::new();
        unsafe {
            readopts.set_snapshot(&self.snap);
        }
        self.db.get_opt(key, &readopts)
    }

    pub fn get_cf(&self, cf: &CFHandle, key: &[u8]) -> Result<Option<DBVector>, String> {
        let mut readopts = ReadOptions::new();
        unsafe {
            readopts.set_snapshot(&self.snap);
        }
        self.db.get_cf_opt(cf, key, &readopts)
    }

    /// Get the snapshot's sequence number.
    pub fn get_sequence_number(&self) -> u64 {
        unsafe { crocksdb_ffi::crocksdb_get_snapshot_sequence_number(self.snap.get_inner()) }
    }
}

impl<D: Deref<Target = DB>> Drop for Snapshot<D> {
    fn drop(&mut self) {
        unsafe { self.db.release_snap(&self.snap) }
    }
}

// This is for the DB and write batches to share the same API
pub trait Writable {
    fn put(&self, key: &[u8], value: &[u8]) -> Result<(), String>;
    fn put_cf(&self, cf: &CFHandle, key: &[u8], value: &[u8]) -> Result<(), String>;
    fn merge(&self, key: &[u8], value: &[u8]) -> Result<(), String>;
    fn merge_cf(&self, cf: &CFHandle, key: &[u8], value: &[u8]) -> Result<(), String>;
    fn delete(&self, key: &[u8]) -> Result<(), String>;
    fn delete_cf(&self, cf: &CFHandle, key: &[u8]) -> Result<(), String>;
    fn single_delete(&self, key: &[u8]) -> Result<(), String>;
    fn single_delete_cf(&self, cf: &CFHandle, key: &[u8]) -> Result<(), String>;
    fn delete_range(&self, begin_key: &[u8], end_key: &[u8]) -> Result<(), String>;
    fn delete_range_cf(
        &self,
        cf: &CFHandle,
        begin_key: &[u8],
        end_key: &[u8],
    ) -> Result<(), String>;
}

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

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

pub struct KeyVersion {
    pub key: String,
    pub value: String,
    pub seq: u64,
    pub value_type: c_int,
}

impl DB {
    pub fn open_default(path: &str) -> Result<DB, String> {
        let mut opts = DBOptions::new();
        opts.create_if_missing(true);
        DB::open(opts, path)
    }

    pub fn open(opts: DBOptions, path: &str) -> Result<DB, String> {
        let cfds: Vec<&str> = vec![];
        DB::open_cf(opts, path, cfds)
    }

    pub fn open_with_ttl(opts: DBOptions, path: &str, ttls: &[i32]) -> Result<DB, String> {
        let cfds: Vec<&str> = vec![];
        if ttls.len() == 0 {
            return Err("ttls is empty in with_ttl function".to_owned());
        }
        DB::open_cf_with_ttl(opts, path, cfds, ttls)
    }

    pub fn open_cf<'a, T>(opts: DBOptions, path: &str, cfds: Vec<T>) -> Result<DB, String>
    where
        T: Into<ColumnFamilyDescriptor<'a>>,
    {
        DB::open_cf_internal(opts, path, cfds, &[], None)
    }

    pub fn open_cf_with_ttl<'a, T>(
        opts: DBOptions,
        path: &str,
        cfds: Vec<T>,
        ttls: &[i32],
    ) -> Result<DB, String>
    where
        T: Into<ColumnFamilyDescriptor<'a>>,
    {
        if ttls.len() == 0 {
            return Err("ttls is empty in with_ttl function".to_owned());
        }
        DB::open_cf_internal(opts, path, cfds, ttls, None)
    }

    pub fn open_for_read_only(
        opts: DBOptions,
        path: &str,
        error_if_log_file_exist: bool,
    ) -> Result<DB, String> {
        let cfds: Vec<&str> = vec![];
        DB::open_cf_for_read_only(opts, path, cfds, error_if_log_file_exist)
    }

    pub fn open_cf_for_read_only<'a, T>(
        opts: DBOptions,
        path: &str,
        cfds: Vec<T>,
        error_if_log_file_exist: bool,
    ) -> Result<DB, String>
    where
        T: Into<ColumnFamilyDescriptor<'a>>,
    {
        DB::open_cf_internal(opts, path, cfds, &[], Some(error_if_log_file_exist))
    }

    fn open_cf_internal<'a, T>(
        mut opts: DBOptions,
        path: &str,
        cfds: Vec<T>,
        ttls: &[i32],
        // if none, open for read write mode.
        // otherwise, open for read only.
        error_if_log_file_exist: Option<bool>,
    ) -> Result<DB, String>
    where
        T: Into<ColumnFamilyDescriptor<'a>>,
    {
        const ERR_CONVERT_PATH: &str = "Failed to convert path to CString when opening rocksdb";
        const ERR_NULL_DB_ONINIT: &str = "Could not initialize database";
        const ERR_NULL_CF_HANDLE: &str = "Received null column family handle from DB";

        let cpath = CString::new(path.as_bytes()).map_err(|_| ERR_CONVERT_PATH.to_owned())?;
        fs::create_dir_all(&Path::new(path)).map_err(|e| {
            format!(
                "Failed to create rocksdb directory: \
                 src/rocksdb.rs:                              \
                 {:?}",
                e
            )
        })?;

        let mut descs = cfds.into_iter().map(|t| t.into()).collect();
        let mut ttls_vec = ttls.to_vec();
        ensure_default_cf_exists(&mut descs, &mut ttls_vec, !opts.titan_inner.is_null());

        let (names, options) = split_descriptors(descs, !opts.titan_inner.is_null());
        let cstrings = build_cstring_list(&names);

        let cf_names: Vec<*const _> = cstrings.iter().map(|cs| cs.as_ptr()).collect();
        let cf_handles: Vec<_> = vec![ptr::null_mut(); cf_names.len()];
        let cf_options: Vec<_> = options
            .iter()
            .map(|x| x.inner as *const crocksdb_ffi::Options)
            .collect();
        let titan_cf_options: Vec<_> = options
            .iter()
            .map(|x| {
                if !x.titan_inner.is_null() {
                    unsafe {
                        crocksdb_ffi::ctitandb_options_set_rocksdb_options(x.titan_inner, x.inner);
                    }
                }
                x.titan_inner as *const crocksdb_ffi::DBTitanDBOptions
            })
            .collect();

        let readonly = error_if_log_file_exist.is_some();

        let with_ttl = if ttls_vec.len() > 0 {
            if ttls_vec.len() == cf_names.len() {
                true
            } else {
                return Err("the length of ttls not equal to length of cfs".to_owned());
            }
        } else {
            false
        };

        let db = {
            let db_options = opts.inner;
            let db_path = cpath.as_ptr();
            let db_cfs_count = cf_names.len() as c_int;
            let db_cf_ptrs = cf_names.as_ptr();
            let db_cf_opts = cf_options.as_ptr();
            let titan_cf_opts = titan_cf_options.as_ptr();
            let db_cf_handles = cf_handles.as_ptr();

            let titan_options = opts.titan_inner;
            if !titan_options.is_null() {
                unsafe {
                    crocksdb_ffi::ctitandb_options_set_rocksdb_options(titan_options, db_options);
                }
                if error_if_log_file_exist.is_some() {
                    return Err("TitanDB doesn't support read only mode.".to_owned());
                } else if with_ttl {
                    return Err("TitanDB doesn't support ttl.".to_owned());
                }
            }

            if !with_ttl {
                if let Some(flag) = error_if_log_file_exist {
                    unsafe {
                        ffi_try!(crocksdb_open_for_read_only_column_families(
                            db_options,
                            db_path,
                            db_cfs_count,
                            db_cf_ptrs,
                            db_cf_opts,
                            db_cf_handles,
                            flag
                        ))
                    }
                } else if titan_options.is_null() {
                    unsafe {
                        ffi_try!(crocksdb_open_column_families(
                            db_options,
                            db_path,
                            db_cfs_count,
                            db_cf_ptrs,
                            db_cf_opts,
                            db_cf_handles
                        ))
                    }
                } else {
                    unsafe {
                        ffi_try!(ctitandb_open_column_families(
                            db_path,
                            titan_options,
                            db_cfs_count,
                            db_cf_ptrs,
                            titan_cf_opts,
                            db_cf_handles
                        ))
                    }
                }
            } else {
                let ttl_array = ttls_vec.as_ptr() as *const c_int;

                unsafe {
                    ffi_try!(crocksdb_open_column_families_with_ttl(
                        db_options,
                        db_path,
                        db_cfs_count,
                        db_cf_ptrs,
                        db_cf_opts,
                        ttl_array,
                        readonly,
                        db_cf_handles
                    ))
                }
            }
        };

        if cf_handles.iter().any(|h| h.is_null()) {
            return Err(ERR_NULL_CF_HANDLE.to_owned());
        }
        if db.is_null() {
            return Err(ERR_NULL_DB_ONINIT.to_owned());
        }

        unsafe {
            // the options provided when opening db may sanitized, so get the latest options.
            crocksdb_ffi::crocksdb_options_destroy(opts.inner);
            opts.inner = crocksdb_ffi::crocksdb_get_db_options(db);
            if !opts.titan_inner.is_null() {
                crocksdb_ffi::ctitandb_options_destroy(opts.titan_inner);
                opts.titan_inner = crocksdb_ffi::ctitandb_get_titan_db_options(db);
            }
        }
        let mut cfs = Vec::with_capacity(names.len());
        let mut cfs_by_name = BTreeMap::new();
        for (name, h) in names.into_iter().zip(cf_handles) {
            let handle = CFHandle { inner: h };
            let idx = handle.id() as usize;
            while cfs.len() <= idx {
                cfs.push(None);
            }
            cfs[idx] = Some((name.to_owned(), handle));
            cfs_by_name.insert(name.to_owned(), idx);
        }
        Ok(DB {
            cfs,
            opts,
            readonly,
            cfs_by_name,
            inner: db,
            path: path.to_owned(),
            _cf_opts: options,
        })
    }

    pub fn destroy(opts: &DBOptions, path: &str) -> Result<(), String> {
        let cpath = CString::new(path.as_bytes()).unwrap();
        unsafe {
            ffi_try!(crocksdb_destroy_db(opts.inner, cpath.as_ptr()));
        }
        Ok(())
    }

    pub fn repair(opts: DBOptions, path: &str) -> Result<(), String> {
        let cpath = CString::new(path.as_bytes()).unwrap();
        unsafe {
            ffi_try!(crocksdb_repair_db(opts.inner, cpath.as_ptr()));
        }
        Ok(())
    }

    pub fn list_column_families(opts: &DBOptions, path: &str) -> Result<Vec<String>, String> {
        let cpath = match CString::new(path.as_bytes()) {
            Ok(c) => c,
            Err(_) => {
                return Err("Failed to convert path to CString when list \
                            column families"
                    .to_owned());
            }
        };

        let mut cfs: Vec<String> = vec![];
        unsafe {
            let mut lencf: size_t = 0;
            let list = ffi_try!(crocksdb_list_column_families(
                opts.inner,
                cpath.as_ptr(),
                &mut lencf
            ));
            let list_cfs = slice::from_raw_parts(list, lencf);
            for &cf_name in list_cfs {
                let cf = match CStr::from_ptr(cf_name).to_owned().into_string() {
                    Ok(s) => s,
                    Err(e) => return Err(format!("invalid utf8 bytes: {:?}", e)),
                };
                cfs.push(cf);
            }
            crocksdb_ffi::crocksdb_list_column_families_destroy(list, lencf);
        }

        Ok(cfs)
    }

    pub fn env(&self) -> Option<Arc<Env>> {
        self.opts.env()
    }

    pub fn pause_bg_work(&self) {
        unsafe {
            crocksdb_ffi::crocksdb_pause_bg_work(self.inner);
        }
    }

    pub fn continue_bg_work(&self) {
        unsafe {
            crocksdb_ffi::crocksdb_continue_bg_work(self.inner);
        }
    }

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

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

    pub fn multi_batch_write(
        &self,
        batches: &[WriteBatch],
        writeopts: &WriteOptions,
    ) -> Result<(), String> {
        unsafe {
            let b: Vec<*mut DBWriteBatch> = batches.iter().map(|w| w.inner).collect();
            if !b.is_empty() {
                ffi_try!(crocksdb_write_multi_batch(
                    self.inner,
                    writeopts.inner,
                    b.as_ptr(),
                    b.len()
                ));
            }
        }
        Ok(())
    }

    pub fn write(&self, batch: &WriteBatch) -> Result<(), String> {
        self.write_opt(batch, &WriteOptions::new())
    }

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

    pub fn get_opt(&self, key: &[u8], readopts: &ReadOptions) -> Result<Option<DBVector>, String> {
        unsafe {
            let val = ffi_try!(crocksdb_get_pinned(
                self.inner,
                readopts.get_inner(),
                key.as_ptr(),
                key.len() as size_t
            ));
            if val.is_null() {
                Ok(None)
            } else {
                Ok(Some(DBVector::from_pinned_slice(val)))
            }
        }
    }

    pub fn get(&self, key: &[u8]) -> Result<Option<DBVector>, String> {
        self.get_opt(key, &ReadOptions::new())
    }

    pub fn get_cf_opt(
        &self,
        cf: &CFHandle,
        key: &[u8],
        readopts: &ReadOptions,
    ) -> Result<Option<DBVector>, String> {
        unsafe {
            let val = ffi_try!(crocksdb_get_pinned_cf(
                self.inner,
                readopts.get_inner(),
                cf.inner,
                key.as_ptr(),
                key.len() as size_t
            ));
            if val.is_null() {
                Ok(None)
            } else {
                Ok(Some(DBVector::from_pinned_slice(val)))
            }
        }
    }

    pub fn get_cf(&self, cf: &CFHandle, key: &[u8]) -> Result<Option<DBVector>, String> {
        self.get_cf_opt(cf, key, &ReadOptions::new())
    }

    pub fn create_cf<'a, T>(&mut self, cfd: T) -> Result<&CFHandle, String>
    where
        T: Into<ColumnFamilyDescriptor<'a>>,
    {
        let mut cfd = cfd.into();
        let cname = match CString::new(cfd.name.as_bytes()) {
            Ok(c) => c,
            Err(_) => {
                return Err("Failed to convert path to CString when opening rocksdb".to_owned());
            }
        };
        let cname_ptr = cname.as_ptr();
        unsafe {
            let cf_handler = if !self.is_titan() {
                ffi_try!(crocksdb_create_column_family(
                    self.inner,
                    cfd.options.inner,
                    cname_ptr
                ))
            } else {
                if cfd.options.titan_inner.is_null() {
                    cfd.options.set_titandb_options(&TitanDBOptions::new());
                }
                crocksdb_ffi::ctitandb_options_set_rocksdb_options(
                    cfd.options.titan_inner,
                    cfd.options.inner,
                );
                ffi_try!(ctitandb_create_column_family(
                    self.inner,
                    cfd.options.titan_inner,
                    cname_ptr
                ))
            };
            let handle = CFHandle { inner: cf_handler };
            self._cf_opts.push(cfd.options);
            let idx = handle.id() as usize;
            while idx >= self.cfs.len() {
                self.cfs.push(None);
            }
            self.cfs[idx] = Some((cfd.name.to_owned(), handle));
            self.cfs_by_name.insert(cfd.name.to_owned(), idx);
            Ok(&self.cfs[idx].as_ref().unwrap().1)
        }
    }

    pub fn drop_cf(&mut self, name: &str) -> Result<(), String> {
        let id = self.cfs_by_name.remove(name);
        let cf = match id {
            None => return Err(format!("Invalid column family: {}", name)),
            Some(idx) => match self.cfs[idx].take() {
                None => return Err(format!("Invalid column family: {}", name)),
                Some((_, handle)) => handle,
            },
        };

        unsafe {
            ffi_try!(crocksdb_drop_column_family(self.inner, cf.inner));
        }

        Ok(())
    }

    pub fn cf_handle(&self, name: &str) -> Option<&CFHandle> {
        let idx = match self.cfs_by_name.get(name) {
            None => return None,
            Some(idx) => *idx,
        };
        self.cfs[idx].as_ref().map(|h| &h.1)
    }

    /// get all column family names, including 'default'.
    pub fn cf_names(&self) -> Vec<&str> {
        self.cfs
            .iter()
            .filter(|handle| handle.is_some())
            .map(|handle| handle.as_ref().unwrap().0.as_str())
            .collect()
    }

    /// get all column family names, including 'default'.
    pub fn cf_handle_by_id(&self, id: usize) -> Option<&CFHandle> {
        if id >= self.cfs.len() {
            return None;
        }
        self.cfs[id].as_ref().map(|h| &h.1)
    }

    pub fn iter(&self) -> DBIterator<&DB> {
        let opts = ReadOptions::new();
        self.iter_opt(opts)
    }

    pub fn iter_opt(&self, opt: ReadOptions) -> DBIterator<&DB> {
        DBIterator::new(&self, opt)
    }

    pub fn iter_cf(&self, cf_handle: &CFHandle) -> DBIterator<&DB> {
        let opts = ReadOptions::new();
        DBIterator::new_cf(self, cf_handle, opts)
    }

    pub fn iter_cf_opt(&self, cf_handle: &CFHandle, opts: ReadOptions) -> DBIterator<&DB> {
        DBIterator::new_cf(self, cf_handle, opts)
    }

    pub fn snapshot(&self) -> Snapshot<&DB> {
        Snapshot::new(self)
    }

    pub unsafe fn unsafe_snap(&self) -> UnsafeSnap {
        UnsafeSnap::new(self.inner)
    }

    pub unsafe fn release_snap(&self, snap: &UnsafeSnap) {
        crocksdb_ffi::crocksdb_release_snapshot(self.inner, snap.get_inner())
    }

    pub fn put_opt(
        &self,
        key: &[u8],
        value: &[u8],
        writeopts: &WriteOptions,
    ) -> Result<(), String> {
        unsafe {
            ffi_try!(crocksdb_put(
                self.inner,
                writeopts.inner,
                key.as_ptr(),
                key.len() as size_t,
                value.as_ptr(),
                value.len() as size_t
            ));
            Ok(())
        }
    }

    pub fn put_cf_opt(
        &self,
        cf: &CFHandle,
        key: &[u8],
        value: &[u8],
        writeopts: &WriteOptions,
    ) -> Result<(), String> {
        unsafe {
            ffi_try!(crocksdb_put_cf(
                self.inner,
                writeopts.inner,
                cf.inner,
                key.as_ptr(),
                key.len() as size_t,
                value.as_ptr(),
                value.len() as size_t
            ));
            Ok(())
        }
    }
    pub fn merge_opt(
        &self,
        key: &[u8],
        value: &[u8],
        writeopts: &WriteOptions,
    ) -> Result<(), String> {
        unsafe {
            ffi_try!(crocksdb_merge(
                self.inner,
                writeopts.inner,
                key.as_ptr(),
                key.len() as size_t,
                value.as_ptr(),
                value.len() as size_t
            ));
            Ok(())
        }
    }
    fn merge_cf_opt(
        &self,
        cf: &CFHandle,
        key: &[u8],
        value: &[u8],
        writeopts: &WriteOptions,
    ) -> Result<(), String> {
        unsafe {
            ffi_try!(crocksdb_merge_cf(
                self.inner,
                writeopts.inner,
                cf.inner,
                key.as_ptr(),
                key.len() as size_t,
                value.as_ptr(),
                value.len() as size_t
            ));
            Ok(())
        }
    }
    fn delete_opt(&self, key: &[u8], writeopts: &WriteOptions) -> Result<(), String> {
        unsafe {
            ffi_try!(crocksdb_delete(
                self.inner,
                writeopts.inner,
                key.as_ptr(),
                key.len() as size_t
            ));
            Ok(())
        }
    }

    fn delete_cf_opt(
        &self,
        cf: &CFHandle,
        key: &[u8],
        writeopts: &WriteOptions,
    ) -> Result<(), String> {
        unsafe {
            ffi_try!(crocksdb_delete_cf(
                self.inner,
                writeopts.inner,
                cf.inner,
                key.as_ptr(),
                key.len() as size_t
            ));
            Ok(())
        }
    }

    fn single_delete_opt(&self, key: &[u8], writeopts: &WriteOptions) -> Result<(), String> {
        unsafe {
            ffi_try!(crocksdb_single_delete(
                self.inner,
                writeopts.inner,
                key.as_ptr(),
                key.len() as size_t
            ));
            Ok(())
        }
    }

    fn single_delete_cf_opt(
        &self,
        cf: &CFHandle,
        key: &[u8],
        writeopts: &WriteOptions,
    ) -> Result<(), String> {
        unsafe {
            ffi_try!(crocksdb_single_delete_cf(
                self.inner,
                writeopts.inner,
                cf.inner,
                key.as_ptr(),
                key.len() as size_t
            ));
            Ok(())
        }
    }

    fn delete_range_cf_opt(
        &self,
        cf: &CFHandle,
        begin_key: &[u8],
        end_key: &[u8],
        writeopts: &WriteOptions,
    ) -> Result<(), String> {
        unsafe {
            ffi_try!(crocksdb_delete_range_cf(
                self.inner,
                writeopts.inner,
                cf.inner,
                begin_key.as_ptr(),
                begin_key.len() as size_t,
                end_key.as_ptr(),
                end_key.len() as size_t
            ));
            Ok(())
        }
    }

    /// Flush all memtable data.
    /// If wait, the flush will wait until the flush is done.
    pub fn flush(&self, wait: bool) -> Result<(), String> {
        unsafe {
            let mut opts = FlushOptions::new();
            opts.set_wait(wait);
            ffi_try!(crocksdb_flush(self.inner, opts.inner));
            Ok(())
        }
    }

    /// Flush all memtable data for specified cf.
    /// If wait, the flush will wait until the flush is done.
    pub fn flush_cf(&self, cf: &CFHandle, wait: bool) -> Result<(), String> {
        unsafe {
            let mut opts = FlushOptions::new();
            opts.set_wait(wait);
            ffi_try!(crocksdb_flush_cf(self.inner, cf.inner, opts.inner));
            Ok(())
        }
    }

    /// Flushes multiple column families.
    /// If atomic flush is not enabled, flush_cfs is equivalent to
    /// calling flush_cf multiple times.
    /// If atomic flush is enabled, flush_cfs will flush all column families
    /// specified in `cfs` up to the latest sequence number at the time
    /// when flush is requested.
    pub fn flush_cfs(&self, cfs: &[&CFHandle], wait: bool) -> Result<(), String> {
        unsafe {
            let cfs: Vec<*mut _> = cfs.iter().map(|cf| cf.inner).collect();
            let mut opts = FlushOptions::new();
            opts.set_wait(wait);
            ffi_try!(crocksdb_flush_cfs(
                self.inner,
                cfs.as_ptr(),
                cfs.len(),
                opts.inner
            ));
            Ok(())
        }
    }

    /// Flush the WAL memory buffer to the file. If sync is true, it calls SyncWAL
    /// afterwards.
    pub fn flush_wal(&self, sync: bool) -> Result<(), String> {
        unsafe {
            ffi_try!(crocksdb_flush_wal(self.inner, sync));
            Ok(())
        }
    }

    /// Sync the wal. Note that Write() followed by SyncWAL() is not exactly the
    /// same as Write() with sync=true: in the latter case the changes won't be
    /// visible until the sync is done.
    /// Currently only works if allow_mmap_writes = false in Options.
    pub fn sync_wal(&self) -> Result<(), String> {
        unsafe {
            ffi_try!(crocksdb_sync_wal(self.inner));
            Ok(())
        }
    }

    /// Get the sequence number of the most recent transaction.
    pub fn get_latest_sequence_number(&self) -> u64 {
        unsafe { crocksdb_ffi::crocksdb_get_latest_sequence_number(self.inner) }
    }

    /// Return the approximate file system space used by keys in each ranges.
    ///
    /// Note that the returned sizes measure file system space usage, so
    /// if the user data compresses by a factor of ten, the returned
    /// sizes will be one-tenth the size of the corresponding user data size.
    ///
    /// Due to lack of abi, only data flushed to disk is taken into account.
    pub fn get_approximate_sizes(&self, ranges: &[Range]) -> Vec<u64> {
        self.get_approximate_sizes_cfopt(None, ranges)
    }

    pub fn get_approximate_sizes_cf(&self, cf: &CFHandle, ranges: &[Range]) -> Vec<u64> {
        self.get_approximate_sizes_cfopt(Some(cf), ranges)
    }

    fn get_approximate_sizes_cfopt(&self, cf: Option<&CFHandle>, ranges: &[Range]) -> Vec<u64> {
        let start_keys: Vec<*const u8> = ranges.iter().map(|x| x.start_key.as_ptr()).collect();
        let start_key_lens: Vec<_> = ranges.iter().map(|x| x.start_key.len()).collect();
        let end_keys: Vec<*const u8> = ranges.iter().map(|x| x.end_key.as_ptr()).collect();
        let end_key_lens: Vec<_> = ranges.iter().map(|x| x.end_key.len()).collect();
        let mut sizes: Vec<u64> = vec![0; ranges.len()];
        let (n, start_key_ptr, start_key_len_ptr, end_key_ptr, end_key_len_ptr, size_ptr) = (
            ranges.len() as i32,
            start_keys.as_ptr(),
            start_key_lens.as_ptr(),
            end_keys.as_ptr(),
            end_key_lens.as_ptr(),
            sizes.as_mut_ptr(),
        );
        match cf {
            None => unsafe {
                crocksdb_ffi::crocksdb_approximate_sizes(
                    self.inner,
                    n,
                    start_key_ptr,
                    start_key_len_ptr,
                    end_key_ptr,
                    end_key_len_ptr,
                    size_ptr,
                )
            },
            Some(cf) => unsafe {
                crocksdb_ffi::crocksdb_approximate_sizes_cf(
                    self.inner,
                    cf.inner,
                    n,
                    start_key_ptr,
                    start_key_len_ptr,
                    end_key_ptr,
                    end_key_len_ptr,
                    size_ptr,
                )
            },
        }
        sizes
    }

    // Return the approximate number of records and size in the range of memtables.
    pub fn get_approximate_memtable_stats(&self, range: &Range) -> (u64, u64) {
        let (mut count, mut size) = (0, 0);
        unsafe {
            crocksdb_ffi::crocksdb_approximate_memtable_stats(
                self.inner,
                range.start_key.as_ptr(),
                range.start_key.len(),
                range.end_key.as_ptr(),
                range.end_key.len(),
                &mut count,
                &mut size,
            );
        }
        (count, size)
    }

    // Return the approximate number of records and size in the range of memtables of the cf.
    pub fn get_approximate_memtable_stats_cf(&self, cf: &CFHandle, range: &Range) -> (u64, u64) {
        let (mut count, mut size) = (0, 0);
        unsafe {
            crocksdb_ffi::crocksdb_approximate_memtable_stats_cf(
                self.inner,
                cf.inner,
                range.start_key.as_ptr(),
                range.start_key.len(),
                range.end_key.as_ptr(),
                range.end_key.len(),
                &mut count,
                &mut size,
            );
        }
        (count, size)
    }

    pub fn compact_range(&self, start_key: Option<&[u8]>, end_key: Option<&[u8]>) {
        unsafe {
            let (start, s_len) = start_key.map_or((ptr::null(), 0), |k| (k.as_ptr(), k.len()));
            let (end, e_len) = end_key.map_or((ptr::null(), 0), |k| (k.as_ptr(), k.len()));
            crocksdb_ffi::crocksdb_compact_range(self.inner, start, s_len, end, e_len);
        }
    }

    pub fn compact_range_cf(
        &self,
        cf: &CFHandle,
        start_key: Option<&[u8]>,
        end_key: Option<&[u8]>,
    ) {
        unsafe {
            let (start, s_len) = start_key.map_or((ptr::null(), 0), |k| (k.as_ptr(), k.len()));
            let (end, e_len) = end_key.map_or((ptr::null(), 0), |k| (k.as_ptr(), k.len()));
            crocksdb_ffi::crocksdb_compact_range_cf(self.inner, cf.inner, start, s_len, end, e_len);
        }
    }

    pub fn compact_range_cf_opt(
        &self,
        cf: &CFHandle,
        compact_options: &CompactOptions,
        start_key: Option<&[u8]>,
        end_key: Option<&[u8]>,
    ) {
        unsafe {
            let (start, s_len) = start_key.map_or((ptr::null(), 0), |k| (k.as_ptr(), k.len()));
            let (end, e_len) = end_key.map_or((ptr::null(), 0), |k| (k.as_ptr(), k.len()));
            crocksdb_ffi::crocksdb_compact_range_cf_opt(
                self.inner,
                cf.inner,
                compact_options.inner,
                start,
                s_len,
                end,
                e_len,
            );
        }
    }

    pub fn delete_files_in_range(
        &self,
        start_key: &[u8],
        end_key: &[u8],
        include_end: bool,
    ) -> Result<(), String> {
        unsafe {
            if self.is_titan() {
                ffi_try!(ctitandb_delete_files_in_range(
                    self.inner,
                    start_key.as_ptr(),
                    start_key.len() as size_t,
                    end_key.as_ptr(),
                    end_key.len() as size_t,
                    include_end
                ));
            } else {
                ffi_try!(crocksdb_delete_files_in_range(
                    self.inner,
                    start_key.as_ptr(),
                    start_key.len() as size_t,
                    end_key.as_ptr(),
                    end_key.len() as size_t,
                    include_end
                ));
            }
            Ok(())
        }
    }

    pub fn delete_files_in_range_cf(
        &self,
        cf: &CFHandle,
        start_key: &[u8],
        end_key: &[u8],
        include_end: bool,
    ) -> Result<(), String> {
        unsafe {
            if self.is_titan() {
                ffi_try!(ctitandb_delete_files_in_range_cf(
                    self.inner,
                    cf.inner,
                    start_key.as_ptr(),
                    start_key.len() as size_t,
                    end_key.as_ptr(),
                    end_key.len() as size_t,
                    include_end
                ));
            } else {
                ffi_try!(crocksdb_delete_files_in_range_cf(
                    self.inner,
                    cf.inner,
                    start_key.as_ptr(),
                    start_key.len() as size_t,
                    end_key.as_ptr(),
                    end_key.len() as size_t,
                    include_end
                ));
            }
            Ok(())
        }
    }

    pub fn delete_files_in_ranges_cf(
        &self,
        cf: &CFHandle,
        ranges: &[Range],
        include_end: bool,
    ) -> Result<(), String> {
        let start_keys: Vec<*const u8> = ranges.iter().map(|x| x.start_key.as_ptr()).collect();
        let start_keys_lens: Vec<_> = ranges.iter().map(|x| x.start_key.len()).collect();
        let limit_keys: Vec<*const u8> = ranges.iter().map(|x| x.end_key.as_ptr()).collect();
        let limit_keys_lens: Vec<_> = ranges.iter().map(|x| x.end_key.len()).collect();
        unsafe {
            if self.is_titan() {
                ffi_try!(ctitandb_delete_files_in_ranges_cf(
                    self.inner,
                    cf.inner,
                    start_keys.as_ptr(),
                    start_keys_lens.as_ptr(),
                    limit_keys.as_ptr(),
                    limit_keys_lens.as_ptr(),
                    ranges.len(),
                    include_end
                ));
            } else {
                ffi_try!(crocksdb_delete_files_in_ranges_cf(
                    self.inner,
                    cf.inner,
                    start_keys.as_ptr(),
                    start_keys_lens.as_ptr(),
                    limit_keys.as_ptr(),
                    limit_keys_lens.as_ptr(),
                    ranges.len(),
                    include_end
                ));
            }
        }
        Ok(())
    }

    pub fn delete_blob_files_in_range(
        &self,
        start_key: &[u8],
        end_key: &[u8],
        include_end: bool,
    ) -> Result<(), String> {
        unsafe {
            if self.is_titan() {
                ffi_try!(ctitandb_delete_blob_files_in_range(
                    self.inner,
                    start_key.as_ptr(),
                    start_key.len() as size_t,
                    end_key.as_ptr(),
                    end_key.len() as size_t,
                    include_end
                ));
            }
            Ok(())
        }
    }

    pub fn delete_blob_files_in_range_cf(
        &self,
        cf: &CFHandle,
        start_key: &[u8],
        end_key: &[u8],
        include_end: bool,
    ) -> Result<(), String> {
        unsafe {
            if self.is_titan() {
                ffi_try!(ctitandb_delete_blob_files_in_range_cf(
                    self.inner,
                    cf.inner,
                    start_key.as_ptr(),
                    start_key.len() as size_t,
                    end_key.as_ptr(),
                    end_key.len() as size_t,
                    include_end
                ));
            }
            Ok(())
        }
    }

    pub fn delete_blob_files_in_ranges_cf(
        &self,
        cf: &CFHandle,
        ranges: &[Range],
        include_end: bool,
    ) -> Result<(), String> {
        unsafe {
            if self.is_titan() {
                let start_keys: Vec<*const u8> =
                    ranges.iter().map(|x| x.start_key.as_ptr()).collect();
                let start_keys_lens: Vec<_> = ranges.iter().map(|x| x.start_key.len()).collect();
                let limit_keys: Vec<*const u8> =
                    ranges.iter().map(|x| x.end_key.as_ptr()).collect();
                let limit_keys_lens: Vec<_> = ranges.iter().map(|x| x.end_key.len()).collect();
                ffi_try!(ctitandb_delete_blob_files_in_ranges_cf(
                    self.inner,
                    cf.inner,
                    start_keys.as_ptr(),
                    start_keys_lens.as_ptr(),
                    limit_keys.as_ptr(),
                    limit_keys_lens.as_ptr(),
                    ranges.len(),
                    include_end
                ));
            }
        }
        Ok(())
    }

    pub fn get_property_value(&self, name: &str) -> Option<String> {
        self.get_property_value_cf_opt(None, name)
    }

    pub fn get_property_value_cf(&self, cf: &CFHandle, name: &str) -> Option<String> {
        self.get_property_value_cf_opt(Some(cf), name)
    }

    /// Return the int property in rocksdb.
    /// Return None if the property not exists or not int type.
    pub fn get_property_int(&self, name: &str) -> Option<u64> {
        self.get_property_int_cf_opt(None, name)
    }

    pub fn get_property_int_cf(&self, cf: &CFHandle, name: &str) -> Option<u64> {
        self.get_property_int_cf_opt(Some(cf), name)
    }

    fn get_property_value_cf_opt(&self, cf: Option<&CFHandle>, name: &str) -> Option<String> {
        unsafe {
            let prop_name = CString::new(name).unwrap();

            let value = match cf {
                None => crocksdb_ffi::crocksdb_property_value(self.inner, prop_name.as_ptr()),
                Some(cf) => crocksdb_ffi::crocksdb_property_value_cf(
                    self.inner,
                    cf.inner,
                    prop_name.as_ptr(),
                ),
            };

            if value.is_null() {
                return None;
            }

            // Must valid UTF-8 format.
            let s = CStr::from_ptr(value).to_str().unwrap().to_owned();
            libc::free(value as *mut c_void);
            Some(s)
        }
    }

    fn get_property_int_cf_opt(&self, cf: Option<&CFHandle>, name: &str) -> Option<u64> {
        // Rocksdb guarantees that the return property int
        // value is u64 if exists.
        if let Some(value) = self.get_property_value_cf_opt(cf, name) {
            if let Ok(num) = value.as_str().parse::<u64>() {
                return Some(num);
            }
        }

        None
    }

    pub fn get_statistics(&self) -> Option<String> {
        self.opts.get_statistics()
    }

    pub fn reset_statistics(&self) {
        self.opts.reset_statistics();
    }

    pub fn get_statistics_ticker_count(&self, ticker_type: DBStatisticsTickerType) -> u64 {
        self.opts.get_statistics_ticker_count(ticker_type)
    }

    pub fn get_and_reset_statistics_ticker_count(
        &self,
        ticker_type: DBStatisticsTickerType,
    ) -> u64 {
        self.opts.get_and_reset_statistics_ticker_count(ticker_type)
    }

    pub fn get_statistics_histogram_string(
        &self,
        hist_type: DBStatisticsHistogramType,
    ) -> Option<String> {
        self.opts.get_statistics_histogram_string(hist_type)
    }

    pub fn get_statistics_histogram(
        &self,
        hist_type: DBStatisticsHistogramType,
    ) -> Option<HistogramData> {
        self.opts.get_statistics_histogram(hist_type)
    }

    pub fn get_db_options(&self) -> DBOptions {
        unsafe {
            let inner = crocksdb_ffi::crocksdb_get_db_options(self.inner);
            DBOptions::from_raw(inner)
        }
    }

    pub fn get_map_property_cf(&self, cf: &CFHandle, name: &str) -> Option<MapProperty> {
        unsafe {
            let info = MapProperty::new();
            let cname = CString::new(name.as_bytes()).unwrap();
            if !crocksdb_ffi::crocksdb_get_map_property_cf(
                self.inner,
                cf.inner,
                cname.as_ptr(),
                info.inner,
            ) {
                return None;
            }
            Some(info)
        }
    }

    pub fn set_db_options(&self, options: &[(&str, &str)]) -> Result<(), String> {
        unsafe {
            let name_strs: Vec<_> = options
                .iter()
                .map(|&(n, _)| CString::new(n.as_bytes()).unwrap())
                .collect();
            let name_ptrs: Vec<_> = name_strs.iter().map(|s| s.as_ptr()).collect();
            let value_strs: Vec<_> = options
                .iter()
                .map(|&(_, v)| CString::new(v.as_bytes()).unwrap())
                .collect();
            let value_ptrs: Vec<_> = value_strs.iter().map(|s| s.as_ptr()).collect();
            ffi_try!(crocksdb_set_db_options(
                self.inner,
                name_ptrs.as_ptr() as *const *const c_char,
                value_ptrs.as_ptr() as *const *const c_char,
                options.len() as size_t
            ));
            Ok(())
        }
    }

    pub fn get_options(&self) -> ColumnFamilyOptions {
        let cf = self.cf_handle("default").unwrap();
        unsafe {
            let inner = crocksdb_ffi::crocksdb_get_options_cf(self.inner, cf.inner);
            let titan_inner = if self.is_titan() {
                crocksdb_ffi::ctitandb_get_titan_options_cf(self.inner, cf.inner)
            } else {
                ptr::null_mut::<DBTitanDBOptions>()
            };
            ColumnFamilyOptions::from_raw(inner, titan_inner)
        }
    }

    pub fn get_options_cf(&self, cf: &CFHandle) -> ColumnFamilyOptions {
        unsafe {
            let inner = crocksdb_ffi::crocksdb_get_options_cf(self.inner, cf.inner);
            let titan_inner = if self.is_titan() {
                crocksdb_ffi::ctitandb_get_titan_options_cf(self.inner, cf.inner)
            } else {
                ptr::null_mut::<DBTitanDBOptions>()
            };
            ColumnFamilyOptions::from_raw(inner, titan_inner)
        }
    }

    pub fn set_options_cf(&self, cf: &CFHandle, options: &[(&str, &str)]) -> Result<(), String> {
        unsafe {
            let name_strs: Vec<_> = options
                .iter()
                .map(|&(n, _)| CString::new(n.as_bytes()).unwrap())
                .collect();
            let name_ptrs: Vec<_> = name_strs.iter().map(|s| s.as_ptr()).collect();
            let value_strs: Vec<_> = options
                .iter()
                .map(|&(_, v)| CString::new(v.as_bytes()).unwrap())
                .collect();
            let value_ptrs: Vec<_> = value_strs.iter().map(|s| s.as_ptr()).collect();
            ffi_try!(crocksdb_set_options_cf(
                self.inner,
                cf.inner,
                name_ptrs.as_ptr() as *const *const c_char,
                value_ptrs.as_ptr() as *const *const c_char,
                options.len() as size_t
            ));
            Ok(())
        }
    }

    pub fn ingest_external_file(
        &self,
        opt: &IngestExternalFileOptions,
        files: &[&str],
    ) -> Result<(), String> {
        let c_files = build_cstring_list(files);
        let c_files_ptrs: Vec<*const _> = c_files.iter().map(|s| s.as_ptr()).collect();
        unsafe {
            ffi_try!(crocksdb_ingest_external_file(
                self.inner,
                c_files_ptrs.as_ptr(),
                c_files.len(),
                opt.inner
            ));
        }
        Ok(())
    }

    pub fn ingest_external_file_cf(
        &self,
        cf: &CFHandle,
        opt: &IngestExternalFileOptions,
        files: &[&str],
    ) -> Result<(), String> {
        let c_files = build_cstring_list(files);
        let c_files_ptrs: Vec<*const _> = c_files.iter().map(|s| s.as_ptr()).collect();
        unsafe {
            ffi_try!(crocksdb_ingest_external_file_cf(
                self.inner,
                cf.inner,
                c_files_ptrs.as_ptr(),
                c_files_ptrs.len(),
                opt.inner
            ));
        }
        Ok(())
    }

    /// An optimized version of `ingest_external_file_cf`. It will
    /// first try to ingest files without blocking and fallback to a
    /// blocking ingestion if the optimization fails.
    /// Returns true if a memtable is flushed without blocking.
    pub fn ingest_external_file_optimized(
        &self,
        cf: &CFHandle,
        opt: &IngestExternalFileOptions,
        files: &[&str],
    ) -> Result<bool, String> {
        let c_files = build_cstring_list(files);
        let c_files_ptrs: Vec<*const _> = c_files.iter().map(|s| s.as_ptr()).collect();
        let has_flush = unsafe {
            ffi_try!(crocksdb_ingest_external_file_optimized(
                self.inner,
                cf.inner,
                c_files_ptrs.as_ptr(),
                c_files_ptrs.len(),
                opt.inner
            ))
        };
        Ok(has_flush)
    }

    pub fn backup_at(&self, path: &str) -> Result<BackupEngine, String> {
        let backup_engine = BackupEngine::open(DBOptions::new(), path).unwrap();
        unsafe {
            ffi_try!(crocksdb_backup_engine_create_new_backup(
                backup_engine.inner,
                self.inner
            ))
        }
        Ok(backup_engine)
    }

    pub fn restore_from(
        backup_engine: &BackupEngine,
        restore_db_path: &str,
        restore_wal_path: &str,
        ropts: &RestoreOptions,
    ) -> Result<DB, String> {
        let c_db_path = match CString::new(restore_db_path.as_bytes()) {
            Ok(c) => c,
            Err(_) => {
                return Err(
                    "Failed to convert restore_db_path to CString when restoring rocksdb"
                        .to_owned(),
                );
            }
        };

        let c_wal_path = match CString::new(restore_wal_path.as_bytes()) {
            Ok(c) => c,
            Err(_) => {
                return Err(
                    "Failed to convert restore_wal_path to CString when restoring rocksdb"
                        .to_owned(),
                );
            }
        };

        unsafe {
            ffi_try!(crocksdb_backup_engine_restore_db_from_latest_backup(
                backup_engine.inner,
                c_db_path.as_ptr(),
                c_wal_path.as_ptr(),
                ropts.inner
            ))
        };

        DB::open_default(restore_db_path)
    }

    pub fn get_block_cache_usage(&self) -> u64 {
        self.get_options().get_block_cache_usage()
    }

    pub fn get_block_cache_usage_cf(&self, cf: &CFHandle) -> u64 {
        self.get_options_cf(cf).get_block_cache_usage()
    }

    pub fn get_blob_cache_usage(&self) -> u64 {
        self.get_options().get_blob_cache_usage()
    }

    pub fn get_blob_cache_usage_cf(&self, cf: &CFHandle) -> u64 {
        self.get_options_cf(cf).get_blob_cache_usage()
    }

    pub fn get_properties_of_all_tables(&self) -> Result<TablePropertiesCollection, String> {
        unsafe {
            let props = ffi_try!(crocksdb_get_properties_of_all_tables(self.inner));
            Ok(TablePropertiesCollection::from_raw(props))
        }
    }

    pub fn get_properties_of_all_tables_rc(&self) -> Result<RcTablePropertiesCollection, String> {
        unsafe {
            let props = ffi_try!(crocksdb_get_properties_of_all_tables(self.inner));
            Ok(RcTablePropertiesCollection::new(props))
        }
    }

    pub fn get_properties_of_all_tables_cf(
        &self,
        cf: &CFHandle,
    ) -> Result<TablePropertiesCollection, String> {
        unsafe {
            let props = ffi_try!(crocksdb_get_properties_of_all_tables_cf(
                self.inner, cf.inner
            ));
            Ok(TablePropertiesCollection::from_raw(props))
        }
    }

    pub fn get_properties_of_tables_in_range(
        &self,
        cf: &CFHandle,
        ranges: &[Range],
    ) -> Result<TablePropertiesCollection, String> {
        // Safety: transfers ownership of new non-null pointer
        unsafe {
            let props = self.get_properties_of_tables_in_range_common(cf, ranges)?;
            Ok(TablePropertiesCollection::from_raw(props))
        }
    }

    /// Like `get_properties_of_table_in_range` but the returned family
    /// of types don't contain any lifetimes. This is suitable for wrapping
    /// in further abstractions without needing abstract associated lifetime
    /// parameters. Used by tikv's `engine_rocks`.
    pub fn get_properties_of_tables_in_range_rc(
        &self,
        cf: &CFHandle,
        ranges: &[Range],
    ) -> Result<RcTablePropertiesCollection, String> {
        // Safety: transfers ownership of new non-null pointer
        unsafe {
            let props = self.get_properties_of_tables_in_range_common(cf, ranges)?;
            Ok(RcTablePropertiesCollection::new(props))
        }
    }

    fn get_properties_of_tables_in_range_common(
        &self,
        cf: &CFHandle,
        ranges: &[Range],
    ) -> Result<*mut DBTablePropertiesCollection, String> {
        let start_keys: Vec<*const u8> = ranges.iter().map(|x| x.start_key.as_ptr()).collect();
        let start_keys_lens: Vec<_> = ranges.iter().map(|x| x.start_key.len()).collect();
        let limit_keys: Vec<*const u8> = ranges.iter().map(|x| x.end_key.as_ptr()).collect();
        let limit_keys_lens: Vec<_> = ranges.iter().map(|x| x.end_key.len()).collect();
        unsafe {
            let props = ffi_try!(crocksdb_get_properties_of_tables_in_range(
                self.inner,
                cf.inner,
                ranges.len() as i32,
                start_keys.as_ptr(),
                start_keys_lens.as_ptr(),
                limit_keys.as_ptr(),
                limit_keys_lens.as_ptr()
            ));
            Ok(props)
        }
    }

    pub fn get_all_key_versions(
        &self,
        start_key: &[u8],
        end_key: &[u8],
    ) -> Result<Vec<KeyVersion>, String> {
        unsafe {
            let kvs = ffi_try!(crocksdb_get_all_key_versions(
                self.inner,
                start_key.as_ptr(),
                start_key.len() as size_t,
                end_key.as_ptr(),
                end_key.len() as size_t
            ));
            let size = crocksdb_ffi::crocksdb_keyversions_count(kvs) as usize;
            let mut key_versions = Vec::with_capacity(size);
            for i in 0..size {
                key_versions.push(KeyVersion {
                    key: CStr::from_ptr(crocksdb_ffi::crocksdb_keyversions_key(kvs, i))
                        .to_string_lossy()
                        .into_owned(),
                    value: CStr::from_ptr(crocksdb_ffi::crocksdb_keyversions_value(kvs, i))
                        .to_string_lossy()
                        .into_owned(),
                    seq: crocksdb_ffi::crocksdb_keyversions_seq(kvs, i),
                    value_type: crocksdb_ffi::crocksdb_keyversions_type(kvs, i),
                })
            }
            crocksdb_ffi::crocksdb_keyversions_destroy(kvs);
            Ok(key_versions)
        }
    }

    pub fn get_column_family_meta_data(&self, cf: &CFHandle) -> ColumnFamilyMetaData {
        unsafe {
            let inner = crocksdb_ffi::crocksdb_column_family_meta_data_create();
            crocksdb_ffi::crocksdb_get_column_family_meta_data(self.inner, cf.inner, inner);
            ColumnFamilyMetaData::from_ptr(inner)
        }
    }

    pub fn compact_files_cf(
        &self,
        cf: &CFHandle,
        opts: &CompactionOptions,
        input_files: &[String],
        output_level: i32,
    ) -> Result<(), String> {
        unsafe {
            let input_file_cstrs: Vec<_> = input_files
                .iter()
                .map(|s| CString::new(s.as_bytes()).unwrap())
                .collect();
            let input_file_names: Vec<_> = input_file_cstrs.iter().map(|s| s.as_ptr()).collect();
            ffi_try!(crocksdb_compact_files_cf(
                self.inner,
                cf.inner,
                opts.inner,
                input_file_names.as_ptr() as *const *const c_char,
                input_file_names.len(),
                output_level
            ));
            Ok(())
        }
    }
}

impl Writable for DB {
    fn put(&self, key: &[u8], value: &[u8]) -> Result<(), String> {
        self.put_opt(key, value, &WriteOptions::new())
    }

    fn put_cf(&self, cf: &CFHandle, key: &[u8], value: &[u8]) -> Result<(), String> {
        self.put_cf_opt(cf, key, value, &WriteOptions::new())
    }

    fn merge(&self, key: &[u8], value: &[u8]) -> Result<(), String> {
        self.merge_opt(key, value, &WriteOptions::new())
    }

    fn merge_cf(&self, cf: &CFHandle, key: &[u8], value: &[u8]) -> Result<(), String> {
        self.merge_cf_opt(cf, key, value, &WriteOptions::new())
    }

    fn delete(&self, key: &[u8]) -> Result<(), String> {
        self.delete_opt(key, &WriteOptions::new())
    }

    fn delete_cf(&self, cf: &CFHandle, key: &[u8]) -> Result<(), String> {
        self.delete_cf_opt(cf, key, &WriteOptions::new())
    }

    fn single_delete(&self, key: &[u8]) -> Result<(), String> {
        self.single_delete_opt(key, &WriteOptions::new())
    }

    fn single_delete_cf(&self, cf: &CFHandle, key: &[u8]) -> Result<(), String> {
        self.single_delete_cf_opt(cf, key, &WriteOptions::new())
    }

    fn delete_range(&self, begin_key: &[u8], end_key: &[u8]) -> Result<(), String> {
        let handle = self.cf_handle("default").unwrap();
        self.delete_range_cf(handle, begin_key, end_key)
    }

    fn delete_range_cf(
        &self,
        cf: &CFHandle,
        begin_key: &[u8],
        end_key: &[u8],
    ) -> Result<(), String> {
        self.delete_range_cf_opt(cf, begin_key, end_key, &WriteOptions::new())
    }
}

impl Drop for DB {
    fn drop(&mut self) {
        // SyncWAL before call close.
        if !self.readonly {
            // DB::SyncWal requires writable file support thread safe sync, but
            // not all types of env can create writable file that support thread
            // safe sync. eg, MemEnv.
            self.sync_wal().unwrap_or_else(|_| {});
        }
        unsafe {
            self.cfs.clear();
            crocksdb_ffi::crocksdb_close(self.inner);
        }
    }
}

impl Writable for WriteBatch {
    fn put(&self, key: &[u8], value: &[u8]) -> Result<(), String> {
        unsafe {
            crocksdb_ffi::crocksdb_writebatch_put(
                self.inner,
                key.as_ptr(),
                key.len() as size_t,
                value.as_ptr(),
                value.len() as size_t,
            );
            Ok(())
        }
    }

    fn put_cf(&self, cf: &CFHandle, key: &[u8], value: &[u8]) -> Result<(), String> {
        unsafe {
            crocksdb_ffi::crocksdb_writebatch_put_cf(
                self.inner,
                cf.inner,
                key.as_ptr(),
                key.len() as size_t,
                value.as_ptr(),
                value.len() as size_t,
            );
            Ok(())
        }
    }

    fn merge(&self, key: &[u8], value: &[u8]) -> Result<(), String> {
        unsafe {
            crocksdb_ffi::crocksdb_writebatch_merge(
                self.inner,
                key.as_ptr(),
                key.len() as size_t,
                value.as_ptr(),
                value.len() as size_t,
            );
            Ok(())
        }
    }

    fn merge_cf(&self, cf: &CFHandle, key: &[u8], value: &[u8]) -> Result<(), String> {
        unsafe {
            crocksdb_ffi::crocksdb_writebatch_merge_cf(
                self.inner,
                cf.inner,
                key.as_ptr(),
                key.len() as size_t,
                value.as_ptr(),
                value.len() as size_t,
            );
            Ok(())
        }
    }

    fn delete(&self, key: &[u8]) -> Result<(), String> {
        unsafe {
            crocksdb_ffi::crocksdb_writebatch_delete(self.inner, key.as_ptr(), key.len() as size_t);
            Ok(())
        }
    }

    fn delete_cf(&self, cf: &CFHandle, key: &[u8]) -> Result<(), String> {
        unsafe {
            crocksdb_ffi::crocksdb_writebatch_delete_cf(
                self.inner,
                cf.inner,
                key.as_ptr(),
                key.len() as size_t,
            );
            Ok(())
        }
    }

    fn single_delete(&self, key: &[u8]) -> Result<(), String> {
        unsafe {
            crocksdb_ffi::crocksdb_writebatch_single_delete(
                self.inner,
                key.as_ptr(),
                key.len() as size_t,
            );
            Ok(())
        }
    }

    fn single_delete_cf(&self, cf: &CFHandle, key: &[u8]) -> Result<(), String> {
        unsafe {
            crocksdb_ffi::crocksdb_writebatch_single_delete_cf(
                self.inner,
                cf.inner,
                key.as_ptr(),
                key.len() as size_t,
            );
            Ok(())
        }
    }

    fn delete_range(&self, begin_key: &[u8], end_key: &[u8]) -> Result<(), String> {
        unsafe {
            crocksdb_ffi::crocksdb_writebatch_delete_range(
                self.inner,
                begin_key.as_ptr(),
                begin_key.len(),
                end_key.as_ptr(),
                end_key.len(),
            );
            Ok(())
        }
    }

    fn delete_range_cf(
        &self,
        cf: &CFHandle,
        begin_key: &[u8],
        end_key: &[u8],
    ) -> Result<(), String> {
        unsafe {
            crocksdb_ffi::crocksdb_writebatch_delete_range_cf(
                self.inner,
                cf.inner,
                begin_key.as_ptr(),
                begin_key.len(),
                end_key.as_ptr(),
                end_key.len(),
            );
            Ok(())
        }
    }
}

pub struct DBVector {
    pinned_slice: *mut DBPinnableSlice,
}

impl Debug for DBVector {
    fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
        write!(formatter, "{:?}", &**self)
    }
}

impl<'a> PartialEq<&'a [u8]> for DBVector {
    fn eq(&self, rhs: &&[u8]) -> bool {
        **rhs == **self
    }
}

impl Deref for DBVector {
    type Target = [u8];
    fn deref(&self) -> &[u8] {
        let mut val_len: size_t = 0;
        let val_len_ptr = &mut val_len as *mut size_t;
        unsafe {
            let val = crocksdb_ffi::crocksdb_pinnableslice_value(self.pinned_slice, val_len_ptr);
            slice::from_raw_parts(val, val_len)
        }
    }
}

impl Drop for DBVector {
    fn drop(&mut self) {
        unsafe {
            crocksdb_ffi::crocksdb_pinnableslice_destroy(self.pinned_slice);
        }
    }
}

impl DBVector {
    pub fn from_pinned_slice(s: *mut DBPinnableSlice) -> DBVector {
        DBVector { pinned_slice: s }
    }

    pub fn to_utf8(&self) -> Option<&str> {
        from_utf8(self.deref()).ok()
    }
}

pub struct BackupEngine {
    inner: *mut DBBackupEngine,
}

impl BackupEngine {
    pub fn open(opts: DBOptions, path: &str) -> Result<BackupEngine, String> {
        let cpath = match CString::new(path.as_bytes()) {
            Ok(c) => c,
            Err(_) => {
                return Err(
                    "Failed to convert path to CString when opening rocksdb backup engine"
                        .to_owned(),
                );
            }
        };

        if let Err(e) = fs::create_dir_all(path) {
            return Err(format!(
                "Failed to create rocksdb backup directory: {:?}",
                e
            ));
        }

        let backup_engine =
            unsafe { ffi_try!(crocksdb_backup_engine_open(opts.inner, cpath.as_ptr())) };

        Ok(BackupEngine {
            inner: backup_engine,
        })
    }
}

impl Drop for BackupEngine {
    fn drop(&mut self) {
        unsafe {
            crocksdb_ffi::crocksdb_backup_engine_close(self.inner);
        }
    }
}

// SstFileReader is used to read sst files that are generated by DB or
// SstFileWriter.
pub struct SstFileReader {
    inner: *mut crocksdb_ffi::SstFileReader,
    _opt: ColumnFamilyOptions,
}

unsafe impl Send for SstFileReader {}

impl SstFileReader {
    /// Creates a new SstFileReader.
    pub fn new(opt: ColumnFamilyOptions) -> Self {
        unsafe {
            Self {
                inner: crocksdb_ffi::crocksdb_sstfilereader_create(opt.inner),
                _opt: opt,
            }
        }
    }

    /// Opens a local SST file for reading.
    pub fn open(&mut self, name: &str) -> Result<(), String> {
        let path =
            CString::new(name.to_owned()).map_err(|e| format!("invalid path {}: {:?}", name, e))?;
        unsafe {
            ffi_try!(crocksdb_sstfilereader_open(self.inner, path.as_ptr()));
        }
        Ok(())
    }

    pub fn iter(&self) -> DBIterator<&Self> {
        self.iter_opt(ReadOptions::new())
    }

    pub fn iter_opt(&self, readopts: ReadOptions) -> DBIterator<&Self> {
        unsafe {
            DBIterator {
                inner: crocksdb_ffi::crocksdb_sstfilereader_new_iterator(
                    self.inner,
                    readopts.get_inner(),
                ),
                _db: self,
                _readopts: readopts,
            }
        }
    }

    /// Create an iterator out of a reference-counted SstFileReader.
    ///
    /// This exists due to restrictions on lifetimes in associated types.
    /// See RocksSstIterator in TiKV's engine_rocks.
    pub fn iter_rc(this: Rc<Self>) -> DBIterator<Rc<Self>> {
        Self::iter_opt_rc(this, ReadOptions::new())
    }

    pub fn iter_opt_rc(this: Rc<Self>, readopts: ReadOptions) -> DBIterator<Rc<Self>> {
        unsafe {
            DBIterator {
                inner: crocksdb_ffi::crocksdb_sstfilereader_new_iterator(
                    this.inner,
                    readopts.get_inner(),
                ),
                _db: this,
                _readopts: readopts,
            }
        }
    }

    pub fn read_table_properties<F: FnOnce(&TableProperties)>(&self, mut action: F) {
        extern "C" fn callback<F: FnOnce(&TableProperties)>(
            ctx: *mut c_void,
            ptr: *const crocksdb_ffi::DBTableProperties,
        ) {
            unsafe {
                let caller = ptr::read(ctx as *mut F);
                caller(TableProperties::from_ptr(ptr));
            }
        }

        unsafe {
            crocksdb_ffi::crocksdb_sstfilereader_read_table_properties(
                self.inner,
                &mut action as *mut F as *mut c_void,
                callback::<F>,
            );
            mem::forget(action);
        }
    }

    pub fn verify_checksum(&self) -> Result<(), String> {
        unsafe { ffi_try!(crocksdb_sstfilereader_verify_checksum(self.inner)) };
        Ok(())
    }
}

impl Drop for SstFileReader {
    fn drop(&mut self) {
        unsafe { crocksdb_ffi::crocksdb_sstfilereader_destroy(self.inner) }
    }
}

/// SstFileWriter is used to create sst files that can be added to database later
/// All keys in files generated by SstFileWriter will have sequence number = 0
pub struct SstFileWriter {
    inner: *mut crocksdb_ffi::SstFileWriter,
    _env_opt: EnvOptions,
    _opt: ColumnFamilyOptions,
}

unsafe impl Send for SstFileWriter {}

impl SstFileWriter {
    pub fn new(env_opt: EnvOptions, opt: ColumnFamilyOptions) -> SstFileWriter {
        unsafe {
            SstFileWriter {
                inner: crocksdb_ffi::crocksdb_sstfilewriter_create(env_opt.inner, opt.inner),
                _env_opt: env_opt,
                _opt: opt,
            }
        }
    }

    pub fn new_cf(env_opt: EnvOptions, opt: ColumnFamilyOptions, cf: &CFHandle) -> SstFileWriter {
        unsafe {
            SstFileWriter {
                inner: crocksdb_ffi::crocksdb_sstfilewriter_create_cf(
                    env_opt.inner,
                    opt.inner,
                    cf.inner,
                ),
                _env_opt: env_opt,
                _opt: opt,
            }
        }
    }

    /// Prepare SstFileWriter to write into file located at "file_path".
    pub fn open(&mut self, name: &str) -> Result<(), String> {
        let path = match CString::new(name.to_owned()) {
            Err(e) => return Err(format!("invalid path {}: {:?}", name, e)),
            Ok(p) => p,
        };
        unsafe {
            ffi_try!(crocksdb_sstfilewriter_open(self.inner, path.as_ptr()));
        }
        Ok(())
    }

    /// Add key, value to currently opened file
    /// REQUIRES: key is after any previously added key according to comparator.
    pub fn put(&mut self, key: &[u8], val: &[u8]) -> Result<(), String> {
        unsafe {
            ffi_try!(crocksdb_sstfilewriter_put(
                self.inner,
                key.as_ptr(),
                key.len(),
                val.as_ptr(),
                val.len()
            ));
            Ok(())
        }
    }

    pub fn merge(&mut self, key: &[u8], val: &[u8]) -> Result<(), String> {
        unsafe {
            ffi_try!(crocksdb_sstfilewriter_merge(
                self.inner,
                key.as_ptr(),
                key.len(),
                val.as_ptr(),
                val.len()
            ));
            Ok(())
        }
    }

    pub fn delete(&mut self, key: &[u8]) -> Result<(), String> {
        unsafe {
            ffi_try!(crocksdb_sstfilewriter_delete(
                self.inner,
                key.as_ptr(),
                key.len()
            ));
            Ok(())
        }
    }

    pub fn delete_range(&mut self, begin_key: &[u8], end_key: &[u8]) -> Result<(), String> {
        unsafe {
            ffi_try!(crocksdb_sstfilewriter_delete_range(
                self.inner,
                begin_key.as_ptr(),
                begin_key.len(),
                end_key.as_ptr(),
                end_key.len()
            ));
            Ok(())
        }
    }

    /// Finalize writing to sst file and close file.
    pub fn finish(&mut self) -> Result<ExternalSstFileInfo, String> {
        let info = ExternalSstFileInfo::new();
        unsafe {
            ffi_try!(crocksdb_sstfilewriter_finish(self.inner, info.inner));
        }
        Ok(info)
    }

    pub fn file_size(&mut self) -> u64 {
        unsafe { crocksdb_ffi::crocksdb_sstfilewriter_file_size(self.inner) as u64 }
    }
}

impl Drop for SstFileWriter {
    fn drop(&mut self) {
        unsafe { crocksdb_ffi::crocksdb_sstfilewriter_destroy(self.inner) }
    }
}

pub struct ExternalSstFileInfo {
    inner: *mut crocksdb_ffi::ExternalSstFileInfo,
}

impl ExternalSstFileInfo {
    pub fn new() -> ExternalSstFileInfo {
        unsafe {
            ExternalSstFileInfo {
                inner: crocksdb_ffi::crocksdb_externalsstfileinfo_create(),
            }
        }
    }

    pub fn file_path(&self) -> PathBuf {
        let mut len: size_t = 0;
        unsafe {
            let ptr = crocksdb_ffi::crocksdb_externalsstfileinfo_file_path(self.inner, &mut len);
            let bytes = slice::from_raw_parts(ptr, len as usize);
            PathBuf::from(String::from_utf8(bytes.to_owned()).unwrap())
        }
    }

    pub fn smallest_key(&self) -> &[u8] {
        let mut len: size_t = 0;
        unsafe {
            let ptr = crocksdb_ffi::crocksdb_externalsstfileinfo_smallest_key(self.inner, &mut len);
            slice::from_raw_parts(ptr, len as usize)
        }
    }

    pub fn largest_key(&self) -> &[u8] {
        let mut len: size_t = 0;
        unsafe {
            let ptr = crocksdb_ffi::crocksdb_externalsstfileinfo_largest_key(self.inner, &mut len);
            slice::from_raw_parts(ptr, len as usize)
        }
    }

    pub fn sequence_number(&self) -> u64 {
        unsafe { crocksdb_ffi::crocksdb_externalsstfileinfo_sequence_number(self.inner) as u64 }
    }

    pub fn file_size(&self) -> u64 {
        unsafe { crocksdb_ffi::crocksdb_externalsstfileinfo_file_size(self.inner) as u64 }
    }

    pub fn num_entries(&self) -> u64 {
        unsafe { crocksdb_ffi::crocksdb_externalsstfileinfo_num_entries(self.inner) as u64 }
    }
}

impl Drop for ExternalSstFileInfo {
    fn drop(&mut self) {
        unsafe {
            crocksdb_ffi::crocksdb_externalsstfileinfo_destroy(self.inner);
        }
    }
}

pub fn supported_compression() -> Vec<DBCompressionType> {
    unsafe {
        let size = crocksdb_ffi::crocksdb_get_supported_compression_number() as usize;
        let mut v: Vec<DBCompressionType> = Vec::with_capacity(size);
        let pv = v.as_mut_ptr();
        crocksdb_ffi::crocksdb_get_supported_compression(pv, size as size_t);
        v.set_len(size);
        v
    }
}

pub struct Env {
    pub inner: *mut DBEnv,
    #[allow(dead_code)]
    base: Option<Arc<Env>>,
}

unsafe impl Send for Env {}

unsafe impl Sync for Env {}

impl Default for Env {
    fn default() -> Env {
        unsafe {
            Env {
                inner: crocksdb_ffi::crocksdb_default_env_create(),
                base: None,
            }
        }
    }
}

impl Env {
    pub fn new_mem() -> Env {
        unsafe {
            Env {
                inner: crocksdb_ffi::crocksdb_mem_env_create(),
                base: None,
            }
        }
    }

    // Create a ctr encrypted env with a given base env and a given ciper text.
    // The length of ciper text must be 2^n, and must be less or equal to 2048.
    // The recommanded block size are 1024, 512 and 256.
    pub fn new_ctr_encrypted_env(base_env: Arc<Env>, ciphertext: &[u8]) -> Result<Env, String> {
        let len = ciphertext.len();
        if len > 2048 || !len.is_power_of_two() {
            return Err(
                "ciphertext length must be less or equal to 2048, and must be power of 2"
                    .to_owned(),
            );
        }
        let env = unsafe {
            crocksdb_ffi::crocksdb_ctr_encrypted_env_create(
                base_env.inner,
                ciphertext.as_ptr() as *const c_char,
                len,
            )
        };
        Ok(Env {
            inner: env,
            base: Some(base_env),
        })
    }

    // Create a ctr encrypted env with the default env
    pub fn new_default_ctr_encrypted_env(ciphertext: &[u8]) -> Result<Env, String> {
        Env::new_ctr_encrypted_env(Arc::new(Env::default()), ciphertext)
    }

    // Create an encrypted env that accepts an external key manager.
    #[cfg(feature = "encryption")]
    pub fn new_key_managed_encrypted_env<T: EncryptionKeyManager>(
        base_env: Arc<Env>,
        key_manager: T,
    ) -> Result<Env, String> {
        let db_key_manager = DBEncryptionKeyManager::new(key_manager);
        let env = unsafe {
            crocksdb_ffi::crocksdb_key_managed_encrypted_env_create(
                base_env.inner,
                db_key_manager.inner,
            )
        };
        Ok(Env {
            inner: env,
            base: Some(base_env),
        })
    }

    pub fn new_file_system_inspected_env<T: FileSystemInspector>(
        base_env: Arc<Env>,
        file_system_inspector: T,
    ) -> Result<Env, String> {
        let db_file_system_inspector = DBFileSystemInspector::new(file_system_inspector);
        let env = unsafe {
            crocksdb_ffi::crocksdb_file_system_inspected_env_create(
                base_env.inner,
                db_file_system_inspector.inner,
            )
        };
        Ok(Env {
            inner: env,
            base: Some(base_env),
        })
    }

    pub fn new_sequential_file(
        &self,
        path: &str,
        opts: EnvOptions,
    ) -> Result<SequentialFile, String> {
        unsafe {
            let file_path = CString::new(path).unwrap();
            let file = ffi_try!(crocksdb_sequential_file_create(
                self.inner,
                file_path.as_ptr(),
                opts.inner
            ));
            Ok(SequentialFile::new(file))
        }
    }

    pub fn file_exists(&self, path: &str) -> Result<(), String> {
        unsafe {
            let file_path = CString::new(path).unwrap();
            ffi_try!(crocksdb_env_file_exists(self.inner, file_path.as_ptr()));
            Ok(())
        }
    }

    pub fn delete_file(&self, path: &str) -> Result<(), String> {
        unsafe {
            let file_path = CString::new(path).unwrap();
            ffi_try!(crocksdb_env_delete_file(self.inner, file_path.as_ptr()));
            Ok(())
        }
    }
}

impl Drop for Env {
    fn drop(&mut self) {
        unsafe {
            crocksdb_ffi::crocksdb_env_destroy(self.inner);
        }
    }
}

pub struct SequentialFile {
    inner: *mut DBSequentialFile,
}

impl SequentialFile {
    fn new(inner: *mut DBSequentialFile) -> SequentialFile {
        SequentialFile { inner: inner }
    }

    pub fn skip(&mut self, n: usize) -> Result<(), String> {
        unsafe {
            ffi_try!(crocksdb_sequential_file_skip(self.inner, n as size_t));
            Ok(())
        }
    }
}

unsafe impl Send for SequentialFile {}

impl io::Read for SequentialFile {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        unsafe {
            let mut err = ptr::null_mut();
            let size = crocksdb_ffi::crocksdb_sequential_file_read(
                self.inner,
                buf.len() as size_t,
                buf.as_mut_ptr(),
                &mut err,
            );
            if !err.is_null() {
                return Err(io::Error::new(
                    io::ErrorKind::Other,
                    crocksdb_ffi::error_message(err),
                ));
            }
            Ok(size as usize)
        }
    }
}

impl Drop for SequentialFile {
    fn drop(&mut self) {
        unsafe {
            crocksdb_ffi::crocksdb_sequential_file_destroy(self.inner);
        }
    }
}

pub struct Cache {
    pub inner: *mut DBCache,
}

impl Cache {
    pub fn new_lru_cache(opt: LRUCacheOptions) -> Cache {
        // This is ok because LRUCacheOptions always contains a valid pointer
        unsafe {
            Cache {
                inner: crocksdb_ffi::new_lru_cache(opt.inner),
            }
        }
    }
}

impl Drop for Cache {
    fn drop(&mut self) {
        unsafe {
            crocksdb_ffi::crocksdb_cache_destroy(self.inner);
        }
    }
}

pub struct MemoryAllocator {
    pub inner: *mut DBMemoryAllocator,
}

impl MemoryAllocator {
    #[cfg(feature = "jemalloc")]
    pub fn new_jemalloc_memory_allocator() -> Result<MemoryAllocator, String> {
        unsafe {
            let allocator = MemoryAllocator {
                inner: ffi_try!(crocksdb_jemalloc_nodump_allocator_create()),
            };
            Ok(allocator)
        }
    }
}

impl Drop for MemoryAllocator {
    fn drop(&mut self) {
        unsafe {
            crocksdb_ffi::crocksdb_memory_allocator_destroy(self.inner);
        }
    }
}

pub fn set_external_sst_file_global_seq_no(
    db: &DB,
    cf: &CFHandle,
    file: &str,
    seq_no: u64,
) -> Result<u64, String> {
    let cfile = CString::new(file).unwrap();
    unsafe {
        let pre_seq_no = ffi_try!(crocksdb_set_external_sst_file_global_seq_no(
            db.inner,
            cf.inner,
            cfile.as_ptr(),
            seq_no
        ));
        Ok(pre_seq_no)
    }
}

pub fn load_latest_options(
    dbpath: &str,
    env: &Env,
    ignore_unknown_options: bool,
) -> Result<Option<(DBOptions, Vec<CColumnFamilyDescriptor>)>, String> {
    const ERR_CONVERT_PATH: &str = "Failed to convert path to CString when load latest options";

    let dbpath = CString::new(dbpath.as_bytes()).map_err(|_| ERR_CONVERT_PATH.to_owned())?;
    let db_options = DBOptions::new();
    unsafe {
        let raw_cf_descs: *mut *mut crocksdb_ffi::ColumnFamilyDescriptor = ptr::null_mut();
        let mut cf_descs_len: size_t = 0;

        let ok = ffi_try!(crocksdb_load_latest_options(
            dbpath.as_ptr(),
            env.inner,
            db_options.inner,
            &raw_cf_descs,
            &mut cf_descs_len,
            ignore_unknown_options
        ));
        if !ok {
            return Ok(None);
        }
        let cf_descs_list = slice::from_raw_parts(raw_cf_descs, cf_descs_len);
        let cf_descs = cf_descs_list
            .iter()
            .map(|raw_cf_desc| CColumnFamilyDescriptor::from_raw(*raw_cf_desc))
            .collect();

        libc::free(raw_cf_descs as *mut c_void);

        Ok(Some((db_options, cf_descs)))
    }
}

pub fn run_ldb_tool(ldb_args: &[String], opts: &DBOptions) {
    unsafe {
        let ldb_args_cstrs: Vec<_> = ldb_args
            .iter()
            .map(|s| CString::new(s.as_bytes()).unwrap())
            .collect();
        let args: Vec<_> = ldb_args_cstrs.iter().map(|s| s.as_ptr()).collect();
        crocksdb_ffi::crocksdb_run_ldb_tool(
            args.len() as i32,
            args.as_ptr() as *const *const c_char,
            opts.inner,
        );
    }
}

pub fn run_sst_dump_tool(sst_dump_args: &[String], opts: &DBOptions) {
    unsafe {
        let sst_dump_args_cstrs: Vec<_> = sst_dump_args
            .iter()
            .map(|s| CString::new(s.as_bytes()).unwrap())
            .collect();
        let args: Vec<_> = sst_dump_args_cstrs.iter().map(|s| s.as_ptr()).collect();
        crocksdb_ffi::crocksdb_run_sst_dump_tool(
            args.len() as i32,
            args.as_ptr() as *const *const c_char,
            opts.inner,
        );
    }
}

#[cfg(test)]
mod test {
    use librocksdb_sys::DBValueType;
    use std::fs;
    use std::path::Path;
    use std::str;
    use std::string::String;
    use std::thread;
    use write_batch::WriteBatchRef;

    use super::*;
    use crate::tempdir_with_prefix;

    #[test]
    fn external() {
        let path = tempdir_with_prefix("_rust_rocksdb_externaltest");
        let db = DB::open_default(path.path().to_str().unwrap()).unwrap();
        let p = db.put(b"k1", b"v1111");
        assert!(p.is_ok());
        let r: Result<Option<DBVector>, String> = db.get(b"k1");
        assert!(r.unwrap().unwrap().to_utf8().unwrap() == "v1111");
        assert!(db.delete(b"k1").is_ok());
        assert!(db.get(b"k1").unwrap().is_none());
    }

    #[allow(unused_variables)]
    #[test]
    fn errors_do_stuff() {
        let path = tempdir_with_prefix("_rust_rocksdb_error");
        let path_str = path.path().to_str().unwrap();
        let db = DB::open_default(path_str).unwrap();
        let opts = DBOptions::new();
        // The DB will still be open when we try to destroy and the lock should fail
        match DB::destroy(&opts, path_str) {
            Err(ref s) => {
                assert!(
                    s.contains("IO error: ") && s.contains("lock"),
                    "expect lock fail, but got {}",
                    s
                );
            }
            Ok(_) => panic!("should fail"),
        }
    }

    #[test]
    fn writebatch_works() {
        let path = tempdir_with_prefix("_rust_rocksdb_writebacktest");
        let db = DB::open_default(path.path().to_str().unwrap()).unwrap();

        // test put
        let batch = WriteBatch::new();
        assert!(db.get(b"k1").unwrap().is_none());
        assert_eq!(batch.count(), 0);
        assert!(batch.is_empty());
        let _ = batch.put(b"k1", b"v1111");
        assert_eq!(batch.count(), 1);
        assert!(!batch.is_empty());
        assert!(db.get(b"k1").unwrap().is_none());
        let p = db.write(&batch);
        assert!(p.is_ok());
        let r = db.get(b"k1");
        assert_eq!(r.unwrap().unwrap(), b"v1111");

        // test delete
        let batch = WriteBatch::new();
        let _ = batch.delete(b"k1");
        assert_eq!(batch.count(), 1);
        assert!(!batch.is_empty());
        let p = db.write(&batch);
        assert!(p.is_ok());
        assert!(db.get(b"k1").unwrap().is_none());

        let batch = WriteBatch::new();
        let prev_size = batch.data_size();
        let _ = batch.delete(b"k1");
        assert!(batch.data_size() > prev_size);
        batch.clear();
        assert_eq!(batch.data_size(), prev_size);

        // test save point
        let mut batch = WriteBatch::new();
        batch.set_save_point();
        batch.pop_save_point().unwrap();
        batch.put(b"k10", b"v10").unwrap();
        batch.set_save_point();
        batch.put(b"k11", b"v11").unwrap();
        batch.set_save_point();
        batch.put(b"k12", b"v12").unwrap();
        batch.set_save_point();
        batch.put(b"k13", b"v13").unwrap();
        batch.rollback_to_save_point().unwrap();
        batch.rollback_to_save_point().unwrap();
        let p = db.write(&batch);
        assert!(p.is_ok());
        let r = db.get(b"k10");
        assert_eq!(r.unwrap().unwrap(), b"v10");
        let r = db.get(b"k11");
        assert_eq!(r.unwrap().unwrap(), b"v11");
        let r = db.get(b"k12");
        assert!(r.unwrap().is_none());
        let r = db.get(b"k13");
        assert!(r.unwrap().is_none());

        // test with capacity
        let batch = WriteBatch::with_capacity(1024);
        batch.put(b"kc1", b"v1").unwrap();
        batch.put(b"kc2", b"v2").unwrap();
        let p = db.write(&batch);
        assert!(p.is_ok());
        let r = db.get(b"kc1");
        assert!(r.unwrap().is_some());
        let r = db.get(b"kc2");
        assert!(r.unwrap().is_some());
    }

    #[test]
    fn iterator_test() {
        let path = tempdir_with_prefix("_rust_rocksdb_iteratortest");

        let db = DB::open_default(path.path().to_str().unwrap()).unwrap();
        db.put(b"k1", b"v1111").expect("");
        db.put(b"k2", b"v2222").expect("");
        db.put(b"k3", b"v3333").expect("");
        let mut iter = db.iter();
        iter.seek(SeekKey::Start).unwrap();
        for (k, v) in &mut iter {
            println!(
                "Hello {}: {}",
                str::from_utf8(&*k).unwrap(),
                str::from_utf8(&*v).unwrap()
            );
        }
    }

    #[test]
    fn approximate_size_test() {
        let path = tempdir_with_prefix("_rust_rocksdb_iteratortest");
        let db = DB::open_default(path.path().to_str().unwrap()).unwrap();
        for i in 1..8000 {
            db.put(
                format!("{:04}", i).as_bytes(),
                format!("{:04}", i).as_bytes(),
            )
            .expect("");
        }
        db.flush(true).expect("");
        assert!(db.get(b"0001").expect("").is_some());
        db.flush(true).expect("");
        let sizes = db.get_approximate_sizes(&[
            Range::new(b"0000", b"2000"),
            Range::new(b"2000", b"4000"),
            Range::new(b"4000", b"6000"),
            Range::new(b"6000", b"8000"),
            Range::new(b"8000", b"9999"),
        ]);
        assert_eq!(sizes.len(), 5);
        for s in &sizes[0..4] {
            assert!(*s > 0);
        }
        assert_eq!(sizes[4], 0);
    }

    #[test]
    fn property_test() {
        let path = tempdir_with_prefix("_rust_rocksdb_propertytest");
        let db = DB::open_default(path.path().to_str().unwrap()).unwrap();
        db.put(b"a1", b"v1").unwrap();
        db.flush(true).unwrap();
        let prop_name = "rocksdb.total-sst-files-size";
        let st1 = db.get_property_int(prop_name).unwrap();
        assert!(st1 > 0);
        db.put(b"a2", b"v2").unwrap();
        db.flush(true).unwrap();
        let st2 = db.get_property_int(prop_name).unwrap();
        assert!(st2 > st1);
    }

    #[test]
    fn list_column_families_test() {
        let path = tempdir_with_prefix("_rust_rocksdb_list_column_families_test");
        let mut cfs = ["default", "cf1", "cf2", "cf3"];
        {
            let mut cfs_opts = vec![];
            for _ in 0..cfs.len() {
                cfs_opts.push(ColumnFamilyOptions::new());
            }

            let mut opts = DBOptions::new();
            opts.create_if_missing(true);
            let mut db = DB::open(opts, path.path().to_str().unwrap()).unwrap();
            for (cf, cf_opts) in cfs.iter().zip(cfs_opts) {
                if *cf == "default" {
                    continue;
                }
                db.create_cf((*cf, cf_opts)).unwrap();
            }
        }
        let opts_list_cfs = DBOptions::new();
        let mut cfs_vec =
            DB::list_column_families(&opts_list_cfs, path.path().to_str().unwrap()).unwrap();
        cfs_vec.sort();
        cfs.sort();
        assert_eq!(cfs_vec, cfs);
    }

    #[test]
    fn backup_db_test() {
        let key = b"foo";
        let value = b"bar";

        let db_dir = tempdir_with_prefix("_rust_rocksdb_backuptest");
        let db = DB::open_default(db_dir.path().to_str().unwrap()).unwrap();
        let p = db.put(key, value);
        assert!(p.is_ok());

        // Make a backup.
        let backup_dir = tempdir_with_prefix("_rust_rocksdb_backuptest_backup");
        let backup_engine = db.backup_at(backup_dir.path().to_str().unwrap()).unwrap();

        // Restore it.
        let ropt1 = RestoreOptions::new();
        let mut ropt2 = RestoreOptions::new();
        ropt2.set_keep_log_files(true);
        let ropts = [ropt1, ropt2];
        for ropt in &ropts {
            let restore_dir = tempdir_with_prefix("_rust_rocksdb_backuptest_restore");
            let restored_db = DB::restore_from(
                &backup_engine,
                restore_dir.path().to_str().unwrap(),
                restore_dir.path().to_str().unwrap(),
                &ropt,
            )
            .unwrap();

            let r = restored_db.get(key);
            assert!(r.unwrap().unwrap().to_utf8().unwrap() == str::from_utf8(value).unwrap());
        }
    }

    #[test]
    fn log_dir_test() {
        let db_dir = tempdir_with_prefix("_rust_rocksdb_logdirtest");
        let db_path = db_dir.path().to_str().unwrap();
        let log_path = format!("{}", Path::new(&db_path).join("log_path").display());
        fs::create_dir_all(&log_path).unwrap();

        let mut opts = DBOptions::new();
        opts.create_if_missing(true);
        opts.set_db_log_dir(&log_path);

        DB::open(opts, db_path).unwrap();

        // Check LOG file.
        let mut read_dir = fs::read_dir(&log_path).unwrap();
        let entry = read_dir.next().unwrap().unwrap();
        let name = entry.file_name();
        name.to_str().unwrap().find("LOG").unwrap();

        for entry in fs::read_dir(&db_path).unwrap() {
            let entry = entry.unwrap();
            let name = entry.file_name();
            assert!(name.to_str().unwrap().find("LOG").is_none());
        }
    }

    #[test]
    fn single_delete_test() {
        let path = tempdir_with_prefix("_rust_rocksdb_singledeletetest");
        let db = DB::open_default(path.path().to_str().unwrap()).unwrap();

        db.put(b"a", b"v1").unwrap();
        let a = db.get(b"a");
        assert_eq!(a.unwrap().unwrap().to_utf8().unwrap(), "v1");
        db.single_delete(b"a").unwrap();
        let a = db.get(b"a");
        assert!(a.unwrap().is_none());

        db.put(b"a", b"v2").unwrap();
        let a = db.get(b"a");
        assert_eq!(a.unwrap().unwrap().to_utf8().unwrap(), "v2");
        db.single_delete(b"a").unwrap();
        let a = db.get(b"a");
        assert!(a.unwrap().is_none());

        let cf_handle = db.cf_handle("default").unwrap();
        db.put_cf(cf_handle, b"a", b"v3").unwrap();
        let a = db.get_cf(cf_handle, b"a");
        assert_eq!(a.unwrap().unwrap().to_utf8().unwrap(), "v3");
        db.single_delete_cf(cf_handle, b"a").unwrap();
        let a = db.get_cf(cf_handle, b"a");
        assert!(a.unwrap().is_none());

        db.put_cf(cf_handle, b"a", b"v4").unwrap();
        let a = db.get_cf(cf_handle, b"a");
        assert_eq!(a.unwrap().unwrap().to_utf8().unwrap(), "v4");
        db.single_delete_cf(cf_handle, b"a").unwrap();
        let a = db.get_cf(cf_handle, b"a");
        assert!(a.unwrap().is_none());
    }

    #[test]
    fn test_pause_bg_work() {
        let path = tempdir_with_prefix("_rust_rocksdb_pause_bg_work");
        let db = DB::open_default(path.path().to_str().unwrap()).unwrap();
        let db = Arc::new(db);
        let db1 = db.clone();
        let builder = thread::Builder::new().name(String::from("put-thread"));
        let h = builder
            .spawn(move || {
                db1.put(b"k1", b"v1").unwrap();
                db1.put(b"k2", b"v2").unwrap();
                db1.flush(true).unwrap();
                db1.compact_range(None, None);
            })
            .unwrap();
        // Wait until all currently running background processes finish.
        db.pause_bg_work();
        assert_eq!(
            db.get_property_int("rocksdb.num-running-compactions")
                .unwrap(),
            0
        );
        assert_eq!(
            db.get_property_int("rocksdb.num-running-flushes").unwrap(),
            0
        );
        db.continue_bg_work();
        h.join().unwrap();
    }

    #[test]
    fn snapshot_test() {
        let path = "_rust_rocksdb_snapshottest";
        {
            let db = DB::open_default(path).unwrap();
            let p = db.put(b"k1", b"v1111");
            assert!(p.is_ok());

            let snap = db.snapshot();
            let mut r: Result<Option<DBVector>, String> = snap.get(b"k1");
            assert!(r.unwrap().unwrap().to_utf8().unwrap() == "v1111");

            r = db.get(b"k1");
            assert!(r.unwrap().unwrap().to_utf8().unwrap() == "v1111");

            let p = db.put(b"k2", b"v2222");
            assert!(p.is_ok());

            assert!(db.get(b"k2").unwrap().is_some());
            assert!(snap.get(b"k2").unwrap().is_none());
        }
        let opts = DBOptions::new();
        assert!(DB::destroy(&opts, path).is_ok());
    }

    #[test]
    fn block_cache_usage() {
        let path = tempdir_with_prefix("_rust_rocksdb_block_cache_usage");
        let db = DB::open_default(path.path().to_str().unwrap()).unwrap();

        for i in 0..200 {
            db.put(format!("k_{}", i).as_bytes(), b"v").unwrap();
        }
        db.flush(true).unwrap();
        for i in 0..200 {
            db.get(format!("k_{}", i).as_bytes()).unwrap();
        }

        assert!(db.get_block_cache_usage() > 0);
        let cf_handle = db.cf_handle("default").unwrap();
        assert!(db.get_block_cache_usage_cf(cf_handle) > 0);
    }

    #[test]
    fn flush_cf() {
        let path = tempdir_with_prefix("_rust_rocksdb_flush_cf");
        let mut opts = DBOptions::new();
        opts.create_if_missing(true);
        let mut db = DB::open(opts, path.path().to_str().unwrap()).unwrap();
        db.create_cf("cf").unwrap();

        let cf_handle = db.cf_handle("cf").unwrap();
        for i in 0..200 {
            db.put_cf(cf_handle, format!("k_{}", i).as_bytes(), b"v")
                .unwrap();
        }
        db.flush_cf(cf_handle, true).unwrap();

        let total_sst_files_size = db
            .get_property_int_cf(cf_handle, "rocksdb.total-sst-files-size")
            .unwrap();
        assert!(total_sst_files_size > 0);
    }

    #[test]
    fn test_supported_compression() {
        let mut com = supported_compression();
        let len_before = com.len();
        assert!(com.len() != 0);
        com.dedup();
        assert_eq!(len_before, com.len());
        for c in com {
            println!("{:?}", c);
            println!("{}", c as u32);
            match c as u32 {
                0..=5 | 7 | 0x40 => assert!(true),
                _ => assert!(false),
            }
        }
    }

    #[test]
    fn test_get_all_key_versions() {
        let mut opts = DBOptions::new();
        opts.create_if_missing(true);
        let path = tempdir_with_prefix("_rust_rocksdb_get_all_key_version_test");
        let db = DB::open(opts, path.path().to_str().unwrap()).unwrap();

        let samples = vec![
            (b"key1".to_vec(), b"value1".to_vec()),
            (b"key2".to_vec(), b"value2".to_vec()),
            (b"key3".to_vec(), b"value3".to_vec()),
            (b"key4".to_vec(), b"value4".to_vec()),
        ];

        // Put 4 keys.
        for &(ref k, ref v) in &samples {
            db.put(k, v).unwrap();
            assert_eq!(v.as_slice(), &*db.get(k).unwrap().unwrap());
        }
        db.flush(true).unwrap();
        let key_versions = db.get_all_key_versions(b"key2", b"key4").unwrap();
        assert_eq!(key_versions[1].key, "key3");
        assert_eq!(key_versions[1].value, "value3");
        assert_eq!(key_versions[1].seq, 3);
    }

    #[test]
    fn test_get_approximate_memtable_stats() {
        let mut opts = DBOptions::new();
        opts.create_if_missing(true);
        let path = tempdir_with_prefix("_rust_rocksdb_get_approximate_memtable_stats");
        let db = DB::open(opts, path.path().to_str().unwrap()).unwrap();

        let samples = [
            (b"key1", b"value1"),
            (b"key2", b"value2"),
            (b"key3", b"value3"),
            (b"key4", b"value4"),
        ];

        for &(k, v) in &samples {
            db.put(k, v).unwrap();
        }

        let range = Range::new(b"a", b"z");

        let (count, size) = db.get_approximate_memtable_stats(&range);
        assert!(count > 0);
        assert!(size > 0);

        let cf = db.cf_handle("default").unwrap();
        let (count, size) = db.get_approximate_memtable_stats_cf(cf, &range);
        assert!(count > 0);
        assert!(size > 0);
    }

    #[test]
    fn test_set_options() {
        let mut opts = DBOptions::new();
        opts.create_if_missing(true);
        let path = tempdir_with_prefix("_rust_rocksdb_set_option");

        let db = DB::open(opts, path.path().to_str().unwrap()).unwrap();
        let cf = db.cf_handle("default").unwrap();

        let db_opts = db.get_db_options();
        assert_eq!(db_opts.get_max_background_jobs(), 2);
        db.set_db_options(&[("max_background_jobs", "8")]).unwrap();
        let db_opts = db.get_db_options();
        assert_eq!(db_opts.get_max_background_jobs(), 8);

        db.set_db_options(&[("max_background_compactions", "6")])
            .unwrap();
        db.set_db_options(&[("max_background_flushes", "3")])
            .unwrap();
        let db_opts = db.get_db_options();
        assert_eq!(db_opts.get_max_background_jobs(), 8);
        assert_eq!(db_opts.get_max_background_compactions(), 6);
        assert_eq!(db_opts.get_max_background_flushes(), 3);

        let cf_opts = db.get_options_cf(cf);
        assert_eq!(cf_opts.get_disable_auto_compactions(), false);
        db.set_options_cf(cf, &[("disable_auto_compactions", "true")])
            .unwrap();
        let cf_opts = db.get_options_cf(cf);
        assert_eq!(cf_opts.get_disable_auto_compactions(), true);
    }

    #[test]
    fn test_load_latest_options() {
        let path = tempdir_with_prefix("_rust_rocksdb_load_latest_option");
        let dbpath = path.path().to_str().unwrap().clone();
        let cf_name: &str = "cf_dynamic_level_bytes";

        // test when options not exist
        assert!(load_latest_options(dbpath, &Env::default(), false)
            .unwrap()
            .is_none());

        let mut opts = DBOptions::new();
        opts.create_if_missing(true);
        let mut db = DB::open(opts, dbpath).unwrap();

        let mut cf_opts = ColumnFamilyOptions::new();
        cf_opts.set_level_compaction_dynamic_level_bytes(true);
        db.create_cf((cf_name.clone(), cf_opts)).unwrap();
        let cf_handle = db.cf_handle(cf_name.clone()).unwrap();
        let cf_opts = db.get_options_cf(cf_handle);
        assert!(cf_opts.get_level_compaction_dynamic_level_bytes());

        let (_, cf_descs) = load_latest_options(dbpath, &Env::default(), false)
            .unwrap()
            .unwrap();

        for cf_desc in cf_descs {
            if cf_desc.name() == cf_name {
                assert!(cf_desc.options().get_level_compaction_dynamic_level_bytes());
            } else {
                assert!(!cf_desc.options().get_level_compaction_dynamic_level_bytes());
            }
        }
    }

    #[test]
    fn test_sequence_number() {
        let path = tempdir_with_prefix("_rust_rocksdb_sequence_number");

        let mut opts = DBOptions::new();
        opts.create_if_missing(true);
        let db = DB::open(opts, path.path().to_str().unwrap()).unwrap();

        let snap = db.snapshot();
        let snap_seq = snap.get_sequence_number();
        let seq1 = db.get_latest_sequence_number();
        assert_eq!(snap_seq, seq1);

        db.put(b"key", b"value").unwrap();
        let seq2 = db.get_latest_sequence_number();
        assert!(seq2 > seq1);
    }

    #[test]
    fn test_atomic_flush() {
        let path = tempdir_with_prefix("_rust_rocksdb_test_atomic_flush");
        let cfs = ["default", "cf1", "cf2", "cf3"];
        let mut cfs_opts = vec![];
        for _ in 0..cfs.len() {
            cfs_opts.push(ColumnFamilyOptions::new());
        }

        {
            let mut opts = DBOptions::new();
            opts.create_if_missing(true);
            opts.set_atomic_flush(true);
            let mut db = DB::open(opts, path.path().to_str().unwrap()).unwrap();
            let wb = WriteBatch::new();
            for (cf, cf_opts) in cfs.iter().zip(cfs_opts.iter().cloned()) {
                if *cf != "default" {
                    db.create_cf((*cf, cf_opts)).unwrap();
                }
                let handle = db.cf_handle(cf).unwrap();
                wb.put_cf(handle, b"k", cf.as_bytes()).unwrap();
            }
            let mut options = WriteOptions::new();
            options.disable_wal(true);
            db.write_opt(&wb, &options).unwrap();
            let handles: Vec<_> = cfs.iter().map(|name| db.cf_handle(name).unwrap()).collect();
            db.flush_cfs(&handles, true).unwrap();
        }

        let opts = DBOptions::new();
        let db = DB::open_cf(
            opts,
            path.path().to_str().unwrap(),
            cfs.iter().map(|cf| *cf).zip(cfs_opts).collect(),
        )
        .unwrap();
        for cf in &cfs {
            let handle = db.cf_handle(cf).unwrap();
            assert_eq!(db.get_cf(handle, b"k").unwrap().unwrap(), cf.as_bytes());
        }
    }

    #[test]
    fn test_map_property() {
        let path = tempdir_with_prefix("_rust_rocksdb_get_map_property");
        let dbpath = path.path().to_str().unwrap().clone();

        let mut opts = DBOptions::new();
        opts.create_if_missing(true);
        let db = DB::open(opts, dbpath).unwrap();

        let cf_handle = db.cf_handle("default").unwrap();
        let mp = db.get_map_property_cf(cf_handle, "rocksdb.cfstats");
        assert!(mp.is_some());
    }

    #[test]
    fn test_multi_batch_write() {
        let mut opts = DBOptions::new();
        opts.create_if_missing(true);
        opts.enable_multi_batch_write(true);
        let path = tempdir_with_prefix("_rust_rocksdb_multi_batch");

        let db = DB::open(opts, path.path().to_str().unwrap()).unwrap();
        let cf = db.cf_handle("default").unwrap();
        let mut data = Vec::new();
        for s in &[b"ab", b"cd", b"ef"] {
            let w = WriteBatch::new();
            w.put_cf(cf, s.to_vec().as_slice(), b"a").unwrap();
            data.push(w);
        }
        db.multi_batch_write(&data, &WriteOptions::new()).unwrap();
        for s in &[b"ab", b"cd", b"ef"] {
            let v = db.get_cf(cf, s.to_vec().as_slice()).unwrap();
            assert!(v.is_some());
            assert_eq!(v.unwrap().to_utf8().unwrap(), "a");
        }
    }

    #[test]
    fn test_get_db_path_from_option() {
        let mut opts = DBOptions::new();
        opts.create_if_missing(true);
        let dir = tempdir_with_prefix("_rust_rocksdb_get_db_path_from_option");
        let path = dir.path().to_str().unwrap();
        let db = DB::open(opts, path).unwrap();
        let path_num = db.get_db_options().get_db_paths_num();
        assert_eq!(1, path_num);
        let first_path = db.get_db_options().get_db_path(0).unwrap();
        assert_eq!(path, first_path.as_str());
    }

    #[test]
    fn test_write_append() {
        let mut opts = DBOptions::new();
        opts.create_if_missing(true);
        let path = tempdir_with_prefix("_rust_rocksdb_multi_batch");

        let db = DB::open(opts, path.path().to_str().unwrap()).unwrap();
        let cf = db.cf_handle("default").unwrap();
        let mut wb = WriteBatch::new();
        for s in &[b"ab", b"cd", b"ef"] {
            let w = WriteBatch::new();
            w.put_cf(cf, s.to_vec().as_slice(), b"a").unwrap();
            wb.append(w.data());
        }
        db.write(&wb).unwrap();
        for s in &[b"ab", b"cd", b"ef"] {
            let v = db.get_cf(cf, s.to_vec().as_slice()).unwrap();
            assert!(v.is_some());
            assert_eq!(v.unwrap().to_utf8().unwrap(), "a");
        }
    }

    fn inner_test_write_batch_iter<F>(iter_fn: F)
    where
        F: FnOnce(&DB, &mut WriteBatch),
    {
        let temp_dir = tempdir_with_prefix("_rust_rocksdb_write_batch_iterate");
        let path = temp_dir.path().to_str().unwrap();
        let cfs = ["default", "cf1"];
        let mut cfs_opts = vec![];
        for _ in 0..cfs.len() {
            cfs_opts.push(ColumnFamilyOptions::new());
        }
        let mut opts = DBOptions::new();
        opts.create_if_missing(true);
        let mut db = DB::open(opts, path).unwrap();
        for (cf, cf_opts) in cfs.iter().zip(cfs_opts.iter().cloned()) {
            if *cf != "default" {
                db.create_cf((*cf, cf_opts)).unwrap();
            }
        }

        let mut wb = WriteBatch::new();
        let default_cf = db.cf_handle("default").unwrap();
        let cf1 = db.cf_handle("cf1").unwrap();
        db.put_cf(default_cf, b"k1", b"v0").unwrap();
        db.put_cf(cf1, b"k1", b"v0").unwrap();

        wb.put_cf(default_cf, b"k2", b"v1").unwrap();
        wb.put_cf(cf1, b"k2", b"v1").unwrap();
        wb.delete_cf(default_cf, b"k1").unwrap();
        wb.delete_cf(cf1, b"k1").unwrap();
        iter_fn(&db, &mut wb);

        for cf in &["default", "cf1"] {
            let handle = db.cf_handle(cf).unwrap();
            let v0 = db.get_cf(handle, b"k1").unwrap();
            assert!(v0.is_none());

            let v1 = db.get_cf(handle, b"k2").unwrap();
            assert!(v1.is_some());
            assert_eq!(v1.unwrap().to_utf8().unwrap(), "v1");
        }
    }

    #[test]
    fn test_write_batch_iterate() {
        inner_test_write_batch_iter(|db, wb| {
            let cf_names = db.cf_names();
            wb.iterate(&cf_names, |cf, write_type, key, value| {
                let handle = db.cf_handle(cf).unwrap();
                match write_type {
                    DBValueType::TypeValue => {
                        db.put_cf(handle, key, value.unwrap()).unwrap();
                    }
                    DBValueType::TypeDeletion => {
                        db.delete_cf(handle, key).unwrap();
                    }
                    _ => (),
                }
            });
        });
    }

    #[test]
    fn test_write_batch_ref_iter() {
        inner_test_write_batch_iter(|db, wb| {
            let wb_ref = WriteBatchRef::new(wb.data());
            assert_eq!(wb.count(), wb_ref.count());
            for (value_type, c, key, value) in wb_ref.iter() {
                let handle = db.cf_handle_by_id(c as usize).unwrap();
                match value_type {
                    DBValueType::TypeValue => {
                        db.put_cf(handle, key, value).unwrap();
                    }
                    DBValueType::TypeDeletion => {
                        db.delete_cf(handle, key).unwrap();
                    }
                    _ => {
                        println!("error type, cf: {}", c);
                    }
                }
            }
        });
    }

    #[test]
    fn test_write_batch_iter() {
        inner_test_write_batch_iter(|db, wb| {
            for (value_type, c, key, value) in wb.iter() {
                let handle = db.cf_handle_by_id(c as usize).unwrap();
                match value_type {
                    DBValueType::TypeValue => {
                        db.put_cf(handle, key, value).unwrap();
                    }
                    DBValueType::TypeDeletion => {
                        db.delete_cf(handle, key).unwrap();
                    }
                    _ => {
                        println!("error type, cf: {}", c);
                    }
                }
            }
        });
    }
}