#![allow(unsafe_code)]
use crate::Index;
use std::cell::RefCell;
thread_local! {
static REGISTRY: RefCell<Vec<Option<Index>>> = const { RefCell::new(Vec::new()) };
}
#[no_mangle]
pub extern "C" fn dsidx_alloc(len: u32) -> u32 {
let slice = vec![0u8; len as usize].into_boxed_slice();
Box::into_raw(slice) as *mut u8 as u32
}
#[no_mangle]
pub unsafe extern "C" fn dsidx_free(ptr: u32, len: u32) {
if ptr == 0 {
return;
}
let slice = std::slice::from_raw_parts_mut(ptr as *mut u8, len as usize);
drop(Box::from_raw(slice));
}
#[no_mangle]
pub unsafe extern "C" fn dsidx_open(ptr: u32, len: u32) -> u32 {
let bytes = std::slice::from_raw_parts(ptr as *const u8, len as usize);
let owned = bytes.to_vec();
match Index::from_bytes(&owned) {
Ok(index) => REGISTRY.with(|r| {
let mut registry = r.borrow_mut();
let handle = registry.len() as u32 + 1;
registry.push(Some(index));
handle
}),
Err(_) => 0,
}
}
#[no_mangle]
pub unsafe extern "C" fn dsidx_close(handle: u32) {
REGISTRY.with(|r| {
let mut registry = r.borrow_mut();
let slot = (handle as usize)
.checked_sub(1)
.and_then(|i| registry.get_mut(i));
if let Some(slot) = slot {
*slot = None;
}
});
}
#[no_mangle]
pub unsafe extern "C" fn dsidx_query(
handle: u32,
qptr: u32,
qlen: u32,
limit: u32,
out_ptr: u32,
out_cap: u32,
) -> u32 {
let query_bytes = std::slice::from_raw_parts(qptr as *const u8, qlen as usize);
let query = match std::str::from_utf8(query_bytes) {
Ok(q) => q.to_string(),
Err(_) => return 3,
};
REGISTRY.with(|r| {
let mut registry = r.borrow_mut();
let slot = (handle as usize)
.checked_sub(1)
.and_then(|i| registry.get_mut(i));
let Some(index_slot) = slot else { return 2 };
let Some(index) = index_slot.as_ref() else {
return 2;
};
let hits = index.query(&query, limit.max(1) as usize);
let mut json = String::from("[");
for (n, hit) in hits.iter().enumerate() {
if n > 0 {
json.push(',');
}
json.push_str(&format!("{{\"doc\":{},\"score\":{}}}", hit.doc, hit.score));
}
json.push(']');
let out = std::slice::from_raw_parts_mut(out_ptr as *mut u8, out_cap as usize);
let n = json.len().min(out.len());
out[..n].copy_from_slice(&json.as_bytes()[..n]);
n as u32
})
}