Skip to content

Commit

Permalink
feat: add trait impls for references types involving newtypes
Browse files Browse the repository at this point in the history
  • Loading branch information
molpopgen committed May 8, 2024
1 parent 29c1237 commit f04e54c
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
39 changes: 39 additions & 0 deletions src/sys/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Self, Self::Error> {
Expand All @@ -69,12 +75,25 @@ macro_rules! impl_id_traits {
}
}

impl TryFrom<&$idtype> for usize {
type Error = $crate::TskitError;
fn try_from(value: &$idtype) -> Result<Self, Self::Error> {
(*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;

Expand All @@ -83,6 +102,14 @@ macro_rules! impl_id_traits {
}
}

impl TryFrom<&$idtype> for SizeType {
type Error = $crate::TskitError;

fn try_from(value: &$idtype) -> Result<Self, Self::Error> {
SizeType::try_from(*value)
}
}

impl PartialEq<super::bindings::tsk_id_t> for $idtype {
fn eq(&self, other: &super::bindings::tsk_id_t) -> bool {
self.0 == *other
Expand Down Expand Up @@ -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;

Expand Down
14 changes: 14 additions & 0 deletions src/sys/newtypes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}

0 comments on commit f04e54c

Please sign in to comment.