use std::{ffi::CStr, sync::OnceLock};
use crate::{ffi, lib_version::LIB_VERSION};
fn lib_version() -> String {
let ptr = unsafe { ffi::cad_version() };
if ptr.is_null() {
return String::new();
}
let owned = unsafe { CStr::from_ptr(ptr) }
.to_string_lossy()
.into_owned();
unsafe { ffi::cad_free_string(ptr) };
owned
}
#[must_use]
pub fn version() -> String {
lib_version()
}
fn ensure_lib_version(expected: &str, lib: &str) -> Result<(), String> {
if lib == expected {
return Ok(());
}
Err(format!(
"native libcadlib v{lib} does not match these Rust bindings (v{expected}); install it \
with install-cadlib.sh or install-cadlib.ps1 from the v{expected} release"
))
}
static CHECKED: OnceLock<Result<(), String>> = OnceLock::new();
pub(crate) fn check_lib_version() -> Result<(), String> {
CHECKED
.get_or_init(|| ensure_lib_version(LIB_VERSION, &lib_version()))
.clone()
}
#[cfg(test)]
mod tests {
use super::{check_lib_version, ensure_lib_version, lib_version, LIB_VERSION};
#[test]
fn linked_lib_matches_bindings() {
assert_eq!(check_lib_version(), Ok(()));
}
#[test]
fn mismatched_lib_is_rejected() {
let lib = lib_version();
let expected = format!("{LIB_VERSION}-mismatch");
assert_eq!(
ensure_lib_version(&expected, &lib),
Err(format!(
"native libcadlib v{lib} does not match these Rust bindings (v{expected}); \
install it with install-cadlib.sh or install-cadlib.ps1 from the v{expected} \
release"
))
);
}
}