use crate::errors::ValidationError;
use crate::traits::ValueObject;
pub type UnixTimestampInput = i64;
pub type UnixTimestampOutput = i64;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct UnixTimestamp(i64);
impl ValueObject for UnixTimestamp {
type Input = UnixTimestampInput;
type Output = UnixTimestampOutput;
type Error = ValidationError;
fn new(value: Self::Input) -> Result<Self, Self::Error> {
if value < 0 {
return Err(ValidationError::invalid(
"UnixTimestamp",
&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 UnixTimestamp {
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 ts = UnixTimestamp::new(0).unwrap();
assert_eq!(*ts.value(), 0);
}
#[test]
fn accepts_positive() {
let ts = UnixTimestamp::new(1_700_000_000).unwrap();
assert_eq!(*ts.value(), 1_700_000_000);
}
#[test]
fn rejects_negative() {
assert!(UnixTimestamp::new(-1).is_err());
}
#[test]
fn into_inner_roundtrip() {
let ts = UnixTimestamp::new(42).unwrap();
assert_eq!(ts.into_inner(), 42);
}
#[test]
fn display() {
let ts = UnixTimestamp::new(1_000).unwrap();
assert_eq!(ts.to_string(), "1000");
}
}