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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
use dashu_base::Sign;
use dashu_int::{DoubleWord, IBig, UBig};

use crate::{error::panic_divide_by_0, repr::Repr};

/// An arbitrary precision rational number.
///
/// This struct represents an rational number with arbitrarily large numerator and denominator
/// based on [UBig] and [IBig].
#[derive(PartialOrd, Ord)]
#[repr(transparent)]
pub struct RBig(pub(crate) Repr);

/// An arbitrary precision rational number without strict reduction.
///
/// This struct is almost the same as [RBig], except for that the numerator and the
/// denominator are allowed to have common divisors **other than a power of 2**. This allows
/// faster computation because [Gcd][dashu_base::Gcd] is not required for each operation.
///
/// Since the representation is not canonicalized, [Hash] is not implemented for [Relaxed].
/// Please use [RBig] if you want to store the rational number in a hash set, or use `num_order::NumHash`.
///
/// # Conversion from/to [RBig]
///
/// To convert from [RBig], use [RBig::relax()]. To convert to [RBig], use [Relaxed::canonicalize()].
#[derive(PartialEq, Eq, PartialOrd, Ord)]
#[repr(transparent)]
pub struct Relaxed(pub(crate) Repr); // the result is not always normalized

impl RBig {
    /// [RBig] with value 0
    pub const ZERO: Self = Self(Repr::zero());
    /// [RBig] with value 1
    pub const ONE: Self = Self(Repr::one());
    /// [RBig] with value -1
    pub const NEG_ONE: Self = Self(Repr::neg_one());

    /// Create a rational number from a signed numerator and an unsigned denominator
    ///
    /// # Examples
    ///
    /// ```
    /// # use dashu_int::{IBig, UBig};
    /// # use dashu_ratio::RBig;
    /// assert_eq!(RBig::from_parts(IBig::ZERO, UBig::ONE), RBig::ZERO);
    /// assert_eq!(RBig::from_parts(IBig::ONE, UBig::ONE), RBig::ONE);
    /// assert_eq!(RBig::from_parts(IBig::NEG_ONE, UBig::ONE), RBig::NEG_ONE);
    /// ```
    #[inline]
    pub fn from_parts(numerator: IBig, denominator: UBig) -> Self {
        if denominator.is_zero() {
            panic_divide_by_0()
        }

        Self(
            Repr {
                numerator,
                denominator,
            }
            .reduce(),
        )
    }
    /// Convert the rational number into (numerator, denumerator) parts.
    ///
    /// # Examples
    ///
    /// ```
    /// # use dashu_int::{IBig, UBig};
    /// # use dashu_ratio::RBig;
    /// assert_eq!(RBig::ZERO.into_parts(), (IBig::ZERO, UBig::ONE));
    /// assert_eq!(RBig::ONE.into_parts(), (IBig::ONE, UBig::ONE));
    /// assert_eq!(RBig::NEG_ONE.into_parts(), (IBig::NEG_ONE, UBig::ONE));
    /// ```
    #[inline]
    pub fn into_parts(self) -> (IBig, UBig) {
        (self.0.numerator, self.0.denominator)
    }

    /// Create a rational number from a signed numerator and a signed denominator
    ///
    /// # Examples
    ///
    /// ```
    /// # use dashu_int::{IBig, UBig};
    /// # use dashu_ratio::RBig;
    /// assert_eq!(RBig::from_parts_signed(1.into(), 1.into()), RBig::ONE);
    /// assert_eq!(RBig::from_parts_signed(12.into(), (-12).into()), RBig::NEG_ONE);
    /// ```
    #[inline]
    pub fn from_parts_signed(numerator: IBig, denominator: IBig) -> Self {
        let (sign, mag) = denominator.into_parts();
        Self::from_parts(numerator * sign, mag)
    }

