use crate::error::{PyrucastError, Result};
pub trait Named: Copy + Sized + 'static {
const LABEL: &'static str;
const VALUES: &'static [Self];
fn name(self) -> &'static str;
fn aliases() -> &'static [(&'static str, Self)] {
&[]
}
fn from_name(s: &str) -> Option<Self> {
let wanted = s.trim();
Self::VALUES
.iter()
.copied()
.find(|v| v.name().eq_ignore_ascii_case(wanted))
.or_else(|| {
Self::aliases()
.iter()
.find(|(alias, _)| alias.eq_ignore_ascii_case(wanted))
.map(|(_, v)| *v)
})
}
fn parse(s: &str) -> Result<Self> {
Self::from_name(s).ok_or_else(|| {
PyrucastError::Message(format!(
"unknown {} '{}' (expected {})",
Self::LABEL,
s.trim(),
Self::names()
))
})
}
fn names() -> String {
Self::VALUES
.iter()
.map(|v| v.name())
.collect::<Vec<_>>()
.join("|")
}
}
#[macro_export]
macro_rules! named_enum {
($($ty:ty),+ $(,)?) => { $(
#[cfg(feature = "python-api")]
impl<'a, 'py> ::pyo3::FromPyObject<'a, 'py> for $ty {
type Error = ::pyo3::PyErr;
fn extract(
obj: ::pyo3::Borrowed<'a, 'py, ::pyo3::PyAny>,
) -> ::std::result::Result<Self, ::pyo3::PyErr> {
let name: String = obj.extract()?;
<$ty as $crate::named::Named>::parse(&name)
.map_err(|e| ::pyo3::exceptions::PyValueError::new_err(e.to_string()))
}
}
#[cfg(feature = "stub-gen")]
impl ::pyo3_stub_gen::PyStubType for $ty {
fn type_output() -> ::pyo3_stub_gen::TypeInfo {
::pyo3_stub_gen::TypeInfo::builtin("str")
}
}
)+ };
}
named_enum!(
crate::atoms::ElementType,
crate::atoms::Interpolation,
crate::atoms::QuadratureRule,
crate::models::Physics,
crate::models::damage::law::DamageLaw,
crate::models::tensor::Kinematics,
crate::models::plasticity::law::PlasticLaw,
crate::models::shell::ShellModel,
crate::models::symmetry::MaterialSymmetry,
crate::containers::evolution::OutOfRange,
crate::ops::mesh::FrontRelax,
);
#[cfg(feature = "viz")]
named_enum!(crate::viz::Colormap);