1use std::{ffi::CStr, sync::OnceLock};
9
10use crate::{ffi, lib_version::LIB_VERSION};
11
12fn lib_version() -> String {
14 let ptr = unsafe { ffi::cad_version() };
16 if ptr.is_null() {
17 return String::new();
18 }
19 let owned = unsafe { CStr::from_ptr(ptr) }
21 .to_string_lossy()
22 .into_owned();
23 unsafe { ffi::cad_free_string(ptr) };
25 owned
26}
27
28#[must_use]
30pub fn version() -> String {
31 lib_version()
32}
33
34fn ensure_lib_version(expected: &str, lib: &str) -> Result<(), String> {
36 if lib == expected {
37 return Ok(());
38 }
39 Err(format!(
40 "native libcadlib v{lib} does not match these Rust bindings (v{expected}); install it \
41 with install-cadlib.sh or install-cadlib.ps1 from the v{expected} release"
42 ))
43}
44
45static CHECKED: OnceLock<Result<(), String>> = OnceLock::new();
46
47pub(crate) fn check_lib_version() -> Result<(), String> {
50 CHECKED
51 .get_or_init(|| ensure_lib_version(LIB_VERSION, &lib_version()))
52 .clone()
53}
54
55#[cfg(test)]
56mod tests {
57 use super::{check_lib_version, ensure_lib_version, lib_version, LIB_VERSION};
58
59 #[test]
60 fn linked_lib_matches_bindings() {
61 assert_eq!(check_lib_version(), Ok(()));
62 }
63
64 #[test]
65 fn mismatched_lib_is_rejected() {
66 let lib = lib_version();
67 let expected = format!("{LIB_VERSION}-mismatch");
68 assert_eq!(
69 ensure_lib_version(&expected, &lib),
70 Err(format!(
71 "native libcadlib v{lib} does not match these Rust bindings (v{expected}); \
72 install it with install-cadlib.sh or install-cadlib.ps1 from the v{expected} \
73 release"
74 ))
75 );
76 }
77}