microfloat 0.1.3

8-bit and sub-byte floating point types
Documentation
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
use core::cmp::Ordering;
use core::marker::PhantomData;
use core::num::FpCategory;

use crate::bits::{
    abs_bits, classify_bits, decode_f32, encode_f32, infinity_bits, nan_bits, neg_zero_bits,
    negate_bits, next_down_bits, next_up_bits, one_bits, total_key,
};
use crate::format::{Format, NanEncoding, SignMode};

#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct MicroFloat<F: Format> {
    pub bits: u8,
    _format: PhantomData<F>,
}

impl<F: Format> MicroFloat<F> {
    pub const ZERO: Self = Self::from_bits(0);
    pub const NEG_ZERO: Self = Self::from_bits(neg_zero_bits::<F>());
    pub const ONE: Self = Self::from_bits(one_bits::<F>());
    pub const NEG_ONE: Self = Self::from_bits(negate_bits::<F>(one_bits::<F>()));
    pub const INFINITY: Self = Self::from_bits(infinity_bits::<F>(false));
    pub const NAN: Self = Self::from_bits(nan_bits::<F>(false));

    pub const fn from_bits(bits: u8) -> Self {
        Self {
            bits,
            _format: PhantomData,
        }
    }

    pub const fn to_bits(self) -> u8 {
        self.bits
    }

    pub const fn from_le_bytes(bytes: [u8; 1]) -> Self {
        Self::from_bits(u8::from_le_bytes(bytes))
    }

    pub const fn from_be_bytes(bytes: [u8; 1]) -> Self {
        Self::from_bits(u8::from_be_bytes(bytes))
    }

    pub const fn from_ne_bytes(bytes: [u8; 1]) -> Self {
        Self::from_bits(u8::from_ne_bytes(bytes))
    }

    pub const fn to_le_bytes(self) -> [u8; 1] {
        self.bits.to_le_bytes()
    }

    pub const fn to_be_bytes(self) -> [u8; 1] {
        self.bits.to_be_bytes()
    }

    pub const fn to_ne_bytes(self) -> [u8; 1] {
        self.bits.to_ne_bytes()
    }

    pub fn from_f32(value: f32) -> Self {
        Self::from_bits(encode_f32::<F>(value))
    }

