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
use num::Float;
use std::fmt::Debug;
#[derive(Clone, Eq, Hash, PartialEq)]
pub struct FloatingPointComponents(u64, i16, i8);
#[derive(Debug)]
pub struct NanError;
pub struct FloatWrap<F: Float>(F);
impl FloatingPointComponents {
#[inline]
pub fn new<F: Float>(num: F) -> Result<Self, NanError> {
Self::try_from(FloatWrap(num))
}
}
impl FloatingPointComponents {
#[inline]
pub fn as_f32(&self) -> f32 {
let sign_f = self.2 as f32;
let mantissa_f = self.0 as f32;
let exponent_f = (2 as f32).powf(self.1 as f32);
sign_f * mantissa_f * exponent_f
}
#[inline]
pub fn as_f64(&self) -> f64 {
let sign_f = self.2 as f64;
let mantissa_f = self.0 as f64;
let exponent_f = (2 as f64).powf(self.1 as f64);
sign_f * mantissa_f * exponent_f
}
}
impl std::fmt::Debug for FloatingPointComponents {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Float")
.field("sign", &self.2)
.field("mantissa", &self.0)
.field("exponent", &(2 as f64).powf(self.1 as f64))
.finish()
.and(write!(f, " ({})", self.as_f64()))
}
}
impl<F: Float> TryFrom<FloatWrap<F>> for FloatingPointComponents {
type Error = NanError;
fn try_from(value: FloatWrap<F>) -> Result<Self, Self::Error> {
let value = value.0;
if value.is_nan() {
return Err(NanError);
}
let (mantissa, exponent, sign) = value.integer_decode();
Ok(Self(mantissa, exponent, sign))
}
}
impl Into<f64> for &FloatingPointComponents {
fn into(self) -> f64 {
let sign_f = self.2 as f64;
let mantissa_f = self.0 as f64;
let exponent_f = (2 as f64).powf(self.1 as f64);
sign_f * mantissa_f * exponent_f
}
}
impl Into<f32> for &FloatingPointComponents {
fn into(self) -> f32 {
let sign_f = self.2 as f32;
let mantissa_f = self.0 as f32;
let exponent_f = (2 as f32).powf(self.1 as f32);
sign_f * mantissa_f * exponent_f
}
}
impl Into<f64> for FloatingPointComponents {
fn into(self) -> f64 {
let sign_f = self.2 as f64;
let mantissa_f = self.0 as f64;
let exponent_f = (2 as f64).powf(self.1 as f64);
sign_f * mantissa_f * exponent_f
}
}
impl Into<f32> for FloatingPointComponents {
fn into(self) -> f32 {
let sign_f = self.2 as f32;
let mantissa_f = self.0 as f32;
let exponent_f = (2 as f32).powf(self.1 as f32);
sign_f * mantissa_f * exponent_f
}
}