@@ -589,6 +589,12 @@ impl BigUint {
589589 }
590590 }
591591
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+
592598 #[ inline]
593599 fn shl_unit ( & self , n_unit : uint ) -> BigUint {
594600 if n_unit == 0 || self . is_zero ( ) { return ( * self ) . clone ( ) ; }
@@ -1102,6 +1108,16 @@ impl BigInt {
11021108 Minus => 0
11031109 }
11041110 }
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+ }
11051121}
11061122
11071123#[cfg(test)]
@@ -1281,6 +1297,16 @@ mod biguint_tests {
12811297 assert_eq ! ( BigUint :: new( ~[ 0 , 0 , -1 ] ) . to_uint( ) , uint:: max_value) ;
12821298 }
12831299
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+
12841310 static sum_triples : & ' static [ ( & ' static [ BigDigit ] ,
12851311 & ' static [ BigDigit ] ,
12861312 & ' static [ BigDigit ] ) ] = & [
@@ -1700,6 +1726,21 @@ mod bigint_tests {
17001726 ) . to_uint( ) == 0 ) ;
17011727 }
17021728
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+
17031744 static sum_triples: & ' static [ ( & ' static [ BigDigit ] ,
17041745 & ' static [ BigDigit ] ,
17051746 & ' static [ BigDigit ] ) ] = & [
0 commit comments