grafix_toolbox/kit/policies/math/
cast.rs1pub use half::f16;
2pub mod matrix;
3
4pub trait Cast<T> {
5 fn to(val: T) -> Self;
6}
7
8macro_rules! to_int {
9 ($t: ty, $($f: ty),+) => {
10 $(impl Cast<$f> for $t {
11 #[inline(always)]
12 fn to(v: $f) -> Self {
13 #[cfg(debug_assertions)]
14 {
15 <$t>::try_from(v).unwrap_or_else(|_| ERROR!("Error casting {v} to {}", stringify!($t)))
16 }
17 #[cfg(not(debug_assertions))]
18 {
19 v as $t
20 }
21 }
22 })+
23 }
24}
25macro_rules! to_float {
26 ($t: ty, $($f: ty),+) => {
27 $(impl Cast<$f> for $t {
28 #[inline(always)]
29 fn to(v: $f) -> Self {
30 ASSERT!(
31 v.trunc() >= Self::MIN as $f && v.trunc() <= Self::MAX as $f,
32 "Error casting {v} to {}", super::super::pre::type_name::<Self>()
33 );
34 unsafe { v.to_int_unchecked() }
35 }
36 })+
37 }
38}
39macro_rules! impl_self {
40 ($t: ty, $($f: ty),+) => {
41 $(impl Cast<$f> for $t {
42 #[inline(always)]
43 fn to(v: $f) -> Self {
44 v as Self
45 }
46 })+
47 }
48}
49macro_rules! impl_to_half {
50 ($($t: ty),+) => {
51 $(impl Cast<$t> for f16 {
52 #[inline(always)]
53 fn to(v: $t) -> f16 {
54 f16::from_f32(v as f32)
55 }
56 })+
57 }
58}
59macro_rules! impl_from_half {
60 ($($t: ty),+) => {
61 $(impl Cast<f16> for $t {
62 #[inline(always)]
63 fn to(v: f16) -> Self {
64 Self::to(v.to_f32())
65 }
66 })+
67 }
68}
69
70macro_rules! impl_cast {
71 ($($t: ty),+) => {
72 $(
73 to_int!($t, bool, u8, i8, u16, i16, u32, i32, u64, i64, u128, i128, usize, isize);
74 to_float!($t, f32, f64);
75 impl_from_half!($t);
76 impl_to_half!($t);
77 impl_self!(f32, $t);
78 impl_self!(f64, $t);
79 )+
80 }
81}
82impl_cast!(u8, i8, u16, i16, u32, i32, u64, i64, u128, i128, usize, isize);
83impl_self!(f32, f32, f64);
84impl_self!(f64, f32, f64);
85impl_self!(f16, f16);
86impl_from_half!(f32);
87impl_to_half!(f32);
88
89impl Cast<f16> for f64 {
90 #[inline(always)]
91 fn to(v: f16) -> Self {
92 v.to_f64()
93 }
94}
95impl Cast<f64> for f16 {
96 #[inline(always)]
97 fn to(v: f64) -> Self {
98 Self::from_f64(v)
99 }
100}
101
102impl Cast<bool> for f16 {
103 #[inline(always)]
104 fn to(v: bool) -> Self {
105 Self::from_f32(v as u32 as f32)
106 }
107}
108impl Cast<bool> for f32 {
109 #[inline(always)]
110 fn to(v: bool) -> Self {
111 v as u32 as Self
112 }
113}
114impl Cast<bool> for f64 {
115 #[inline(always)]
116 fn to(v: bool) -> Self {
117 v as u32 as Self
118 }
119}
120
121macro_rules! from_ref {
122 ($t: ty, $($f: ty),+) => {
123 $(impl Cast<&$f> for $t {
124 #[inline(always)]
125 fn to(v: &$f) -> Self {
126 Self::to(*v)
127 }
128 }
129 impl Cast<&mut $f> for $t {
130 #[inline(always)]
131 fn to(v: &mut $f) -> Self {
132 Self::to(*v)
133 }
134 })+
135 }
136}
137macro_rules! impl_cast_ref {
138 ($($t: ty),+) => {
139 $(from_ref!($t, bool, u8, i8, u16, i16, u32, i32, u64, i64, u128, i128, f16, f32, f64, usize, isize);)+
140 }
141}
142impl_cast_ref!(u8, i8, u16, i16, u32, i32, u64, i64, u128, i128, f16, f32, f64, usize, isize);
143
144mod nalgebra;
145mod tuples;