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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
// Copyright © 2016–2019 University of Malta

// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation, either version 3 of
// the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// this program. If not, see <https://www.gnu.org/licenses/>.

use crate::ext::xmpq;
use crate::ext::xmpz;
use crate::rational::big;
use crate::rational::ParseRationalError;
#[cfg(try_from)]
use crate::rational::TryFromFloatError;
use crate::{Assign, Integer, Rational};
use gmp_mpfr_sys::gmp;
use std::cmp::Ordering;
#[cfg(try_from)]
use std::convert::TryFrom;
#[cfg(try_from)]
use std::error::Error;
use std::fmt::{Binary, Debug, Display, Formatter, LowerHex, Octal, Result as FmtResult, UpperHex};
use std::hash::{Hash, Hasher};
use std::i32;
use std::mem;
use std::str::FromStr;

impl Default for Rational {
    #[inline]
    fn default() -> Rational {
        Rational::new()
    }
}

impl Clone for Rational {
    #[inline]
    fn clone(&self) -> Rational {
        unsafe {
            let_uninit_ptr!(dst: Rational, dst_ptr);
            let inner_ptr = cast_ptr_mut!(dst_ptr, gmp::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());
            assume_init!(dst)
        }
    }

    #[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 {
    fn hash<H>(&self, state: &mut H)
    where
        H: Hasher,
    {
        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) {
        mem::drop(mem::replace(self, src));
    }
}

impl Assign<&Rational> for Rational {
    #[inline]
    fn assign(&mut self, src: &Rational) {
        xmpq::set(self, Some(src));
    }
}

impl From<&Rational> for Rational {
    #[inline]
    fn from(src: &Rational) -> Self {
        unsafe {
            let_uninit_ptr!(dst, dst_ptr);
            xmpq::init_set(dst_ptr, src);
            assume_init!(dst)
        }
    }
}

impl<Num> Assign<Num> for Rational
where
    Integer: Assign<Num>,
{
    #[inline]
    fn assign(&mut self, src: Num) {
        // no need to canonicalize, as denominator will be 1.
        let num_den = unsafe { self.as_mut_numer_denom_no_canonicalization() };
        num_den.0.assign(src);
        <Integer as Assign<u32>>::assign(num_den.1, 1);
    }
}

impl<Num> From<Num> for Rational
where
    Integer: From<Num>,
{
    #[inline]
    fn from(src: Num) -> Self {
        unsafe {
            let_uninit_ptr!(dst: Rational, dst_ptr);
            let inner_ptr = cast_ptr_mut!(dst_ptr, gmp::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);
            assume_init!(dst)
        }
    }
}

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(src: (Num, Den)) -> Self {
        unsafe {
            let_uninit_ptr!(dst: Rational, dst_ptr);
            let inner_ptr = cast_ptr_mut!(dst_ptr, gmp::mpq_t);
            let num = cast_ptr_mut!(gmp::mpq_numref(inner_ptr), Integer);
            num.write(Integer::from(src.0));
            let den = cast_ptr_mut!(gmp::mpq_denref(inner_ptr), Integer);
            den.write(Integer::from(src.1));
            assert_ne!((*den).cmp0(), Ordering::Equal, "division by zero");
            gmp::mpq_canonicalize(inner_ptr);
            assume_init!(dst)
        }
    }
}

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 {
        unsafe {
            let_uninit_ptr!(dst: Rational, dst_ptr);
            let inner_ptr = cast_ptr_mut!(dst_ptr, gmp::mpq_t);
            let num = cast_ptr_mut!(gmp::mpq_numref(inner_ptr), Integer);
            num.write(Integer::from(&src.0));
            let den = cast_ptr_mut!(gmp::mpq_denref(inner_ptr), Integer);
            den.write(Integer::from(&src.1));
            assert_ne!((*den).cmp0(), Ordering::Equal, "division by zero");
            gmp::mpq_canonicalize(inner_ptr);
            assume_init!(dst)
        }
    }
}

#[cfg(try_from)]
impl TryFrom<f32> for Rational {
    type Error = TryFromFloatError;
    #[inline]
    fn try_from(value: f32) -> Result<Self, TryFromFloatError> {
        Rational::from_f32(value).ok_or(TryFromFloatError { _unused: () })
    }
}

#[cfg(try_from)]
impl TryFrom<f64> for Rational {
    type Error = TryFromFloatError;
    #[inline]
    fn try_from(value: f64) -> Result<Self, TryFromFloatError> {
        Rational::from_f64(value).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)
}

#[cfg(try_from)]
impl Error for TryFromFloatError {
    fn description(&self) -> &str {
        "conversion of infinite or NaN value attempted"
    }
}

#[cfg(try_from)]
impl Display for TryFromFloatError {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        Display::fmt(self.description(), f)
    }
}

unsafe impl Send for Rational {}
unsafe impl Sync for Rational {}

#[cfg(test)]
#[allow(clippy::float_cmp)]
mod tests {
    use crate::{Assign, Rational};
    #[cfg(try_from)]
    use std::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));
    }

    #[cfg(try_from)]
    #[test]
    fn check_fallible_conversions() {
        use crate::tests::{F32, F64};
        use Rational;
        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);
                }
            }
        }
    }
}