hmath/bigint/convert/
from.rs1use crate::{Ratio, BigInt, UBigInt, ConversionError};
2use crate::{impl_from_for_ref, impl_tryfrom_for_ref, impl_trait_for_general};
3
4macro_rules! impl_from_ref_bigint {
5 ($t: ty) => (
6 impl_from_for_ref!(BigInt, $t);
7 );
8 ($t: ty, $($u: ty), +) => (
9 impl_from_ref_bigint!($t);
10 impl_from_ref_bigint!($($u),+);
11 )
12}
13
14macro_rules! impl_tryfrom_ref_bigint {
15 ($t: ty) => (
16 impl_tryfrom_for_ref!(BigInt, $t);
17 );
18 ($t: ty, $($u: ty), +) => (
19 impl_tryfrom_ref_bigint!($t);
20 impl_tryfrom_ref_bigint!($($u),+);
21 )
22}
23
24impl_from_ref_bigint!(bool, u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);
25impl_tryfrom_ref_bigint!(f32, f64);
26
27impl From<bool> for BigInt {
28 fn from(b: bool) -> Self {
29 if b {
30 BigInt::one()
31 } else {
32 BigInt::zero()
33 }
34 }
35}
36
37impl TryFrom<f32> for BigInt {
39 type Error = ConversionError;
40
41 fn try_from(n: f32) -> Result<Self, Self::Error> {
42 Ok(Ratio::try_from(n)?.truncate_bi())
43 }
44}
45
46impl TryFrom<f64> for BigInt {
48 type Error = ConversionError;
49
50 fn try_from(n: f64) -> Result<Self, Self::Error> {
51 Ok(Ratio::try_from(n)?.truncate_bi())
52 }
53}
54
55impl_trait_for_general!(From, i8, BigInt, from_i32);
56impl_trait_for_general!(From, i16, BigInt, from_i32);
57impl_trait_for_general!(From, i32, BigInt, from_i32);
58impl_trait_for_general!(From, i64, BigInt, from_i64);
59impl_trait_for_general!(From, i128, BigInt, from_i128);
60impl_trait_for_general!(From, u8, BigInt, from_i32);
61impl_trait_for_general!(From, u16, BigInt, from_i32);
62impl_trait_for_general!(From, u32, BigInt, from_i64);
63
64impl_trait_for_general!(TryFrom, &str, BigInt, from_string);
65
66impl From<isize> for BigInt {
67 fn from(n: isize) -> Self {
68 BigInt::from_i64(n as i64)
69 }
70}
71
72impl From<u64> for BigInt {
73 fn from(n: u64) -> Self {
74 BigInt::from_ubi(UBigInt::from_u64(n), false)
75 }
76}
77
78impl From<u128> for BigInt {
79 fn from(n: u128) -> Self {
80 BigInt::from_ubi(UBigInt::from_u128(n), false)
81 }
82}
83
84impl From<usize> for BigInt {
85 fn from(n: usize) -> Self {
86 BigInt::from_ubi(UBigInt::from_u64(n as u64), false)
87 }
88}
89
90impl TryFrom<String> for BigInt {
91 type Error = ConversionError;
92
93 fn try_from(n: String) -> Result<Self, Self::Error> {
94 BigInt::from_string(&n)
95 }
96}
97
98impl From<&Ratio> for BigInt {
99 fn from(n: &Ratio) -> Self {
100 n.truncate_bi()
101 }
102}
103
104impl From<&UBigInt> for BigInt {
105 fn from(n: &UBigInt) -> Self {
106 BigInt::from_ubi(n.clone(), false)
107 }
108}