Skip to main content

castep_cell_io/units/
inv_length_units.rs

1use castep_cell_fmt::{Cell, CellValue, ToCell, ToCellValue};
2use castep_cell_fmt::parse::FromCellValue;
3use castep_cell_fmt::{CResult, Error};
4use castep_cell_fmt::query::value_as_str;
5use serde::{Deserialize, Serialize};
6
7/// Specifies the units in which inverse length will be reported.
8///
9/// Keyword type: String
10///
11/// Default: 1/ang
12///
13/// Example:
14/// INV_LENGTH_UNIT : 1/nm
15#[derive(
16    Debug, Default, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize,
17)]
18#[serde(rename = "INV_LENGTH_UNIT")] // Ensures correct key name during serde
19pub enum InvLengthUnit {
20    /// Bohr-1
21    #[serde(alias = "1/BOHR", alias = "1/bohr")]
22    Bohr,
23    /// Meter-1
24    #[serde(alias = "1/M", alias = "1/m")]
25    Meter,
26    /// Nanometer-1
27    #[serde(alias = "1/NM", alias = "1/nm")]
28    NanoMeter,
29    /// Å-1
30    #[serde(alias = "1/ANG", alias = "1/ang")]
31    #[default]
32    Angstrom,
33}
34
35// Implement ToCell for InvLengthUnit to enable serialization via your custom backend
36impl FromCellValue for InvLengthUnit {
37    fn from_cell_value(value: &CellValue<'_>) -> CResult<Self> {
38        match value_as_str(value)?.to_ascii_lowercase().as_str() {
39            "1/bohr" => Ok(Self::Bohr),
40            "1/m" => Ok(Self::Meter),
41            "1/nm" => Ok(Self::NanoMeter),
42            "1/ang" => Ok(Self::Angstrom),
43            other => Err(Error::Message(format!(
44                "unknown InvLengthUnit: {other}"
45            ))),
46        }
47    }
48}
49
50impl ToCell for InvLengthUnit {
51    fn to_cell(&self) -> Cell<'_> {
52        // Create a KeyValue Cell with the name "INV_LENGTH_UNIT" and the unit string as the value.
53        Cell::KeyValue("INV_LENGTH_UNIT", self.to_cell_value())
54    }
55}
56
57// Implement ToCellValue for InvLengthUnit.
58impl ToCellValue for InvLengthUnit {
59    fn to_cell_value(&self) -> CellValue<'_> {
60        CellValue::String(
61            match self {
62                InvLengthUnit::Bohr => "1/bohr",
63                InvLengthUnit::Meter => "1/m",
64                InvLengthUnit::NanoMeter => "1/nm",
65                InvLengthUnit::Angstrom => "1/ang",
66            }
67            .to_string(), // Convert &str to String for CellValue::String
68        )
69    }
70}
71
72