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
use num::Float;

#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct FloatingPointScalars(u64, i16, i8);

/// Error type that indicates a `NaN` was used to attempt to create a [`FloatingPointScalars`].
#[derive(Debug)]
pub struct NanError;

/// A wrapper struct around floats to avoid conflict with blanket impl of TryFrom. 
pub struct FloatWrap<F: Float>(F);

impl FloatingPointScalars {
    /// Creates a new [`FloatingPointScalars`] from a [`Float`].
    #[inline]
    pub fn new<F: Float>(num: F) -> Result<Self, NanError> {
        Self::try_from(FloatWrap(num))
    }
}

impl<F: Float> TryFrom<FloatWrap<F>> for FloatingPointScalars {
    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 &FloatingPointScalars {
    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 &FloatingPointScalars {
    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 FloatingPointScalars {
    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 FloatingPointScalars {
    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
    }
}