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
// Copyright 2017 LambdaStack All rights reserved.
//
// 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.
#![cfg(unix)]
#![allow(unused_imports)]

use crate::JsonData;

use crate::admin_sockets::*;
use crate::error::*;
use crate::json::*;
use crate::JsonValue;
use byteorder::{LittleEndian, WriteBytesExt};
use futures::task::SpawnExt;
use libc::*;
use nom::number::complete::le_u32;
use nom::IResult;
use serde_json;

use crate::completion::with_completion;
use crate::rados::*;
#[cfg(feature = "rados_striper")]
use crate::rados_striper::*;
use crate::status::*;
use std::ffi::{CStr, CString};
use std::marker::PhantomData;
use std::{ptr, str};

use crate::utils::*;
use std::io::{BufRead, Cursor};
use std::net::IpAddr;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use crate::list_stream::ListStream;
use crate::read_stream::ReadStream;
pub use crate::write_sink::WriteSink;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use uuid::Uuid;

const CEPH_OSD_TMAP_HDR: char = 'h';
const CEPH_OSD_TMAP_SET: char = 's';
const CEPH_OSD_TMAP_CREATE: char = 'c';
const CEPH_OSD_TMAP_RM: char = 'r';

const DEFAULT_READ_BYTES: usize = 64 * 1024;

#[derive(Debug, Clone)]
pub enum CephHealth {
    Ok,
    Warning,
    Error,
}

#[derive(Debug, Clone)]
pub enum CephCommandTypes {
    Mon,
    Osd,
    Pgs,
}

named!(
    parse_header<TmapOperation>,
    do_parse!(
        char!(CEPH_OSD_TMAP_HDR)
            >> data_len: le_u32
            >> data: take!(data_len)
            >> (TmapOperation::Header {
                data: data.to_vec()
            })
    )
);

named!(
    parse_create<TmapOperation>,
    do_parse!(
        char!(CEPH_OSD_TMAP_CREATE)
            >> key_name_len: le_u32
            >> key_name: take_str!(key_name_len)
            >> data_len: le_u32
            >> data: take!(data_len)
            >> (TmapOperation::Create {
                name: key_name.to_string(),
                data: data.to_vec(),
            })
    )
);

named!(
    parse_set<TmapOperation>,
    do_parse!(
        char!(CEPH_OSD_TMAP_SET)
            >> key_name_len: le_u32
            >> key_name: take_str!(key_name_len)
            >> data_len: le_u32
            >> data: take!(data_len)
            >> (TmapOperation::Set {
                key: key_name.to_string(),
                data: data.to_vec(),
            })
    )
);

named!(
    parse_remove<TmapOperation>,
    do_parse!(
        char!(CEPH_OSD_TMAP_RM)
            >> key_name_len: le_u32
            >> key_name: take_str!(key_name_len)
            >> (TmapOperation::Remove {
                name: key_name.to_string(),
            })
    )
);

#[derive(Debug)]
pub enum TmapOperation {
    Header { data: Vec<u8> },
    Set { key: String, data: Vec<u8> },
    Create { name: String, data: Vec<u8> },
    Remove { name: String },
}

impl TmapOperation {
    fn serialize(&self) -> RadosResult<Vec<u8>> {
        let mut buffer: Vec<u8> = Vec::new();
        match *self {
            TmapOperation::Header { ref data } => {
                buffer.push(CEPH_OSD_TMAP_HDR as u8);
                buffer.write_u32::<LittleEndian>(data.len() as u32)?;
                buffer.extend_from_slice(data);
            }
            TmapOperation::Set { ref key, ref data } => {
                buffer.push(CEPH_OSD_TMAP_SET as u8);
                buffer.write_u32::<LittleEndian>(key.len() as u32)?;
                buffer.extend(key.as_bytes());
                buffer.write_u32::<LittleEndian>(data.len() as u32)?;
                buffer.extend_from_slice(data);
            }
            TmapOperation::Create { ref name, ref data } => {
                buffer.push(CEPH_OSD_TMAP_CREATE as u8);
                buffer.write_u32::<LittleEndian>(name.len() as u32)?;
                buffer.extend(name.as_bytes());
                buffer.write_u32::<LittleEndian>(data.len() as u32)?;
                buffer.extend_from_slice(data);
            }
            TmapOperation::Remove { ref name } => {
                buffer.push(CEPH_OSD_TMAP_RM as u8);
                buffer.write_u32::<LittleEndian>(name.len() as u32)?;
                buffer.extend(name.as_bytes());
            }
        }
        Ok(buffer)
    }

    fn deserialize(input: &[u8]) -> IResult<&[u8], Vec<TmapOperation>> {
        many0!(
            input,
            alt!(
                complete!(parse_header)
                    | complete!(parse_create)
                    | complete!(parse_set)
                    | complete!(parse_remove)
            )
        )
    }
}

/// Helper to iterate over pool objects
#[derive(Debug)]
pub struct Pool {
    pub ctx: rados_list_ctx_t,
}

#[derive(Debug)]
pub struct CephObject {
    pub name: String,
    pub entry_locator: String,
    pub namespace: String,
}

impl Iterator for Pool {
    type Item = CephObject;
    fn next(&mut self) -> Option<CephObject> {
        let mut entry_ptr: *mut *const ::libc::c_char = ptr::null_mut();
        let mut key_ptr: *mut *const ::libc::c_char = ptr::null_mut();
        let mut nspace_ptr: *mut *const ::libc::c_char = ptr::null_mut();

        unsafe {
            let ret_code =
                rados_nobjects_list_next(self.ctx, &mut entry_ptr, &mut key_ptr, &mut nspace_ptr);
            if ret_code == -ENOENT {
                // We're done
                rados_nobjects_list_close(self.ctx);
                None
            } else if ret_code < 0 {
                // Unknown error
                None
            } else {
                let object_name = CStr::from_ptr(entry_ptr as *const ::libc::c_char);
                let mut object_locator = String::new();
                let mut namespace = String::new();
                if !key_ptr.is_null() {
                    object_locator.push_str(
                        &CStr::from_ptr(key_ptr as *const ::libc::c_char).to_string_lossy(),
                    );
                }
                if !nspace_ptr.is_null() {
                    namespace.push_str(
                        &CStr::from_ptr(nspace_ptr as *const ::libc::c_char).to_string_lossy(),
                    );
                }

                Some(CephObject {
                    name: object_name.to_string_lossy().into_owned(),
                    entry_locator: object_locator,
                    namespace,
                })
            }
        }
    }
}

/// A helper to create rados read operation
/// An object read operation stores a number of operations which can be
/// executed atomically.
#[derive(Debug)]
pub struct ReadOperation {
    pub object_name: String,
    /// flags are set by calling LIBRADOS_OPERATION_NOFLAG |
    /// LIBRADOS_OPERATION_BALANCE_READS
    /// all the other flags are documented in rados.rs
    pub flags: u32,
    read_op_handle: rados_read_op_t,
}

impl Drop for ReadOperation {
    fn drop(&mut self) {
        unsafe {
            rados_release_read_op(self.read_op_handle);
        }
    }
}

/// A helper to create rados write operation
/// An object write operation stores a number of operations which can be
/// executed atomically.
#[derive(Debug)]
pub struct WriteOperation {
    pub object_name: String,
    /// flags are set by calling LIBRADOS_OPERATION_NOFLAG |
    /// LIBRADOS_OPERATION_ORDER_READS_WRITES
    /// all the other flags are documented in rados.rs
    pub flags: u32,
    pub mtime: time_t,
    write_op_handle: rados_write_op_t,
}

impl Drop for WriteOperation {
    fn drop(&mut self) {
        unsafe {
            rados_release_write_op(self.write_op_handle);
        }
    }
}

/// A rados object extended attribute with name and value.
/// Can be iterated over
#[derive(Debug)]
pub struct XAttr {
    pub name: String,
    pub value: String,
    iter: rados_xattrs_iter_t,
}

/// The version of the librados library.
#[derive(Debug)]
pub struct RadosVersion {
    pub major: i32,
    pub minor: i32,
    pub extra: i32,
}

impl XAttr {
    /// Creates a new XAttr.  Call rados_getxattrs to create the iterator for
    /// this struct
    pub fn new(iter: rados_xattrs_iter_t) -> XAttr {
        XAttr {
            name: String::new(),
            value: String::new(),
            iter,
        }
    }
}

impl Iterator for XAttr {
    type Item = XAttr;

    fn next(&mut self) -> Option<Self::Item> {
        // max xattr name is 255 bytes from what I can find
        let mut name: *const c_char = ptr::null();
        // max xattr is 64Kb from what I can find
        let mut value: *const c_char = ptr::null();
        let mut val_length: usize = 0;
        unsafe {
            let ret_code = rados_getxattrs_next(self.iter, &mut name, &mut value, &mut val_length);

            if ret_code < 0 {
                // Something failed, however Iterator doesn't return Result so we return None
                None
            }
            // end of iterator reached
            else if value.is_null() && val_length == 0 {
                rados_getxattrs_end(self.iter);
                None
            } else {
                let name = CStr::from_ptr(name);
                // value string
                let s_bytes = std::slice::from_raw_parts(value, val_length);
                // Convert from i8 -> u8
                let bytes: Vec<u8> = s_bytes.iter().map(|c| *c as u8).collect();
                Some(XAttr {
                    name: name.to_string_lossy().into_owned(),
                    value: String::from_utf8_lossy(&bytes).into_owned(),
                    iter: self.iter,
                })
            }
        }
    }
}

/// Owns a ioctx handle
pub struct IoCtx {
    // This is pub within the crate to enable Completions to use it
    pub ioctx: rados_ioctx_t,
}

unsafe impl Send for IoCtx {}
unsafe impl Sync for IoCtx {}

impl Drop for IoCtx {
    fn drop(&mut self) {
        if !self.ioctx.is_null() {
            unsafe {
                rados_ioctx_destroy(self.ioctx);
            }
        }
    }
}

/// Owns a rados_striper handle
#[cfg(feature = "rados_striper")]
pub struct RadosStriper {
    rados_striper: rados_ioctx_t,
}

#[cfg(feature = "rados_striper")]
impl Drop for RadosStriper {
    fn drop(&mut self) {
        if !self.rados_striper.is_null() {
            unsafe {
                rados_striper_destroy(self.rados_striper);
            }
        }
    }
}

/// Owns a rados handle
pub struct Rados {
    rados: rados_t,
    phantom: PhantomData<IoCtx>,
}

