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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
use core::cmp::Ordering;
use core::fmt::{Display, Formatter, Result};
use core::ops::{Add, Div, Mul, Sub};
pub type Frequency = OrderableF32;
pub type FrequencyValue = OrderableF32;
#[derive(Debug, Copy, Clone)]
pub struct OrderableF32(f32);
impl OrderableF32 {
#[inline(always)]
pub fn val(&self) -> f32 {
self.0
}
}
impl From<f32> for OrderableF32 {
#[inline(always)]
fn from(val: f32) -> Self {
debug_assert_ne!(f32::NAN, val, "NaN-values are not supported!");
Self(val)
}
}
impl Display for OrderableF32 {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
write!(f, "{}", self.0)
}
}
impl Ord for OrderableF32 {
#[inline(always)]
fn cmp(&self, other: &Self) -> Ordering {
self.partial_cmp(other).unwrap()
}
}
impl Eq for OrderableF32 {}
impl PartialEq for OrderableF32 {
#[inline(always)]
fn eq(&self, other: &Self) -> bool {
match self.cmp(other) {
Ordering::Equal => true,
_ => false,
}
}
}
impl PartialOrd for OrderableF32 {
#[inline(always)]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(if self.val() < other.val() {
Ordering::Less
} else if self.val() == other.val() {
Ordering::Equal
} else {
Ordering::Greater
})
}
}
impl Add for OrderableF32 {
type Output = OrderableF32;
#[inline(always)]
fn add(self, other: Self) -> Self::Output {
(self.val() + other.val()).into()
}
}
impl Sub for OrderableF32 {
type Output = OrderableF32;
#[inline(always)]
fn sub(self, other: Self) -> Self::Output {
(self.val() - other.val()).into()
}
}
impl Mul for OrderableF32 {
type Output = OrderableF32;
#[inline(always)]
fn mul(self, other: Self) -> Self::Output {
(self.val() * other.val()).into()
}
}
impl Div for OrderableF32 {
type Output = OrderableF32;
#[inline(always)]
fn div(self, other: Self) -> Self::Output {
let quotient = self.val() / other.val();
debug_assert_ne!(f32::NAN, quotient, "NaN is not allowed");
debug_assert_ne!(f32::INFINITY, quotient, "INFINITY is not allowed");
quotient.into()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_orderablef32() {
let f1: OrderableF32 = (2.0_f32).into();
let f2: OrderableF32 = (-7.0_f32).into();
let f3 = f1 + f2;
let f4 = f1 - f2;
assert_eq!(-5.0, f3.val(), "add must work");
assert_eq!(9.0, f4.val(), "add must work");
assert!(f2 < f1, "Compare must work");
assert!(f1 > f2, "Compare must work");
assert_eq!(f1, f1, "Equal must work");
}
}