From 39fdf2dd58fc7adc056373fe2d444eb09a9dec79 Mon Sep 17 00:00:00 2001 From: Chris Sellers Date: Mon, 15 Apr 2024 21:46:40 +1000 Subject: [PATCH] Refine UnixNanos implementation and add tests --- nautilus_core/core/src/nanos.rs | 79 +++++++++++++++++++++++++++------ 1 file changed, 65 insertions(+), 14 deletions(-) diff --git a/nautilus_core/core/src/nanos.rs b/nautilus_core/core/src/nanos.rs index d735469071c1..53ce4bb0a891 100644 --- a/nautilus_core/core/src/nanos.rs +++ b/nautilus_core/core/src/nanos.rs @@ -41,6 +41,14 @@ impl UnixNanos { } } +impl Deref for UnixNanos { + type Target = u64; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + impl PartialEq for UnixNanos { fn eq(&self, other: &u64) -> bool { self.0 == *other @@ -91,20 +99,6 @@ impl FromStr for UnixNanos { } } -// impl Into for UnixNanos { -// fn into(self) -> u64 { -// self.0 -// } -// } - -impl Deref for UnixNanos { - type Target = u64; - - fn deref(&self) -> &Self::Target { - &self.0 - } -} - impl Add for UnixNanos { type Output = Self; fn add(self, rhs: Self) -> Self::Output { @@ -210,4 +204,61 @@ mod tests { let nanos = UnixNanos::from(123); assert_eq!(format!("{nanos}"), "123"); } + + #[rstest] + fn test_addition() { + let nanos1 = UnixNanos::from(100); + let nanos2 = UnixNanos::from(200); + let result = nanos1 + nanos2; + assert_eq!(result.as_u64(), 300); + } + + #[rstest] + fn test_add_assign() { + let mut nanos = UnixNanos::from(100); + nanos += 50_u64; + assert_eq!(nanos.as_u64(), 150); + } + + #[rstest] + fn test_subtraction() { + let nanos1 = UnixNanos::from(200); + let nanos2 = UnixNanos::from(100); + let result = nanos1 - nanos2; + assert_eq!(result.as_u64(), 100); + } + + #[rstest] + fn test_sub_assign() { + let mut nanos = UnixNanos::from(200); + nanos -= 50_u64; + assert_eq!(nanos.as_u64(), 150); + } + + #[rstest] + fn test_multiplication_assign() { + let mut nanos = UnixNanos::from(100); + nanos *= 3_u64; + assert_eq!(nanos.as_u64(), 300); + } + + #[rstest] + fn test_from_str() { + let nanos: UnixNanos = "123".parse().unwrap(); + assert_eq!(nanos.as_u64(), 123); + } + + #[rstest] + fn test_from_str_invalid() { + let result = "abc".parse::(); + assert!(result.is_err()); + } + + #[rstest] + fn test_serde_json() { + let nanos = UnixNanos::from(123); + let json = serde_json::to_string(&nanos).unwrap(); + let deserialized: UnixNanos = serde_json::from_str(&json).unwrap(); + assert_eq!(deserialized, nanos); + } }