Skip to content

Commit cf875bb

Browse files
authored
feat: add From/TryFrom impls for references types involving newtypes (#634)
1 parent 7be315b commit cf875bb

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

src/sys/macros.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,12 @@ macro_rules! impl_id_traits {
5656
}
5757
}
5858

59+
impl From<&super::bindings::tsk_id_t> for $idtype {
60+
fn from(value: &super::bindings::tsk_id_t) -> Self {
61+
Self(*value)
62+
}
63+
}
64+
5965
impl TryFrom<$idtype> for usize {
6066
type Error = $crate::TskitError;
6167
fn try_from(value: $idtype) -> Result<Self, Self::Error> {
@@ -69,12 +75,25 @@ macro_rules! impl_id_traits {
6975
}
7076
}
7177

78+
impl TryFrom<&$idtype> for usize {
79+
type Error = $crate::TskitError;
80+
fn try_from(value: &$idtype) -> Result<Self, Self::Error> {
81+
(*value).try_into()
82+
}
83+
}
84+
7285
impl From<$idtype> for super::bindings::tsk_id_t {
7386
fn from(value: $idtype) -> Self {
7487
value.0
7588
}
7689
}
7790

91+
impl From<&$idtype> for super::bindings::tsk_id_t {
92+
fn from(value: &$idtype) -> Self {
93+
value.0
94+
}
95+
}
96+
7897
impl TryFrom<$idtype> for SizeType {
7998
type Error = $crate::TskitError;
8099

@@ -83,6 +102,14 @@ macro_rules! impl_id_traits {
83102
}
84103
}
85104

105+
impl TryFrom<&$idtype> for SizeType {
106+
type Error = $crate::TskitError;
107+
108+
fn try_from(value: &$idtype) -> Result<Self, Self::Error> {
109+
SizeType::try_from(*value)
110+
}
111+
}
112+
86113
impl PartialEq<super::bindings::tsk_id_t> for $idtype {
87114
fn eq(&self, other: &super::bindings::tsk_id_t) -> bool {
88115
self.0 == *other
@@ -182,12 +209,24 @@ macro_rules! impl_f64_newtypes {
182209
}
183210
}
184211

212+
impl From<&f64> for $type {
213+
fn from(value: &f64) -> Self {
214+
Self(*value)
215+
}
216+
}
217+
185218
impl From<$type> for f64 {
186219
fn from(value: $type) -> Self {
187220
value.0
188221
}
189222
}
190223

224+
impl From<&$type> for f64 {
225+
fn from(value: &$type) -> Self {
226+
value.0
227+
}
228+
}
229+
191230
impl std::ops::Sub for $type {
192231
type Output = Self;
193232

src/sys/newtypes.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -229,3 +229,17 @@ fn test_usize_to_size_type() {
229229
let s = SizeType::try_from(x).ok();
230230
assert_eq!(s, Some(0.into()));
231231
}
232+
233+
#[test]
234+
fn test_from_reference() {
235+
let x = 2;
236+
let y = NodeId::from(&x);
237+
assert_eq!(y, 2);
238+
assert_eq!(2, tsk_id_t::from(&y));
239+
}
240+
241+
#[test]
242+
fn test_try_from_reference() {
243+
let y = NodeId::from(2);
244+
assert_eq!(2, usize::try_from(&y).unwrap());
245+
}

0 commit comments

Comments
 (0)