unsafe impl Send for Rados {}
unsafe impl Sync for Rados {}

impl Drop for Rados {
    fn drop(&mut self) {
        if !self.rados.is_null() {
            unsafe {
                rados_shutdown(self.rados);
            }
        }
    }
}

/// Connect to a Ceph cluster and return a connection handle rados_t
pub fn connect_to_ceph(user_id: &str, config_file: &str) -> RadosResult<Rados> {
    let connect_id = CString::new(user_id)?;
    let conf_file = CString::new(config_file)?;
    unsafe {
        let mut cluster_handle: rados_t = ptr::null_mut();
        let ret_code = rados_create(&mut cluster_handle, connect_id.as_ptr());
        if ret_code < 0 {
            return Err(ret_code.into());
        }
        let ret_code = rados_conf_read_file(cluster_handle, conf_file.as_ptr());
        if ret_code < 0 {
            return Err(ret_code.into());
        }
        let ret_code = rados_connect(cluster_handle);
        if ret_code < 0 {
            return Err(ret_code.into());
        }
        Ok(Rados {
            rados: cluster_handle,
            phantom: PhantomData,
        })
    }
}

/// Non-blocking wrapper for `connect_to_ceph`
pub async fn connect_to_ceph_async(user_id: &str, config_file: &str) -> RadosResult<Rados> {
    let user_id = user_id.to_string();
    let config_file = config_file.to_string();

    // librados doesn't have async initialization, so wrap it in a thread pool.
    let pool = futures::executor::ThreadPool::builder()
        .pool_size(1)
        .create()
        .expect("Could not spawn thread pool");
    pool.spawn_with_handle(async move { connect_to_ceph(&user_id, &config_file) })
        .expect("Could not spawn background task")
        .await
}

impl Rados {
    pub fn inner(&self) -> &rados_t {
        &self.rados
    }

    /// Disconnect from a Ceph cluster and destroy the connection handle rados_t
    /// For clean up, this is only necessary after connect_to_ceph() has
    /// succeeded.
    pub fn disconnect_from_ceph(&self) {
        if self.rados.is_null() {
            // No need to do anything
            return;
        }
        unsafe {
            rados_shutdown(self.rados);
        }
    }

    fn conn_guard(&self) -> RadosResult<()> {
        if self.rados.is_null() {
            return Err(RadosError::new(
                "Rados not connected.  Please initialize cluster".to_string(),
            ));
        }
        Ok(())
    }

