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//
1516use libc::{c_char, c_int, c_void, size_t};
17use std::cmp::Ordering;
18use std::ffi::CString;
19use std::slice;
2021pub type CompareFn = dyn Fn(&[u8], &[u8]) -> Ordering;
2223pub struct ComparatorCallback {
24pub name: CString,
25pub f: Box<CompareFn>,
26}
2728pub unsafe extern "C" fn destructor_callback(raw_cb: *mut c_void) {
29 drop(Box::from_raw(raw_cb as *mut ComparatorCallback));
30}
3132pub unsafe extern "C" fn name_callback(raw_cb: *mut c_void) -> *const c_char {
33let cb: &mut ComparatorCallback = &mut *(raw_cb as *mut ComparatorCallback);
34let ptr = cb.name.as_ptr();
35 ptr as *const c_char
36}
3738pub 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 {
45let cb: &mut ComparatorCallback = &mut *(raw_cb as *mut ComparatorCallback);
46let a: &[u8] = slice::from_raw_parts(a_raw as *const u8, a_len);
47let b: &[u8] = slice::from_raw_parts(b_raw as *const u8, b_len);
48match (cb.f)(a, b) {
49 Ordering::Less => -1,
50 Ordering::Equal => 0,
51 Ordering::Greater => 1,
52 }
53}