    /// Create a rational number in a const context
    ///
    /// The magnitude of the numerator and the denominator is limited to
    /// a [DoubleWord][dashu_int::DoubleWord].
    ///
    /// # Examples
    ///
    /// ```
    /// # use dashu_int::Sign;
    /// # use dashu_ratio::{RBig, Relaxed};
    /// const ONE: RBig = RBig::from_parts_const(Sign::Positive, 1, 1);
    /// assert_eq!(ONE, RBig::ONE);
    /// const NEG_ONE: RBig = RBig::from_parts_const(Sign::Negative, 1, 1);
    /// assert_eq!(NEG_ONE, RBig::NEG_ONE);
    /// ```
    #[inline]
    pub const fn from_parts_const(
        sign: Sign,
        mut numerator: DoubleWord,
        mut denominator: DoubleWord,
    ) -> Self {
        if denominator == 0 {
            panic_divide_by_0()
        } else if numerator == 0 {
            return Self::ZERO;
        }

        if numerator > 1 && denominator > 1 {
            // perform a naive but const gcd
            let (mut y, mut r) = (denominator, numerator % denominator);
            while r > 1 {
                let new_r = y % r;
                y = r;
                r = new_r;
            }
            if r == 0 {
                numerator /= y;
                denominator /= y;
            }
        }

        Self(Repr {
            numerator: IBig::from_parts_const(sign, numerator),
            denominator: UBig::from_dword(denominator),
        })
    }

    /// Get the numerator of the rational number
    ///
    /// # Examples
    ///
    /// ```
    /// # use dashu_int::IBig;
    /// # use dashu_ratio::RBig;
    /// assert_eq!(RBig::ZERO.numerator(), &IBig::ZERO);
    /// assert_eq!(RBig::ONE.numerator(), &IBig::ONE);
    /// ```
    #[inline]
    pub fn numerator(&self) -> &IBig {
        &self.0.numerator
    }

    /// Get the denominator of the rational number
    ///
    /// # Examples
    ///
    /// ```
    /// # use dashu_int::UBig;
    /// # use dashu_ratio::RBig;
    /// assert_eq!(RBig::ZERO.denominator(), &UBig::ONE);
    /// assert_eq!(RBig::ONE.denominator(), &UBig::ONE);
    /// ```
    #[inline]
    pub fn denominator(&self) -> &UBig {
        &self.0.denominator
    }

    /// Convert this rational number into a [Relaxed] version
    ///
    /// # Examples
    ///
    /// ```
    /// # use dashu_ratio::{RBig, Relaxed};
    /// assert_eq!(RBig::ZERO.relax(), Relaxed::ZERO);
    /// assert_eq!(RBig::ONE.relax(), Relaxed::ONE);
    /// ```
    #[inline]
    pub fn relax(self) -> Relaxed {
        Relaxed(self.0)
    }

    /// Check whether the number is 0
    ///
    /// # Examples
    ///
    /// ```
    /// # use dashu_ratio::RBig;
    /// assert!(RBig::ZERO.is_zero());
    /// assert!(!RBig::ONE.is_zero());
    /// ```
    #[inline]
    pub const fn is_zero(&self) -> bool {
        self.0.numerator.is_zero()
    }

    /// Check whether the number is 1
    ///
    /// # Examples
    ///
    /// ```
    /// # use dashu_ratio::RBig;
    /// assert!(!RBig::ZERO.is_one());
    /// assert!(RBig::ONE.is_one());
    /// ```
    #[inline]
    pub const fn is_one(&self) -> bool {
        self.0.numerator.is_one()
    }
}

// This custom implementation is necessary due to https://github.com/rust-lang/rust/issues/98374
impl Clone for RBig {
    #[inline]
    fn clone(&self) -> RBig {
        RBig(self.0.clone())
    }
    #[inline]
    fn clone_from(&mut self, source: &RBig) {
        self.0.clone_from(&source.0)
    }
}

impl Default for RBig {
    #[inline]
    fn default() -> Self {
        Self::ZERO
    }
}

