fasti 0.2.0

Dates, calendars, business-day conventions and day-count fractions for financial code. Native Rust, no_std, float-free; designed after QuantLib's ql/time.
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
//! [`Fraction`] — an integer rational `num / den`.
//!
//! Returned by [`DayCount`](crate::DayCount) and used as the crate-wide
//! rational scalar. Stored in reduced form; numerator is `i64` (sign lives
//! there), denominator is `u64` and always positive. Fallible arithmetic is
//! exposed only as `checked_*` — no operator overloads.

use core::{cmp::Ordering, fmt};

use crate::TimeError;

/// An integer rational `numerator / denominator`, stored in reduced
/// form (no common factor between `|numerator|` and denominator).
///
/// The numerator is signed; the denominator is always positive.
///
/// ```
/// use fasti::Fraction;
///
/// // Reducing happens at construction.
/// let half = Fraction::new(2, 4)?;
/// assert_eq!(half.parts(), (1, 2));
///
/// // Addition on a common denominator.
/// let third = Fraction::new(1, 3)?;
/// let sum = third.checked_add(third).expect("no overflow");
/// assert_eq!(sum.parts(), (2, 3));
///
/// // Negative numerator — sign is preserved through reduction.
/// assert_eq!(Fraction::new(-30, 360)?.parts(), (-1, 12));
/// # Ok::<(), fasti::TimeError>(())
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Fraction {
    num: i64,
    den: u64,
}

impl Fraction {
    /// The zero fraction, `0 / 1`.
    ///
    /// ```
    /// use fasti::Fraction;
    /// assert_eq!(Fraction::ZERO.parts(), (0, 1));
    /// assert!(Fraction::ZERO.is_zero());
    /// ```
    pub const ZERO: Self = Self { num: 0, den: 1 };

    /// Construct a `Fraction` from a signed numerator and a
    /// positive denominator, reducing by `gcd(|num|, den)`.
    ///
    /// Returns [`TimeError::ZeroDenominator`] if `den == 0`.
    ///
    /// ```
    /// use fasti::{TimeError, Fraction};
    /// assert_eq!(Fraction::new(7, 360)?.parts(), (7, 360));
    /// assert_eq!(Fraction::new(0, 5)?.parts(), (0, 1));
    /// assert_eq!(Fraction::new(2, 4)?.parts(), (1, 2));
    /// assert_eq!(Fraction::new(-30, 360)?.parts(), (-1, 12));
    /// assert_eq!(Fraction::new(7, 0), Err(TimeError::ZeroDenominator));
    /// # Ok::<(), fasti::TimeError>(())
    /// ```
    pub fn new(num: i64, den: u64) -> Result<Self, TimeError> {
        if den == 0 {
            return Err(TimeError::ZeroDenominator);
        }
        let common_u128 = gcd(u128::from(num.unsigned_abs()), u128::from(den));
        // gcd ≤ min(|num|, den) ≤ u64::MAX, so the narrowing is exact.
        #[allow(clippy::cast_possible_truncation)]
        let common = common_u128 as u64;
        let reduced_den = den / common;
        // Signed division in i128 handles the num == i64::MIN edge case.
        let reduced_num_i128 = i128::from(num) / i128::from(common);
        // |reduced_num| ≤ |num| ≤ |i64::MIN|, so the result fits i64.
        #[allow(clippy::cast_possible_truncation)]
        let reduced_num = reduced_num_i128 as i64;
        Ok(Self {
            num: reduced_num,
            den: reduced_den,
        })
    }

    /// The signed numerator of the reduced fraction.
    #[must_use]
    pub const fn numerator(self) -> i64 {
        self.num
    }

    /// The denominator of the reduced fraction. Always non-zero.
    #[must_use]
    pub const fn denominator(self) -> u64 {
        self.den
    }

    /// `(numerator, denominator)` of the reduced fraction, for use
    /// with checked integer arithmetic (multiply before divide).
    #[must_use]
    pub const fn parts(self) -> (i64, u64) {
        (self.num, self.den)
    }

    /// `true` iff the fraction is exactly zero.
    #[must_use]
    pub const fn is_zero(self) -> bool {
        self.num == 0
    }

    /// `true` iff the fraction is strictly negative.
    #[must_use]
    pub const fn is_negative(self) -> bool {
        self.num < 0
    }

