use std::ffi::CString;
use std::io;
use bindings::*;
use keyvi_match::KeyviMatch;
use keyvi_match_iterator::KeyviMatchIterator;
use keyvi_string::KeyviString;
pub struct Dictionary {
dict: *mut root::keyvi_dictionary,
}
unsafe impl Send for Dictionary {}
unsafe impl Sync for Dictionary {}
impl Dictionary {
pub fn new(filename: &str) -> io::Result<Dictionary> {
let fn_c = CString::new(filename)?;
let ptr = unsafe { root::keyvi_create_dictionary(fn_c.as_ptr()) };
if ptr.is_null() {
Err(io::Error::new(
io::ErrorKind::InvalidInput,
"could not load file",
))
} else {
Ok(Dictionary { dict: ptr })
}
}
pub fn with_loading_strategy(
filename: &str,
loading_strategy: root::keyvi::dictionary::LoadingStrategy,
) -> io::Result<Dictionary> {
let fn_c = CString::new(filename)?;
let ptr = unsafe {
root::keyvi_create_dictionary_with_loading_strategy(fn_c.as_ptr(), loading_strategy)
};
if ptr.is_null() {
Err(io::Error::new(
io::ErrorKind::InvalidInput,
"could not load file",
))
} else {
Ok(Dictionary { dict: ptr })
}
}
pub fn statistics(&self) -> String {
let c_buf: *mut ::std::os::raw::c_char =
unsafe { root::keyvi_dictionary_get_statistics(self.dict) };
KeyviString::new(c_buf).to_owned()
}
pub fn size(&self) -> usize {
unsafe { root::keyvi_dictionary_get_size(self.dict) }
}
pub fn get(&self, key: &str) -> KeyviMatch {
let match_ptr = unsafe {
root::keyvi_dictionary_get(
self.dict,
key.as_ptr() as *const ::std::os::raw::c_char,
key.len() as usize,
)
};
KeyviMatch::new(match_ptr)
}
pub fn get_all_items(&self) -> KeyviMatchIterator {
let ptr = unsafe { root::keyvi_dictionary_get_all_items(self.dict) };
KeyviMatchIterator::new(ptr)
}
pub fn get_prefix_completions(&self, key: &str, cutoff: usize) -> KeyviMatchIterator {
let ptr = unsafe {
root::keyvi_dictionary_get_prefix_completions(
self.dict,
key.as_ptr() as *const ::std::os::raw::c_char,
key.len() as usize,
cutoff,
)
};
KeyviMatchIterator::new(ptr)
}
pub fn get_fuzzy(&self, key: &str, max_edit_distance: usize) -> KeyviMatchIterator {
let ptr = unsafe {
root::keyvi_dictionary_get_fuzzy(
self.dict,
key.as_ptr() as *const ::std::os::raw::c_char,
key.len() as usize,
max_edit_distance,
)
};
KeyviMatchIterator::new(ptr)
}
pub fn get_multi_word_completions(&self, key: &str, cutoff: usize) -> KeyviMatchIterator {
let ptr = unsafe {
root::keyvi_dictionary_get_multi_word_completions(
self.dict,
key.as_ptr() as *const ::std::os::raw::c_char,
key.len() as usize,
cutoff,
)
};
KeyviMatchIterator::new(ptr)
}
}
impl Drop for Dictionary {
fn drop(&mut self) {
unsafe {
root::keyvi_dictionary_destroy(self.dict);
}
}
}