1use super::{F48Dot16, Fixed};
4
5#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
7#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
8#[cfg_attr(feature = "bytemuck", derive(bytemuck::AnyBitPattern))]
9#[repr(transparent)]
10pub struct FWord(i16);
11
12#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
14#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
15#[cfg_attr(feature = "bytemuck", derive(bytemuck::AnyBitPattern))]
16#[repr(transparent)]
17pub struct UfWord(u16);
18
19impl FWord {
20 pub const fn new(raw: i16) -> Self {
21 Self(raw)
22 }
23
24 pub const fn to_i16(self) -> i16 {
25 self.0
26 }
27
28 pub const fn to_fixed(self) -> Fixed {
30 Fixed::from_i32(self.0 as i32)
31 }
32
33 #[inline(always)]
40 pub fn apply_delta(self, delta: F48Dot16) -> f32 {
41 self.0 as f32 + delta.to_f64() as f32
42 }
43
44 pub const fn to_be_bytes(self) -> [u8; 2] {
46 self.0.to_be_bytes()
47 }
48}
49
50impl UfWord {
51 pub const fn new(raw: u16) -> Self {
52 Self(raw)
53 }
54
55 pub const fn to_u16(self) -> u16 {
56 self.0
57 }
58
59 pub const fn to_fixed(self) -> Fixed {
61 Fixed::from_i32(self.0 as i32)
62 }
63
64 #[inline(always)]
71 pub fn apply_delta(self, delta: F48Dot16) -> f32 {
72 self.0 as f32 + delta.to_f64() as f32
73 }
74
75 pub const fn to_be_bytes(self) -> [u8; 2] {
77 self.0.to_be_bytes()
78 }
79}
80
81impl std::fmt::Display for FWord {
82 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
83 self.0.fmt(f)
84 }
85}
86
87impl std::fmt::Display for UfWord {
88 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
89 self.0.fmt(f)
90 }
91}
92
93impl From<u16> for UfWord {
94 fn from(src: u16) -> Self {
95 UfWord(src)
96 }
97}
98
99impl From<i16> for FWord {
100 fn from(src: i16) -> Self {
101 FWord(src)
102 }
103}
104
105impl From<FWord> for i16 {
106 fn from(src: FWord) -> Self {
107 src.0
108 }
109}
110
111impl From<UfWord> for u16 {
112 fn from(src: UfWord) -> Self {
113 src.0
114 }
115}
116
117crate::newtype_scalar!(FWord, [u8; 2]);
118crate::newtype_scalar!(UfWord, [u8; 2]);
119#[cfg(test)]
122mod tests {
123 use super::*;
124
125 #[test]
128 fn apply_delta() {
129 assert_eq!(FWord::new(100).apply_delta(F48Dot16::from_f64(2.5)), 102.5);
130 assert_eq!(
131 FWord::new(-100).apply_delta(F48Dot16::from_f64(-0.25)),
132 -100.25
133 );
134 assert_eq!(
135 UfWord::new(1000).apply_delta(F48Dot16::from_f64(-1.5)),
136 998.5
137 );
138 assert_eq!(UfWord::new(0).apply_delta(F48Dot16::ZERO), 0.0);
139 }
140}