arvo 0.5.0

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

/// Input type for [`NonNegativeDecimal`].
pub type NonNegativeDecimalInput = Decimal;

/// Output type for [`NonNegativeDecimal`].
pub type NonNegativeDecimalOutput = Decimal;

/// A non-negative decimal number (`Decimal >= 0`).
///
/// Negative values are rejected on construction. Zero is allowed.
///
/// # Example
///
/// ```rust,ignore
/// use arvo::primitives::NonNegativeDecimal;
/// use arvo::traits::ValueObject;
/// use rust_decimal_macros::dec;
///
/// let amount = NonNegativeDecimal::new(dec!(0)).unwrap();
/// assert_eq!(*amount.value(), dec!(0));
///
/// assert!(NonNegativeDecimal::new(dec!(-0.01)).is_err());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct NonNegativeDecimal(Decimal);

impl ValueObject for NonNegativeDecimal {
    type Input = NonNegativeDecimalInput;
    type Output = NonNegativeDecimalOutput;
    type Error = ValidationError;

    fn new(value: Self::Input) -> Result<Self, Self::Error> {
        if value < Decimal::ZERO {
            return Err(ValidationError::OutOfRange {
                type_name: "NonNegativeDecimal",
                min: "0".into(),
                max: "".into(),
                actual: value.to_string(),
            });
        }
        Ok(Self(value))
    }

    fn value(&self) -> &Self::Output {
        &self.0
    }

    fn into_inner(self) -> Self::Input {
        self.0
    }
}

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

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

    #[test]
    fn accepts_zero() {
        let d = NonNegativeDecimal::new(Decimal::ZERO).unwrap();
        assert_eq!(d.value(), &Decimal::ZERO);
    }

    #[test]
    fn accepts_positive_value() {
        let d = NonNegativeDecimal::new(Decimal::from_str("1.5").unwrap()).unwrap();
        assert_eq!(d.value(), &Decimal::from_str("1.5").unwrap());
    }

    #[test]
    fn rejects_negative() {
        assert!(NonNegativeDecimal::new(Decimal::from_str("-0.01").unwrap()).is_err());
    }
}