    /// Set the value of a configuration option
    pub fn config_set(&self, name: &str, value: &str) -> RadosResult<()> {
        if !self.rados.is_null() {
            return Err(RadosError::new(
                "Rados should not be connected when this function is called".into(),
            ));
        }
        let name_str = CString::new(name)?;
        let value_str = CString::new(value)?;
        unsafe {
            let ret_code = rados_conf_set(self.rados, name_str.as_ptr(), value_str.as_ptr());
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }

    /// Get the value of a configuration option
    pub fn config_get(&self, name: &str) -> RadosResult<String> {
        let name_str = CString::new(name)?;
        // 5K should be plenty for a config key right?
        let mut buffer: Vec<u8> = Vec::with_capacity(5120);
        unsafe {
            let ret_code = rados_conf_get(
                self.rados,
                name_str.as_ptr(),
                buffer.as_mut_ptr() as *mut c_char,
                buffer.capacity(),
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
            // Ceph doesn't return how many bytes were written
            buffer.set_len(5120);
            // We need to search for the first NUL byte
            let num_bytes = buffer.iter().position(|x| x == &0u8);
            buffer.set_len(num_bytes.unwrap_or(0));
            Ok(String::from_utf8_lossy(&buffer).into_owned())
        }
    }

    /// Create an io context. The io context allows you to perform operations
    /// within a particular pool.
    /// For more details see rados_ioctx_t.
    pub fn get_rados_ioctx(&self, pool_name: &str) -> RadosResult<IoCtx> {
        self.conn_guard()?;
        let pool_name_str = CString::new(pool_name)?;
        unsafe {
            let mut ioctx: rados_ioctx_t = ptr::null_mut();
            let ret_code = rados_ioctx_create(self.rados, pool_name_str.as_ptr(), &mut ioctx);
            if ret_code < 0 {
                return Err(ret_code.into());
            }
            Ok(IoCtx { ioctx })
        }
    }

    /// Create an io context. The io context allows you to perform operations
    /// within a particular pool.
    /// For more details see rados_ioctx_t.
    pub fn get_rados_ioctx2(&self, pool_id: i64) -> RadosResult<IoCtx> {
        self.conn_guard()?;
        unsafe {
            let mut ioctx: rados_ioctx_t = ptr::null_mut();
            let ret_code = rados_ioctx_create2(self.rados, pool_id, &mut ioctx);
            if ret_code < 0 {
                return Err(ret_code.into());
            }
            Ok(IoCtx { ioctx })
        }
    }
}

impl IoCtx {
    pub fn inner(&self) -> &rados_ioctx_t {
        &self.ioctx
    }

    /// This just tells librados that you no longer need to use the io context.
    /// It may not be freed immediately if there are pending asynchronous
    /// requests on it, but you
    /// should not use an io context again after calling this function on it.
    /// This does not guarantee any asynchronous writes have completed. You must
    /// call rados_aio_flush()
    /// on the io context before destroying it to do that.
    pub fn destroy_rados_ioctx(&self) {
        if self.ioctx.is_null() {
            // No need to do anything
            return;
        }
        unsafe {
            rados_ioctx_destroy(self.ioctx);
        }
    }
    fn ioctx_guard(&self) -> RadosResult<()> {
        if self.ioctx.is_null() {
            return Err(RadosError::new(
                "Rados ioctx not created.  Please initialize first".to_string(),
            ));
        }
        Ok(())
    }
    /// Note: Ceph uses kibibytes: https://en.wikipedia.org/wiki/Kibibyte
    pub fn rados_stat_pool(&self) -> RadosResult<Struct_rados_pool_stat_t> {
        self.ioctx_guard()?;
        let mut pool_stat = Struct_rados_pool_stat_t::default();
        unsafe {
            let ret_code = rados_ioctx_pool_stat(self.ioctx, &mut pool_stat);
            if ret_code < 0 {
                return Err(ret_code.into());
            }
            Ok(pool_stat)
        }
    }

    pub fn rados_pool_set_auid(&self, auid: u64) -> RadosResult<()> {
        self.ioctx_guard()?;
        unsafe {
            let ret_code = rados_ioctx_pool_set_auid(self.ioctx, auid);
            if ret_code < 0 {
                return Err(ret_code.into());
            }
            Ok(())
        }
    }

    pub fn rados_pool_get_auid(&self) -> RadosResult<u64> {
        self.ioctx_guard()?;
        let mut auid: u64 = 0;
        unsafe {
            let ret_code = rados_ioctx_pool_get_auid(self.ioctx, &mut auid);
            if ret_code < 0 {
                return Err(ret_code.into());
            }
            Ok(auid)
        }
    }

    /// Test whether the specified pool requires alignment or not.
    pub fn rados_pool_requires_alignment(&self) -> RadosResult<bool> {
        self.ioctx_guard()?;
        unsafe {
            let ret_code = rados_ioctx_pool_requires_alignment(self.ioctx);
            if ret_code < 0 {
                return Err(ret_code.into());
            }
            if ret_code == 0 {
                Ok(false)
            } else {
                Ok(true)
            }
        }
    }

    /// Get the alignment flavor of a pool
    pub fn rados_pool_required_alignment(&self) -> RadosResult<u64> {
        self.ioctx_guard()?;
        unsafe {
            let ret_code = rados_ioctx_pool_required_alignment(self.ioctx);
            Ok(ret_code)
        }
    }

    /// Get the pool id of the io context
    pub fn rados_object_get_id(&self) -> RadosResult<i64> {
        self.ioctx_guard()?;
        unsafe {
            let pool_id = rados_ioctx_get_id(self.ioctx);
            Ok(pool_id)
        }
    }

    /// Get the pool name of the io context
    pub fn rados_get_pool_name(&self) -> RadosResult<String> {
        self.ioctx_guard()?;
        let mut buffer: Vec<u8> = Vec::with_capacity(500);

        unsafe {
            // length of string stored, or -ERANGE if buffer too small
            let ret_code = rados_ioctx_get_pool_name(
                self.ioctx,
                buffer.as_mut_ptr() as *mut c_char,
                buffer.capacity() as c_uint,
            );
            if ret_code == -ERANGE {
                // Buffer was too small
                buffer.reserve(1000);
                buffer.set_len(1000);
                let ret_code = rados_ioctx_get_pool_name(
                    self.ioctx,
                    buffer.as_mut_ptr() as *mut c_char,
                    buffer.capacity() as c_uint,
                );
                if ret_code < 0 {
                    return Err(ret_code.into());
                }
                Ok(String::from_utf8_lossy(&buffer).into_owned())
            } else if ret_code < 0 {
                Err(ret_code.into())
            } else {
                buffer.set_len(ret_code as usize);
                Ok(String::from_utf8_lossy(&buffer).into_owned())
            }
        }
    }

    /// Set the key for mapping objects to pgs within an io context.
    pub fn rados_locator_set_key(&self, key: &str) -> RadosResult<()> {
        self.ioctx_guard()?;
        let key_str = CString::new(key)?;
        unsafe {
            rados_ioctx_locator_set_key(self.ioctx, key_str.as_ptr());
        }
        Ok(())
    }

    /// Set the namespace for objects within an io context
    /// The namespace specification further refines a pool into different
    /// domains. The mapping of objects to pgs is also based on this value.
    pub fn rados_set_namespace(&self, namespace: &str) -> RadosResult<()> {
        self.ioctx_guard()?;
        let namespace_str = CString::new(namespace)?;
        unsafe {
            rados_ioctx_set_namespace(self.ioctx, namespace_str.as_ptr());
        }
        Ok(())
    }

    /// Start listing objects in a pool
    pub fn rados_list_pool_objects(&self) -> RadosResult<rados_list_ctx_t> {
        self.ioctx_guard()?;
        let mut rados_list_ctx: rados_list_ctx_t = ptr::null_mut();
        unsafe {
            let ret_code = rados_nobjects_list_open(self.ioctx, &mut rados_list_ctx);
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(rados_list_ctx)
    }

    /// Create a pool-wide snapshot
    pub fn rados_snap_create(&self, snap_name: &str) -> RadosResult<()> {
        self.ioctx_guard()?;

        let snap_name_str = CString::new(snap_name)?;
        unsafe {
            let ret_code = rados_ioctx_snap_create(self.ioctx, snap_name_str.as_ptr());
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }

    /// Delete a pool snapshot
    pub fn rados_snap_remove(&self, snap_name: &str) -> RadosResult<()> {
        self.ioctx_guard()?;
        let snap_name_str = CString::new(snap_name)?;

        unsafe {
            let ret_code = rados_ioctx_snap_remove(self.ioctx, snap_name_str.as_ptr());
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }

    /// Rollback an object to a pool snapshot
    /// The contents of the object will be the same as when the snapshot was
    /// taken.
    pub fn rados_snap_rollback(&self, object_name: &str, snap_name: &str) -> RadosResult<()> {
        self.ioctx_guard()?;
        let snap_name_str = CString::new(snap_name)?;
        let object_name_str = CString::new(object_name)?;

        unsafe {
            let ret_code = rados_ioctx_snap_rollback(
                self.ioctx,
                object_name_str.as_ptr(),
                snap_name_str.as_ptr(),
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }

    /// Set the snapshot from which reads are performed.
    /// Subsequent reads will return data as it was at the time of that
    /// snapshot.
    pub fn rados_snap_set_read(&self, snap_id: u64) -> RadosResult<()> {
        self.ioctx_guard()?;

        unsafe {
            rados_ioctx_snap_set_read(self.ioctx, snap_id);
        }
        Ok(())
    }

    /// Allocate an ID for a self-managed snapshot
    /// Get a unique ID to put in the snaphot context to create a snapshot.
    /// A clone of an object is not created until a write with the new snapshot
    /// context is completed.
    pub fn rados_selfmanaged_snap_create(&self) -> RadosResult<u64> {
        self.ioctx_guard()?;
        let mut snap_id: u64 = 0;
        unsafe {
            let ret_code = rados_ioctx_selfmanaged_snap_create(self.ioctx, &mut snap_id);
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(snap_id)
    }

    /// Remove a self-managed snapshot
    /// This increases the snapshot sequence number, which will cause snapshots
    /// to be removed lazily.
    pub fn rados_selfmanaged_snap_remove(&self, snap_id: u64) -> RadosResult<()> {
        self.ioctx_guard()?;

        unsafe {
            let ret_code = rados_ioctx_selfmanaged_snap_remove(self.ioctx, snap_id);
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }

    /// Rollback an object to a self-managed snapshot
    /// The contents of the object will be the same as when the snapshot was
    /// taken.
    pub fn rados_selfmanaged_snap_rollback(
        &self,
        object_name: &str,
        snap_id: u64,
    ) -> RadosResult<()> {
        self.ioctx_guard()?;
        let object_name_str = CString::new(object_name)?;

        unsafe {
            let ret_code = rados_ioctx_selfmanaged_snap_rollback(
                self.ioctx,
                object_name_str.as_ptr(),
                snap_id,
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }

    /// Set the snapshot context for use when writing to objects
    /// This is stored in the io context, and applies to all future writes.
    // pub fn rados_selfmanaged_snap_set_write_ctx(ctx: rados_ioctx_t) ->
    // RadosResult<()> {
    // if ctx.is_null() {
    // return Err(RadosError::new("Rados ioctx not created.  Please initialize
    // first".to_string()));
    // }
    //
    // unsafe {
    // }
    // }
    /// List all the ids of pool snapshots
    // pub fn rados_snap_list(ctx: rados_ioctx_t, snaps: *mut rados_snap_t) ->
    // RadosResult<()> {
    // if ctx.is_null() {
    // return Err(RadosError::new("Rados ioctx not created.  Please initialize
    // first".to_string()));
    // }
    // let mut buffer: Vec<u64> = Vec::with_capacity(500);
    //
    //
    // unsafe {
    // let ret_code = rados_ioctx_snap_list(ctx, &mut buffer, buffer.capacity());
    // if ret_code == -ERANGE {
    // }
    // if ret_code < 0 {
    // return Err(ret_code.into());
    // }
    // }
    // Ok(buffer)
    // }
    /// Get the id of a pool snapshot
    pub fn rados_snap_lookup(&self, snap_name: &str) -> RadosResult<u64> {
        self.ioctx_guard()?;
        let snap_name_str = CString::new(snap_name)?;
        let mut snap_id: u64 = 0;
        unsafe {
            let ret_code =
                rados_ioctx_snap_lookup(self.ioctx, snap_name_str.as_ptr(), &mut snap_id);
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(snap_id)
    }

    /// Get the name of a pool snapshot
    pub fn rados_snap_get_name(&self, snap_id: u64) -> RadosResult<String> {
        self.ioctx_guard()?;

        let out_buffer: Vec<u8> = Vec::with_capacity(500);
        let out_buff_size = out_buffer.capacity();
        let out_str = CString::new(out_buffer)?;
        unsafe {
            let ret_code = rados_ioctx_snap_get_name(
                self.ioctx,
                snap_id,
                out_str.as_ptr() as *mut c_char,
                out_buff_size as c_int,
            );
            if ret_code == -ERANGE {}
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(out_str.to_string_lossy().into_owned())
    }

    /// Find when a pool snapshot occurred
    pub fn rados_snap_get_stamp(&self, snap_id: u64) -> RadosResult<time_t> {
        self.ioctx_guard()?;

        let mut time_id: time_t = 0;
        unsafe {
            let ret_code = rados_ioctx_snap_get_stamp(self.ioctx, snap_id, &mut time_id);
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(time_id)
    }

    /// Return the version of the last object read or written to.
    /// This exposes the internal version number of the last object read or
    /// written via this io context
    pub fn rados_get_object_last_version(&self) -> RadosResult<u64> {
        self.ioctx_guard()?;
        unsafe {
            let obj_id = rados_get_last_version(self.ioctx);
            Ok(obj_id)
        }
    }

    /// Write len bytes from buf into the oid object, starting at offset off.
    /// The value of len must be <= UINT_MAX/2.
    pub fn rados_object_write(
        &self,
        object_name: &str,
        buffer: &[u8],
        offset: u64,
    ) -> RadosResult<()> {
        self.ioctx_guard()?;
        let obj_name_str = CString::new(object_name)?;

        unsafe {
            let ret_code = rados_write(
                self.ioctx,
                obj_name_str.as_ptr(),
                buffer.as_ptr() as *const c_char,
                buffer.len(),
                offset,
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }

    /// The object is filled with the provided data. If the object exists, it is
    /// atomically
    /// truncated and then written.
    pub fn rados_object_write_full(&self, object_name: &str, buffer: &[u8]) -> RadosResult<()> {
        self.ioctx_guard()?;
        let obj_name_str = CString::new(object_name)?;

        unsafe {
            let ret_code = rados_write_full(
                self.ioctx,
                obj_name_str.as_ptr(),
                buffer.as_ptr() as *const ::libc::c_char,
                buffer.len(),
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }

    pub async fn rados_async_object_write(
        &self,
        object_name: &str,
        buffer: &[u8],
        offset: u64,
    ) -> RadosResult<u32> {
        self.ioctx_guard()?;
        let obj_name_str = CString::new(object_name)?;

        with_completion(&self, |c| unsafe {
            rados_aio_write(
                self.ioctx,
                obj_name_str.as_ptr(),
                c,
                buffer.as_ptr() as *const ::libc::c_char,
                buffer.len(),
                offset,
            )
        })?
        .await
    }

    /// Async variant of rados_object_append
    pub async fn rados_async_object_append(
        self: &Arc<Self>,
        object_name: &str,
        buffer: &[u8],
    ) -> RadosResult<u32> {
        self.ioctx_guard()?;
        let obj_name_str = CString::new(object_name)?;

        with_completion(self, |c| unsafe {
            rados_aio_append(
                self.ioctx,
                obj_name_str.as_ptr(),
                c,
                buffer.as_ptr() as *const ::libc::c_char,
                buffer.len(),
            )
        })?
        .await
    }

    /// Async variant of rados_object_write_full
    pub async fn rados_async_object_write_full(
        &self,
        object_name: &str,
        buffer: &[u8],
    ) -> RadosResult<u32> {
        self.ioctx_guard()?;
        let obj_name_str = CString::new(object_name)?;

        with_completion(&self, |c| unsafe {
            rados_aio_write_full(
                self.ioctx,
                obj_name_str.as_ptr(),
                c,
                buffer.as_ptr() as *const ::libc::c_char,
                buffer.len(),
            )
        })?
        .await
    }

    /// Async variant of rados_object_remove
    pub async fn rados_async_object_remove(&self, object_name: &str) -> RadosResult<()> {
        self.ioctx_guard()?;
        let object_name_str = CString::new(object_name)?;

        with_completion(self, |c| unsafe {
            rados_aio_remove(self.ioctx, object_name_str.as_ptr() as *const c_char, c)
        })?
        .await
        .map(|_r| ())
    }

    /// Async variant of rados_object_read
    pub async fn rados_async_object_read(
        self: &Arc<Self>,
        object_name: &str,
        fill_buffer: &mut Vec<u8>,
        read_offset: u64,
    ) -> RadosResult<u32> {
        self.ioctx_guard()?;
        let obj_name_str = CString::new(object_name)?;

        if fill_buffer.capacity() == 0 {
            fill_buffer.reserve_exact(DEFAULT_READ_BYTES);
        }

        let result = with_completion(self, |c| unsafe {
            rados_aio_read(
                self.ioctx,
                obj_name_str.as_ptr(),
                c,
                fill_buffer.as_mut_ptr() as *mut c_char,
                fill_buffer.capacity(),
                read_offset,
            )
        })?
        .await;

        if let Ok(rval) = &result {
            unsafe {
                let len = *rval as usize;
                assert!(len <= fill_buffer.capacity());
                fill_buffer.set_len(len);
            }
        }

        result
    }

    /// Streaming read of a RADOS object.  The `ReadStream` object implements `futures::Stream`
    /// for use with Stream-aware code like hyper's Body::wrap_stream.
    ///
    /// Useful for reading large objects incrementally, or anywhere you are using an interface
    /// that expects a stream (such as proxying objects via an HTTP server).
    ///
    /// Efficiency: If size_hint is not specified, and this function is used on a small object, it will
    /// issue spurious read-ahead operations beyond the object's size.
    /// If you have an object that you know is small, prefer to use a single `rados_async_object_read`
    /// instead of this streaming variant.
    ///
    /// * `buffer_size` - How much data should be read per rados read operation.  This is also
    ///   how much data is emitted in each Item from the stream.
    /// * `concurrency` - How many RADOS operations should be run in parallel for this stream,
    ///   or None to use a default.
    /// * `size_hint` - If you have prior knowledge of the object's size in bytes, pass it here to enable
    ///   the stream to issue fewer read-ahead operations than it would by default.  This is just
    ///   a hint, and does not bound the data returned -- if the object is smaller or larger
    ///   than `size_hint` then the actual object size will be reflected in the stream's output.
    pub fn rados_async_object_read_stream(
        &self,
        object_name: &str,
        buffer_size: Option<usize>,
        concurrency: Option<usize>,
        size_hint: Option<u64>,
    ) -> ReadStream<'_> {
        ReadStream::new(self, object_name, buffer_size, concurrency, size_hint)
    }

    /// Streaming write of a RADOS object.  The `WriteSink` object implements `futures::Sink`.  Combine
    /// it with other stream-aware code, or bring the SinkExt trait into scope to get methods
    /// like send, send_all.
    ///
    /// Efficiency: this class does not coalesce writes, so each Item you send into it,
    ///
    ///
    /// * `concurrency` - How many RADOS operations should be run in parallel for this stream,
    ///   or None to use a default.
    pub fn rados_async_object_write_stream(
        &self,
        object_name: &str,
        concurrency: Option<usize>,
    ) -> WriteSink<'_> {
        WriteSink::new(self, object_name, concurrency)
    }

    /// Get object stats (size,SystemTime)
    pub async fn rados_async_object_stat(
        &self,
        object_name: &str,
    ) -> RadosResult<(u64, SystemTime)> {
        self.ioctx_guard()?;
        let object_name_str = CString::new(object_name)?;
        let mut psize: u64 = 0;
        let mut time: ::libc::time_t = 0;

        with_completion(self, |c| unsafe {
            rados_aio_stat(
                self.ioctx,
                object_name_str.as_ptr(),
                c,
                &mut psize,
                &mut time,
            )
        })?
        .await?;
        Ok((psize, (UNIX_EPOCH + Duration::from_secs(time as u64))))
    }

    pub fn rados_async_object_list(&self) -> RadosResult<ListStream> {
        self.ioctx_guard()?;
        let mut rados_list_ctx: rados_list_ctx_t = ptr::null_mut();
        unsafe {
            let r = rados_nobjects_list_open(self.ioctx, &mut rados_list_ctx);
            if r == 0 {
                Ok(ListStream::new(rados_list_ctx))
            } else {
                Err(r.into())
            }
        }
    }

    /// Async variant of rados_object_getxattr
    pub async fn rados_async_object_getxattr(
        &self,
        object_name: &str,
        attr_name: &str,
        fill_buffer: &mut [u8],
    ) -> RadosResult<u32> {
        self.ioctx_guard()?;
        let object_name_str = CString::new(object_name)?;
        let attr_name_str = CString::new(attr_name)?;

        with_completion(self, |c| unsafe {
            rados_aio_getxattr(
                self.ioctx,
                object_name_str.as_ptr() as *const c_char,
                c,
                attr_name_str.as_ptr() as *const c_char,
                fill_buffer.as_mut_ptr() as *mut c_char,
                fill_buffer.len(),
            )
        })?
        .await
    }

    /// Async variant of rados_object_setxattr
    pub async fn rados_async_object_setxattr(
        &self,
        object_name: &str,
        attr_name: &str,
        attr_value: &[u8],
    ) -> RadosResult<u32> {
        self.ioctx_guard()?;
        let object_name_str = CString::new(object_name)?;
        let attr_name_str = CString::new(attr_name)?;

        with_completion(self, |c| unsafe {
            rados_aio_setxattr(
                self.ioctx,
                object_name_str.as_ptr() as *const c_char,
                c,
                attr_name_str.as_ptr() as *const c_char,
                attr_value.as_ptr() as *mut c_char,
                attr_value.len(),
            )
        })?
        .await
    }

    /// Async variant of rados_object_rmxattr
    pub async fn rados_async_object_rmxattr(
        &self,
        object_name: &str,
        attr_name: &str,
    ) -> RadosResult<u32> {
        self.ioctx_guard()?;
        let object_name_str = CString::new(object_name)?;
        let attr_name_str = CString::new(attr_name)?;

        with_completion(self, |c| unsafe {
            rados_aio_rmxattr(
                self.ioctx,
                object_name_str.as_ptr() as *const c_char,
                c,
                attr_name_str.as_ptr() as *const c_char,
            )
        })?
        .await
    }

    /// Efficiently copy a portion of one object to another
    /// If the underlying filesystem on the OSD supports it, this will be a
    /// copy-on-write clone.
    /// The src and dest objects must be in the same pg. To ensure this, the io
    /// context should
    /// have a locator key set (see rados_ioctx_locator_set_key()).
    pub fn rados_object_clone_range(
        &self,
        dst_object_name: &str,
        dst_offset: u64,
        src_object_name: &str,
        src_offset: u64,
        length: usize,
    ) -> RadosResult<()> {
        self.ioctx_guard()?;
        let dst_name_str = CString::new(dst_object_name)?;
        let src_name_str = CString::new(src_object_name)?;

        unsafe {
            let ret_code = rados_clone_range(
                self.ioctx,
                dst_name_str.as_ptr(),
                dst_offset,
                src_name_str.as_ptr(),
                src_offset,
                length,
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }

    /// Append len bytes from buf into the oid object.
    pub fn rados_object_append(&self, object_name: &str, buffer: &[u8]) -> RadosResult<()> {
        self.ioctx_guard()?;
        let obj_name_str = CString::new(object_name)?;

        unsafe {
            let ret_code = rados_append(
                self.ioctx,
                obj_name_str.as_ptr(),
                buffer.as_ptr() as *const c_char,
                buffer.len(),
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }

    /// Read data from an object.  This fills the slice given and returns the
    /// amount of bytes read
    /// The io context determines the snapshot to read from, if any was set by
    /// rados_ioctx_snap_set_read().
    /// Default read size is 64K unless you call Vec::with_capacity
    /// with a larger size.
    pub fn rados_object_read(
        &self,
        object_name: &str,
        fill_buffer: &mut Vec<u8>,
        read_offset: u64,
    ) -> RadosResult<i32> {
        self.ioctx_guard()?;
        let object_name_str = CString::new(object_name)?;
        let mut len = fill_buffer.capacity();
        if len == 0 {
            fill_buffer.reserve_exact(DEFAULT_READ_BYTES);
            len = fill_buffer.capacity();
        }

        unsafe {
            let ret_code = rados_read(
                self.ioctx,
                object_name_str.as_ptr(),
                fill_buffer.as_mut_ptr() as *mut c_char,
                len,
                read_offset,
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
            fill_buffer.set_len(ret_code as usize);
            Ok(ret_code)
        }
    }

    /// Delete an object
    /// Note: This does not delete any snapshots of the object.
    pub fn rados_object_remove(&self, object_name: &str) -> RadosResult<()> {
        self.ioctx_guard()?;
        let object_name_str = CString::new(object_name)?;

        unsafe {
            let ret_code = rados_remove(self.ioctx, object_name_str.as_ptr() as *const c_char);
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }

    /// Resize an object
    /// If this enlarges the object, the new area is logically filled with
    /// zeroes. If this shrinks the object, the excess data is removed.
    pub fn rados_object_trunc(&self, object_name: &str, new_size: u64) -> RadosResult<()> {
        self.ioctx_guard()?;
        let object_name_str = CString::new(object_name)?;

        unsafe {
            let ret_code = rados_trunc(self.ioctx, object_name_str.as_ptr(), new_size);
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }

    /// Get the value of an extended attribute on an object.
    pub fn rados_object_getxattr(
        &self,
        object_name: &str,
        attr_name: &str,
        fill_buffer: &mut [u8],
    ) -> RadosResult<i32> {
        self.ioctx_guard()?;
        let object_name_str = CString::new(object_name)?;
        let attr_name_str = CString::new(attr_name)?;

        unsafe {
            let ret_code = rados_getxattr(
                self.ioctx,
                object_name_str.as_ptr() as *const c_char,
                attr_name_str.as_ptr() as *const c_char,
                fill_buffer.as_mut_ptr() as *mut c_char,
                fill_buffer.len(),
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
            Ok(ret_code)
        }
    }

    /// Set an extended attribute on an object.
    pub fn rados_object_setxattr(
        &self,
        object_name: &str,
        attr_name: &str,
        attr_value: &mut [u8],
    ) -> RadosResult<()> {
        self.ioctx_guard()?;
        let object_name_str = CString::new(object_name)?;
        let attr_name_str = CString::new(attr_name)?;

        unsafe {
            let ret_code = rados_setxattr(
                self.ioctx,
                object_name_str.as_ptr() as *const c_char,
                attr_name_str.as_ptr() as *const c_char,
                attr_value.as_mut_ptr() as *mut c_char,
                attr_value.len(),
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }

    /// Delete an extended attribute from an object.
    pub fn rados_object_rmxattr(&self, object_name: &str, attr_name: &str) -> RadosResult<()> {
        self.ioctx_guard()?;
        let object_name_str = CString::new(object_name)?;
        let attr_name_str = CString::new(attr_name)?;

        unsafe {
            let ret_code = rados_rmxattr(
                self.ioctx,
                object_name_str.as_ptr() as *const c_char,
                attr_name_str.as_ptr() as *const c_char,
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }

    /// Get the rados_xattrs_iter_t reference to iterate over xattrs on an
    /// object Used in conjuction with XAttr::new() to iterate.
    pub fn rados_get_xattr_iterator(&self, object_name: &str) -> RadosResult<rados_xattrs_iter_t> {
        self.ioctx_guard()?;
        let object_name_str = CString::new(object_name)?;
        let mut xattr_iterator_handle: rados_xattrs_iter_t = ptr::null_mut();

        unsafe {
            let ret_code = rados_getxattrs(
                self.ioctx,
                object_name_str.as_ptr(),
                &mut xattr_iterator_handle,
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(xattr_iterator_handle)
    }

    /// Get object stats (size,SystemTime)
    pub fn rados_object_stat(&self, object_name: &str) -> RadosResult<(u64, SystemTime)> {
        self.ioctx_guard()?;
        let object_name_str = CString::new(object_name)?;
        let mut psize: u64 = 0;
        let mut time: ::libc::time_t = 0;

        unsafe {
            let ret_code = rados_stat(self.ioctx, object_name_str.as_ptr(), &mut psize, &mut time);
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok((psize, (UNIX_EPOCH + Duration::from_secs(time as u64))))
    }

    /// Update tmap (trivial map)
    pub fn rados_object_tmap_update(
        &self,
        object_name: &str,
        update: TmapOperation,
    ) -> RadosResult<()> {
        self.ioctx_guard()?;
        let object_name_str = CString::new(object_name)?;
        let buffer = update.serialize()?;
        unsafe {
            let ret_code = rados_tmap_update(
                self.ioctx,
                object_name_str.as_ptr(),
                buffer.as_ptr() as *const c_char,
                buffer.len(),
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }

    /// Fetch complete tmap (trivial map) object
    pub fn rados_object_tmap_get(&self, object_name: &str) -> RadosResult<Vec<TmapOperation>> {
        self.ioctx_guard()?;
        let object_name_str = CString::new(object_name)?;
        let mut buffer: Vec<u8> = Vec::with_capacity(500);

        unsafe {
            let ret_code = rados_tmap_get(
                self.ioctx,
                object_name_str.as_ptr(),
                buffer.as_mut_ptr() as *mut c_char,
                buffer.capacity(),
            );
            if ret_code == -ERANGE {
                buffer.reserve(1000);
                buffer.set_len(1000);
                let ret_code = rados_tmap_get(
                    self.ioctx,
                    object_name_str.as_ptr(),
                    buffer.as_mut_ptr() as *mut c_char,
                    buffer.capacity(),
                );
                if ret_code < 0 {
                    return Err(ret_code.into());
                }
            } else if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        match TmapOperation::deserialize(&buffer) {
            Ok((_, tmap)) => Ok(tmap),
            Err(nom::Err::Incomplete(needed)) => Err(RadosError::new(format!(
                "deserialize of ceph tmap failed.
            Input from Ceph was too small.  Needed: {:?} more bytes",
                needed
            ))),
            Err(nom::Err::Error(e)) => Err(RadosError::new(
                String::from_utf8_lossy(e.input).to_string(),
            )),
            Err(nom::Err::Failure(e)) => Err(RadosError::new(
                String::from_utf8_lossy(e.input).to_string(),
            )),
        }
    }

    /// Execute an OSD class method on an object
    /// The OSD has a plugin mechanism for performing complicated operations on
    /// an object atomically.
    /// These plugins are called classes. This function allows librados users to
    /// call the custom
    /// methods. The input and output formats are defined by the class. Classes
    /// in ceph.git can
    /// be found in src/cls subdirectories
    pub fn rados_object_exec(
        &self,
        object_name: &str,
        class_name: &str,
        method_name: &str,
        input_buffer: &[u8],
        output_buffer: &mut [u8],
    ) -> RadosResult<()> {
        self.ioctx_guard()?;
        let object_name_str = CString::new(object_name)?;
        let class_name_str = CString::new(class_name)?;
        let method_name_str = CString::new(method_name)?;

        unsafe {
            let ret_code = rados_exec(
                self.ioctx,
                object_name_str.as_ptr(),
                class_name_str.as_ptr(),
                method_name_str.as_ptr(),
                input_buffer.as_ptr() as *const c_char,
                input_buffer.len(),
                output_buffer.as_mut_ptr() as *mut c_char,
                output_buffer.len(),
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }

    /// Sychronously notify watchers of an object
    /// This blocks until all watchers of the object have received and reacted
    /// to the notify, or a timeout is reached.
    pub fn rados_object_notify(&self, object_name: &str, data: &[u8]) -> RadosResult<()> {
        self.ioctx_guard()?;
        let object_name_str = CString::new(object_name)?;

        unsafe {
            let ret_code = rados_notify(
                self.ioctx,
                object_name_str.as_ptr(),
                0,
                data.as_ptr() as *const c_char,
                data.len() as i32,
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }
    // pub fn rados_object_notify2(ctx: rados_ioctx_t, object_name: &str) ->
    // RadosResult<()> {
    // if ctx.is_null() {
    // return Err(RadosError::new("Rados ioctx not created.  Please initialize
    // first".to_string()));
    // }
    //
    // unsafe {
    // }
    // }
    //
    /// Acknolwedge receipt of a notify
    pub fn rados_object_notify_ack(
        &self,
        object_name: &str,
        notify_id: u64,
        cookie: u64,
        buffer: Option<&[u8]>,
    ) -> RadosResult<()> {
        self.ioctx_guard()?;
        let object_name_str = CString::new(object_name)?;

        match buffer {
            Some(buf) => unsafe {
                let ret_code = rados_notify_ack(
                    self.ioctx,
                    object_name_str.as_ptr(),
                    notify_id,
                    cookie,
                    buf.as_ptr() as *const c_char,
                    buf.len() as i32,
                );
                if ret_code < 0 {
                    return Err(ret_code.into());
                }
            },
            None => unsafe {
                let ret_code = rados_notify_ack(
                    self.ioctx,
                    object_name_str.as_ptr(),
                    notify_id,
                    cookie,
                    ptr::null(),
                    0,
                );
                if ret_code < 0 {
                    return Err(ret_code.into());
                }
            },
        }
        Ok(())
    }
    /// Set allocation hint for an object
    /// This is an advisory operation, it will always succeed (as if it was
    /// submitted with a
    /// LIBRADOS_OP_FLAG_FAILOK flag set) and is not guaranteed to do anything
    /// on the backend.
    pub fn rados_object_set_alloc_hint(
        &self,
        object_name: &str,
        expected_object_size: u64,
        expected_write_size: u64,
    ) -> RadosResult<()> {
        self.ioctx_guard()?;
        let object_name_str = CString::new(object_name)?;

        unsafe {
            let ret_code = rados_set_alloc_hint(
                self.ioctx,
                object_name_str.as_ptr(),
                expected_object_size,
                expected_write_size,
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }

    // Perform a compound read operation synchronously
    pub fn rados_perform_read_operations(&self, read_op: ReadOperation) -> RadosResult<()> {
        self.ioctx_guard()?;
        let object_name_str = CString::new(read_op.object_name.clone())?;

        unsafe {
            let ret_code = rados_read_op_operate(
                read_op.read_op_handle,
                self.ioctx,
                object_name_str.as_ptr(),
                read_op.flags as i32,
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }

    // Perform a compound write operation synchronously
    pub fn rados_commit_write_operations(&self, write_op: &mut WriteOperation) -> RadosResult<()> {
        self.ioctx_guard()?;
        let object_name_str = CString::new(write_op.object_name.clone())?;

        unsafe {
            let ret_code = rados_write_op_operate(
                write_op.write_op_handle,
                self.ioctx,
                object_name_str.as_ptr(),
                &mut write_op.mtime,
                write_op.flags as i32,
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }

    /// Take an exclusive lock on an object.
    pub fn rados_object_lock_exclusive(
        &self,
        object_name: &str,
        lock_name: &str,
        cookie_name: &str,
        description: &str,
        duration_time: &mut timeval,
        lock_flags: u8,
    ) -> RadosResult<()> {
        self.ioctx_guard()?;
        let object_name_str = CString::new(object_name)?;
        let lock_name_str = CString::new(lock_name)?;
        let cookie_name_str = CString::new(cookie_name)?;
        let description_str = CString::new(description)?;

        unsafe {
            let ret_code = rados_lock_exclusive(
                self.ioctx,
                object_name_str.as_ptr(),
                lock_name_str.as_ptr(),
                cookie_name_str.as_ptr(),
                description_str.as_ptr(),
                duration_time,
                lock_flags,
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }

    /// Take a shared lock on an object.
    pub fn rados_object_lock_shared(
        &self,
        object_name: &str,
        lock_name: &str,
        cookie_name: &str,
        description: &str,
        tag_name: &str,
        duration_time: &mut timeval,
        lock_flags: u8,
    ) -> RadosResult<()> {
        self.ioctx_guard()?;
        let object_name_str = CString::new(object_name)?;
        let lock_name_str = CString::new(lock_name)?;
        let cookie_name_str = CString::new(cookie_name)?;
        let description_str = CString::new(description)?;
        let tag_name_str = CString::new(tag_name)?;

        unsafe {
            let ret_code = rados_lock_shared(
                self.ioctx,
                object_name_str.as_ptr(),
                lock_name_str.as_ptr(),
                cookie_name_str.as_ptr(),
                tag_name_str.as_ptr(),
                description_str.as_ptr(),
                duration_time,
                lock_flags,
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }

    /// Release a shared or exclusive lock on an object.
    pub fn rados_object_unlock(
        &self,
        object_name: &str,
        lock_name: &str,
        cookie_name: &str,
    ) -> RadosResult<()> {
        self.ioctx_guard()?;
        let object_name_str = CString::new(object_name)?;
        let lock_name_str = CString::new(lock_name)?;
        let cookie_name_str = CString::new(cookie_name)?;

        unsafe {
            let ret_code = rados_unlock(
                self.ioctx,
                object_name_str.as_ptr(),
                lock_name_str.as_ptr(),
                cookie_name_str.as_ptr(),
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }

    /// List clients that have locked the named object lock and information
    /// about the lock.
    /// The number of bytes required in each buffer is put in the corresponding
    /// size out parameter.
    /// If any of the provided buffers are too short, -ERANGE is returned after
    /// these sizes are filled in.
    // pub fn rados_object_list_lockers(ctx: rados_ioctx_t, object_name: &str,
    // lock_name: &str, exclusive: u8, ) ->
    // RadosResult<isize> {
    // if ctx.is_null() {
    // return Err(RadosError::new("Rados ioctx not created.  Please initialize
    // first".to_string()));
    // }
    // let object_name_str = try!(CString::new(object_name));
    //
    // unsafe {
    // let ret_code = rados_list_lockers(ctx,
    // o: *const ::libc::c_char,
    // name: *const ::libc::c_char,
    // exclusive: *mut ::libc::c_int,
    // tag: *mut ::libc::c_char,
    // tag_len: *mut size_t,
    // clients: *mut ::libc::c_char,
    // clients_len: *mut size_t,
    // cookies: *mut ::libc::c_char,
    // cookies_len: *mut size_t,
    // addrs: *mut ::libc::c_char,
    // addrs_len: *mut size_t);
    // }
    // }
    /// Releases a shared or exclusive lock on an object, which was taken by the
    /// specified client.
    pub fn rados_object_break_lock(
        &self,
        object_name: &str,
        lock_name: &str,
        client_name: &str,
        cookie_name: &str,
    ) -> RadosResult<()> {
        self.ioctx_guard()?;
        let object_name_str = CString::new(object_name)?;
        let lock_name_str = CString::new(lock_name)?;
        let cookie_name_str = CString::new(cookie_name)?;
        let client_name_str = CString::new(client_name)?;

        unsafe {
            let ret_code = rados_break_lock(
                self.ioctx,
                object_name_str.as_ptr(),
                lock_name_str.as_ptr(),
                client_name_str.as_ptr(),
                cookie_name_str.as_ptr(),
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }

    /// Create a rados striper.
    /// For more details see rados_striper_t.
    #[cfg(feature = "rados_striper")]
    pub fn get_rados_striper(self) -> RadosResult<RadosStriper> {
        self.ioctx_guard()?;
        unsafe {
            let mut rados_striper: rados_striper_t = ptr::null_mut();
            let ret_code = rados_striper_create(self.ioctx, &mut rados_striper);
            if ret_code < 0 {
                return Err(ret_code.into());
            }
            Ok(RadosStriper { rados_striper })
        }
    }
}

impl Rados {
    pub fn rados_blacklist_client(&self, client: IpAddr, expire_seconds: u32) -> RadosResult<()> {
        self.conn_guard()?;
        let client_address = CString::new(client.to_string())?;
        unsafe {
            let ret_code = rados_blacklist_add(
                self.rados,
                client_address.as_ptr() as *mut c_char,
                expire_seconds,
            );

            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }

    /// Returns back a collection of Rados Pools
    ///
    /// pool_buffer should be allocated with:
    /// ```
    /// let capacity = 10;
    /// let pool_buffer: Vec<u8> = Vec::with_capacity(capacity);
    /// ```
    /// buf_size should be the value used with_capacity
    ///
    /// Returns Ok(Vec<String>) - A list of Strings of the pool names.
    #[allow(unused_variables)]
    pub fn rados_pools(&self) -> RadosResult<Vec<String>> {
        self.conn_guard()?;
        let mut pools: Vec<String> = Vec::new();
        let pool_slice: &[u8];
        let mut pool_buffer: Vec<u8> = Vec::with_capacity(500);

        unsafe {
            let len = rados_pool_list(
                self.rados,
                pool_buffer.as_mut_ptr() as *mut c_char,
                pool_buffer.capacity(),
            );
            if len > pool_buffer.capacity() as i32 {
                // rados_pool_list requires more buffer than we gave it
                pool_buffer.reserve(len as usize);
                let len = rados_pool_list(
                    self.rados,
                    pool_buffer.as_mut_ptr() as *mut c_char,
                    pool_buffer.capacity(),
                );
                // Tell the Vec how much Ceph read into the buffer
                pool_buffer.set_len(len as usize);
            } else {
                // Tell the Vec how much Ceph read into the buffer
                pool_buffer.set_len(len as usize);
            }
        }
        let mut cursor = Cursor::new(&pool_buffer);
        loop {
            let mut string_buf: Vec<u8> = Vec::new();
            let read = cursor.read_until(0x00, &mut string_buf)?;
            // 0 End of the pool_buffer;
            // 1 Read a double \0.  Time to break
            if read == 0 || read == 1 {
                break;
            } else {
                // Read a String
                pools.push(String::from_utf8_lossy(&string_buf[..read - 1]).into_owned());
            }
        }

        Ok(pools)
    }

    /// Create a pool with default settings
    /// The default owner is the admin user (auid 0). The default crush rule is
    /// rule 0.
    pub fn rados_create_pool(&self, pool_name: &str) -> RadosResult<()> {
        self.conn_guard()?;
        let pool_name_str = CString::new(pool_name)?;
        unsafe {
            let ret_code = rados_pool_create(self.rados, pool_name_str.as_ptr());
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }
    /// Delete a pool and all data inside it
    /// The pool is removed from the cluster immediately, but the actual data is
    /// deleted in
    /// the background.
    pub fn rados_delete_pool(&self, pool_name: &str) -> RadosResult<()> {
        self.conn_guard()?;
        let pool_name_str = CString::new(pool_name)?;
        unsafe {
            let ret_code = rados_pool_delete(self.rados, pool_name_str.as_ptr());
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }

    /// Lookup a Ceph pool id.  If the pool doesn't exist it will return
    /// Ok(None).
    pub fn rados_lookup_pool(&self, pool_name: &str) -> RadosResult<Option<i64>> {
        self.conn_guard()?;
        let pool_name_str = CString::new(pool_name)?;
        unsafe {
            let ret_code: i64 = rados_pool_lookup(self.rados, pool_name_str.as_ptr());
            if ret_code >= 0 {
                Ok(Some(ret_code))
            } else if ret_code as i32 == -ENOENT {
                Ok(None)
            } else {
                Err((ret_code as i32).into())
            }
        }
    }

    pub fn rados_reverse_lookup_pool(&self, pool_id: i64) -> RadosResult<String> {
        self.conn_guard()?;
        let mut buffer: Vec<u8> = Vec::with_capacity(500);

        unsafe {
            let ret_code = rados_pool_reverse_lookup(
                self.rados,
                pool_id,
                buffer.as_mut_ptr() as *mut c_char,
                buffer.capacity(),
            );
            if ret_code == -ERANGE {
                // Buffer was too small
                buffer.reserve(1000);
                buffer.set_len(1000);
                let ret_code = rados_pool_reverse_lookup(
                    self.rados,
                    pool_id,
                    buffer.as_mut_ptr() as *mut c_char,
                    buffer.capacity(),
                );
                if ret_code < 0 {
                    return Err(ret_code.into());
                }
                Ok(String::from_utf8_lossy(&buffer).into_owned())
            } else if ret_code < 0 {
                Err(ret_code.into())
            } else {
                Ok(String::from_utf8_lossy(&buffer).into_owned())
            }
        }
    }
}

/// Get the version of librados.
pub fn rados_libversion() -> RadosVersion {
    let mut major: c_int = 0;
    let mut minor: c_int = 0;
    let mut extra: c_int = 0;
    unsafe {
        rados_version(&mut major, &mut minor, &mut extra);
    }
    RadosVersion {
        major,
        minor,
        extra,
    }
}

impl Rados {
    /// Read usage info about the cluster
    /// This tells you total space, space used, space available, and number of
    /// objects.
    /// These are not updated immediately when data is written, they are
    /// eventually consistent.
    /// Note: Ceph uses kibibytes: https://en.wikipedia.org/wiki/Kibibyte
    pub fn rados_stat_cluster(&self) -> RadosResult<Struct_rados_cluster_stat_t> {
        self.conn_guard()?;
        let mut cluster_stat = Struct_rados_cluster_stat_t::default();
        unsafe {
            let ret_code = rados_cluster_stat(self.rados, &mut cluster_stat);
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }

        Ok(cluster_stat)
    }

    pub fn rados_fsid(&self) -> RadosResult<Uuid> {
        self.conn_guard()?;
        let mut fsid_buffer: Vec<u8> = Vec::with_capacity(37);
        unsafe {
            let ret_code = rados_cluster_fsid(
                self.rados,
                fsid_buffer.as_mut_ptr() as *mut c_char,
                fsid_buffer.capacity(),
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
            // Tell the Vec how much Ceph read into the buffer
            fsid_buffer.set_len(ret_code as usize);
        }
        // Ceph actually returns the fsid as a uuid string
        let fsid_str = String::from_utf8(fsid_buffer)?;
        // Parse into a UUID and return
        Ok(fsid_str.parse()?)
    }

    /// Ping a monitor to assess liveness
    /// May be used as a simply way to assess liveness, or to obtain
    /// information about the monitor in a simple way even in the
    /// absence of quorum.
    pub fn ping_monitor(&self, mon_id: &str) -> RadosResult<String> {
        self.conn_guard()?;

        let mon_id_str = CString::new(mon_id)?;
        let mut out_str: *mut c_char = ptr::null_mut();
        let mut str_length: usize = 0;
        unsafe {
            let ret_code = rados_ping_monitor(
                self.rados,
                mon_id_str.as_ptr(),
                &mut out_str,
                &mut str_length,
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
            if !out_str.is_null() {
                // valid string
                let s_bytes = std::slice::from_raw_parts(out_str, str_length);
                // Convert from i8 -> u8
                let bytes: Vec<u8> = s_bytes.iter().map(|c| *c as u8).collect();
                // Tell rados we're done with this buffer
                rados_buffer_free(out_str);
                Ok(String::from_utf8_lossy(&bytes).into_owned())
            } else {
                Ok("".into())
            }
        }
    }
}

/// Ceph version - Ceph during the make release process generates the version
/// number along with
/// the github hash of the release and embeds the hard coded value into
/// `ceph.py` which is the
/// the default ceph utility.
pub fn ceph_version(socket: &str) -> Option<String> {
    let cmd = "version";

    admin_socket_command(&cmd, socket).ok().and_then(|json| {
        json_data(&json)
            .and_then(|jsondata| json_find(jsondata, &[cmd]).map(|data| json_as_string(&data)))
    })
}

/// This version call parses the `ceph -s` output. It does not need `sudo`
/// rights like
/// `ceph_version` does since it pulls from the admin socket.
pub fn ceph_version_parse() -> Option<String> {
    match run_cli("ceph --version") {
        Ok(output) => {
            let n = output.status.code().unwrap();
            if n == 0 {
                Some(String::from_utf8_lossy(&output.stdout).to_string())
            } else {
                Some(String::from_utf8_lossy(&output.stderr).to_string())
            }
        }
        Err(_) => None,
    }
}

impl Rados {
    /// Only single String value
    pub fn ceph_status(&self, keys: &[&str]) -> RadosResult<String> {
        self.conn_guard()?;
        match self.ceph_mon_command("prefix", "status", Some("json")) {
            Ok((json, _)) => match json {
                Some(json) => match json_data(&json) {
                    Some(jsondata) => {
                        if let Some(data) = json_find(jsondata, keys) {
                            Ok(json_as_string(&data))
                        } else {
                            Err(RadosError::new(
                                "The attributes were not found in the output.".to_string(),
                            ))
                        }
                    }
                    _ => Err(RadosError::new("JSON data not found.".to_string())),
                },
                _ => Err(RadosError::new("JSON data not found.".to_string())),
            },
            Err(e) => Err(e),
        }
    }

    /// string with the `health HEALTH_OK` or `HEALTH_WARN` or `HEALTH_ERR`
    /// which is also not efficient.
    pub fn ceph_health_string(&self) -> RadosResult<String> {
        self.conn_guard()?;
        match self.ceph_mon_command("prefix", "health", None) {
            Ok((data, _)) => Ok(data.unwrap().replace("\n", "")),
            Err(e) => Err(e),
        }
    }

    /// Returns an enum value of:
    /// CephHealth::Ok
    /// CephHealth::Warning
    /// CephHealth::Error
    pub fn ceph_health(&self) -> CephHealth {
        match self.ceph_health_string() {
            Ok(health) => {
                if health.contains("HEALTH_OK") {
                    CephHealth::Ok
                } else if health.contains("HEALTH_WARN") {
                    CephHealth::Warning
                } else {
                    CephHealth::Error
                }
            }
            Err(_) => CephHealth::Error,
        }
    }

    /// Higher level `ceph_command`
    pub fn ceph_command(
        &self,
        name: &str,
        value: &str,
        cmd_type: CephCommandTypes,
        keys: &[&str],
    ) -> RadosResult<JsonData> {
        self.conn_guard()?;
        match cmd_type {
            CephCommandTypes::Osd => Err(RadosError::new("OSD CMDs Not implemented.".to_string())),
            CephCommandTypes::Pgs => Err(RadosError::new("PGS CMDS Not implemented.".to_string())),
            _ => match self.ceph_mon_command(name, value, Some("json")) {
                Ok((json, _)) => match json {
                    Some(json) => match json_data(&json) {
                        Some(jsondata) => {
                            if let Some(data) = json_find(jsondata, keys) {
                                Ok(data)
                            } else {
                                Err(RadosError::new(
                                    "The attributes were not found in the output.".to_string(),
                                ))
                            }
                        }
                        _ => Err(RadosError::new("JSON data not found.".to_string())),
                    },
                    _ => Err(RadosError::new("JSON data not found.".to_string())),
                },
                Err(e) => Err(e),
            },
        }
    }

    /// Returns the list of available commands
    pub fn ceph_commands(&self, keys: Option<&[&str]>) -> RadosResult<JsonData> {
        self.conn_guard()?;
        match self.ceph_mon_command("prefix", "get_command_descriptions", Some("json")) {
            Ok((json, _)) => match json {
                Some(json) => match json_data(&json) {
                    Some(jsondata) => {
                        if let Some(k) = keys {
                            if let Some(data) = json_find(jsondata, k) {
                                Ok(data)
                            } else {
                                Err(RadosError::new(
                                    "The attributes were not found in the output.".to_string(),
                                ))
                            }
                        } else {
                            Ok(jsondata)
                        }
                    }
                    _ => Err(RadosError::new("JSON data not found.".to_string())),
                },
                _ => Err(RadosError::new("JSON data not found.".to_string())),
            },
            Err(e) => Err(e),
        }
    }

    /// Mon command that does not pass in a data payload.
    pub fn ceph_mon_command(
        &self,
        name: &str,
        value: &str,
        format: Option<&str>,
    ) -> RadosResult<(Option<String>, Option<String>)> {
        let data: Vec<*mut c_char> = Vec::with_capacity(1);
        self.ceph_mon_command_with_data(name, value, format, data)
    }

    pub fn ceph_mon_command_without_data(
        &self,
        cmd: &serde_json::Value,
    ) -> RadosResult<(Vec<u8>, Option<String>)> {
        self.conn_guard()?;
        let cmd_string = cmd.to_string();
        debug!("ceph_mon_command_without_data: {}", cmd_string);
        let data: Vec<*mut c_char> = Vec::with_capacity(1);
        let cmds = CString::new(cmd_string).unwrap();

        let mut outbuf_len = 0;
        let mut outs = ptr::null_mut();
        let mut outs_len = 0;

        // Ceph librados allocates these buffers internally and the pointer that comes
        // back must be
        // freed by call `rados_buffer_free`
        let mut outbuf = ptr::null_mut();
        let mut out: Vec<u8> = vec![];
        let mut status_string: Option<String> = None;

        debug!("Calling rados_mon_command with {:?}", cmd);

        unsafe {
            // cmd length is 1 because we only allow one command at a time.
            let ret_code = rados_mon_command(
                self.rados,
                &mut cmds.as_ptr(),
                1,
                data.as_ptr() as *mut c_char,
                data.len() as usize,
                &mut outbuf,
                &mut outbuf_len,
                &mut outs,
                &mut outs_len,
            );
            debug!("return code: {}", ret_code);
            if ret_code < 0 {
                if outs_len > 0 && !outs.is_null() {
                    let slice = ::std::slice::from_raw_parts(outs as *const u8, outs_len as usize);
                    rados_buffer_free(outs);
                    return Err(RadosError::new(String::from_utf8_lossy(slice).into_owned()));
                }
                return Err(ret_code.into());
            }

            // Copy the data from outbuf and then call rados_buffer_free instead libc::free
            if outbuf_len > 0 && !outbuf.is_null() {
                let slice = ::std::slice::from_raw_parts(outbuf as *const u8, outbuf_len as usize);
                out = slice.to_vec();

                rados_buffer_free(outbuf);
            }
            if outs_len > 0 && !outs.is_null() {
                let slice = ::std::slice::from_raw_parts(outs as *const u8, outs_len as usize);
                status_string = Some(String::from_utf8(slice.to_vec())?);
                rados_buffer_free(outs);
            }
        }

        Ok((out, status_string))
    }

    /// Mon command that does pass in a data payload.
    /// Most all of the commands pass through this function.
    pub fn ceph_mon_command_with_data(
        &self,
        name: &str,
        value: &str,
        format: Option<&str>,
        data: Vec<*mut c_char>,
    ) -> RadosResult<(Option<String>, Option<String>)> {
        self.conn_guard()?;

        let mut cmd_strings: Vec<String> = Vec::new();
        match format {
            Some(fmt) => cmd_strings.push(format!(
                "{{\"{}\": \"{}\", \"format\": \"{}\"}}",
                name, value, fmt
            )),
            None => cmd_strings.push(format!("{{\"{}\": \"{}\"}}", name, value)),
        }

        let cstrings: Vec<CString> = cmd_strings[..]
            .iter()
            .map(|s| CString::new(s.clone()).unwrap())
            .collect();
        let mut cmds: Vec<*const c_char> = cstrings.iter().map(|c| c.as_ptr()).collect();

        let mut outbuf = ptr::null_mut();
        let mut outs = ptr::null_mut();
        let mut outbuf_len = 0;
        let mut outs_len = 0;

        // Ceph librados allocates these buffers internally and the pointer that comes
        // back must be
        // freed by call `rados_buffer_free`
        let mut str_outbuf: Option<String> = None;
        let mut str_outs: Option<String> = None;

        debug!("Calling rados_mon_command with {:?}", cstrings);

        unsafe {
            // cmd length is 1 because we only allow one command at a time.
            let ret_code = rados_mon_command(
                self.rados,
                cmds.as_mut_ptr(),
                1,
                data.as_ptr() as *mut c_char,
                data.len() as usize,
                &mut outbuf,
                &mut outbuf_len,
                &mut outs,
                &mut outs_len,
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }

            // Copy the data from outbuf and then  call rados_buffer_free instead libc::free
            if outbuf_len > 0 {
                let c_str_outbuf: &CStr = CStr::from_ptr(outbuf);
                let buf_outbuf: &[u8] = c_str_outbuf.to_bytes();
                let str_slice_outbuf: &str = str::from_utf8(buf_outbuf).unwrap();
                str_outbuf = Some(str_slice_outbuf.to_owned());

                rados_buffer_free(outbuf);
            }

            if outs_len > 0 {
                let c_str_outs: &CStr = CStr::from_ptr(outs);
                let buf_outs: &[u8] = c_str_outs.to_bytes();
                let str_slice_outs: &str = str::from_utf8(buf_outs).unwrap();
                str_outs = Some(str_slice_outs.to_owned());

                rados_buffer_free(outs);
            }
        }

        Ok((str_outbuf, str_outs))
    }

    /// OSD command that does not pass in a data payload.
    pub fn ceph_osd_command(
        &self,
        id: i32,
        name: &str,
        value: &str,
        format: Option<&str>,
    ) -> RadosResult<(Option<String>, Option<String>)> {
        let data: Vec<*mut c_char> = Vec::with_capacity(1);
        self.ceph_osd_command_with_data(id, name, value, format, data)
    }

    /// OSD command that does pass in a data payload.
    pub fn ceph_osd_command_with_data(
        &self,
        id: i32,
        name: &str,
        value: &str,
        format: Option<&str>,
        data: Vec<*mut c_char>,
    ) -> RadosResult<(Option<String>, Option<String>)> {
        self.conn_guard()?;

        let mut cmd_strings: Vec<String> = Vec::new();
        match format {
            Some(fmt) => cmd_strings.push(format!(
                "{{\"{}\": \"{}\", \"format\": \"{}\"}}",
                name, value, fmt
            )),
            None => cmd_strings.push(format!("{{\"{}\": \"{}\"}}", name, value)),
        }

        let cstrings: Vec<CString> = cmd_strings[..]
            .iter()
            .map(|s| CString::new(s.clone()).unwrap())
            .collect();
        let mut cmds: Vec<*const c_char> = cstrings.iter().map(|c| c.as_ptr()).collect();

        let mut outbuf = ptr::null_mut();
        let mut outs = ptr::null_mut();
        let mut outbuf_len = 0;
        let mut outs_len = 0;

        // Ceph librados allocates these buffers internally and the pointer that comes
        // back must be
        // freed by call `rados_buffer_free`
        let mut str_outbuf: Option<String> = None;
        let mut str_outs: Option<String> = None;

        unsafe {
            // cmd length is 1 because we only allow one command at a time.
            let ret_code = rados_osd_command(
                self.rados,
                id,
                cmds.as_mut_ptr(),
                1,
                data.as_ptr() as *mut c_char,
                data.len() as usize,
                &mut outbuf,
                &mut outbuf_len,
                &mut outs,
                &mut outs_len,
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }

            // Copy the data from outbuf and then  call rados_buffer_free instead libc::free
            if outbuf_len > 0 {
                let c_str_outbuf: &CStr = CStr::from_ptr(outbuf);
                let buf_outbuf: &[u8] = c_str_outbuf.to_bytes();
                let str_slice_outbuf: &str = str::from_utf8(buf_outbuf).unwrap();
                str_outbuf = Some(str_slice_outbuf.to_owned());

                rados_buffer_free(outbuf);
            }

            if outs_len > 0 {
                let c_str_outs: &CStr = CStr::from_ptr(outs);
                let buf_outs: &[u8] = c_str_outs.to_bytes();
                let str_slice_outs: &str = str::from_utf8(buf_outs).unwrap();
                str_outs = Some(str_slice_outs.to_owned());

                rados_buffer_free(outs);
            }
        }

        Ok((str_outbuf, str_outs))
    }

    /// PG command that does not pass in a data payload.
    pub fn ceph_pgs_command(
        &self,
        pg: &str,
        name: &str,
        value: &str,
        format: Option<&str>,
    ) -> RadosResult<(Option<String>, Option<String>)> {
        let data: Vec<*mut c_char> = Vec::with_capacity(1);
        self.ceph_pgs_command_with_data(pg, name, value, format, data)
    }

    /// PG command that does pass in a data payload.
    pub fn ceph_pgs_command_with_data(
        &self,
        pg: &str,
        name: &str,
        value: &str,
        format: Option<&str>,
        data: Vec<*mut c_char>,
    ) -> RadosResult<(Option<String>, Option<String>)> {
        self.conn_guard()?;

        let mut cmd_strings: Vec<String> = Vec::new();
        match format {
            Some(fmt) => cmd_strings.push(format!(
                "{{\"{}\": \"{}\", \"format\": \"{}\"}}",
                name, value, fmt
            )),
            None => cmd_strings.push(format!("{{\"{}\": \"{}\"}}", name, value)),
        }

        let pg_str = CString::new(pg).unwrap();
        let cstrings: Vec<CString> = cmd_strings[..]
            .iter()
            .map(|s| CString::new(s.clone()).unwrap())
            .collect();
        let mut cmds: Vec<*const c_char> = cstrings.iter().map(|c| c.as_ptr()).collect();

        let mut outbuf = ptr::null_mut();
        let mut outs = ptr::null_mut();
        let mut outbuf_len = 0;
        let mut outs_len = 0;

        // Ceph librados allocates these buffers internally and the pointer that comes
        // back must be
        // freed by call `rados_buffer_free`
        let mut str_outbuf: Option<String> = None;
        let mut str_outs: Option<String> = None;

        unsafe {
            // cmd length is 1 because we only allow one command at a time.
            let ret_code = rados_pg_command(
                self.rados,
                pg_str.as_ptr(),
                cmds.as_mut_ptr(),
                1,
                data.as_ptr() as *mut c_char,
                data.len() as usize,
                &mut outbuf,
                &mut outbuf_len,
                &mut outs,
                &mut outs_len,
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }

            // Copy the data from outbuf and then  call rados_buffer_free instead libc::free
            if outbuf_len > 0 {
                let c_str_outbuf: &CStr = CStr::from_ptr(outbuf);
                let buf_outbuf: &[u8] = c_str_outbuf.to_bytes();
                let str_slice_outbuf: &str = str::from_utf8(buf_outbuf).unwrap();
                str_outbuf = Some(str_slice_outbuf.to_owned());

                rados_buffer_free(outbuf);
            }

            if outs_len > 0 {
                let c_str_outs: &CStr = CStr::from_ptr(outs);
                let buf_outs: &[u8] = c_str_outs.to_bytes();
                let str_slice_outs: &str = str::from_utf8(buf_outs).unwrap();
                str_outs = Some(str_slice_outs.to_owned());

                rados_buffer_free(outs);
            }
        }

        Ok((str_outbuf, str_outs))
    }
}

#[cfg(feature = "rados_striper")]
impl RadosStriper {
    pub fn inner(&self) -> &rados_striper_t {
        &self.rados_striper
    }

    /// This just tells librados that you no longer need to use the striper.
    pub fn destroy_rados_striper(&self) {
        if self.rados_striper.is_null() {
            // No need to do anything
            return;
        }
        unsafe {
            rados_striper_destroy(self.rados_striper);
        }
    }

    fn rados_striper_guard(&self) -> RadosResult<()> {
        if self.rados_striper.is_null() {
            return Err(RadosError::new(
                "Rados striper not created. Please initialize first".to_string(),
            ));
        }
        Ok(())
    }

    /// Write len bytes from buf into the oid object, starting at offset off.
    /// The value of len must be <= UINT_MAX/2.
    pub fn rados_object_write(
        &self,
        object_name: &str,
        buffer: &[u8],
        offset: u64,
    ) -> RadosResult<()> {
        self.rados_striper_guard()?;
        let obj_name_str = CString::new(object_name)?;

        unsafe {
            let ret_code = rados_striper_write(
                self.rados_striper,
                obj_name_str.as_ptr(),
                buffer.as_ptr() as *const c_char,
                buffer.len(),
                offset,
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }

    /// The object is filled with the provided data. If the object exists, it is
    /// atomically
    /// truncated and then written.
    pub fn rados_object_write_full(&self, object_name: &str, buffer: &[u8]) -> RadosResult<()> {
        self.rados_striper_guard()?;
        let obj_name_str = CString::new(object_name)?;

        unsafe {
            let ret_code = rados_striper_write_full(
                self.rados_striper,
                obj_name_str.as_ptr(),
                buffer.as_ptr() as *const ::libc::c_char,
                buffer.len(),
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }

    /// Append len bytes from buf into the oid object.
    pub fn rados_object_append(&self, object_name: &str, buffer: &[u8]) -> RadosResult<()> {
        self.rados_striper_guard()?;
        let obj_name_str = CString::new(object_name)?;

        unsafe {
            let ret_code = rados_striper_append(
                self.rados_striper,
                obj_name_str.as_ptr(),
                buffer.as_ptr() as *const c_char,
                buffer.len(),
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }

    /// Read data from an object.  This fills the slice given and returns the
    /// amount of bytes read
    /// The io context determines the snapshot to read from, if any was set by
    /// rados_ioctx_snap_set_read().
    /// Default read size is 64K unless you call Vec::with_capacity(1024*128)
    /// with a larger size.
    pub fn rados_object_read(
        &self,
        object_name: &str,
        fill_buffer: &mut Vec<u8>,
        read_offset: u64,
    ) -> RadosResult<i32> {
        self.rados_striper_guard()?;
        let object_name_str = CString::new(object_name)?;
        let mut len = fill_buffer.capacity();
        if len == 0 {
            fill_buffer.reserve_exact(1024 * 64);
            len = fill_buffer.capacity();
        }

        unsafe {
            let ret_code = rados_striper_read(
                self.rados_striper,
                object_name_str.as_ptr(),
                fill_buffer.as_mut_ptr() as *mut c_char,
                len,
                read_offset,
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
            fill_buffer.set_len(ret_code as usize);
            Ok(ret_code)
        }
    }

    /// Delete an object
    /// Note: This does not delete any snapshots of the object.
    pub fn rados_object_remove(&self, object_name: &str) -> RadosResult<()> {
        self.rados_striper_guard()?;
        let object_name_str = CString::new(object_name)?;

        unsafe {
            let ret_code = rados_striper_remove(
                self.rados_striper,
                object_name_str.as_ptr() as *const c_char,
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }

    /// Resize an object
    /// If this enlarges the object, the new area is logically filled with
    /// zeroes. If this shrinks the object, the excess data is removed.
    pub fn rados_object_trunc(&self, object_name: &str, new_size: u64) -> RadosResult<()> {
        self.rados_striper_guard()?;
        let object_name_str = CString::new(object_name)?;

        unsafe {
            let ret_code =
                rados_striper_trunc(self.rados_striper, object_name_str.as_ptr(), new_size);
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }

    /// Get the value of an extended attribute on an object.
    pub fn rados_object_getxattr(
        &self,
        object_name: &str,
        attr_name: &str,
        fill_buffer: &mut [u8],
    ) -> RadosResult<i32> {
        self.rados_striper_guard()?;
        let object_name_str = CString::new(object_name)?;
        let attr_name_str = CString::new(attr_name)?;

        unsafe {
            let ret_code = rados_striper_getxattr(
                self.rados_striper,
                object_name_str.as_ptr() as *const c_char,
                attr_name_str.as_ptr() as *const c_char,
                fill_buffer.as_mut_ptr() as *mut c_char,
                fill_buffer.len(),
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
            Ok(ret_code)
        }
    }

    /// Set an extended attribute on an object.
    pub fn rados_object_setxattr(
        &self,
        object_name: &str,
        attr_name: &str,
        attr_value: &mut [u8],
    ) -> RadosResult<()> {
        self.rados_striper_guard()?;
        let object_name_str = CString::new(object_name)?;
        let attr_name_str = CString::new(attr_name)?;

        unsafe {
            let ret_code = rados_striper_setxattr(
                self.rados_striper,
                object_name_str.as_ptr() as *const c_char,
                attr_name_str.as_ptr() as *const c_char,
                attr_value.as_mut_ptr() as *mut c_char,
                attr_value.len(),
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }

    /// Delete an extended attribute from an object.
    pub fn rados_object_rmxattr(&self, object_name: &str, attr_name: &str) -> RadosResult<()> {
        self.rados_striper_guard()?;
        let object_name_str = CString::new(object_name)?;
        let attr_name_str = CString::new(attr_name)?;

        unsafe {
            let ret_code = rados_striper_rmxattr(
                self.rados_striper,
                object_name_str.as_ptr() as *const c_char,
                attr_name_str.as_ptr() as *const c_char,
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(())
    }

    /// Get the rados_xattrs_iter_t reference to iterate over xattrs on an
    /// object Used in conjuction with XAttr::new() to iterate.
    pub fn rados_get_xattr_iterator(&self, object_name: &str) -> RadosResult<rados_xattrs_iter_t> {
        self.rados_striper_guard()?;
        let object_name_str = CString::new(object_name)?;
        let mut xattr_iterator_handle: rados_xattrs_iter_t = ptr::null_mut();

        unsafe {
            let ret_code = rados_striper_getxattrs(
                self.rados_striper,
                object_name_str.as_ptr(),
                &mut xattr_iterator_handle,
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok(xattr_iterator_handle)
    }

    /// Get object stats (size,SystemTime)
    pub fn rados_object_stat(&self, object_name: &str) -> RadosResult<(u64, SystemTime)> {
        self.rados_striper_guard()?;
        let object_name_str = CString::new(object_name)?;
        let mut psize: u64 = 0;
        let mut time: ::libc::time_t = 0;

        unsafe {
            let ret_code = rados_striper_stat(
                self.rados_striper,
                object_name_str.as_ptr(),
                &mut psize,
                &mut time,
            );
            if ret_code < 0 {
                return Err(ret_code.into());
            }
        }
        Ok((psize, (UNIX_EPOCH + Duration::from_secs(time as u64))))
    }
}