#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Fixed(pub i32);
impl Fixed {
pub const SCALE: i32 = 1 << 16;
pub const ONE: Fixed = Fixed(Self::SCALE);
pub const ZERO: Fixed = Fixed(0);
pub const MAX: Fixed = Fixed(i32::MAX);
pub const MIN: Fixed = Fixed(i32::MIN);
pub const fn from_int(v: i32) -> Fixed {
if v > i32::MAX >> 16 {
Fixed(i32::MAX)
} else if v < i32::MIN >> 16 {
Fixed(i32::MIN)
} else {
Fixed(v << 16)
}
}
pub const fn to_int(self) -> i32 {
if self.0 >= 0 {
self.0 >> 16
} else {
-((self.0.unsigned_abs() >> 16) as i32)
}
}
pub const fn from_bits(bits: i32) -> Fixed {
Fixed(bits)
}
pub const fn to_bits(self) -> i32 {
self.0
}
pub const fn saturating_add(self, other: Fixed) -> Fixed {
Fixed(self.0.saturating_add(other.0))
}
pub const fn saturating_sub(self, other: Fixed) -> Fixed {
Fixed(self.0.saturating_sub(other.0))
}
pub const fn saturating_mul_int(self, k: i32) -> Fixed {
match self.0.checked_mul(k) {
Some(v) => Fixed(v),
None => {
if (self.0 < 0) ^ (k < 0) {
Fixed(i32::MIN)
} else {
Fixed(i32::MAX)
}
}
}
}
pub const fn checked_div_int(self, k: i32) -> Option<Fixed> {
match self.0.checked_div(k) {
Some(v) => Some(Fixed(v)),
None => None,
}
}
}