@@ -589,6 +589,12 @@ impl BigUint {
589
589
}
590
590
}
591
591
592
+ /// Converts this BigUint into a positively-signed BigInt.
593
+ #[ inline]
594
+ pub fn to_bigint ( & self ) -> BigInt {
595
+ BigInt :: from_biguint ( Plus , self . clone ( ) )
596
+ }
597
+
592
598
#[ inline]
593
599
fn shl_unit ( & self , n_unit : uint ) -> BigUint {
594
600
if n_unit == 0 || self . is_zero ( ) { return ( * self ) . clone ( ) ; }
@@ -1102,6 +1108,16 @@ impl BigInt {
1102
1108
Minus => 0
1103
1109
}
1104
1110
}
1111
+
1112
+ /// Converts this BigInt into a BigUint. Negative BigInts are
1113
+ /// converted to zero-valued BigUints.
1114
+ #[inline]
1115
+ pub fn to_biguint(&self) -> BigUint {
1116
+ match self.sign {
1117
+ Plus => self.data.clone(),
1118
+ _ => Zero::zero()
1119
+ }
1120
+ }
1105
1121
}
1106
1122
1107
1123
#[cfg(test)]
@@ -1281,6 +1297,16 @@ mod biguint_tests {
1281
1297
assert_eq ! ( BigUint :: new( ~[ 0 , 0 , -1 ] ) . to_uint( ) , uint:: max_value) ;
1282
1298
}
1283
1299
1300
+ #[ test ]
1301
+ fn test_convert_to_bigint ( ) {
1302
+ fn check ( n : BigUint , ans : BigInt ) {
1303
+ assert_eq ! ( n. to_bigint( ) , ans) ;
1304
+ assert_eq ! ( n. to_bigint( ) . to_biguint( ) , n) ;
1305
+ }
1306
+ check ( Zero :: zero ( ) , Zero :: zero ( ) ) ;
1307
+ check( BigUint :: from_uint( 637 ) , BigInt :: from_uint( 637 ) ) ;
1308
+ }
1309
+
1284
1310
static sum_triples : & ' static [ ( & ' static [ BigDigit ] ,
1285
1311
& ' static [ BigDigit ] ,
1286
1312
& ' static [ BigDigit ] ) ] = & [
@@ -1700,6 +1726,21 @@ mod bigint_tests {
1700
1726
) . to_uint( ) == 0 ) ;
1701
1727
}
1702
1728
1729
+ #[ test]
1730
+ fn test_convert_to_biguint ( ) {
1731
+ fn check ( n : BigInt , ans_1 : BigUint , ans_2 : BigInt ) {
1732
+ assert_eq ! ( n. to_biguint( ) , ans_1) ;
1733
+ assert_eq ! ( n. to_biguint( ) . to_bigint( ) , ans_2) ;
1734
+ }
1735
+ let zero: BigInt = Zero :: zero ( ) ;
1736
+ let unsigned_zero: BigUint = Zero :: zero ( ) ;
1737
+ let positive: BigInt = BigInt :: from_uint ( 637 ) ;
1738
+ let negative = -positive;
1739
+ check ( zero. clone ( ) , unsigned_zero. clone ( ) , zero. clone ( ) ) ;
1740
+ check ( positive. clone ( ) , BigUint :: from_uint ( 637 ) , positive) ;
1741
+ check ( negative, unsigned_zero, zero) ;
1742
+ }
1743
+
1703
1744
static sum_triples: & ' static [ ( & ' static [ BigDigit ] ,
1704
1745
& ' static [ BigDigit ] ,
1705
1746
& ' static [ BigDigit ] ) ] = & [
0 commit comments