rocksdb/
comparator.rs

1// Copyright 2020 Tyler Neely
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14//
15
16use libc::{c_char, c_int, c_void, size_t};
17use std::cmp::Ordering;
18use std::ffi::CString;
19use std::slice;
20
21pub type CompareFn = dyn Fn(&[u8], &[u8]) -> Ordering;
22
23pub struct ComparatorCallback {
24    pub name: CString,
25    pub f: Box<CompareFn>,
26}
27
28pub unsafe extern "C" fn destructor_callback(raw_cb: *mut c_void) {
29    drop(Box::from_raw(raw_cb as *mut ComparatorCallback));
30}
31
32pub unsafe extern "C" fn name_callback(raw_cb: *mut c_void) -> *const c_char {
33    let cb: &mut ComparatorCallback = &mut *(raw_cb as *mut ComparatorCallback);
34    let ptr = cb.name.as_ptr();
35    ptr as *const c_char
36}
37
38pub unsafe extern "C" fn compare_callback(
39    raw_cb: *mut c_void,
40    a_raw: *const c_char,
41    a_len: size_t,
42    b_raw: *const c_char,
43    b_len: size_t,
44) -> c_int {
45    let cb: &mut ComparatorCallback = &mut *(raw_cb as *mut ComparatorCallback);
46    let a: &[u8] = slice::from_raw_parts(a_raw as *const u8, a_len);
47    let b: &[u8] = slice::from_raw_parts(b_raw as *const u8, b_len);
48    match (cb.f)(a, b) {
49        Ordering::Less => -1,
50        Ordering::Equal => 0,
51        Ordering::Greater => 1,
52    }
53}