From 57d4669d974d65cf894dc698537f7ae3f83d7f2f Mon Sep 17 00:00:00 2001 From: Alexander Regueiro Date: Sun, 20 Nov 2016 21:17:18 +0000 Subject: [PATCH] Added explicit `CompareFn` type for comparator function. Changed return type of comparator function from `i32` to `std::cmp::Ordering`. --- src/comparator.rs | 11 +++++++++-- src/rocksdb_options.rs | 6 +++--- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/comparator.rs b/src/comparator.rs index 58fc65a..ae998d9 100644 --- a/src/comparator.rs +++ b/src/comparator.rs @@ -13,15 +13,18 @@ // limitations under the License. // +use std::cmp::Ordering; use std::ffi::CString; use std::mem; use std::slice; use libc::{c_char, c_int, c_void, size_t}; +pub type CompareFn = fn(&[u8], &[u8]) -> Ordering; + pub struct ComparatorCallback { pub name: CString, - pub f: fn(&[u8], &[u8]) -> i32, + pub f: CompareFn, } pub unsafe extern "C" fn destructor_callback(raw_cb: *mut c_void) { @@ -43,5 +46,9 @@ pub unsafe extern "C" fn compare_callback(raw_cb: *mut c_void, let cb: &mut ComparatorCallback = &mut *(raw_cb as *mut ComparatorCallback); let a: &[u8] = slice::from_raw_parts(a_raw as *const u8, a_len as usize); let b: &[u8] = slice::from_raw_parts(b_raw as *const u8, b_len as usize); - (cb.f)(a, b) + match (cb.f)(a, b) { + Ordering::Less => -1, + Ordering::Equal => 0, + Ordering::Greater => 1, + } } diff --git a/src/rocksdb_options.rs b/src/rocksdb_options.rs index 49b03ff..d0067a7 100644 --- a/src/rocksdb_options.rs +++ b/src/rocksdb_options.rs @@ -19,7 +19,7 @@ use std::mem; use libc::{self, c_int, c_uchar, c_uint, c_void, size_t, uint64_t}; use {BlockBasedOptions, Options, WriteOptions}; -use comparator::{self, ComparatorCallback}; +use comparator::{self, ComparatorCallback, CompareFn}; use ffi; use merge_operator::{self, MergeFn, MergeOperatorCallback, full_merge_callback, partial_merge_callback}; @@ -220,7 +220,7 @@ impl Options { /// The client must ensure that the comparator supplied here has the same /// name and orders keys *exactly* the same as the comparator provided to /// previous open calls on the same DB. - pub fn set_comparator(&mut self, name: &str, compare_fn: fn(&[u8], &[u8]) -> i32) { + pub fn set_comparator(&mut self, name: &str, compare_fn: CompareFn) { let cb = Box::new(ComparatorCallback { name: CString::new(name.as_bytes()).unwrap(), f: compare_fn, @@ -236,7 +236,7 @@ impl Options { } #[deprecated(since = "0.5.0", note = "add_comparator has been renamed to set_comparator")] - pub fn add_comparator(&mut self, name: &str, compare_fn: fn(&[u8], &[u8]) -> i32) { + pub fn add_comparator(&mut self, name: &str, compare_fn: CompareFn) { self.set_comparator(name, compare_fn); }