arvo 1.0.0

Validated, immutable value objects for common domain types (email, money, identifiers, …)
Documentation
use crate::errors::ValidationError;
use crate::traits::ValueObject;

/// Unit of energy.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum EnergyUnit {
    J,
    KJ,
    MJ,
    KWh,
    Cal,
    Kcal,
}

#[cfg(feature = "serde")]
impl From<Energy> for String {
    fn from(v: Energy) -> String {
        v.canonical
    }
}

impl TryFrom<String> for Energy {
    type Error = ValidationError;
    fn try_from(s: String) -> Result<Self, Self::Error> {
        Self::try_from(s.as_str())
    }
}

impl std::fmt::Display for EnergyUnit {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            EnergyUnit::J => write!(f, "J"),
            EnergyUnit::KJ => write!(f, "kJ"),
            EnergyUnit::MJ => write!(f, "MJ"),
            EnergyUnit::KWh => write!(f, "kWh"),
            EnergyUnit::Cal => write!(f, "cal"),
            EnergyUnit::Kcal => write!(f, "kcal"),
        }
    }
}

/// Input for [`Energy`].
#[derive(Debug, Clone, PartialEq)]
pub struct EnergyInput {
    pub value: f64,
    pub unit: EnergyUnit,
}

/// A validated energy measurement.
///
/// **Validation:** value must be finite and non-negative.
///
/// # Example
///
/// ```rust,ignore
/// use arvo::measurement::{Energy, EnergyInput, EnergyUnit};
/// use arvo::traits::ValueObject;
///
/// let e = Energy::new(EnergyInput { value: 500.0, unit: EnergyUnit::Kcal })?;
/// assert_eq!(e.value(), "500 kcal");
/// ```
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(try_from = "String", into = "String"))]
pub struct Energy {
    value: f64,
    unit: EnergyUnit,
    canonical: String,
}

impl ValueObject for Energy {
    type Input = EnergyInput;
    type Error = ValidationError;

    fn new(input: Self::Input) -> Result<Self, Self::Error> {
        if !input.value.is_finite() || input.value < 0.0 {
            return Err(ValidationError::invalid("Energy", &input.value.to_string()));
        }
        let canonical = format!("{} {}", input.value, input.unit);
        Ok(Self {
            value: input.value,
            unit: input.unit,
            canonical,
        })
    }

    fn into_inner(self) -> Self::Input {
        EnergyInput {
            value: self.value,
            unit: self.unit,
        }
    }
}

impl Energy {
    pub fn value(&self) -> &str {
        &self.canonical
    }

    pub fn amount(&self) -> f64 {
        self.value
    }
    pub fn unit(&self) -> &EnergyUnit {
        &self.unit
    }
}

impl TryFrom<&str> for Energy {
    type Error = ValidationError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        let err = || ValidationError::invalid("Energy", value);
        let (val_str, unit_str) = value.trim().split_once(' ').ok_or_else(err)?;
        let val: f64 = val_str.trim().parse().map_err(|_| err())?;
        let unit = match unit_str.trim() {
            "J" => EnergyUnit::J,
            "kJ" => EnergyUnit::KJ,
            "MJ" => EnergyUnit::MJ,
            "kWh" => EnergyUnit::KWh,
            "cal" => EnergyUnit::Cal,
            "kcal" => EnergyUnit::Kcal,
            _ => return Err(err()),
        };
        Self::new(EnergyInput { value: val, unit })
    }
}

impl std::fmt::Display for Energy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.canonical)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn accepts_valid() {
        let e = Energy::new(EnergyInput {
            value: 500.0,
            unit: EnergyUnit::Kcal,
        })
        .unwrap();
        assert_eq!(e.value(), "500 kcal");
    }

    #[test]
    fn accepts_zero() {
        assert!(
            Energy::new(EnergyInput {
                value: 0.0,
                unit: EnergyUnit::J
            })
            .is_ok()
        );
    }

    #[test]
    fn rejects_negative() {
        assert!(
            Energy::new(EnergyInput {
                value: -1.0,
                unit: EnergyUnit::J
            })
            .is_err()
        );
    }

    #[test]
    fn rejects_nan() {
        assert!(
            Energy::new(EnergyInput {
                value: f64::NAN,
                unit: EnergyUnit::J
            })
            .is_err()
        );
    }

    #[test]
    fn try_from_parses_valid() {
        let e = Energy::try_from("1.5 kJ").unwrap();
        assert_eq!(e.value(), "1.5 kJ");
    }

    #[test]
    fn try_from_rejects_no_space() {
        assert!(Energy::try_from("1.5").is_err());
    }

    #[test]
    fn try_from_rejects_unknown_unit() {
        assert!(Energy::try_from("1.5 BTU").is_err());
    }

    #[cfg(feature = "serde")]
    #[test]
    fn serde_roundtrip() {
        let v = Energy::try_from("1.5 kJ").unwrap();
        let json = serde_json::to_string(&v).unwrap();
        let back: Energy = serde_json::from_str(&json).unwrap();
        assert_eq!(v.value(), back.value());
    }

    #[cfg(feature = "serde")]
    #[test]
    fn serde_serializes_as_canonical_string() {
        let v = Energy::try_from("1.5 kJ").unwrap();
        let json = serde_json::to_string(&v).unwrap();
        assert!(json.contains("1.5 kJ"));
    }
}