Skip to content

Commit db6cdfe

Browse files
authored
Merge pull request #2414 from krakow10/gcd
Calculate GCD in Ratio::new
2 parents 809050c + 80cfa9f commit db6cdfe

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

src/animation.rs

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,19 @@ impl Clone for Frame {
6464
}
6565

6666
/// The delay of a frame relative to the previous one.
67+
///
68+
/// The ratio is reduced on construction which means equality comparisons is reliable even when
69+
/// mixing different bases. Note however that there is an upper limit to the delays that can be
70+
/// represented exactly when using [`Self::from_saturating_duration`] which depends on the
71+
/// granularity of the interval.
72+
///
73+
/// ```
74+
/// use image::Delay;
75+
/// let delay_10ms = Delay::from_numer_denom_ms(10, 1);
76+
/// let delay_10000us = Delay::from_numer_denom_ms(10_000, 1_000);
77+
///
78+
/// assert_eq!(delay_10ms, delay_10000us);
79+
/// ```
6780
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd)]
6881
pub struct Delay {
6982
ratio: Ratio,
@@ -304,6 +317,14 @@ impl From<Delay> for Duration {
304317
}
305318
}
306319

320+
#[inline]
321+
const fn gcd(mut a: u32, mut b: u32) -> u32 {
322+
while b != 0 {
323+
(a, b) = (b, a.rem_euclid(b));
324+
}
325+
a
326+
}
327+
307328
#[derive(Copy, Clone, Debug)]
308329
pub(crate) struct Ratio {
309330
numer: u32,
@@ -314,9 +335,10 @@ impl Ratio {
314335
#[inline]
315336
pub(crate) fn new(numerator: u32, denominator: u32) -> Self {
316337
assert_ne!(denominator, 0);
338+
let divisor = gcd(numerator, denominator);
317339
Self {
318-
numer: numerator,
319-
denom: denominator,
340+
numer: numerator / divisor,
341+
denom: denominator / divisor,
320342
}
321343
}
322344

0 commit comments

Comments
 (0)