Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add trait impls for references types involving newtypes #634

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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());
}
Loading