use crate::errors::ValidationError;
use crate::traits::ValueObject;
pub type NonNegativeIntInput = i64;
pub type NonNegativeIntOutput = i64;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct NonNegativeInt(i64);
impl ValueObject for NonNegativeInt {
type Input = NonNegativeIntInput;
type Output = NonNegativeIntOutput;
type Error = ValidationError;
fn new(value: Self::Input) -> Result<Self, Self::Error> {
if value < 0 {
return Err(ValidationError::OutOfRange {
type_name: "NonNegativeInt",
min: "0".into(),
max: i64::MAX.to_string(),
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 NonNegativeInt {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepts_zero() {
let n = NonNegativeInt::new(0).unwrap();
assert_eq!(*n.value(), 0);
}
#[test]
fn accepts_positive_value() {
let n = NonNegativeInt::new(100).unwrap();
assert_eq!(*n.value(), 100);
}
#[test]
fn rejects_negative() {
assert!(NonNegativeInt::new(-1).is_err());
}
}