Documentation
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
// numera::number::rational::q::sized
//
//!
//
// TOC
//
// - macro
//   - define_rational_sized
// - definitions
//   - Rational[8|16|32|64|128]

#[cfg(feature = "try_from")]
use crate::number::rational::Rationals;
use crate::{
    error::{NumeraErrors, NumeraResult, RationalErrors},
    number::{
        integer::*,
        macros::impl_larger_smaller,
        traits::{
            Bound, ConstLowerBounded, ConstNegOne, ConstOne, ConstUpperBounded, ConstZero, Count,
            Countable, Ident, LowerBounded, NegOne, Negative, Number, One, Positive, Sign,
            UpperBounded, Zero,
        },
    },
};
use core::{
    cmp::Ordering,
    fmt,
    hash::{Hash, Hasher},
    num::{NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8},
};
use devela::paste;

/* macro */

/// # What it does
/// - defines a Rational of a concrete size.
/// - implements Number: Bound + Count + Ident + Sign
/// - implements Default → 0
///
/// # Args
/// - `$name`: the base name of the rational. e.g. `Rational`.
/// - `$abbr`: the base abbreviated name, E.g. `Q`.
///
/// - `$numi`: the base name of the inner representation of the numerator.
/// - `$numim`: the base name of the innermost representation of the numerator.
/// - `$deni`: the base name of the inner representation of the numerator.
/// - `$denim`: the base name of the innermost representation of the numerator.
///
/// - `$doc_num`: the type of number.
/// - `$doc_type`: adds to the type doc-comment.
// - `$doc_new`: adds to the `new` constructor doc-comment.
///
/// - `$doc_sign`: an optional negative sign
/// - `$doc_lower`: the lower bound of the number type.
/// - `$doc_upper`: the upper bound of the number type.
///
/// - `$num`: the integer base type for the numerator. e.g. `Integer`.
/// - `$den`: the integer base type for the denominator. e.g. `NonZeroInteger`.
///
/// grouped:
/// - `$doc_det`: the determinant before the bit size. e.g. "An" (8-bit) or "A" 16-bit.
/// - `$b`: the size in bits of the primitive used.
macro_rules! define_rational_sized {
    // defines multiple integer types, with an inner primitive.
    (multi $name:ident, $abbr:ident,
     $numi:ident, $numim:ident, $deni:ident, $denim:ident,
     $doc_num:literal, $doc_type:literal, // $doc_new:literal,
     $doc_sign:literal, $doc_lower:expr, $doc_upper:expr,
     $num:ident, $den:ident,
        $(
            (
             $doc_det:literal, $b:expr,
             larger: $larger:literal, $larger_b:literal,
             smaller: $smaller:literal, $smaller_b:literal
            )
        ),+
     ) => {
        $(
            define_rational_sized![single $name, $abbr,
               $numi, $numim, $deni, $denim,
               $doc_num, $doc_type, // $doc_new,
               $doc_sign, $doc_lower, $doc_upper,
               $num, $den,
               ($doc_det, $b,
                larger: $larger, $larger_b,
                smaller: $smaller, $smaller_b
               )];
        )+
    };
    // defines a single integer type, with an inner primitive.
    (single $name:ident, $abbr:ident,
     $numi:ident, $numim:ident, $deni:ident, $denim:ident,
     $doc_num:literal, $doc_type:literal, // $doc_new:literal,
     $doc_sign:literal, $doc_lower:expr, $doc_upper:expr,
     $num:ident, $den:ident,
     (
      $doc_det:literal, $b:expr,
      larger: $larger:literal, $larger_b:literal,
      smaller: $smaller:literal, $smaller_b:literal
      )
    ) => { paste! {
        #[doc = $doc_det " "$b "-bit " $doc_num $doc_type ","]
        #[doc = "also known as [`" [<$abbr$b>] "`][super::" [<$abbr$b>] "]."]
        #[doc = "\n\nThe range of valid numeric values is $\\lbrack"
        $doc_sign "$[`" $numim$b "::" $doc_lower "`] $\\dots$ [`"
        $denim$b "::" $doc_upper "`]$\\rbrack$."]

        #[derive(Clone, Copy)]
        pub struct [<$name$b>] {
            pub num: [<$num$b>],
            pub den: [<$den$b>],
        }

        /// Returns $0/1$.
        impl Default for [<$name$b>] {
            fn default() -> Self {
                Self {
                    num: [<$num$b>]::ZERO,
                    den: [<$den$b>]::ONE,
                }
            }
        }

        impl Hash for [<$name$b>] {
            /// The hash of equivalent functions with different numerator and/or
            /// denominator is considered different, even if they are considered
            /// equal by the `PartialEq` and `Eq` implementations.
            fn hash<H: Hasher>(&self, state: &mut H) {
                self.num.hash(state);
                self.den.hash(state);
            }
        }

        impl PartialEq for [<$name$b>] {
            /// Equivalent functions are considered equal, even if they are
            /// considered different by the `Hash` implementation.
            fn eq(&self, other: &Self) -> bool {
                // upcast first
                let uself = self.as_larger_or_same();
                let uother = other.as_larger_or_same();

                // compare by cross-multiplying
                uself.num * uother.den.into() == uother.num * uself.den.into()

                // IMPROVE: if it overflows try reducing
                // let rself = uself.reduced();
                // let rother = uother.reduced();
                // rself.num == rother.num && rself.den == rother.den
            }
        }
        impl Eq for [<$name$b>] {}

        impl PartialOrd for [<$name$b>] {
            fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
                // upcast first
                let uself = self.as_larger_or_same();
                let uother = other.as_larger_or_same();

                // compare by cross-multiplying
                let lhs = uself.num * uother.den.into();
                let rhs = uother.num * uself.den.into();

                // IMPROVE: if it overflows try reducing

                lhs.partial_cmp(&rhs)
            }
        }
        impl Ord for [<$name$b>] {
            fn cmp(&self, other: &Self) -> Ordering {
                self.partial_cmp(&other).unwrap()
            }
        }

        impl fmt::Display for [<$name$b>]  {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(f, "{}/{}", self.num, self.den)
            }
        }
        impl fmt::Debug for [<$name$b>]  {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(f, "{}({}/{})", stringify!([<$abbr$b>]), self.num, self.den)
                // MAYBE?
                // write!(f, "{}({:?}/{:?})", stringify!([<$abbr$b>]), self.num, self.den)
            }
        }

        impl [<$name$b>]  {
            #[doc = "Returns a new `" [<$name$b>] "`."]
            ///
            /// # Errors
            /// If the `denominator` is `0`.
            #[inline]
            pub const fn new(numerator: [<i$b>], denominator: [<i$b>])
                -> NumeraResult<Self> {
                if let Ok(den) = [<$den$b>]::new(denominator) {
                    let num = [<$num$b>]::new(numerator);
                    Ok(Self{ num, den })
                } else {
                    Err(NumeraErrors::Rational(RationalErrors::ZeroDenominator))
                }
            }

            #[doc = "Returns a new `" [<$name$b>] "`."]
            ///
            /// # Safety
            /// The `denominator` must not be 0.
            ///
            /// # Panics
            /// Panics in debug if the `denominator` is 0.
            #[inline]
            #[cfg(not(feature = "safe"))]
            #[cfg_attr(feature = "nightly", doc(cfg(feature = "not(safe)")))]
            pub const unsafe fn new_unchecked(numerator: [<i$b>], denominator: [<i$b>])
                -> Self {
                debug_assert![denominator != 0];
                Self {
                    num: [<$num$b>]::new(numerator),
                    den: [<$den$b>]::new_unchecked(denominator),
                }
            }
        }

        /* resizing */

        // uses try_from
        impl_larger_smaller![$name, $b, Rationals,
            larger: $larger, $larger_b, smaller: $smaller, $smaller_b
        ];

        /* sign */

        impl Sign for [<$name$b>] {
            #[inline]
            fn can_negative(&self) -> bool { true }
            #[inline]
            fn can_positive(&self) -> bool { true }
            #[inline]
            fn is_negative(&self) -> bool {
                self.num.is_negative() && self.den.is_positive() ||
                self.num.is_positive() && self.den.is_negative()
            }
            #[inline]
            fn is_positive(&self) -> bool {
                self.num.is_negative() && self.den.is_negative() ||
                self.num.is_positive() && self.den.is_positive()
            }
        }
        impl Positive for [<$name$b>] {}
        impl Negative for [<$name$b>] {}

        /* bound */

        impl Bound for [<$name$b>] {
            #[inline]
            fn is_lower_bounded(&self) -> bool { true }
            #[inline]
            fn is_upper_bounded(&self) -> bool { true }
            #[inline]
            fn lower_bound(&self) -> Option<Self> {
                Some(<Self as ConstLowerBounded>::MIN)
            }
            #[inline]
            fn upper_bound(&self) -> Option<Self> {
                Some(<Self as ConstUpperBounded>::MAX)
            }
        }
        impl LowerBounded for [<$name$b>] {
            #[inline]
            fn new_min() -> Self { <Self as ConstLowerBounded>::MIN }
        }
        impl UpperBounded for [<$name$b>] {
            #[inline]
            fn new_max() -> Self { <Self as ConstUpperBounded>::MAX }
        }
        impl ConstLowerBounded for [<$name$b>] {
            const MIN: Self = Self {
                    num: [<$num$b>]::MIN,
                    den: [<$den$b>]::ONE,
                };
        }
        impl ConstUpperBounded for [<$name$b>] {
            const MAX: Self = Self {
                    num: [<$num$b>]::MAX,
                    den: [<$den$b>]::ONE,
                };
        }

        /* count */

        impl Count for [<$name$b>] {
            #[inline]
            fn is_countable(&self) -> bool { true }
        }

        impl Countable for [<$name$b>] {
            /// Returns the next rational value by increasing the
            /// numerator, while maintaining the same denominator.
            #[inline]
            fn next(&self) -> NumeraResult<Self> {
                Ok(Self {
                    num: self.num.0.checked_add(1)
                        .ok_or(RationalErrors::NumeratorOverflow)?.into(),
                    den: self.den,
                })
            }
            /// Returns the previous rational value by decreasing the
            /// numerator, while maintaining the same denominator.
            #[inline]
            fn previous(&self) -> NumeraResult<Self> {
                Ok(Self {
                    num: self.num.0.checked_sub(1)
                        .ok_or(RationalErrors::NumeratorUnderflow)?.into(),
                    den: self.den,
                })
            }
        }

        /* ident */

        impl Ident for [<$name$b>] {
            #[inline]
            fn can_zero(&self) -> bool { true }
            #[inline]
            fn can_one(&self) -> bool { true }
            #[inline]
            fn can_neg_one(&self) -> bool { true }

            #[inline]
            fn is_zero(&self) -> bool { self.num.is_zero() }
            #[inline]
            fn is_one(&self) -> bool { self.num == self.den.into() }
            #[inline]
            fn is_neg_one(&self) -> bool { self.num.neg() == self.den.into() }
        }
        impl ConstZero for [<$name$b>] {
            const ZERO: Self = Self {
                num: [<$num$b>]::ZERO,
                den: [<$den$b>]::ONE,
            };
        }
        impl Zero for [<$name$b>] {
            #[inline]
            fn new_zero() -> Self { <Self as ConstZero>::ZERO }
        }
        impl ConstOne for [<$name$b>] {
            const ONE: Self = Self {
                num: [<$num$b>]::ONE,
                den: [<$den$b>]::ONE,
            };
        }
        impl One for [<$name$b>] {
            #[inline]
            fn new_one() -> Self { <Self as ConstOne>::ONE }
        }
        impl ConstNegOne for [<$name$b>] {
            const NEG_ONE: Self = Self {
                num: [<$num$b>]::NEG_ONE,
                den: [<$den$b>]::ONE,
            };
        }
        impl NegOne for [<$name$b>] {
            #[inline]
            fn new_neg_one() -> Self { <Self as ConstNegOne>::NEG_ONE }
        }

        /* Number */

        impl Number for [<$name$b>] {
            type InnerRepr = ([<$numi$b>], [<$deni$b>]);
            type InnermostRepr = ([<$numim$b>], [<$denim$b>]);

            /// Forms a new rational from a numerator and denominator.
            ///
            /// # Errors
            /// If the denominator (`value.1`) equals 0.
            #[inline]
            fn from_inner_repr(value: Self::InnerRepr) -> NumeraResult<Self> {
                Ok(
                    Self {
                        num: [<$num$b>]::from_inner_repr(value.0)?,
                        den: [<$den$b>]::from_inner_repr(value.1)
                            .map_err(|_| RationalErrors::ZeroDenominator)?,
                    }
                )
            }

            /// Forms a new rational from a numerator and denominator.
            #[inline]
            #[cfg(not(feature = "safe"))]
            #[cfg_attr(feature = "nightly", doc(cfg(feature = "not(safe)")))]
            unsafe fn from_inner_repr_unchecked(value: Self::InnerRepr) -> Self {
                Self {
                    num: [<$num$b>]::from_inner_repr_unchecked(value.0),
                    den: [<$den$b>]::from_inner_repr_unchecked(value.1),
                }
            }

            /// Forms a new rational from a numerator and denominator.
            ///
            /// # Errors
            /// If the denominator (`value.1`) equals 0.
            #[inline]
            fn from_innermost_repr(value: Self::InnermostRepr) -> NumeraResult<Self> {
                Ok(
                    Self {
                        num: [<$num$b>]::from_innermost_repr(value.0)?,
                        den: [<$den$b>]::from_innermost_repr(value.1)
                            .map_err(|_| RationalErrors::ZeroDenominator)?,
                    }
                )
            }

            /// Forms a new rational from a numerator and denominator.
            ///
            /// # Panics
            /// Panics in debug if the given `value` is `0`.
            ///
            /// # Safety
            /// The given `value` must not be `0`.
            #[inline]
            #[cfg(not(feature = "safe"))]
            #[cfg_attr(feature = "nightly", doc(cfg(feature = "not(safe)")))]
            unsafe fn from_innermost_repr_unchecked(value: Self::InnermostRepr) -> Self {
                debug_assert![value.1 != [<$numim$b>]::ZERO];
                Self {
                    num: [<$num$b>]::from_innermost_repr_unchecked(value.0),
                    den: [<$den$b>]::from_innermost_repr_unchecked(value.1),
                }
            }

            #[inline]
            fn into_inner_repr(self) -> Self::InnerRepr { (self.num.into(), self.den.into()) }

            #[inline]
            fn into_innermost_repr(self) -> Self::InnermostRepr { (self.num.into(), self.den.into()) }
        }
    }};
}

