From 01be9e9904be9c3c492fa0718a9f4677ea02b8f6 Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Tue, 24 Sep 2013 20:07:44 -0700 Subject: [PATCH] extra: Add ToBigInt and ToBigUint traits --- src/libextra/num/bigint.rs | 90 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) diff --git a/src/libextra/num/bigint.rs b/src/libextra/num/bigint.rs index dd2acdb2e14c..925fe9da3e41 100644 --- a/src/libextra/num/bigint.rs +++ b/src/libextra/num/bigint.rs @@ -547,6 +547,52 @@ impl FromPrimitive for BigUint { } } +pub trait ToBigUint { + fn to_biguint(&self) -> Option; +} + +impl ToBigUint for BigInt { + #[inline] + fn to_biguint(&self) -> Option { + if self.sign == Plus { + Some(self.data.clone()) + } else if self.sign == Zero { + Some(Zero::zero()) + } else { + None + } + } +} + +impl ToBigUint for BigUint { + #[inline] + fn to_biguint(&self) -> Option { + Some(self.clone()) + } +} + +macro_rules! impl_to_biguint( + ($T:ty, $from_ty:path) => { + impl ToBigUint for $T { + #[inline] + fn to_biguint(&self) -> Option { + $from_ty(*self) + } + } + } +) + +impl_to_biguint!(int, FromPrimitive::from_int) +impl_to_biguint!(i8, FromPrimitive::from_i8) +impl_to_biguint!(i16, FromPrimitive::from_i16) +impl_to_biguint!(i32, FromPrimitive::from_i32) +impl_to_biguint!(i64, FromPrimitive::from_i64) +impl_to_biguint!(uint, FromPrimitive::from_uint) +impl_to_biguint!(u8, FromPrimitive::from_u8) +impl_to_biguint!(u16, FromPrimitive::from_u16) +impl_to_biguint!(u32, FromPrimitive::from_u32) +impl_to_biguint!(u64, FromPrimitive::from_u64) + impl ToStrRadix for BigUint { fn to_str_radix(&self, radix: uint) -> ~str { assert!(1 < radix && radix <= 16); @@ -1140,6 +1186,50 @@ impl FromPrimitive for BigInt { } } +pub trait ToBigInt { + fn to_bigint(&self) -> Option; +} + +impl ToBigInt for BigInt { + #[inline] + fn to_bigint(&self) -> Option { + Some(self.clone()) + } +} + +impl ToBigInt for BigUint { + #[inline] + fn to_bigint(&self) -> Option { + if self.is_zero() { + Some(Zero::zero()) + } else { + Some(BigInt { sign: Plus, data: self.clone() }) + } + } +} + +macro_rules! impl_to_bigint( + ($T:ty, $from_ty:path) => { + impl ToBigInt for $T { + #[inline] + fn to_bigint(&self) -> Option { + $from_ty(*self) + } + } + } +) + +impl_to_bigint!(int, FromPrimitive::from_int) +impl_to_bigint!(i8, FromPrimitive::from_i8) +impl_to_bigint!(i16, FromPrimitive::from_i16) +impl_to_bigint!(i32, FromPrimitive::from_i32) +impl_to_bigint!(i64, FromPrimitive::from_i64) +impl_to_bigint!(uint, FromPrimitive::from_uint) +impl_to_bigint!(u8, FromPrimitive::from_u8) +impl_to_bigint!(u16, FromPrimitive::from_u16) +impl_to_bigint!(u32, FromPrimitive::from_u32) +impl_to_bigint!(u64, FromPrimitive::from_u64) + impl ToStrRadix for BigInt { #[inline] fn to_str_radix(&self, radix: uint) -> ~str {