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
use crate::{FuzzyEq, FuzzyZero};
use crate::utils::f64_bound;
macro_rules! wrap {
($name:ident) => {
impl From<f64> for $name {
#[inline]
fn from(n: f64) -> Self {
$name::new(n)
}
}
impl PartialEq for $name {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.0.fuzzy_eq(&other.0)
}
}
};
}
#[derive(Clone, Copy, Debug)]
pub struct NormalizedValue(f64);
impl NormalizedValue {
#[inline]
pub fn new(n: f64) -> Self {
debug_assert!(n.is_finite());
debug_assert!((0.0..=1.0).contains(&n));
NormalizedValue(f64_bound(0.0, n, 1.0))
}
#[inline]
pub fn value(&self) -> f64 {
self.0
}
#[inline]
pub fn to_u8(&self) -> u8 {
(self.0 * 255.0).ceil() as u8
}
}
impl std::ops::Mul<NormalizedValue> for NormalizedValue {
type Output = Self;
#[inline]
fn mul(self, rhs: NormalizedValue) -> Self::Output {
NormalizedValue::new(self.0 * rhs.0)
}
}
impl Default for NormalizedValue {
#[inline]
fn default() -> Self {
NormalizedValue::new(1.0)
}
}
wrap!(NormalizedValue);
pub type Opacity = NormalizedValue;
#[derive(Clone, Copy, Debug)]
pub struct PositiveNumber(f64);
impl PositiveNumber {
#[inline]
pub fn new(n: f64) -> Self {
debug_assert!(n.is_finite());
debug_assert!(!n.is_sign_negative());
let n = if n.is_sign_negative() { 0.0 } else { n };
PositiveNumber(n)
}
#[inline]
pub fn value(&self) -> f64 {
self.0
}
#[inline]
pub fn is_zero(&self) -> bool {
self.0.is_fuzzy_zero()
}
}
wrap!(PositiveNumber);
impl std::fmt::Display for PositiveNumber {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
#[derive(Clone, Copy, Debug)]
pub struct NonZeroF64(f64);
impl NonZeroF64 {
#[inline]
pub fn new(n: f64) -> Option<Self> {
if n.is_fuzzy_zero() {
None
} else {
Some(NonZeroF64(n))
}
}
#[inline]
pub fn value(&self) -> f64 {
self.0
}
}