/* definitions */

define_rational_sized![multi Rational, Q,
    i, i, NonZeroI, i,
    "rational number", ", from the set $\\Bbb{Q}$",
    // "",
    "", MIN, MAX,
    Integer, NonZeroInteger,
    ("A 2 ×", 8, larger: true, 16, smaller: false, 4),
    ("A 2 ×", 16, larger: true, 32, smaller: true, 8),
    ("A 2 ×", 32, larger: true, 64, smaller: true, 16),
    ("A 2 ×", 64, larger: true, 128, smaller: true, 32),
    ("A 2 ×", 128, larger: false, 256, smaller: true, 64)
];

#[cfg(test)]
mod tests {
    use crate::all::*;

    #[test]
    fn q_define_sized() -> NumeraResult<()> {
        assert_eq![
            Rational8::from_innermost_repr((5, 0)),
            Err(RationalErrors::ZeroDenominator.into())
        ];

        let _q5 = Rational8::from_innermost_repr((5, 1))?;

        // Display
        #[cfg(feature = "std")]
        assert_eq![_q5.to_string(), "5/1"];

        // PartialEq
        assert![Q8::new(4, 2)? == Q8::new(4, 2)?]; // eq non-reduced
        assert![Q8::new(4, 2)? == Q8::new(2, 1)?]; // eq reduced
        assert![Q8::new(4, 2)? != Q8::new(3, 1)?]; // ne

        // PartialOrd
        assert![Q8::new(3, 2)? < Q8::new(4, 2)?];
        assert![Q8::new(3, 2)? > Q8::new(3, 5)?];

        // Bound
        // Count
        // Ident
        // Sign

        // #[cfg(feature = "std")]
        // {
        //     use std::panic::catch_unwind;
        //     // 0 denominator
        //     assert![catch_unwind(|| Rational8::from_inner_repr((5, 0)).unwrap()).is_err()];
        // }

        Ok(())
    }
}