    /// Negate the fraction. Returns [`None`] if the numerator is
    /// `i64::MIN`, which has no positive `i64` counterpart.
    ///
    /// ```
    /// use fasti::Fraction;
    /// let pos = Fraction::new(7, 360)?;
    /// let neg = pos.checked_neg().expect("non-MIN numerator");
    /// assert_eq!(neg.parts(), (-7, 360));
    /// // Round trip.
    /// assert_eq!(neg.checked_neg().expect("non-MIN numerator"), pos);
    /// // i64::MIN cannot be negated as i64.
    /// let edge = Fraction::new(i64::MIN, 1)?;
    /// assert_eq!(edge.checked_neg(), None);
    /// # Ok::<(), fasti::TimeError>(())
    /// ```
    #[must_use]
    pub const fn checked_neg(self) -> Option<Self> {
        match self.num.checked_neg() {
            Some(num) => Some(Self { num, den: self.den }),
            None => None,
        }
    }

    /// Add two fractions, returning [`None`] if any intermediate or
    /// the reduced result does not fit in `(i64, u64)`.
    ///
    /// ```
    /// use fasti::Fraction;
    /// let a = Fraction::new(1, 2)?;
    /// let b = Fraction::new(1, 4)?;
    /// assert_eq!(
    ///     a.checked_add(b).expect("no overflow").parts(),
    ///     (3, 4),
    /// );
    /// // Adding the negation cancels.
    /// let neg = Fraction::new(-1, 2)?;
    /// assert_eq!(a.checked_add(neg), Some(Fraction::ZERO));
    /// # Ok::<(), fasti::TimeError>(())
    /// ```
    #[must_use]
    pub fn checked_add(self, other: Self) -> Option<Self> {
        let lhs_num = i128::from(self.num);
        let rhs_num = i128::from(other.num);
        let lhs_den = i128::from(self.den);
        let rhs_den = i128::from(other.den);
        let num = lhs_num
            .checked_mul(rhs_den)?
            .checked_add(rhs_num.checked_mul(lhs_den)?)?;
        let den = lhs_den.checked_mul(rhs_den)?;
        let common_unsigned = gcd(num.unsigned_abs(), den.unsigned_abs());
        // common ≤ den ≤ i128::MAX, so the signed conversion succeeds.
        let common = i128::try_from(common_unsigned).ok()?;
        let reduced_num = num / common;
        let reduced_den = den / common;
        Some(Self {
            num: i64::try_from(reduced_num).ok()?,
            den: u64::try_from(reduced_den).ok()?,
        })
    }

    /// Multiply two fractions. Returns [`None`] if any intermediate or
    /// the reduced result does not fit in `(i64, u64)`.
    ///
    /// ```
    /// use fasti::Fraction;
    /// // 1/2 × 1/3 = 1/6.
    /// let half = Fraction::new(1, 2)?;
    /// let third = Fraction::new(1, 3)?;
    /// assert_eq!(half.checked_mul(third).expect("fits").parts(), (1, 6));
    /// // 10% × 1/4 = (1/10) × (1/4) = 1/40 (Bps lifted as 1_000/10_000).
    /// let ten_pct = Fraction::new(1_000, 10_000)?;
    /// let quarter = Fraction::new(90, 360)?;
    /// assert_eq!(ten_pct.checked_mul(quarter).expect("fits").parts(), (1, 40));
    /// // Sign composes: negative × positive = negative.
    /// let neg_half = Fraction::new(-1, 2)?;
    /// assert_eq!(neg_half.checked_mul(third).expect("fits").parts(), (-1, 6));
    /// # Ok::<(), fasti::TimeError>(())
    /// ```
    #[must_use]
    pub fn checked_mul(self, other: Self) -> Option<Self> {
        let num = i128::from(self.num).checked_mul(i128::from(other.num))?;
        let den = i128::from(self.den).checked_mul(i128::from(other.den))?;
        let common_unsigned = gcd(num.unsigned_abs(), den.unsigned_abs());
        let common = i128::try_from(common_unsigned).ok()?;
        let reduced_num = num / common;
        let reduced_den = den / common;
        Some(Self {
            num: i64::try_from(reduced_num).ok()?,
            den: u64::try_from(reduced_den).ok()?,
        })
    }

