use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_int, c_ulonglong};
use std::path::Path;
use std::ptr;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;
use crate::{Dispatcher, MismatchPolicy};
static INIT: AtomicBool = AtomicBool::new(false);
struct ProfileHandle {
dispatcher: Dispatcher,
}
pub struct SiliceraProfile {
inner: Mutex<ProfileHandle>,
}
#[no_mangle]
pub extern "C" fn silicera_init() -> c_int {
INIT.store(true, Ordering::SeqCst);
0
}
#[no_mangle]
pub unsafe extern "C" fn silicera_profile_load(
path: *const c_char,
strict_machine: c_int,
out_profile: *mut *mut SiliceraProfile,
) -> c_int {
if path.is_null() || out_profile.is_null() {
return -1;
}
let cstr = unsafe { CStr::from_ptr(path) };
let path_str = match cstr.to_str() {
Ok(s) => s,
Err(_) => return -2,
};
let policy = if strict_machine != 0 {
MismatchPolicy::StrictMachine
} else {
MismatchPolicy::FallbackBaseline
};
let dispatcher = match Dispatcher::open(Path::new(path_str), policy) {
Ok(d) => d,
Err(_) => return -2,
};
let boxed = Box::new(SiliceraProfile {
inner: Mutex::new(ProfileHandle { dispatcher }),
});
unsafe {
*out_profile = Box::into_raw(boxed);
}
0
}
#[no_mangle]
pub unsafe extern "C" fn silicera_variant_select(
profile: *mut SiliceraProfile,
size_bytes: c_ulonglong,
buf: *mut c_char,
buf_len: usize,
) -> c_int {
if profile.is_null() || buf.is_null() || buf_len == 0 {
return -1;
}
let handle = unsafe { &*profile };
let name = {
let g = match handle.inner.lock() {
Ok(g) => g,
Err(_) => return -2,
};
g.dispatcher.size(size_bytes).to_string()
};
let cstr = match CString::new(name) {
Ok(c) => c,
Err(_) => return -2,
};
let bytes = cstr.as_bytes_with_nul();
if bytes.len() > buf_len {
return -3;
}
unsafe {
ptr::copy_nonoverlapping(bytes.as_ptr() as *const c_char, buf, bytes.len());
}
0
}
#[no_mangle]
pub unsafe extern "C" fn silicera_profile_free(profile: *mut SiliceraProfile) {
if profile.is_null() {
return;
}
unsafe {
drop(Box::from_raw(profile));
}
}