Skip to main content

smpte_timecode/timecode/
ratio.rs

1use core::cmp::Ordering;
2
3use super::TimecodeError;
4
5/// An exact non-negative rational number, always stored in lowest terms.
6///
7/// Seconds, frame rates, sample rates and pull factors are ratios so that NTSC rates such as
8/// 30000/1001 frames per second never pick up floating-point error.
9#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
10pub struct Ratio {
11    numer: u64,
12    denom: u64,
13}
14
15impl Ratio {
16    /// Creates `numer / denom` in lowest terms.
17    ///
18    /// # Errors
19    ///
20    /// [`TimecodeError::ZeroDenominator`] when `denom` is zero.
21    pub const fn new(numer: u64, denom: u64) -> Result<Self, TimecodeError> {
22        if denom == 0 {
23            return Err(TimecodeError::ZeroDenominator);
24        }
25        Ok(Self::reduced(numer, denom))
26    }
27
28    /// Creates the whole number `value`.
29    pub const fn from_integer(value: u64) -> Self {
30        Self {
31            numer: value,
32            denom: 1,
33        }
34    }
35
36    /// The numerator in lowest terms.
37    pub const fn numer(self) -> u64 {
38        self.numer
39    }
40
41    /// The denominator in lowest terms. Never zero.
42    pub const fn denom(self) -> u64 {
43        self.denom
44    }
45
46    /// Multiplies two ratios, or returns `None` when the reduced result does not fit in `u64`.
47    pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
48        // Cross-reducing first keeps every exact product that fits from overflowing on the way.
49        let left = gcd(self.numer, rhs.denom);
50        let right = gcd(rhs.numer, self.denom);
51        let numer = (self.numer / left) as u128 * (rhs.numer / right) as u128;
52        let denom = (self.denom / right) as u128 * (rhs.denom / left) as u128;
53        if numer > u64::MAX as u128 || denom > u64::MAX as u128 {
54            return None;
55        }
56        Some(Self {
57            numer: numer as u64,
58            denom: denom as u64,
59        })
60    }
61
62    /// The nearest `f64`, for display and plotting. Arithmetic in this crate never uses it.
63    pub fn to_f64(self) -> f64 {
64        self.numer as f64 / self.denom as f64
65    }
66
67    pub(crate) const fn reduced(numer: u64, denom: u64) -> Self {
68        let divisor = gcd(numer, denom);
69        Self {
70            numer: numer / divisor,
71            denom: denom / divisor,
72        }
73    }
74}
75
76impl Ord for Ratio {
77    fn cmp(&self, other: &Self) -> Ordering {
78        (u128::from(self.numer) * u128::from(other.denom))
79            .cmp(&(u128::from(other.numer) * u128::from(self.denom)))
80    }
81}
82
83impl PartialOrd for Ratio {
84    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
85        Some(self.cmp(other))
86    }
87}
88
89/// How a conversion picks a whole number when the exact result falls between two.
90#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
91pub enum Rounding {
92    /// The largest whole number not above the exact result.
93    Down,
94    /// The smallest whole number not below the exact result.
95    Up,
96    /// The closest whole number, with exact halves rounded up.
97    Nearest,
98}
99
100impl Rounding {
101    /// Divides `numer` by a non-zero `denom` with this rounding.
102    pub(crate) const fn divide(self, numer: u128, denom: u128) -> u128 {
103        let quotient = numer / denom;
104        let remainder = numer % denom;
105        let round_up = match self {
106            Self::Down => false,
107            Self::Up => remainder != 0,
108            // remainder >= denom - remainder, written so neither side can overflow.
109            Self::Nearest => remainder >= denom - remainder,
110        };
111        if round_up { quotient + 1 } else { quotient }
112    }
113}
114
115const fn gcd(mut a: u64, mut b: u64) -> u64 {
116    while b != 0 {
117        let rest = a % b;
118        a = b;
119        b = rest;
120    }
121    a
122}