From 6858af0dc103a7c223be76335a216954149b3d39 Mon Sep 17 00:00:00 2001 From: Patrick Norton Date: Fri, 15 Apr 2022 21:40:20 -0700 Subject: [PATCH] Added From for BigInt and BigUint --- src/bigint/convert.rs | 12 +++++++++++- src/biguint/convert.rs | 12 +++++++++++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/bigint/convert.rs b/src/bigint/convert.rs index ff8e04ef..f3622035 100644 --- a/src/bigint/convert.rs +++ b/src/bigint/convert.rs @@ -10,7 +10,7 @@ use core::cmp::Ordering::{Equal, Greater, Less}; #[cfg(has_try_from)] use core::convert::TryFrom; use core::str::{self, FromStr}; -use num_traits::{FromPrimitive, Num, ToPrimitive, Zero}; +use num_traits::{FromPrimitive, Num, One, ToPrimitive, Zero}; impl FromStr for BigInt { type Err = ParseBigIntError; @@ -367,6 +367,16 @@ impl_to_bigint!(u128, FromPrimitive::from_u128); impl_to_bigint!(f32, FromPrimitive::from_f32); impl_to_bigint!(f64, FromPrimitive::from_f64); +impl From for BigInt { + fn from(x: bool) -> Self { + if x { + One::one() + } else { + Zero::zero() + } + } +} + #[inline] pub(super) fn from_signed_bytes_be(digits: &[u8]) -> BigInt { let sign = match digits.first() { diff --git a/src/biguint/convert.rs b/src/biguint/convert.rs index 5cf05cb6..36bf43fb 100644 --- a/src/biguint/convert.rs +++ b/src/biguint/convert.rs @@ -17,7 +17,7 @@ use core::mem; use core::str::FromStr; use num_integer::{Integer, Roots}; use num_traits::float::FloatCore; -use num_traits::{FromPrimitive, Num, PrimInt, ToPrimitive, Zero}; +use num_traits::{FromPrimitive, Num, One, PrimInt, ToPrimitive, Zero}; /// Find last set bit /// fls(0) == 0, fls(u32::MAX) == 32 @@ -572,6 +572,16 @@ impl_to_biguint!(u128, FromPrimitive::from_u128); impl_to_biguint!(f32, FromPrimitive::from_f32); impl_to_biguint!(f64, FromPrimitive::from_f64); +impl From for BigUint { + fn from(x: bool) -> Self { + if x { + One::one() + } else { + Zero::zero() + } + } +} + // Extract bitwise digits that evenly divide BigDigit pub(super) fn to_bitwise_digits_le(u: &BigUint, bits: u8) -> Vec { debug_assert!(!u.is_zero() && bits <= 8 && big_digit::BITS % bits == 0);