    /// Compare two fractions by cross-multiplication, widened to `i128`
    /// so the comparison is total and never overflows.
    ///
    /// ```
    /// use core::cmp::Ordering;
    /// use fasti::Fraction;
    /// let third = Fraction::new(1, 3)?;
    /// let half = Fraction::new(1, 2)?;
    /// let neg_third = Fraction::new(-1, 3)?;
    /// assert_eq!(third.cmp_cross(half), Ordering::Less);
    /// assert_eq!(half.cmp_cross(half), Ordering::Equal);
    /// assert_eq!(neg_third.cmp_cross(third), Ordering::Less);
    /// # Ok::<(), fasti::TimeError>(())
    /// ```
    #[must_use]
    pub fn cmp_cross(self, other: Self) -> Ordering {
        let lhs = i128::from(self.num) * i128::from(other.den);
        let rhs = i128::from(other.num) * i128::from(self.den);
        lhs.cmp(&rhs)
    }
}

impl Default for Fraction {
    /// `Default` is [`Self::ZERO`].
    fn default() -> Self {
        Self::ZERO
    }
}

impl PartialOrd for Fraction {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Fraction {
    fn cmp(&self, other: &Self) -> Ordering {
        self.cmp_cross(*other)
    }
}

impl fmt::Display for Fraction {
    /// Formats as `numerator/denominator` in reduced form.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}/{}", self.num, self.den)
    }
}

impl From<Fraction> for (i64, u64) {
    fn from(yf: Fraction) -> Self {
        yf.parts()
    }
}

// ---- helpers ------------------------------------------------------------

/// Greatest common divisor via Euclid's algorithm; `gcd(0, x) = x`.
const fn gcd(mut a: u128, mut b: u128) -> u128 {
    while b != 0 {
        let t = b;
        b = a % b;
        a = t;
    }
    a
}

