use core::ffi::CStr;
use std::path::Path;
use libloading::Library;
use crate::symbols::Symbols;
use crate::{ffi, Error, OutOfBoundsPolicy, Parameter, ParameterValue};
#[derive(Clone, Debug, PartialEq)]
pub struct MaterialPropertyDescription {
pub name: String,
pub output: String,
pub inputs: Vec<String>,
pub parameters: Vec<Parameter>,
pub tfel_version: String,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Evaluation {
pub value: f64,
pub out_of_bounds: Option<usize>,
}
#[derive(Debug)]
pub struct MaterialProperty {
description: MaterialPropertyDescription,
policy: OutOfBoundsPolicy,
function: ffi::MaterialPropertyFn,
_library: Library,
}
impl MaterialProperty {
pub unsafe fn load(
library: impl AsRef<Path>,
name: &str,
parameters: &[(&str, f64)],
policy: OutOfBoundsPolicy,
) -> Result<Self, Error> {
let path = library.as_ref();
let library = unsafe { Library::new(path) }.map_err(|source| Error::Open {
library: path.to_path_buf(),
source,
})?;
let symbols = Symbols {
library: &library,
name,
hypothesis: None,
};
let tfel_version = symbols.check(0)?;
let output = symbols.strings("output", 1)?.remove(0);
let n = usize::from(symbols.u16("nargs")?);
let inputs = if n == 0 {
Vec::new()
} else {
symbols.strings("args", n)?
};
let function = *unsafe { library.get::<ffi::MaterialPropertyFn>(name) }.map_err(|_| {
Error::MissingSymbol {
symbol: name.to_owned(),
}
})?;
let mut status = ffi::OutputStatus::CLEARED;
let ignored = vec![f64::NAN; n];
unsafe {
function(
&mut status,
ignored.as_ptr(),
n,
OutOfBoundsPolicy::None.code(),
)
};
let declared = symbols.parameters()?;
let values: Vec<_> = parameters
.iter()
.map(|&(parameter, value)| (parameter, ParameterValue::Real(value)))
.collect();
unsafe { symbols.set_parameters(&declared, &values)? };
Ok(MaterialProperty {
description: MaterialPropertyDescription {
name: name.to_owned(),
output,
inputs,
parameters: declared,
tfel_version,
},
policy,
function,
_library: library,
})
}
pub fn description(&self) -> &MaterialPropertyDescription {
&self.description
}
pub fn evaluate(&self, inputs: &[f64]) -> Result<Evaluation, Error> {
let expected = self.description.inputs.len();
if inputs.len() != expected {
return Err(Error::WrongLength {
array: "inputs",
expected,
found: inputs.len(),
});
}
let mut status = ffi::OutputStatus::CLEARED;
let value = unsafe {
(self.function)(
&mut status,
inputs.as_ptr(),
inputs.len(),
self.policy.code(),
)
};
let input = (status.bounds_status.unsigned_abs() as usize).checked_sub(1);
let message = CStr::from_bytes_until_nul(&status.msg)
.map(|m| m.to_string_lossy().trim_end().to_owned())
.unwrap_or_default();
match status.status {
0 | 1 => Ok(Evaluation {
value,
out_of_bounds: input,
}),
-1 => Err(Error::OutOfBounds {
input: input
.and_then(|i| self.description.inputs.get(i))
.cloned()
.unwrap_or_default(),
message,
}),
code => {
let message = match code {
_ if !message.is_empty() => message,
-3 => format!("error {} of the C library", status.c_error_number),
-4 => "the value is not finite".to_owned(),
_ => format!("status {code}"),
};
Err(Error::EvaluationFailed { message })
}
}
}
}