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
use crate::{f32, f64};
use crate::num::FpCategory;
use crate::num::dec2flt::rawfp::RawFloat;
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Decoded {
pub mant: u64,
pub minus: u64,
pub plus: u64,
pub exp: i16,
pub inclusive: bool,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum FullDecoded {
Nan,
Infinite,
Zero,
Finite(Decoded),
}
pub trait DecodableFloat: RawFloat + Copy {
fn min_pos_norm_value() -> Self;
}
impl DecodableFloat for f32 {
fn min_pos_norm_value() -> Self { f32::MIN_POSITIVE }
}
impl DecodableFloat for f64 {
fn min_pos_norm_value() -> Self { f64::MIN_POSITIVE }
}
pub fn decode<T: DecodableFloat>(v: T) -> ( bool, FullDecoded) {
let (mant, exp, sign) = v.integer_decode();
let even = (mant & 1) == 0;
let decoded = match v.classify() {
FpCategory::Nan => FullDecoded::Nan,
FpCategory::Infinite => FullDecoded::Infinite,
FpCategory::Zero => FullDecoded::Zero,
FpCategory::Subnormal => {
FullDecoded::Finite(Decoded { mant, minus: 1, plus: 1,
exp, inclusive: even })
}
FpCategory::Normal => {
let minnorm = <T as DecodableFloat>::min_pos_norm_value().integer_decode();
if mant == minnorm.0 {
FullDecoded::Finite(Decoded { mant: mant << 2, minus: 1, plus: 2,
exp: exp - 2, inclusive: even })
} else {
FullDecoded::Finite(Decoded { mant: mant << 1, minus: 1, plus: 1,
exp: exp - 1, inclusive: even })
}
}
};
(sign < 0, decoded)
}