impl Relaxed {
    /// [Relaxed] with value 0
    pub const ZERO: Self = Self(Repr::zero());
    /// [Relaxed] with value 1
    pub const ONE: Self = Self(Repr::one());
    /// [Relaxed] with value -1
    pub const NEG_ONE: Self = Self(Repr::neg_one());

    /// Create a rational number from a signed numerator and a signed denominator
    ///
    /// See [RBig::from_parts] for details.
    #[inline]
    pub fn from_parts(numerator: IBig, denominator: UBig) -> Self {
        if denominator.is_zero() {
            panic_divide_by_0();
        }

        Self(
            Repr {
                numerator,
                denominator,
            }
            .reduce2(),
        )
    }

    /// Convert the rational number into (numerator, denumerator) parts.
    ///
    /// See [RBig::into_parts] for details.
    #[inline]
    pub fn into_parts(self) -> (IBig, UBig) {
        (self.0.numerator, self.0.denominator)
    }

    /// Create a rational number from a signed numerator and a signed denominator
    ///
    /// See [RBig::from_parts_signed] for details.
    #[inline]
    pub fn from_parts_signed(numerator: IBig, denominator: IBig) -> Self {
        let (sign, mag) = denominator.into_parts();
        Self::from_parts(numerator * sign, mag)
    }

    /// Create a rational number in a const context
    ///
    /// See [RBig::from_parts_const] for details.
    #[inline]
    pub const fn from_parts_const(
        sign: Sign,
        numerator: DoubleWord,
        denominator: DoubleWord,
    ) -> Self {
        if denominator == 0 {
            panic_divide_by_0()
        } else if numerator == 0 {
            return Self::ZERO;
        }

        let n2 = numerator.trailing_zeros();
        let d2 = denominator.trailing_zeros();
        let zeros = if n2 <= d2 { n2 } else { d2 };
        Self(Repr {
            numerator: IBig::from_parts_const(sign, numerator >> zeros),
            denominator: UBig::from_dword(denominator >> zeros),
        })
    }

    /// Get the numerator of the rational number
    ///
    /// See [RBig::numerator] for details.
    #[inline]
    pub fn numerator(&self) -> &IBig {
        &self.0.numerator
    }

    /// Get the denominator of the rational number
    ///
    /// See [RBig::denominator] for details.
    #[inline]
    pub fn denominator(&self) -> &UBig {
        &self.0.denominator
    }

    /// Convert this rational number into an [RBig] version
    ///
    /// # Examples
    ///
    /// ```
    /// # use dashu_int::IBig;
    /// # use dashu_ratio::{RBig, Relaxed};
    /// assert_eq!(Relaxed::ONE.canonicalize(), RBig::ONE);
    ///
    /// let r = Relaxed::from_parts(10.into(), 5u8.into());
    /// assert_eq!(r.canonicalize().numerator(), &IBig::from(2));
    /// ```
    #[inline]
    pub fn canonicalize(self) -> RBig {
        RBig(self.0.reduce())
    }

    /// Check whether the number is 0
    ///
    /// See [RBig::is_zero] for details.
    #[inline]
    pub const fn is_zero(&self) -> bool {
        self.0.numerator.is_zero()
    }

    /// Check whether the number is 1
    ///
    /// See [RBig::is_one] for details.
    #[inline]
    pub const fn is_one(&self) -> bool {
        self.0.numerator.is_one()
    }
}

// This custom implementation is necessary due to https://github.com/rust-lang/rust/issues/98374
impl Clone for Relaxed {
    #[inline]
    fn clone(&self) -> Relaxed {
        Relaxed(self.0.clone())
    }
    #[inline]
    fn clone_from(&mut self, source: &Relaxed) {
        self.0.clone_from(&source.0)
    }
}

impl Default for Relaxed {
    #[inline]
    fn default() -> Self {
        Self::ZERO
    }
}