Skip to content

Commit 27833c1

Browse files
authored
refactor: Conversion from row id to usize is now fallible. (#319)
BREAKING CHANGE: TryFrom replaces From.
1 parent ffde091 commit 27833c1

File tree

3 files changed

+13
-6
lines changed

3 files changed

+13
-6
lines changed

examples/forward_simulation.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -368,9 +368,9 @@ fn simplify(
368368
Ok(x) => match x {
369369
Some(idmap) => {
370370
for a in alive.iter_mut() {
371-
a.node0 = idmap[usize::from(a.node0)];
371+
a.node0 = idmap[usize::try_from(a.node0).unwrap()];
372372
assert!(a.node0 != tskit::NodeId::NULL);
373-
a.node1 = idmap[usize::from(a.node1)];
373+
a.node1 = idmap[usize::try_from(a.node1).unwrap()];
374374
assert!(a.node1 != tskit::NodeId::NULL);
375375
}
376376
}

src/_macros.rs

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -248,9 +248,16 @@ macro_rules! impl_id_traits {
248248
}
249249
}
250250

251-
impl From<$idtype> for usize {
252-
fn from(value: $idtype) -> Self {
253-
value.0 as usize
251+
impl TryFrom<$idtype> for usize {
252+
type Error = crate::TskitError;
253+
fn try_from(value: $idtype) -> Result<Self, Self::Error> {
254+
match value.0.try_into() {
255+
Ok(value) => Ok(value),
256+
Err(_) => Err(crate::TskitError::RangeError(format!(
257+
"could not convert {:?} to usize",
258+
value
259+
))),
260+
}
254261
}
255262
}
256263

src/test_simplification.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ mod tests {
3737
assert!(idmap_option.is_some());
3838
let idmap = idmap_option.unwrap();
3939
for &i in samples {
40-
assert_ne!(idmap[usize::from(i)], NodeId::NULL);
40+
assert_ne!(idmap[usize::try_from(i).unwrap()], NodeId::NULL);
4141
}
4242
}
4343
}

0 commit comments

Comments
 (0)