1use crate::{ffi, Error};
17use libc::{self, c_char, c_void, size_t};
18use std::ffi::{CStr, CString};
19use std::path::Path;
20use std::ptr;
21
22pub(crate) unsafe fn from_cstr_without_free(ptr: *const c_char) -> String {
25 let cstr = unsafe { CStr::from_ptr(ptr as *const _) };
26 String::from_utf8_lossy(cstr.to_bytes()).into_owned()
27}
28
29pub(crate) unsafe fn from_cstr_and_free(ptr: *const c_char) -> String {
32 let cstr = unsafe { CStr::from_ptr(ptr as *const _) };
33 let s = String::from_utf8_lossy(cstr.to_bytes()).into_owned();
34 ffi::rocksdb_free(ptr as *mut c_void);
35 s
36}
37
38pub(crate) unsafe fn raw_data(ptr: *const c_char, size: usize) -> Option<Vec<u8>> {
39 if ptr.is_null() {
40 None
41 } else {
42 let mut dst = vec![0; size];
43 unsafe { ptr::copy_nonoverlapping(ptr.cast::<u8>(), dst.as_mut_ptr(), size) };
44
45 Some(dst)
46 }
47}
48
49pub fn convert_rocksdb_error(rocksdb_err: *const c_char) -> Error {
52 let rocksdb_err_str = unsafe { from_cstr_and_free(rocksdb_err) };
53 Error::new(rocksdb_err_str)
54}
55
56pub fn opt_bytes_to_ptr<T: AsRef<[u8]> + ?Sized>(opt: Option<&T>) -> *const c_char {
62 match opt {
63 Some(v) => v.as_ref().as_ptr() as *const c_char,
64 None => ptr::null(),
65 }
66}
67
68pub(crate) fn to_cpath<P: AsRef<Path>>(path: P) -> Result<CString, Error> {
69 let path = path.as_ref();
70
71 #[cfg(unix)]
72 let cpath = {
73 use std::os::unix::ffi::OsStrExt;
74 CString::new(path.as_os_str().as_bytes())
75 };
76
77 #[cfg(not(unix))]
78 let cpath = CString::new(path.to_string_lossy().as_bytes());
79
80 match cpath {
81 Ok(c) => Ok(c),
82 Err(e) => Err(Error::new(format!(
83 "Failed to convert path to CString: {e}"
84 ))),
85 }
86}
87
88#[cfg(all(test, unix))]
89#[test]
90fn to_cpath_preserves_non_utf8_bytes() {
91 use std::ffi::OsString;
92 use std::os::unix::ffi::{OsStrExt, OsStringExt};
93
94 let path = Path::new(&OsString::from_vec(b"rocksdb-\xff".to_vec())).to_path_buf();
95 let cpath = to_cpath(&path).unwrap();
96
97 assert_eq!(path.as_os_str().as_bytes(), cpath.as_bytes());
98}
99
100macro_rules! ffi_try {
104 ( $($function:ident)::*() ) => {
105 ffi_try_impl!($($function)::*())
106 };
107
108 ( $($function:ident)::*( $arg1:expr $(, $arg:expr)* $(,)? ) ) => {
109 ffi_try_impl!($($function)::*($arg1 $(, $arg)* ,))
110 };
111}
112
113macro_rules! ffi_try_impl {
114 ( $($function:ident)::*( $($arg:expr,)*) ) => {{
115 let mut err: *mut ::libc::c_char = ::std::ptr::null_mut();
116 let result = $($function)::*($($arg,)* &mut err);
117 if !err.is_null() {
118 return Err($crate::ffi_util::convert_rocksdb_error(err));
119 }
120 result
121 }};
122}
123
124pub trait CStrLike {
155 type Baked: std::ops::Deref<Target = CStr>;
156 type Error: std::fmt::Debug + std::fmt::Display;
157
158 fn bake(self) -> Result<Self::Baked, Self::Error>;
162
163 fn into_c_string(self) -> Result<CString, Self::Error>;
169}
170
171impl CStrLike for &str {
172 type Baked = CString;
173 type Error = std::ffi::NulError;
174
175 fn bake(self) -> Result<Self::Baked, Self::Error> {
176 CString::new(self)
177 }
178 fn into_c_string(self) -> Result<CString, Self::Error> {
179 CString::new(self)
180 }
181}
182
183impl CStrLike for &String {
186 type Baked = CString;
187 type Error = std::ffi::NulError;
188
189 fn bake(self) -> Result<Self::Baked, Self::Error> {
190 CString::new(self.as_bytes())
191 }
192 fn into_c_string(self) -> Result<CString, Self::Error> {
193 CString::new(self.as_bytes())
194 }
195}
196
197impl CStrLike for &CStr {
198 type Baked = Self;
199 type Error = std::convert::Infallible;
200
201 fn bake(self) -> Result<Self::Baked, Self::Error> {
202 Ok(self)
203 }
204 fn into_c_string(self) -> Result<CString, Self::Error> {
205 Ok(self.to_owned())
206 }
207}
208
209impl CStrLike for CString {
214 type Baked = CString;
215 type Error = std::convert::Infallible;
216
217 fn bake(self) -> Result<Self::Baked, Self::Error> {
218 Ok(self)
219 }
220 fn into_c_string(self) -> Result<CString, Self::Error> {
221 Ok(self)
222 }
223}
224
225impl<'a> CStrLike for &'a CString {
228 type Baked = &'a CStr;
229 type Error = std::convert::Infallible;
230
231 fn bake(self) -> Result<Self::Baked, Self::Error> {
232 Ok(self)
233 }
234 fn into_c_string(self) -> Result<CString, Self::Error> {
235 Ok(self.clone())
236 }
237}
238
239pub struct CSlice {
242 data: *const c_char,
243 len: size_t,
244}
245
246impl CSlice {
247 pub(crate) unsafe fn from_raw_parts(data: *const c_char, len: size_t) -> Self {
256 Self { data, len }
257 }
258}
259
260impl AsRef<[u8]> for CSlice {
261 fn as_ref(&self) -> &[u8] {
262 unsafe { std::slice::from_raw_parts(self.data.cast::<u8>(), self.len) }
263 }
264}
265
266impl Drop for CSlice {
267 fn drop(&mut self) {
268 unsafe {
269 ffi::rocksdb_free(self.data as *mut c_void);
270 }
271 }
272}
273
274#[test]
275fn test_c_str_like_bake() {
276 fn test<S: CStrLike>(value: S) -> Result<usize, S::Error> {
277 value
278 .bake()
279 .map(|value| unsafe { libc::strlen(value.as_ptr()) })
280 }
281
282 assert_eq!(Ok(3), test("foo")); assert_eq!(Ok(3), test(&String::from("foo"))); assert_eq!(Ok(3), test(CString::new("foo").unwrap().as_ref())); assert_eq!(Ok(3), test(&CString::new("foo").unwrap())); assert_eq!(Ok(3), test(CString::new("foo").unwrap())); assert_eq!(3, test("foo\0bar").err().unwrap().nul_position());
289}
290
291#[test]
292fn test_c_str_like_into() {
293 fn test<S: CStrLike>(value: S) -> Result<CString, S::Error> {
294 value.into_c_string()
295 }
296
297 let want = CString::new("foo").unwrap();
298
299 assert_eq!(Ok(want.clone()), test("foo")); assert_eq!(Ok(want.clone()), test(&String::from("foo"))); assert_eq!(
302 Ok(want.clone()),
303 test(CString::new("foo").unwrap().as_ref())
304 ); assert_eq!(Ok(want.clone()), test(&CString::new("foo").unwrap())); assert_eq!(Ok(want), test(CString::new("foo").unwrap())); assert_eq!(3, test("foo\0bar").err().unwrap().nul_position());
309}