    pub fn from_f64(value: f64) -> Self {
        #[expect(
            clippy::cast_possible_truncation,
            reason = "conversion intentionally follows f64-to-f32 rounding before encoding"
        )]
        Self::from_bits(encode_f32::<F>(value as f32))
    }

    pub fn to_f32(self) -> f32 {
        decode_f32::<F>(self.bits)
    }

    pub fn to_f64(self) -> f64 {
        f64::from(self.to_f32())
    }

    pub const fn is_nan(self) -> bool {
        classify_bits::<F>(self.bits).is_nan
    }

    pub const fn is_infinite(self) -> bool {
        classify_bits::<F>(self.bits).is_infinite
    }

    pub const fn is_finite(self) -> bool {
        !self.is_nan() && !self.is_infinite()
    }

    pub const fn is_normal(self) -> bool {
        let class = classify_bits::<F>(self.bits);
        !class.is_nan && !class.is_infinite && !class.is_zero && !class.is_subnormal
    }

    pub const fn classify(self) -> FpCategory {
        let class = classify_bits::<F>(self.bits);
        if class.is_nan {
            FpCategory::Nan
        } else if class.is_infinite {
            FpCategory::Infinite
        } else if class.is_zero {
            FpCategory::Zero
        } else if class.is_subnormal {
            FpCategory::Subnormal
        } else {
            FpCategory::Normal
        }
    }

    pub const fn is_sign_positive(self) -> bool {
        !self.is_sign_negative()
    }

    pub const fn is_sign_negative(self) -> bool {
        match F::SIGN {
            SignMode::Unsigned => false,
            SignMode::Signed => {
                if F::STORAGE_BITS < 8 {
                    self.bits >= F::SIGN_BIT
                } else {
                    (self.bits & F::SIGN_BIT) != 0
                }
            }
        }
    }

    pub const fn copysign(self, sign: Self) -> Self {
        if matches!(F::NAN, NanEncoding::Single(_)) && self.is_nan() {
            return self;
        }
        if matches!(F::SIGN, SignMode::Unsigned) {
            self
        } else if sign.is_sign_negative() {
            Self::from_bits(abs_bits::<F>(self.bits) | F::SIGN_BIT)
        } else {
            Self::from_bits(abs_bits::<F>(self.bits))
        }
    }

    pub const fn signum(self) -> Self {
        if self.is_nan() || matches!(self.classify(), FpCategory::Zero) {
            self
        } else if self.is_sign_negative() {
            Self::NEG_ONE
        } else {
            Self::ONE
        }
    }

    pub const fn abs(self) -> Self {
        if matches!(F::NAN, NanEncoding::Single(_)) && self.is_nan() {
            return self;
        }
        Self::from_bits(abs_bits::<F>(self.bits))
    }

    pub const fn next_up(self) -> Self {
        Self::from_bits(next_up_bits::<F>(self.bits))
    }

    pub const fn next_down(self) -> Self {
        Self::from_bits(next_down_bits::<F>(self.bits))
    }

    pub fn floor(self) -> Self {
        unary_result(self, libm::floorf(self.to_f32()))
    }

    pub fn ceil(self) -> Self {
        unary_result(self, libm::ceilf(self.to_f32()))
    }

    pub fn trunc(self) -> Self {
        unary_result(self, libm::truncf(self.to_f32()))
    }

    pub fn round_ties_even(self) -> Self {
        unary_result(self, libm::rintf(self.to_f32()))
    }

    pub fn recip(self) -> Self {
        unary_result(self, 1.0 / self.to_f32())
    }

    pub fn powf(self, n: Self) -> Self {
        if self.is_nan() {
            if n.classify() == FpCategory::Zero {
                return Self::ONE;
            }
            if self.is_sign_negative() && is_odd_integer(n.to_f32()) {
                return Self::NAN;
            }
            return self;
        }
        if !F::HAS_NAN
            && self.is_sign_negative()
            && self.classify() != FpCategory::Zero
            && !is_integer(n.to_f32())
        {
            return Self::ZERO;
        }
        Self::from_f32(libm::powf(self.to_f32(), n.to_f32()))
    }

    pub fn sqrt(self) -> Self {
        if !F::HAS_NAN && self.is_sign_negative() && self.classify() != FpCategory::Zero {
            return Self::ZERO;
        }
        unary_result(self, libm::sqrtf(self.to_f32()))
    }

    pub fn exp(self) -> Self {
        unary_result(self, libm::expf(self.to_f32()))
    }

    pub fn exp2(self) -> Self {
        unary_result(self, libm::exp2f(self.to_f32()))
    }

    pub fn exp_m1(self) -> Self {
        unary_result(self, libm::expm1f(self.to_f32()))
    }

    pub fn ln(self) -> Self {
        if !F::HAS_NAN && self.is_sign_negative() && self.classify() != FpCategory::Zero {
            return Self::ZERO;
        }
        unary_result(self, libm::logf(self.to_f32()))
    }

    pub fn ln_1p(self) -> Self {
        if !F::HAS_NAN && self.to_f32() < -1.0 {
            return Self::ZERO;
        }
        unary_result(self, libm::log1pf(self.to_f32()))
    }

    pub fn log2(self) -> Self {
        if !F::HAS_NAN && self.is_sign_negative() && self.classify() != FpCategory::Zero {
            return Self::ZERO;
        }
        unary_result(self, libm::log2f(self.to_f32()))
    }

    pub fn log10(self) -> Self {
        if !self.is_nan()
            && matches!(F::NAN, NanEncoding::Ieee | NanEncoding::Outer)
            && self.is_sign_negative()
            && self.classify() != FpCategory::Zero
        {
            return Self::NAN;
        }
        unary_result(self, libm::log10f(self.to_f32()))
    }

    pub fn cbrt(self) -> Self {
        unary_result(self, libm::cbrtf(self.to_f32()))
    }

    pub fn hypot(self, other: Self) -> Self {
        if self.is_infinite() || other.is_infinite() {
            return Self::INFINITY;
        }
        if self.is_nan() {
            return self;
        }
        if other.is_nan() {
            return other;
        }
        Self::from_f32(libm::hypotf(self.to_f32(), other.to_f32()))
    }

    pub fn sin(self) -> Self {
        unary_result(self, libm::sinf(self.to_f32()))
    }

    pub fn cos(self) -> Self {
        unary_result(self, libm::cosf(self.to_f32()))
    }

    pub fn tan(self) -> Self {
        unary_result(self, libm::tanf(self.to_f32()))
    }

    pub fn asin(self) -> Self {
        if matches!(F::NAN, NanEncoding::Ieee | NanEncoding::Outer) && self.to_f32().abs() > 1.0 {
            return Self::NAN;
        }
        unary_result(self, libm::asinf(self.to_f32()))
    }

    pub fn acos(self) -> Self {
        if matches!(F::NAN, NanEncoding::Ieee | NanEncoding::Outer) && self.to_f32().abs() > 1.0 {
            return Self::NAN;
        }
        unary_result(self, libm::acosf(self.to_f32()))
    }

    pub fn atan(self) -> Self {
        unary_result(self, libm::atanf(self.to_f32()))
    }

    pub fn atan2(self, other: Self) -> Self {
        if self.is_nan() {
            return self;
        }
        if other.is_nan() {
            return other;
        }
        Self::from_f32(libm::atan2f(self.to_f32(), other.to_f32()))
    }

    pub fn sinh(self) -> Self {
        unary_result(self, libm::sinhf(self.to_f32()))
    }

    pub fn cosh(self) -> Self {
        unary_result(self, libm::coshf(self.to_f32()))
    }

    pub fn tanh(self) -> Self {
        unary_result(self, libm::tanhf(self.to_f32()))
    }

    pub const fn min(self, other: Self) -> Self {
        if self.is_nan() && other.is_nan() {
            self
        } else if self.is_nan() {
            other
        } else if other.is_nan() || const_is_lt(self, other) {
            self
        } else {
            other
        }
    }

    pub const fn max(self, other: Self) -> Self {
        if self.is_nan() && other.is_nan() {
            self
        } else if self.is_nan() {
            other
        } else if other.is_nan() || const_is_gt(self, other) {
            self
        } else {
            other
        }
    }

    /// Restricts `self` to the interval `[min, max]`.
    ///
    /// # Panics
    ///
    /// Panics if `min > max`, `min` is NaN, or `max` is `NaN`.
    pub const fn clamp(self, min: Self, max: Self) -> Self {
        assert!(
            !min.is_nan() && !max.is_nan(),
            "`min` and `max` must not be `NaN`"
        );
        assert!(
            !const_is_gt(min, max),
            "`min` must be less than or equal to `max`"
        );
        if const_is_lt(self, min) {
            min
        } else if const_is_gt(self, max) {
            max
        } else {
            self
        }
    }

    #[expect(
        clippy::trivially_copy_pass_by_ref,
        reason = "signature matches f32::total_cmp for API compatibility"
    )]
    pub const fn total_cmp(&self, other: &Self) -> Ordering {
        let lhs = total_key::<F>(self.bits);
        let rhs = total_key::<F>(other.bits);
        if lhs < rhs {
            Ordering::Less
        } else if lhs > rhs {
            Ordering::Greater
        } else {
            Ordering::Equal
        }
    }
}

fn unary_result<F: Format>(input: MicroFloat<F>, result: f32) -> MicroFloat<F> {
    if input.is_nan() {
        input
    } else {
        MicroFloat::from_f32(result)
    }
}

const fn const_is_lt<F: Format>(lhs: MicroFloat<F>, rhs: MicroFloat<F>) -> bool {
    if matches!(lhs.classify(), FpCategory::Zero) && matches!(rhs.classify(), FpCategory::Zero) {
        false
    } else {
        decode_f32::<F>(lhs.bits) < decode_f32::<F>(rhs.bits)
    }
}

const fn const_is_gt<F: Format>(lhs: MicroFloat<F>, rhs: MicroFloat<F>) -> bool {
    if matches!(lhs.classify(), FpCategory::Zero) && matches!(rhs.classify(), FpCategory::Zero) {
        false
    } else {
        decode_f32::<F>(lhs.bits) > decode_f32::<F>(rhs.bits)
    }
}

fn is_odd_integer(value: f32) -> bool {
    if !value.is_finite() || !is_integer(value) {
        return false;
    }
    let half = libm::truncf(value * 0.5);
    value - half * 2.0 != 0.0
}

fn is_integer(value: f32) -> bool {
    libm::truncf(value).to_bits() == value.to_bits()
}