summaryrefslogtreecommitdiffstats
path: root/firmware/src/fixpt.rs
blob: 23990ecc82fbb4277c45bef05b90b54ceb79b6f6 (plain)
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
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Fixpt(i16);

macro_rules! fixpt {
    ($numerator:literal / $denominator:literal) => {
        Fixpt::from_fraction($numerator, $denominator)
    };
    ($numerator:literal / $denominator:ident) => {
        Fixpt::from_fraction($numerator, $denominator)
    };
    ($numerator:ident / $denominator:literal) => {
        Fixpt::from_fraction($numerator, $denominator)
    };
    ($numerator:ident / $denominator:ident) => {
        Fixpt::from_fraction($numerator, $denominator)
    };
}
pub(crate) use fixpt;

impl Fixpt {
    pub const SHIFT: usize = 8;

    pub const fn from_int(int: i16) -> Self {
        Self(int << Self::SHIFT)
    }

    #[allow(dead_code)]
    pub const fn from_parts(int: i16, frac: u16) -> Self {
        Self(int << Self::SHIFT | frac as i16)
    }

    pub const fn from_fraction(numerator: i16, denominator: i16) -> Self {
        let mut q: i32 = 1 << Self::SHIFT;
        q *= numerator as i32;
        q /= denominator as i32;
        Self(q as i16)
    }

    #[allow(dead_code)]
    pub const fn to_int(self) -> i16 {
        self.0 >> Self::SHIFT
    }

    pub const fn to_q(self) -> i16 {
        self.0
    }
}

impl From<u8> for Fixpt {
    fn from(value: u8) -> Self {
        Self::from_int(value.into())
    }
}

impl From<i8> for Fixpt {
    fn from(value: i8) -> Self {
        Self::from_int(value.into())
    }
}

impl From<i16> for Fixpt {
    fn from(value: i16) -> Self {
        Self::from_int(value)
    }
}

impl core::ops::Add for Fixpt {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        Self(self.0 + other.0)
    }
}

impl core::ops::Sub for Fixpt {
    type Output = Self;

    fn sub(self, other: Self) -> Self {
        Self(self.0 - other.0)
    }
}

impl core::ops::Mul for Fixpt {
    type Output = Self;

    #[inline(never)]
    fn mul(self, other: Self) -> Self {
        Self(((self.0 as i32 * other.0 as i32) >> Self::SHIFT) as i16)
    }
}

/*
impl core::ops::Div for Fixpt {
    type Output = Self;

    fn div(self, other: Self) -> Self {
        let mut tmp: i32 = self.0.into();
        tmp <<= Self::SHIFT;
        tmp /= other.0 as i32;
        Self(tmp as i16)
    }
}
*/

impl core::ops::Neg for Fixpt {
    type Output = Self;

    fn neg(self) -> Self {
        Self(-self.0)
    }
}

// vim: ts=4 sw=4 expandtab
bues.ch cgit interface