opql/types/
pql_fraction.rs

1use super::*;
2
3#[derive(Clone, Copy, derive_more::Debug, PartialEq, Eq, Display)]
4#[display("{} / {}", self.num, self.den)]
5#[debug("{self}")]
6pub struct PQLFraction {
7    num: FractionInner,
8    den: FractionInner,
9}
10
11impl PQLFraction {
12    pub const fn new(num: FractionInner, den: FractionInner) -> Self {
13        Self { num, den }
14    }
15
16    pub const fn zero() -> Self {
17        Self::new(0, 1)
18    }
19
20    #[allow(clippy::cast_lossless)]
21    pub const fn to_double(self) -> PQLDouble {
22        (self.num as PQLDouble) / (self.den as PQLDouble)
23    }
24
25    /// # Panics
26    /// won't panic since `n_winners` ≤ 10
27    pub(crate) fn pot_share(n_winners: usize) -> Self {
28        let den = FractionInner::try_from(n_winners).unwrap();
29
30        Self::new(1, den)
31    }
32}
33
34#[cfg(test)]
35pub mod tests {
36    use super::*;
37    use crate::*;
38
39    #[test]
40    fn test_zero() {
41        let f = PQLFraction::zero();
42        assert_eq!(f.num, 0);
43        assert_eq!(f.den, 1);
44    }
45
46    #[test]
47    fn test_potshare() {
48        let f = PQLFraction::pot_share(10);
49        assert_eq!(f.num, 1);
50        assert_eq!(f.den, 10);
51    }
52}