Skip to main content

diffsol_c/
matrix_type_c.rs

1use std::os::raw::c_char;
2use std::ptr;
3
4use crate::c_invalid_arg;
5use crate::matrix_type::MatrixType;
6
7const MATRIX_TYPE_NALGEBRA: &[u8] = b"nalgebra_dense\0";
8const MATRIX_TYPE_FAER: &[u8] = b"faer_dense\0";
9const MATRIX_TYPE_FAER_SPARSE: &[u8] = b"faer_sparse\0";
10
11pub(crate) fn matrix_type_from_i32(value: i32) -> Option<MatrixType> {
12    match value {
13        0 => Some(MatrixType::NalgebraDense),
14        1 => Some(MatrixType::FaerDense),
15        2 => Some(MatrixType::FaerSparse),
16        _ => None,
17    }
18}
19
20pub(crate) fn matrix_type_to_i32(value: MatrixType) -> i32 {
21    match value {
22        MatrixType::NalgebraDense => 0,
23        MatrixType::FaerDense => 1,
24        MatrixType::FaerSparse => 2,
25    }
26}
27
28/// Return the number of matrix type enum values.
29///
30/// # Safety
31/// This function is safe to call from C. It does not dereference any
32/// caller-provided pointers.
33#[unsafe(no_mangle)]
34pub unsafe extern "C" fn diffsol_matrix_type_count() -> usize {
35    3
36}
37
38/// Return whether a matrix type enum value is valid.
39///
40/// # Safety
41/// This function is safe to call from C. It does not dereference any
42/// caller-provided pointers.
43#[unsafe(no_mangle)]
44pub unsafe extern "C" fn diffsol_matrix_type_is_valid(value: i32) -> i32 {
45    if matrix_type_from_i32(value).is_some() {
46        1
47    } else {
48        c_invalid_arg!("invalid matrix_type");
49        0
50    }
51}
52
53/// Return the name of a matrix type enum value.
54///
55/// # Safety
56/// The returned pointer is borrowed from static storage owned by this library
57/// and must not be freed or mutated by the caller.
58#[unsafe(no_mangle)]
59pub unsafe extern "C" fn diffsol_matrix_type_name(value: i32) -> *const c_char {
60    match matrix_type_from_i32(value) {
61        Some(MatrixType::NalgebraDense) => MATRIX_TYPE_NALGEBRA.as_ptr() as *const c_char,
62        Some(MatrixType::FaerDense) => MATRIX_TYPE_FAER.as_ptr() as *const c_char,
63        Some(MatrixType::FaerSparse) => MATRIX_TYPE_FAER_SPARSE.as_ptr() as *const c_char,
64        None => {
65            c_invalid_arg!("invalid matrix_type");
66            ptr::null()
67        }
68    }
69}