// ---- Tests --------------------------------------------------------------

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    extern crate alloc;

    use super::*;
    use proptest::prelude::*;

    #[test]
    fn rejects_zero_denominator() {
        assert_eq!(Fraction::new(0, 0), Err(TimeError::ZeroDenominator));
        assert_eq!(Fraction::new(7, 0), Err(TimeError::ZeroDenominator));
        assert_eq!(Fraction::new(-7, 0), Err(TimeError::ZeroDenominator));
    }

    #[test]
    fn reduces_on_construction() {
        assert_eq!(Fraction::new(2, 4).unwrap().parts(), (1, 2));
        assert_eq!(Fraction::new(0, 5).unwrap().parts(), (0, 1));
        assert_eq!(Fraction::new(7, 360).unwrap().parts(), (7, 360));
        assert_eq!(Fraction::new(360, 360).unwrap().parts(), (1, 1));
    }

    #[test]
    fn negative_numerator_round_trips() {
        // Sign lives on the numerator; the denominator stays positive.
        assert_eq!(Fraction::new(-30, 360).unwrap().parts(), (-1, 12));
        assert_eq!(Fraction::new(-7, 360).unwrap().parts(), (-7, 360));
    }

    #[test]
    fn negation_through_construction() {
        let pos = Fraction::new(7, 360).unwrap();
        let neg = Fraction::new(-7, 360).unwrap();
        assert_eq!(pos.numerator(), 7);
        assert_eq!(neg.numerator(), -7);
        assert_eq!(pos.denominator(), neg.denominator());
    }

    #[test]
    fn already_reduced_is_no_op() {
        let f = Fraction::new(7, 360).unwrap();
        let again = Fraction::new(f.numerator(), f.denominator()).unwrap();
        assert_eq!(f, again);
    }

    #[test]
    fn zero_constant() {
        assert_eq!(Fraction::ZERO, Fraction::new(0, 1).unwrap());
        assert_eq!(Fraction::ZERO, Fraction::new(0, 12345).unwrap());
        assert!(Fraction::ZERO.is_zero());
    }

    #[test]
    fn default_is_zero() {
        assert_eq!(Fraction::default(), Fraction::ZERO);
        // Default must be (0, 1), not a derived (0, 0) with zero denominator.
        let parts = Fraction::default().parts();
        assert_eq!(parts, (0, 1));
        assert_ne!(parts.1, 0);
    }

    #[test]
    fn is_negative_examples() {
        assert!(!Fraction::ZERO.is_negative());
        assert!(!Fraction::new(1, 2).unwrap().is_negative());
        assert!(Fraction::new(-1, 2).unwrap().is_negative());
    }

    #[test]
    fn unreduced_inputs_compare_equal() {
        // (1, 2) and (2, 4) reduce to the same canonical form.
        let half = Fraction::new(1, 2).unwrap();
        let two_quarters = Fraction::new(2, 4).unwrap();
        assert_eq!(half, two_quarters);
        assert_eq!(half.cmp_cross(two_quarters), Ordering::Equal);
    }

    #[test]
    fn cmp_cross_orders_correctly() {
        let third = Fraction::new(1, 3).unwrap();
        let half = Fraction::new(1, 2).unwrap();
        let two_thirds = Fraction::new(2, 3).unwrap();
        let neg_third = Fraction::new(-1, 3).unwrap();
        assert_eq!(third.cmp_cross(half), Ordering::Less);
        assert_eq!(half.cmp_cross(third), Ordering::Greater);
        assert_eq!(half.cmp_cross(two_thirds), Ordering::Less);
        assert_eq!(neg_third.cmp_cross(third), Ordering::Less);
        assert_eq!(neg_third.cmp_cross(Fraction::ZERO), Ordering::Less);
    }

    #[test]
    fn checked_add_basic_examples() {
        let third = Fraction::new(1, 3).unwrap();
        let two_thirds = third.checked_add(third).unwrap();
        assert_eq!(two_thirds.parts(), (2, 3));

        let a = Fraction::new(1, 2).unwrap();
        let b = Fraction::new(1, 4).unwrap();
        assert_eq!(a.checked_add(b).unwrap().parts(), (3, 4));
    }

    #[test]
    fn checked_add_zero_is_identity() {
        let f = Fraction::new(7, 360).unwrap();
        assert_eq!(f.checked_add(Fraction::ZERO), Some(f));
        assert_eq!(Fraction::ZERO.checked_add(f), Some(f));
    }

    #[test]
    fn checked_add_with_negation_cancels() {
        let f = Fraction::new(7, 360).unwrap();
        let neg_f = Fraction::new(-7, 360).unwrap();
        assert_eq!(f.checked_add(neg_f), Some(Fraction::ZERO));
    }

    #[test]
    fn checked_add_mixed_signs() {
        // 3/4 + (-1/2) = 1/4.
        let three_quarters = Fraction::new(3, 4).unwrap();
        let neg_half = Fraction::new(-1, 2).unwrap();
        assert_eq!(
            three_quarters.checked_add(neg_half).unwrap().parts(),
            (1, 4),
        );
    }

    #[test]
    fn checked_add_overflows_when_result_exceeds_i64() {
        // (i64::MAX / 2 + 1, 1) + (i64::MAX / 2 + 1, 1) — the reduced
        // numerator of the sum exceeds i64::MAX.
        let half_max = i64::MAX / 2 + 1;
        let a = Fraction::new(half_max, 1).unwrap();
        let b = Fraction::new(half_max, 1).unwrap();
        assert_eq!(a.checked_add(b), None);
    }

    #[test]
    fn display_renders_reduced_form() {
        assert_eq!(alloc::format!("{}", Fraction::new(2, 4).unwrap()), "1/2");
        assert_eq!(alloc::format!("{}", Fraction::ZERO), "0/1");
        assert_eq!(
            alloc::format!("{}", Fraction::new(7, 360).unwrap()),
            "7/360",
        );
        assert_eq!(
            alloc::format!("{}", Fraction::new(-30, 360).unwrap()),
            "-1/12",
        );
    }

    #[test]
    fn into_tuple_round_trips() {
        let f = Fraction::new(7, 360).unwrap();
        let parts: (i64, u64) = f.into();
        assert_eq!(parts, (7, 360));
        let neg = Fraction::new(-7, 360).unwrap();
        let neg_parts: (i64, u64) = neg.into();
        assert_eq!(neg_parts, (-7, 360));
    }

    #[test]
    fn ord_consistent_with_cmp_cross() {
        let a = Fraction::new(1, 3).unwrap();
        let b = Fraction::new(1, 2).unwrap();
        let c = Fraction::new(-1, 2).unwrap();
        assert!(a < b);
        assert!(b > a);
        assert!(c < a);
        assert_eq!(a.cmp(&a), Ordering::Equal);
    }

    #[test]
    fn checked_neg_round_trip() {
        let pos = Fraction::new(7, 360).unwrap();
        let neg = pos.checked_neg().unwrap();
        assert_eq!(neg.parts(), (-7, 360));
        assert_eq!(neg.checked_neg().unwrap(), pos);
        // ZERO negates to ZERO.
        assert_eq!(Fraction::ZERO.checked_neg(), Some(Fraction::ZERO));
    }

    #[test]
    fn checked_neg_returns_none_at_i64_min() {
        let edge = Fraction::new(i64::MIN, 1).unwrap();
        assert_eq!(edge.checked_neg(), None);
    }

    #[test]
    fn handles_i64_min_numerator() {
        // i64::MIN.unsigned_abs() = 2^63 doesn't fit i64; the
        // construction must still produce a valid reduced form.
        let yf = Fraction::new(i64::MIN, 1).unwrap();
        assert_eq!(yf.parts(), (i64::MIN, 1));
        // With a non-trivial gcd:
        let yf = Fraction::new(i64::MIN, 2).unwrap();
        // 2^63 / 2 = 2^62 = i64::MAX/2 + 1; reduced (-2^62, 1).
        assert_eq!(yf.parts(), (i64::MIN / 2, 1));
    }

    // ---- property tests ------------------------------------------------

    proptest! {
        /// New always produces a reduced form: feeding the result
        /// back through `new` is a no-op.
        #[test]
        fn new_is_idempotent_on_reduced_inputs(
            num in -10_000i64..=10_000,
            den in 1u64..=10_000,
        ) {
            let once = Fraction::new(num, den).unwrap();
            let twice = Fraction::new(once.numerator(), once.denominator()).unwrap();
            prop_assert_eq!(once, twice);
        }

        /// Equality matches cross-multiplication: `a == b` iff
        /// `a.cmp_cross(b) == Equal`.
        #[test]
        fn equality_matches_cross_multiplication(
            n1 in -10_000i64..=10_000, d1 in 1u64..=10_000,
            n2 in -10_000i64..=10_000, d2 in 1u64..=10_000,
        ) {
            let a = Fraction::new(n1, d1).unwrap();
            let b = Fraction::new(n2, d2).unwrap();
            prop_assert_eq!(a == b, a.cmp_cross(b) == Ordering::Equal);
        }

        /// Ord total ordering matches cross-multiplication.
        #[test]
        fn ord_matches_cross_multiplication(
            n1 in -10_000i64..=10_000, d1 in 1u64..=10_000,
            n2 in -10_000i64..=10_000, d2 in 1u64..=10_000,
        ) {
            let a = Fraction::new(n1, d1).unwrap();
            let b = Fraction::new(n2, d2).unwrap();
            prop_assert_eq!(a.cmp(&b), a.cmp_cross(b));
        }

        /// Adding zero is the identity.
        #[test]
        fn add_zero_identity(num in -10_000i64..=10_000, den in 1u64..=10_000) {
            let f = Fraction::new(num, den).unwrap();
            prop_assert_eq!(f.checked_add(Fraction::ZERO), Some(f));
            prop_assert_eq!(Fraction::ZERO.checked_add(f), Some(f));
        }

        /// A fraction plus its negation is zero.
        #[test]
        fn add_negation_cancels(num in -10_000i64..=10_000, den in 1u64..=10_000) {
            let f = Fraction::new(num, den).unwrap();
            let neg = Fraction::new(-num, den).unwrap();
            prop_assert_eq!(f.checked_add(neg), Some(Fraction::ZERO));
        }

        /// Addition is commutative whenever it is defined.
        #[test]
        fn add_is_commutative(
            n1 in -10_000i64..=10_000, d1 in 1u64..=10_000,
            n2 in -10_000i64..=10_000, d2 in 1u64..=10_000,
        ) {
            let a = Fraction::new(n1, d1).unwrap();
            let b = Fraction::new(n2, d2).unwrap();
            prop_assert_eq!(a.checked_add(b), b.checked_add(a));
        }

        /// Addition is associative whenever every intermediate
        /// addition succeeds.
        #[test]
        fn add_is_associative(
            n1 in -200i64..=200, d1 in 1u64..=200,
            n2 in -200i64..=200, d2 in 1u64..=200,
            n3 in -200i64..=200, d3 in 1u64..=200,
        ) {
            let a = Fraction::new(n1, d1).unwrap();
            let b = Fraction::new(n2, d2).unwrap();
            let c = Fraction::new(n3, d3).unwrap();
            let lhs = a.checked_add(b).and_then(|r| r.checked_add(c));
            let rhs = b.checked_add(c).and_then(|r| a.checked_add(r));
            prop_assert_eq!(lhs, rhs);
        }
    }
}