clack_common/utils/
fixed_point.rs1use std::ops::Add;
2
3pub type BeatTime = FixedPoint;
5pub type SecondsTime = FixedPoint;
7
8#[repr(C)]
10#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
11pub struct FixedPoint(i64);
12
13impl FixedPoint {
14 pub const FACTOR: i64 = clap_sys::fixedpoint::CLAP_BEATTIME_FACTOR;
17
18 #[allow(clippy::cast_precision_loss)] const FACTOR_F64: f64 = Self::FACTOR as f64;
20
21 #[inline]
23 pub const fn from_bits(bits: i64) -> Self {
24 Self(bits)
25 }
26
27 #[inline]
29 pub const fn to_bits(&self) -> i64 {
30 self.0
31 }
32
33 #[inline]
35 pub const fn from_int(val: i64) -> Self {
36 Self(Self::FACTOR * val)
37 }
38
39 #[inline]
41 pub const fn to_int(&self) -> i64 {
42 self.0 / Self::FACTOR
43 }
44
45 #[inline]
50 #[allow(clippy::cast_precision_loss)]
51 pub const fn to_float(&self) -> f64 {
52 self.0 as f64 / Self::FACTOR_F64
53 }
54
55 #[inline]
57 pub fn from_float(val: f64) -> Self {
58 #[allow(clippy::cast_possible_truncation)] Self((Self::FACTOR_F64 * val).round() as i64)
60 }
61}
62
63impl From<f64> for FixedPoint {
64 #[inline]
65 fn from(val: f64) -> Self {
66 Self::from_float(val)
67 }
68}
69
70impl From<FixedPoint> for f64 {
71 #[inline]
72 fn from(val: FixedPoint) -> Self {
73 val.to_float()
74 }
75}
76
77impl Add for FixedPoint {
78 type Output = Self;
79
80 #[inline]
81 fn add(self, rhs: Self) -> Self::Output {
82 Self::from_bits(self.0 + rhs.0)
83 }
84}