@@ -263,6 +263,27 @@ impl_size_type_comparisons_for_row_ids!(MigrationId);
263263#[ derive( Copy , Clone , Debug , Eq , PartialEq , Ord , PartialOrd , std:: hash:: Hash ) ]
264264pub struct SizeType ( tsk_size_t ) ;
265265
266+ impl SizeType {
267+ /// Convenience function to convert to usize.
268+ ///
269+ /// Works via [`TryFrom`].
270+ ///
271+ /// # Returns
272+ ///
273+ /// * `None` if the underlying value is negative.
274+ /// * `Some(usize)` otherwise.
275+ pub fn to_usize ( & self ) -> Option < usize > {
276+ ( * self ) . try_into ( ) . ok ( )
277+ }
278+
279+ /// Convenience function to convert to usize.
280+ /// Implemented via `as`.
281+ /// Negative values with therefore wrap.
282+ pub fn as_usize ( & self ) -> usize {
283+ self . 0 as usize
284+ }
285+ }
286+
266287impl std:: fmt:: Display for SizeType {
267288 fn fmt ( & self , f : & mut std:: fmt:: Formatter < ' _ > ) -> std:: fmt:: Result {
268289 write ! ( f, "{}" , self . 0 )
@@ -297,9 +318,17 @@ impl TryFrom<SizeType> for usize {
297318 }
298319}
299320
300- impl From < usize > for SizeType {
301- fn from ( value : usize ) -> Self {
302- Self ( value as tsk_size_t )
321+ impl TryFrom < usize > for SizeType {
322+ type Error = TskitError ;
323+
324+ fn try_from ( value : usize ) -> Result < Self , Self :: Error > {
325+ match tsk_size_t:: try_from ( value) {
326+ Ok ( x) => Ok ( Self ( x) ) ,
327+ Err ( _) => Err ( TskitError :: RangeError ( format ! (
328+ "could not convert usize {} to SizeType" ,
329+ value
330+ ) ) ) ,
331+ }
303332 }
304333}
305334
@@ -539,6 +568,22 @@ mod tests {
539568 }
540569}
541570
571+ #[ test]
572+ fn test_usize_to_size_type ( ) {
573+ let x = usize:: MAX ;
574+ let s = SizeType :: try_from ( x) . ok ( ) ;
575+
576+ #[ cfg( target_pointer_width = "64" ) ]
577+ assert_eq ! ( s, Some ( bindings:: tsk_size_t:: MAX . into( ) ) ) ;
578+
579+ #[ cfg( target_pointer_width = "32" ) ]
580+ assert_eq ! ( s, Some ( ( usize :: MAX as bindings:: tsk_size_t) . into( ) ) ) ;
581+
582+ let x = usize:: MIN ;
583+ let s = SizeType :: try_from ( x) . ok ( ) ;
584+ assert_eq ! ( s, Some ( 0 . into( ) ) ) ;
585+ }
586+
542587// Testing modules
543588mod test_fixtures;
544589mod test_simplification;
0 commit comments