1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
use num_rational::Ratio;
#[cfg(feature = "num-bigint")]
use num_bigint::{BigInt, BigUint};
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum FromSqrtError {
Overflow,
Complex,
Unrepresentable,
}
pub trait FromSqrt<T>: Sized {
fn from_sqrt(t: T) -> Result<Self, FromSqrtError>;
}
#[derive(PartialEq, Debug)]
pub enum Approximation<T> {
Approximated(T),
Exact(T),
}
impl<T> Approximation<T> {
pub fn value(self) -> T {
match self {
Approximation::Approximated(v) => v,
Approximation::Exact(v) => v,
}
}
}
pub trait Computable<T> {
fn approximated(&self, limit: &T) -> Approximation<Ratio<T>>;
}
pub trait WithSigned {
type Signed;
fn to_signed(self) -> Self::Signed;
}
pub trait WithUnsigned {
type Unsigned;
fn to_unsigned(self) -> Self::Unsigned;
}
macro_rules! impl_primitive_sign {
($TSigned:ty, $TUnsigned:ty) => {
impl WithSigned for $TUnsigned {
type Signed = $TSigned;
#[inline]
fn to_signed(self) -> Self::Signed {
self as $TSigned
}
}
impl WithSigned for $TSigned {
type Signed = $TSigned;
#[inline]
fn to_signed(self) -> Self {
self
}
}
impl WithUnsigned for $TSigned {
type Unsigned = $TUnsigned;
#[inline]
fn to_unsigned(self) -> Self::Unsigned {
self as $TUnsigned
}
}
impl WithUnsigned for $TUnsigned {
type Unsigned = $TUnsigned;
#[inline]
fn to_unsigned(self) -> Self {
self
}
}
};
}
impl_primitive_sign!(i8, u8);
impl_primitive_sign!(i16, u16);
impl_primitive_sign!(i32, u32);
impl_primitive_sign!(i64, u64);
impl_primitive_sign!(i128, u128);
#[cfg(feature = "num-bigint")]
impl WithSigned for BigUint {
type Signed = BigInt;
#[inline]
fn to_signed(self) -> Self::Signed {
BigInt::from(self)
}
}
#[cfg(feature = "num-bigint")]
impl WithUnsigned for BigUint {
type Unsigned = BigUint;
#[inline]
fn to_unsigned(self) -> Self {
self
}
}
#[cfg(feature = "num-bigint")]
impl WithUnsigned for BigInt {
type Unsigned = BigUint;
#[inline]
fn to_unsigned(self) -> Self::Unsigned {
self.to_biguint().unwrap()
}
}
#[cfg(feature = "num-bigint")]
impl WithSigned for BigInt {
type Signed = BigInt;
#[inline]
fn to_signed(self) -> Self::Signed {
self
}
}