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
use crate::{handle::Handle, ColumnFamily, Error};
use libc::c_char;
use std::ffi::CString;

pub trait SetOptions {
    fn set_options(&self, opts: &[(&str, &str)]) -> Result<(), Error>;
    fn set_options_cf(&self, cf: &ColumnFamily, opts: &[(&str, &str)]) -> Result<(), Error>;
}

impl<T> SetOptions for T
where
    T: Handle<ffi::rocksdb_t>,
{
    fn set_options(&self, opts: &[(&str, &str)]) -> Result<(), Error> {
        let copts = build_coptions(opts)?;
        let cnames: Vec<*const c_char> = copts.iter().map(|opt| opt.0.as_ptr()).collect();
        let cvalues: Vec<*const c_char> = copts.iter().map(|opt| opt.1.as_ptr()).collect();
        let count = opts.len() as i32;

        unsafe {
            ffi_try!(ffi::rocksdb_set_options(
                self.handle(),
                count,
                cnames.as_ptr(),
                cvalues.as_ptr(),
            ));
        }
        Ok(())
    }

    fn set_options_cf(&self, cf: &ColumnFamily, opts: &[(&str, &str)]) -> Result<(), Error> {
        let copts = build_coptions(opts)?;
        let cnames: Vec<*const c_char> = copts.iter().map(|opt| opt.0.as_ptr()).collect();
        let cvalues: Vec<*const c_char> = copts.iter().map(|opt| opt.1.as_ptr()).collect();
        let count = opts.len() as i32;

        unsafe {
            ffi_try!(ffi::rocksdb_set_options_cf(
                self.handle(),
                cf.handle(),
                count,
                cnames.as_ptr(),
                cvalues.as_ptr(),
            ));
        }
        Ok(())
    }
}

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