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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
use crate::ext::xmpq;
use crate::ext::xmpz;
use crate::rational::big;
use crate::rational::{ParseRationalError, TryFromFloatError};
use crate::{Assign, Integer, Rational};
use az::CheckedCast;
use core::convert::TryFrom;
use core::fmt::{
Binary, Debug, Display, Formatter, LowerHex, Octal, Result as FmtResult, UpperHex,
};
use core::hash::{Hash, Hasher};
use core::mem;
use core::mem::MaybeUninit;
use core::str::FromStr;
use gmp_mpfr_sys::gmp;
use gmp_mpfr_sys::gmp::mpq_t;
impl Default for Rational {
#[inline]
fn default() -> Rational {
Rational::new()
}
}
impl Clone for Rational {
#[inline]
fn clone(&self) -> Rational {
unsafe {
let mut dst = MaybeUninit::uninit();
let inner_ptr = cast_ptr_mut!(dst.as_mut_ptr(), mpq_t);
let num = cast_ptr_mut!(gmp::mpq_numref(inner_ptr), Integer);
xmpz::init_set(num, self.numer());
let den = cast_ptr_mut!(gmp::mpq_denref(inner_ptr), Integer);
xmpz::init_set(den, self.denom());
dst.assume_init()
}
}
#[inline]
fn clone_from(&mut self, src: &Rational) {
self.assign(src);
}
}
impl Drop for Rational {
#[inline]
fn drop(&mut self) {
unsafe {
xmpq::clear(self);
}
}
}
impl Hash for Rational {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
self.numer().hash(state);
self.denom().hash(state);
}
}
impl FromStr for Rational {
type Err = ParseRationalError;
#[inline]
fn from_str(src: &str) -> Result<Rational, ParseRationalError> {
Ok(Rational::from(Rational::parse(src)?))
}
}
impl Display for Rational {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
fmt_radix(self, f, 10, false, "")
}
}
impl Debug for Rational {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
fmt_radix(self, f, 10, false, "")
}
}
impl Binary for Rational {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
fmt_radix(self, f, 2, false, "0b")
}
}
impl Octal for Rational {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
fmt_radix(self, f, 8, false, "0o")
}
}
impl LowerHex for Rational {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
fmt_radix(self, f, 16, false, "0x")
}
}
impl UpperHex for Rational {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
fmt_radix(self, f, 16, true, "0x")
}
}
impl Assign for Rational {
#[inline]
fn assign(&mut self, src: Rational) {
drop(mem::replace(self, src));
}
}
impl Assign<&Rational> for Rational {
#[inline]
fn assign(&mut self, src: &Rational) {
xmpq::set(self, src);
}
}
impl From<&Rational> for Rational {
#[inline]
fn from(src: &Rational) -> Self {
unsafe {
let mut dst = MaybeUninit::uninit();
xmpq::init_set(dst.as_mut_ptr(), src);
dst.assume_init()
}
}
}
impl<Num> Assign<Num> for Rational
where
Integer: Assign<Num>,
{
#[inline]
fn assign(&mut self, src: Num) {
let (num, den) = unsafe { self.as_mut_numer_denom_no_canonicalization() };
num.assign(src);
xmpz::set_1(den);
}
}
impl<Num> From<Num> for Rational
where
Integer: From<Num>,
{
#[inline]
fn from(src: Num) -> Self {
unsafe {
let mut dst = MaybeUninit::uninit();
let inner_ptr = cast_ptr_mut!(dst.as_mut_ptr(), mpq_t);
let num = cast_ptr_mut!(gmp::mpq_numref(inner_ptr), Integer);
num.write(Integer::from(src));
let den = cast_ptr_mut!(gmp::mpq_denref(inner_ptr), Integer);
xmpz::init_set_u32(den, 1);
dst.assume_init()
}
}
}
impl<Num, Den> Assign<(Num, Den)> for Rational
where
Integer: Assign<Num> + Assign<Den>,
{
#[inline]
fn assign(&mut self, src: (Num, Den)) {
self.mutate_numer_denom(move |num, den| {
num.assign(src.0);
den.assign(src.1);
})
}
}
impl<Num, Den> From<(Num, Den)> for Rational
where
Integer: From<Num> + From<Den>,
{
#[inline]
fn from((num, den): (Num, Den)) -> Self {
let (num, den) = (Integer::from(num), Integer::from(den));
let mut dst = MaybeUninit::uninit();
xmpq::write_num_den_canonicalize(&mut dst, num, den);
unsafe { dst.assume_init() }
}
}
impl<'a, Num, Den> Assign<&'a (Num, Den)> for Rational
where
Integer: Assign<&'a Num> + Assign<&'a Den>,
{
#[inline]
fn assign(&mut self, src: &'a (Num, Den)) {
self.mutate_numer_denom(|num, den| {
num.assign(&src.0);
den.assign(&src.1);
});
}
}
impl<'a, Num, Den> From<&'a (Num, Den)> for Rational
where
Integer: From<&'a Num> + From<&'a Den>,
{
#[inline]
fn from(src: &'a (Num, Den)) -> Self {
let (num, den) = (Integer::from(&src.0), Integer::from(&src.1));
let mut dst = MaybeUninit::uninit();
xmpq::write_num_den_canonicalize(&mut dst, num, den);
unsafe { dst.assume_init() }
}
}
impl TryFrom<f32> for Rational {
type Error = TryFromFloatError;
#[inline]
fn try_from(value: f32) -> Result<Self, TryFromFloatError> {
value
.checked_cast()
.ok_or(TryFromFloatError { _unused: () })
}
}
impl TryFrom<f64> for Rational {
type Error = TryFromFloatError;
#[inline]
fn try_from(value: f64) -> Result<Self, TryFromFloatError> {
value
.checked_cast()
.ok_or(TryFromFloatError { _unused: () })
}
}
fn fmt_radix(
r: &Rational,
f: &mut Formatter<'_>,
radix: i32,
to_upper: bool,
prefix: &str,
) -> FmtResult {
let mut s = String::new();
big::append_to_string(&mut s, r, radix, to_upper);
let neg = s.starts_with('-');
let buf = if neg { &s[1..] } else { &s[..] };
f.pad_integral(!neg, prefix, buf)
}
unsafe impl Send for Rational {}
unsafe impl Sync for Rational {}
#[cfg(test)]
#[allow(clippy::float_cmp)]
mod tests {
use crate::{Assign, Rational};
use core::convert::TryFrom;
#[test]
fn check_assign() {
let mut r = Rational::from((1, 2));
assert_eq!(r, (1, 2));
let other = Rational::from((-2, 3));
r.assign(&other);
assert_eq!(r, (-2, 3));
r.assign(-other);
assert_eq!(r, (2, 3));
let another = Rational::from(&r);
assert_eq!(another, r);
}
#[test]
fn check_fallible_conversions() {
use crate::tests::{F32, F64};
for &f in F32 {
let r = Rational::try_from(f);
assert_eq!(r.is_ok(), f.is_finite());
#[cfg(feature = "float")]
{
if let Ok(r) = r {
assert_eq!(r, f);
}
}
}
for &f in F64 {
let r = Rational::try_from(f);
assert_eq!(r.is_ok(), f.is_finite());
#[cfg(feature = "float")]
{
if let Ok(r) = r {
assert_eq!(r, f);
}
}
}
}
}