Add conversions for BigInt/BigUint.

This commit is contained in:
2018-05-05 19:41:30 -07:00
parent b01c59a094
commit c34629aa47
2 changed files with 46 additions and 4 deletions

View File

@@ -1,4 +1,6 @@
use cryptonum::unsigned::{UCN,divmod}; use cryptonum::unsigned::{UCN,divmod};
use num::BigInt;
use num::bigint::Sign;
use std::fmt; use std::fmt;
use std::cmp::Ordering; use std::cmp::Ordering;
use std::fmt::Write; use std::fmt::Write;
@@ -102,6 +104,15 @@ impl Into<UCN> for SCN {
} }
} }
impl From<SCN> for BigInt {
fn from(x: SCN) -> BigInt {
let sign = if x.is_negative() { Sign::Minus } else { Sign::Plus };
let numbytes = x.value.contents.len() * 8;
let bytes = x.value.to_bytes(numbytes);
BigInt::from_bytes_be(sign, &bytes)
}
}
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// //
// Comparisons // Comparisons

View File

@@ -350,7 +350,14 @@ define_into!(UCN, u64);
define_into!(UCN, usize); define_into!(UCN, usize);
impl From<BigUint> for UCN { impl From<BigUint> for UCN {
fn from(mut x: BigUint) -> UCN { fn from(x: BigUint) -> UCN {
UCN::from(&x)
}
}
impl<'a> From<&'a BigUint> for UCN {
fn from(inval: &BigUint) -> UCN {
let mut x = inval.clone();
let mut dest = Vec::new(); let mut dest = Vec::new();
let mask = BigUint::from(0xFFFFFFFFFFFFFFFF as u64); let mask = BigUint::from(0xFFFFFFFFFFFFFFFF as u64);
@@ -368,11 +375,28 @@ impl From<BigUint> for UCN {
} }
} }
impl Into<BigUint> for UCN { impl From<BigInt> for UCN {
fn into(self) -> BigUint { fn from(x: BigInt) -> UCN {
UCN::from(&x)
}
}
impl<'a> From<&'a BigInt> for UCN {
fn from(x: &BigInt) -> UCN {
match x.to_biguint() {
None =>
panic!("Attempt to coerce negative BigInt into UCN"),
Some(x) =>
UCN::from(x)
}
}
}
impl From<UCN> for BigUint {
fn from(x: UCN) -> BigUint {
let mut result = BigUint::zero(); let mut result = BigUint::zero();
for part in self.contents.iter().rev() { for part in x.contents.iter().rev() {
result <<= 64; result <<= 64;
result += BigUint::from(*part); result += BigUint::from(*part);
} }
@@ -381,6 +405,13 @@ impl Into<BigUint> for UCN {
} }
} }
impl From<UCN> for BigInt {
fn from(x: UCN) -> BigInt {
let uint = BigUint::from(x);
BigInt::from(uint)
}
}
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// //
// Comparisons // Comparisons