Skip to main content

cadlib/
version_check.rs

1//! First-use compatibility check between these bindings and the native library.
2//!
3//! The bindings accept exactly one native `libcadlib`: the one released with
4//! them. The expected version is the generated [`LIB_VERSION`]; the native lib's
5//! comes from `cad_version()`. Any difference fails, and the error points at the
6//! install scripts of the expected release.
7
8use std::{ffi::CStr, sync::OnceLock};
9
10use crate::{ffi, lib_version::LIB_VERSION};
11
12/// The native library version reported by `cad_version()` (empty if null).
13fn lib_version() -> String {
14    // SAFETY: `cad_version` returns an owned, NUL-terminated C string or null.
15    let ptr = unsafe { ffi::cad_version() };
16    if ptr.is_null() {
17        return String::new();
18    }
19    // SAFETY: `ptr` is a valid string owned by the library, freed below.
20    let owned = unsafe { CStr::from_ptr(ptr) }
21        .to_string_lossy()
22        .into_owned();
23    // SAFETY: hand the library-allocated string back to be freed.
24    unsafe { ffi::cad_free_string(ptr) };
25    owned
26}
27
28/// The version string of the loaded native library (e.g. `"3.4.0"`).
29#[must_use]
30pub fn version() -> String {
31    lib_version()
32}
33
34/// Reports an error unless the native lib version is exactly `expected`.
35fn 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
47/// Verify, once per process, that the native lib is the one these bindings
48/// require. The result is cached so repeated `Cad::load` calls are cheap.
49pub(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}