From 03538ed835bd78b0b9ea94635437d06a93dd4124 Mon Sep 17 00:00:00 2001 From: "Kevin R. Thornton" Date: Wed, 8 May 2024 08:53:11 -0700 Subject: [PATCH] feat: add From/TryFrom impls for references types involving newtypes --- src/sys/macros.rs | 39 +++++++++++++++++++++++++++++++++++++++ src/sys/newtypes.rs | 14 ++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/src/sys/macros.rs b/src/sys/macros.rs index 473a8cc7..cccb4439 100644 --- a/src/sys/macros.rs +++ b/src/sys/macros.rs @@ -56,6 +56,12 @@ macro_rules! impl_id_traits { } } + impl From<&super::bindings::tsk_id_t> for $idtype { + fn from(value: &super::bindings::tsk_id_t) -> Self { + Self(*value) + } + } + impl TryFrom<$idtype> for usize { type Error = $crate::TskitError; fn try_from(value: $idtype) -> Result { @@ -69,12 +75,25 @@ macro_rules! impl_id_traits { } } + impl TryFrom<&$idtype> for usize { + type Error = $crate::TskitError; + fn try_from(value: &$idtype) -> Result { + (*value).try_into() + } + } + impl From<$idtype> for super::bindings::tsk_id_t { fn from(value: $idtype) -> Self { value.0 } } + impl From<&$idtype> for super::bindings::tsk_id_t { + fn from(value: &$idtype) -> Self { + value.0 + } + } + impl TryFrom<$idtype> for SizeType { type Error = $crate::TskitError; @@ -83,6 +102,14 @@ macro_rules! impl_id_traits { } } + impl TryFrom<&$idtype> for SizeType { + type Error = $crate::TskitError; + + fn try_from(value: &$idtype) -> Result { + SizeType::try_from(*value) + } + } + impl PartialEq for $idtype { fn eq(&self, other: &super::bindings::tsk_id_t) -> bool { self.0 == *other @@ -182,12 +209,24 @@ macro_rules! impl_f64_newtypes { } } + impl From<&f64> for $type { + fn from(value: &f64) -> Self { + Self(*value) + } + } + impl From<$type> for f64 { fn from(value: $type) -> Self { value.0 } } + impl From<&$type> for f64 { + fn from(value: &$type) -> Self { + value.0 + } + } + impl std::ops::Sub for $type { type Output = Self; diff --git a/src/sys/newtypes.rs b/src/sys/newtypes.rs index 18cd67c5..bcf73de1 100644 --- a/src/sys/newtypes.rs +++ b/src/sys/newtypes.rs @@ -229,3 +229,17 @@ fn test_usize_to_size_type() { let s = SizeType::try_from(x).ok(); assert_eq!(s, Some(0.into())); } + +#[test] +fn test_from_reference() { + let x = 2; + let y = NodeId::from(&x); + assert_eq!(y, 2); + assert_eq!(2, tsk_id_t::from(&y)); +} + +#[test] +fn test_try_from_reference() { + let y = NodeId::from(2); + assert_eq!(2, usize::try_from(&y).unwrap()); +}