Skip to content

sizetype_usize_conversions #419

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

Merged
merged 1 commit into from
Dec 1, 2022
Merged
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
15 changes: 8 additions & 7 deletions src/_macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -676,12 +676,13 @@ macro_rules! node_table_add_row_with_metadata {
M: $crate::metadata::NodeMetadata,
{
let md = $crate::metadata::EncodedMetadata::new(metadata)?;
let mdlen = md.len()?;
node_table_add_row_details!(flags,
time,
population,
individual,
md.as_ptr(),
md.len().into(),
mdlen.into(),
$table)
}
};
Expand Down Expand Up @@ -761,7 +762,7 @@ macro_rules! edge_table_add_row_with_metadata {
parent,
child,
md.as_ptr(),
md.len().into(),
md.len()?.into(),
$table)
}
};
Expand Down Expand Up @@ -791,7 +792,7 @@ macro_rules! population_table_add_row_with_metadata {
pub fn $name<M>(&mut $self, metadata: &M) -> Result<$crate::PopulationId, $crate::TskitError>
where M: $crate::metadata::PopulationMetadata {
let md = $crate::metadata::EncodedMetadata::new(metadata)?;
population_table_add_row_details!(md.as_ptr(), md.len().into(), $table)
population_table_add_row_details!(md.as_ptr(), md.len()?.into(), $table)
}
};
}
Expand Down Expand Up @@ -865,7 +866,7 @@ macro_rules! individual_table_add_row_with_metadata {
location,
parents,
md.as_ptr(),
md.len().into(),
md.len()?.into(),
$table)
}
};
Expand Down Expand Up @@ -946,7 +947,7 @@ macro_rules! mutation_table_add_row_with_metadata {
time,
derived_state,
md.as_ptr(),
md.len().into(),
md.len()?.into(),
$table)
}
};
Expand Down Expand Up @@ -1002,7 +1003,7 @@ macro_rules! site_table_add_row_with_metadata {
let md = $crate::metadata::EncodedMetadata::new(metadata)?;
site_table_add_row_details!(position, ancestral_state,
md.as_ptr(),
md.len().into(),
md.len()?.into(),
$table)
}
};
Expand Down Expand Up @@ -1076,7 +1077,7 @@ macro_rules! migration_table_add_row_with_metadata {
{
let md = $crate::metadata::EncodedMetadata::new(metadata)?;
migration_table_add_row_details!(span, node, source_dest, time,
md.as_ptr(), md.len().into(), $table)
md.as_ptr(), md.len()?.into(), $table)
}
};
}
Expand Down
51 changes: 48 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,27 @@ impl_size_type_comparisons_for_row_ids!(MigrationId);
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, std::hash::Hash)]
pub struct SizeType(tsk_size_t);

impl SizeType {
/// Convenience function to convert to usize.
///
/// Works via [`TryFrom`].
///
/// # Returns
///
/// * `None` if the underlying value is negative.
/// * `Some(usize)` otherwise.
pub fn to_usize(&self) -> Option<usize> {
(*self).try_into().ok()
}

/// Convenience function to convert to usize.
/// Implemented via `as`.
/// Negative values with therefore wrap.
pub fn as_usize(&self) -> usize {
self.0 as usize
}
}

impl std::fmt::Display for SizeType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
Expand Down Expand Up @@ -297,9 +318,17 @@ impl TryFrom<SizeType> for usize {
}
}

impl From<usize> for SizeType {
fn from(value: usize) -> Self {
Self(value as tsk_size_t)
impl TryFrom<usize> for SizeType {
type Error = TskitError;

fn try_from(value: usize) -> Result<Self, Self::Error> {
match tsk_size_t::try_from(value) {
Ok(x) => Ok(Self(x)),
Err(_) => Err(TskitError::RangeError(format!(
"could not convert usize {} to SizeType",
value
))),
}
}
}

Expand Down Expand Up @@ -539,6 +568,22 @@ mod tests {
}
}

#[test]
fn test_usize_to_size_type() {
let x = usize::MAX;
let s = SizeType::try_from(x).ok();

#[cfg(target_pointer_width = "64")]
assert_eq!(s, Some(bindings::tsk_size_t::MAX.into()));

#[cfg(target_pointer_width = "32")]
assert_eq!(s, Some((usize::MAX as bindings::tsk_size_t).into()));

let x = usize::MIN;
let s = SizeType::try_from(x).ok();
assert_eq!(s, Some(0.into()));
}

// Testing modules
mod test_fixtures;
mod test_simplification;
Expand Down
8 changes: 4 additions & 4 deletions src/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,8 +234,8 @@ impl EncodedMetadata {
}
}

pub(crate) fn len(&self) -> SizeType {
self.encoded.len().into()
pub(crate) fn len(&self) -> Result<SizeType, crate::TskitError> {
SizeType::try_from(self.encoded.len())
}
}

Expand Down Expand Up @@ -365,7 +365,7 @@ mod tests {
let enc = EncodedMetadata::new(&f).unwrap();
let p = enc.as_ptr();
let mut d = vec![];
for i in 0..usize::try_from(enc.len()).unwrap() {
for i in 0..usize::try_from(enc.len().unwrap()).unwrap() {
d.push(unsafe { *p.add(i) as u8 });
}
let df = F::decode(&d).unwrap();
Expand Down Expand Up @@ -399,7 +399,7 @@ mod test_serde {
let enc = EncodedMetadata::new(&f).unwrap();
let p = enc.as_ptr();
let mut d = vec![];
for i in 0..usize::try_from(enc.len()).unwrap() {
for i in 0..usize::try_from(enc.len().unwrap()).unwrap() {
d.push(unsafe { *p.add(i) as u8 });
}
let df = F::decode(&d).unwrap();
Expand Down
2 changes: 1 addition & 1 deletion tests/book_trees.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ fn initialize_from_table_collection() {
// ANCHOR_END: iterate_edge_differences

// ANCHOR: iterate_edge_differences_update_parents
let num_nodes: usize = treeseq.nodes().num_rows().try_into().unwrap();
let num_nodes = treeseq.nodes().num_rows().as_usize();
// num_nodes + 1 to reflect a "virtual root" present in
// the tree arrays
let mut parents = vec![NodeId::NULL; num_nodes + 1];
Expand Down