use castep_cell_fmt::{Cell, CellValue, ToCell, ToCellValue};
use castep_cell_fmt::parse::{FromCellValue, FromKeyValue};
use castep_cell_fmt::{CResult, Error};
use castep_cell_fmt::query::value_as_string;
use serde::{Deserialize, Serialize};
pub type PhononMethod = SeconddMethod;
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename = "SECONDD_METHOD")]
#[derive(Default)]
pub enum SeconddMethod {
#[serde(alias = "linearresponse", alias = "LINEARRESPONSE")]
#[serde(alias = "DFPT", alias = "dfpt")] #[default]
LinearResponse,
#[serde(alias = "finitedisplacement", alias = "FINITEDISPLACEMENT")]
FiniteDisplacement,
}
impl FromCellValue for SeconddMethod {
fn from_cell_value(value: &CellValue<'_>) -> CResult<Self> {
match value_as_string(value)?.to_ascii_lowercase().as_str() {
"linearresponse" | "dfpt" => Ok(Self::LinearResponse),
"finitedisplacement" => Ok(Self::FiniteDisplacement),
other => Err(Error::Message(format!("unknown SeconddMethod: {other}"))),
}
}
}
impl FromKeyValue for SeconddMethod {
const KEY_NAME: &'static str = "SECONDD_METHOD";
fn from_cell_value_kv(value: &CellValue<'_>) -> CResult<Self> {
Self::from_cell_value(value)
}
}
impl ToCell for SeconddMethod {
fn to_cell(&self) -> Cell<'_> {
Cell::KeyValue("SECONDD_METHOD", self.to_cell_value())
}
}
impl ToCellValue for SeconddMethod {
fn to_cell_value(&self) -> CellValue<'_> {
CellValue::String(
match self {
SeconddMethod::LinearResponse => "LINEARRESPONSE",
SeconddMethod::FiniteDisplacement => "FINITEDISPLACEMENT",
}
.to_string(),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use castep_cell_fmt::CellValue;
#[test]
fn test_case_insensitive() {
assert_eq!(SeconddMethod::from_cell_value(&CellValue::Str("linearresponse")).unwrap(), SeconddMethod::LinearResponse);
assert_eq!(SeconddMethod::from_cell_value(&CellValue::Str("LINEARRESPONSE")).unwrap(), SeconddMethod::LinearResponse);
assert_eq!(SeconddMethod::from_cell_value(&CellValue::Str("dfpt")).unwrap(), SeconddMethod::LinearResponse);
}
#[test]
fn test_all_variants() {
assert_eq!(SeconddMethod::from_cell_value(&CellValue::Str("finitedisplacement")).unwrap(), SeconddMethod::FiniteDisplacement);
}
#[test]
fn test_invalid() {
assert!(SeconddMethod::from_cell_value(&CellValue::Str("invalid")).is_err());
}
#[test]
fn test_key_name() {
assert_eq!(SeconddMethod::KEY_NAME, "SECONDD_METHOD");
}
#[test]
fn test_round_trip_serialization() {
let method = SeconddMethod::LinearResponse;
let cell_value = method.to_cell_value();
let parsed = SeconddMethod::from_cell_value(&cell_value).unwrap();
assert_eq!(parsed, method);
let method = SeconddMethod::FiniteDisplacement;
let cell_value = method.to_cell_value();
let parsed = SeconddMethod::from_cell_value(&cell_value).unwrap();
assert_eq!(parsed, method);
}
#[test]
fn test_default_is_linear_response() {
assert_eq!(SeconddMethod::default(), SeconddMethod::LinearResponse);
}
}