Coverage Report

Created: 2025-10-28 08:03

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/half-2.7.1/src/bfloat.rs
Line
Count
Source
1
#[cfg(all(feature = "serde", feature = "alloc"))]
2
#[allow(unused_imports)]
3
use alloc::string::ToString;
4
#[cfg(feature = "bytemuck")]
5
use bytemuck::{Pod, Zeroable};
6
use core::{
7
    cmp::Ordering,
8
    iter::{Product, Sum},
9
    num::FpCategory,
10
    ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Rem, RemAssign, Sub, SubAssign},
11
};
12
#[cfg(not(target_arch = "spirv"))]
13
use core::{
14
    fmt::{
15
        Binary, Debug, Display, Error, Formatter, LowerExp, LowerHex, Octal, UpperExp, UpperHex,
16
    },
17
    num::ParseFloatError,
18
    str::FromStr,
19
};
20
#[cfg(feature = "serde")]
21
use serde::{Deserialize, Serialize};
22
use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};
23
24
pub(crate) mod convert;
25
26
/// A 16-bit floating point type implementing the [`bfloat16`] format.
27
///
28
/// The [`bfloat16`] floating point format is a truncated 16-bit version of the IEEE 754 standard
29
/// `binary32`, a.k.a [`f32`]. [`struct@bf16`] has approximately the same dynamic range as [`f32`] by
30
/// having a lower precision than [`struct@f16`][crate::f16]. While [`struct@f16`][crate::f16] has a precision of
31
/// 11 bits, [`struct@bf16`] has a precision of only 8 bits.
32
///
33
/// [`bfloat16`]: https://en.wikipedia.org/wiki/Bfloat16_floating-point_format
34
#[allow(non_camel_case_types)]
35
#[derive(Clone, Copy, Default)]
36
#[repr(transparent)]
37
#[cfg_attr(feature = "serde", derive(Serialize))]
38
#[cfg_attr(
39
    feature = "rkyv",
40
    derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
41
)]
42
#[cfg_attr(feature = "rkyv", rkyv(resolver = Bf16Resolver))]
43
#[cfg_attr(feature = "bytemuck", derive(Zeroable, Pod))]
44
#[cfg_attr(kani, derive(kani::Arbitrary))]
45
#[derive(FromBytes, Immutable, IntoBytes, KnownLayout)]
46
pub struct bf16(u16);
47
48
impl bf16 {
49
    /// Constructs a [`struct@bf16`] value from the raw bits.
50
    #[inline]
51
    #[must_use]
52
0
    pub const fn from_bits(bits: u16) -> bf16 {
53
0
        bf16(bits)
54
0
    }
55
56
    /// Constructs a [`struct@bf16`] value from a 32-bit floating point value.
57
    ///
58
    /// This operation is lossy. If the 32-bit value is too large to fit, ±∞ will result. NaN values
59
    /// are preserved. Subnormal values that are too tiny to be represented will result in ±0. All
60
    /// other values are truncated and rounded to the nearest representable value.
61
    #[inline]
62
    #[must_use]
63
0
    pub fn from_f32(value: f32) -> bf16 {
64
0
        Self::from_f32_const(value)
65
0
    }
66
67
    /// Constructs a [`struct@bf16`] value from a 32-bit floating point value.
68
    ///
69
    /// This function is identical to [`from_f32`][Self::from_f32] except it never uses hardware
70
    /// intrinsics, which allows it to be `const`. [`from_f32`][Self::from_f32] should be preferred
71
    /// in any non-`const` context.
72
    ///
73
    /// This operation is lossy. If the 32-bit value is too large to fit, ±∞ will result. NaN values
74
    /// are preserved. Subnormal values that are too tiny to be represented will result in ±0. All
75
    /// other values are truncated and rounded to the nearest representable value.
76
    #[inline]
77
    #[must_use]
78
0
    pub const fn from_f32_const(value: f32) -> bf16 {
79
0
        bf16(convert::f32_to_bf16(value))
80
0
    }
81
82
    /// Constructs a [`struct@bf16`] value from a 64-bit floating point value.
83
    ///
84
    /// This operation is lossy. If the 64-bit value is to large to fit, ±∞ will result. NaN values
85
    /// are preserved. 64-bit subnormal values are too tiny to be represented and result in ±0.
86
    /// Exponents that underflow the minimum exponent will result in subnormals or ±0. All other
87
    /// values are truncated and rounded to the nearest representable value.
88
    #[inline]
89
    #[must_use]
90
0
    pub fn from_f64(value: f64) -> bf16 {
91
0
        Self::from_f64_const(value)
92
0
    }
93
94
    /// Constructs a [`struct@bf16`] value from a 64-bit floating point value.
95
    ///
96
    /// This function is identical to [`from_f64`][Self::from_f64] except it never uses hardware
97
    /// intrinsics, which allows it to be `const`. [`from_f64`][Self::from_f64] should be preferred
98
    /// in any non-`const` context.
99
    ///
100
    /// This operation is lossy. If the 64-bit value is to large to fit, ±∞ will result. NaN values
101
    /// are preserved. 64-bit subnormal values are too tiny to be represented and result in ±0.
102
    /// Exponents that underflow the minimum exponent will result in subnormals or ±0. All other
103
    /// values are truncated and rounded to the nearest representable value.
104
    #[inline]
105
    #[must_use]
106
0
    pub const fn from_f64_const(value: f64) -> bf16 {
107
0
        bf16(convert::f64_to_bf16(value))
108
0
    }
109
110
    /// Converts a [`struct@bf16`] into the underlying bit representation.
111
    #[inline]
112
    #[must_use]
113
0
    pub const fn to_bits(self) -> u16 {
114
0
        self.0
115
0
    }
116
117
    /// Returns the memory representation of the underlying bit representation as a byte array in
118
    /// little-endian byte order.
119
    ///
120
    /// # Examples
121
    ///
122
    /// ```rust
123
    /// # use half::prelude::*;
124
    /// let bytes = bf16::from_f32(12.5).to_le_bytes();
125
    /// assert_eq!(bytes, [0x48, 0x41]);
126
    /// ```
127
    #[inline]
128
    #[must_use]
129
0
    pub const fn to_le_bytes(self) -> [u8; 2] {
130
0
        self.0.to_le_bytes()
131
0
    }
132
133
    /// Returns the memory representation of the underlying bit representation as a byte array in
134
    /// big-endian (network) byte order.
135
    ///
136
    /// # Examples
137
    ///
138
    /// ```rust
139
    /// # use half::prelude::*;
140
    /// let bytes = bf16::from_f32(12.5).to_be_bytes();
141
    /// assert_eq!(bytes, [0x41, 0x48]);
142
    /// ```
143
    #[inline]
144
    #[must_use]
145
0
    pub const fn to_be_bytes(self) -> [u8; 2] {
146
0
        self.0.to_be_bytes()
147
0
    }
148
149
    /// Returns the memory representation of the underlying bit representation as a byte array in
150
    /// native byte order.
151
    ///
152
    /// As the target platform's native endianness is used, portable code should use
153
    /// [`to_be_bytes`][bf16::to_be_bytes] or [`to_le_bytes`][bf16::to_le_bytes], as appropriate,
154
    /// instead.
155
    ///
156
    /// # Examples
157
    ///
158
    /// ```rust
159
    /// # use half::prelude::*;
160
    /// let bytes = bf16::from_f32(12.5).to_ne_bytes();
161
    /// assert_eq!(bytes, if cfg!(target_endian = "big") {
162
    ///     [0x41, 0x48]
163
    /// } else {
164
    ///     [0x48, 0x41]
165
    /// });
166
    /// ```
167
    #[inline]
168
    #[must_use]
169
0
    pub const fn to_ne_bytes(self) -> [u8; 2] {
170
0
        self.0.to_ne_bytes()
171
0
    }
172
173
    /// Creates a floating point value from its representation as a byte array in little endian.
174
    ///
175
    /// # Examples
176
    ///
177
    /// ```rust
178
    /// # use half::prelude::*;
179
    /// let value = bf16::from_le_bytes([0x48, 0x41]);
180
    /// assert_eq!(value, bf16::from_f32(12.5));
181
    /// ```
182
    #[inline]
183
    #[must_use]
184
0
    pub const fn from_le_bytes(bytes: [u8; 2]) -> bf16 {
185
0
        bf16::from_bits(u16::from_le_bytes(bytes))
186
0
    }
187
188
    /// Creates a floating point value from its representation as a byte array in big endian.
189
    ///
190
    /// # Examples
191
    ///
192
    /// ```rust
193
    /// # use half::prelude::*;
194
    /// let value = bf16::from_be_bytes([0x41, 0x48]);
195
    /// assert_eq!(value, bf16::from_f32(12.5));
196
    /// ```
197
    #[inline]
198
    #[must_use]
199
0
    pub const fn from_be_bytes(bytes: [u8; 2]) -> bf16 {
200
0
        bf16::from_bits(u16::from_be_bytes(bytes))
201
0
    }
202
203
    /// Creates a floating point value from its representation as a byte array in native endian.
204
    ///
205
    /// As the target platform's native endianness is used, portable code likely wants to use
206
    /// [`from_be_bytes`][bf16::from_be_bytes] or [`from_le_bytes`][bf16::from_le_bytes], as
207
    /// appropriate instead.
208
    ///
209
    /// # Examples
210
    ///
211
    /// ```rust
212
    /// # use half::prelude::*;
213
    /// let value = bf16::from_ne_bytes(if cfg!(target_endian = "big") {
214
    ///     [0x41, 0x48]
215
    /// } else {
216
    ///     [0x48, 0x41]
217
    /// });
218
    /// assert_eq!(value, bf16::from_f32(12.5));
219
    /// ```
220
    #[inline]
221
    #[must_use]
222
0
    pub const fn from_ne_bytes(bytes: [u8; 2]) -> bf16 {
223
0
        bf16::from_bits(u16::from_ne_bytes(bytes))
224
0
    }
225
226
    /// Converts a [`struct@bf16`] value into an [`f32`] value.
227
    ///
228
    /// This conversion is lossless as all values can be represented exactly in [`f32`].
229
    #[inline]
230
    #[must_use]
231
0
    pub fn to_f32(self) -> f32 {
232
0
        self.to_f32_const()
233
0
    }
234
235
    /// Converts a [`struct@bf16`] value into an [`f32`] value.
236
    ///
237
    /// This function is identical to [`to_f32`][Self::to_f32] except it never uses hardware
238
    /// intrinsics, which allows it to be `const`. [`to_f32`][Self::to_f32] should be preferred
239
    /// in any non-`const` context.
240
    ///
241
    /// This conversion is lossless as all values can be represented exactly in [`f32`].
242
    #[inline]
243
    #[must_use]
244
0
    pub const fn to_f32_const(self) -> f32 {
245
0
        convert::bf16_to_f32(self.0)
246
0
    }
247
248
    /// Converts a [`struct@bf16`] value into an [`f64`] value.
249
    ///
250
    /// This conversion is lossless as all values can be represented exactly in [`f64`].
251
    #[inline]
252
    #[must_use]
253
0
    pub fn to_f64(self) -> f64 {
254
0
        self.to_f64_const()
255
0
    }
256
257
    /// Converts a [`struct@bf16`] value into an [`f64`] value.
258
    ///
259
    /// This function is identical to [`to_f64`][Self::to_f64] except it never uses hardware
260
    /// intrinsics, which allows it to be `const`. [`to_f64`][Self::to_f64] should be preferred
261
    /// in any non-`const` context.
262
    ///
263
    /// This conversion is lossless as all values can be represented exactly in [`f64`].
264
    #[inline]
265
    #[must_use]
266
0
    pub const fn to_f64_const(self) -> f64 {
267
0
        convert::bf16_to_f64(self.0)
268
0
    }
269
270
    /// Returns `true` if this value is NaN and `false` otherwise.
271
    ///
272
    /// # Examples
273
    ///
274
    /// ```rust
275
    /// # use half::prelude::*;
276
    ///
277
    /// let nan = bf16::NAN;
278
    /// let f = bf16::from_f32(7.0_f32);
279
    ///
280
    /// assert!(nan.is_nan());
281
    /// assert!(!f.is_nan());
282
    /// ```
283
    #[inline]
284
    #[must_use]
285
0
    pub const fn is_nan(self) -> bool {
286
0
        self.0 & 0x7FFFu16 > 0x7F80u16
287
0
    }
288
289
    /// Returns `true` if this value is ±∞ and `false` otherwise.
290
    ///
291
    /// # Examples
292
    ///
293
    /// ```rust
294
    /// # use half::prelude::*;
295
    ///
296
    /// let f = bf16::from_f32(7.0f32);
297
    /// let inf = bf16::INFINITY;
298
    /// let neg_inf = bf16::NEG_INFINITY;
299
    /// let nan = bf16::NAN;
300
    ///
301
    /// assert!(!f.is_infinite());
302
    /// assert!(!nan.is_infinite());
303
    ///
304
    /// assert!(inf.is_infinite());
305
    /// assert!(neg_inf.is_infinite());
306
    /// ```
307
    #[inline]
308
    #[must_use]
309
0
    pub const fn is_infinite(self) -> bool {
310
0
        self.0 & 0x7FFFu16 == 0x7F80u16
311
0
    }
312
313
    /// Returns `true` if this number is neither infinite nor NaN.
314
    ///
315
    /// # Examples
316
    ///
317
    /// ```rust
318
    /// # use half::prelude::*;
319
    ///
320
    /// let f = bf16::from_f32(7.0f32);
321
    /// let inf = bf16::INFINITY;
322
    /// let neg_inf = bf16::NEG_INFINITY;
323
    /// let nan = bf16::NAN;
324
    ///
325
    /// assert!(f.is_finite());
326
    ///
327
    /// assert!(!nan.is_finite());
328
    /// assert!(!inf.is_finite());
329
    /// assert!(!neg_inf.is_finite());
330
    /// ```
331
    #[inline]
332
    #[must_use]
333
0
    pub const fn is_finite(self) -> bool {
334
0
        self.0 & 0x7F80u16 != 0x7F80u16
335
0
    }
336
337
    /// Returns `true` if the number is neither zero, infinite, subnormal, or NaN.
338
    ///
339
    /// # Examples
340
    ///
341
    /// ```rust
342
    /// # use half::prelude::*;
343
    ///
344
    /// let min = bf16::MIN_POSITIVE;
345
    /// let max = bf16::MAX;
346
    /// let lower_than_min = bf16::from_f32(1.0e-39_f32);
347
    /// let zero = bf16::from_f32(0.0_f32);
348
    ///
349
    /// assert!(min.is_normal());
350
    /// assert!(max.is_normal());
351
    ///
352
    /// assert!(!zero.is_normal());
353
    /// assert!(!bf16::NAN.is_normal());
354
    /// assert!(!bf16::INFINITY.is_normal());
355
    /// // Values between 0 and `min` are subnormal.
356
    /// assert!(!lower_than_min.is_normal());
357
    /// ```
358
    #[inline]
359
    #[must_use]
360
0
    pub const fn is_normal(self) -> bool {
361
0
        let exp = self.0 & 0x7F80u16;
362
0
        exp != 0x7F80u16 && exp != 0
363
0
    }
364
365
    /// Returns the floating point category of the number.
366
    ///
367
    /// If only one property is going to be tested, it is generally faster to use the specific
368
    /// predicate instead.
369
    ///
370
    /// # Examples
371
    ///
372
    /// ```rust
373
    /// use std::num::FpCategory;
374
    /// # use half::prelude::*;
375
    ///
376
    /// let num = bf16::from_f32(12.4_f32);
377
    /// let inf = bf16::INFINITY;
378
    ///
379
    /// assert_eq!(num.classify(), FpCategory::Normal);
380
    /// assert_eq!(inf.classify(), FpCategory::Infinite);
381
    /// ```
382
    #[must_use]
383
0
    pub const fn classify(self) -> FpCategory {
384
0
        let exp = self.0 & 0x7F80u16;
385
0
        let man = self.0 & 0x007Fu16;
386
0
        match (exp, man) {
387
0
            (0, 0) => FpCategory::Zero,
388
0
            (0, _) => FpCategory::Subnormal,
389
0
            (0x7F80u16, 0) => FpCategory::Infinite,
390
0
            (0x7F80u16, _) => FpCategory::Nan,
391
0
            _ => FpCategory::Normal,
392
        }
393
0
    }
394
395
    /// Returns a number that represents the sign of `self`.
396
    ///
397
    /// * 1.0 if the number is positive, +0.0 or [`INFINITY`][bf16::INFINITY]
398
    /// * −1.0 if the number is negative, −0.0` or [`NEG_INFINITY`][bf16::NEG_INFINITY]
399
    /// * [`NAN`][bf16::NAN] if the number is NaN
400
    ///
401
    /// # Examples
402
    ///
403
    /// ```rust
404
    /// # use half::prelude::*;
405
    ///
406
    /// let f = bf16::from_f32(3.5_f32);
407
    ///
408
    /// assert_eq!(f.signum(), bf16::from_f32(1.0));
409
    /// assert_eq!(bf16::NEG_INFINITY.signum(), bf16::from_f32(-1.0));
410
    ///
411
    /// assert!(bf16::NAN.signum().is_nan());
412
    /// ```
413
    #[must_use]
414
0
    pub const fn signum(self) -> bf16 {
415
0
        if self.is_nan() {
416
0
            self
417
0
        } else if self.0 & 0x8000u16 != 0 {
418
0
            Self::NEG_ONE
419
        } else {
420
0
            Self::ONE
421
        }
422
0
    }
423
424
    /// Returns `true` if and only if `self` has a positive sign, including +0.0, NaNs with a
425
    /// positive sign bit and +∞.
426
    ///
427
    /// # Examples
428
    ///
429
    /// ```rust
430
    /// # use half::prelude::*;
431
    ///
432
    /// let nan = bf16::NAN;
433
    /// let f = bf16::from_f32(7.0_f32);
434
    /// let g = bf16::from_f32(-7.0_f32);
435
    ///
436
    /// assert!(f.is_sign_positive());
437
    /// assert!(!g.is_sign_positive());
438
    /// // NaN can be either positive or negative
439
    /// assert!(nan.is_sign_positive() != nan.is_sign_negative());
440
    /// ```
441
    #[inline]
442
    #[must_use]
443
0
    pub const fn is_sign_positive(self) -> bool {
444
0
        self.0 & 0x8000u16 == 0
445
0
    }
446
447
    /// Returns `true` if and only if `self` has a negative sign, including −0.0, NaNs with a
448
    /// negative sign bit and −∞.
449
    ///
450
    /// # Examples
451
    ///
452
    /// ```rust
453
    /// # use half::prelude::*;
454
    ///
455
    /// let nan = bf16::NAN;
456
    /// let f = bf16::from_f32(7.0f32);
457
    /// let g = bf16::from_f32(-7.0f32);
458
    ///
459
    /// assert!(!f.is_sign_negative());
460
    /// assert!(g.is_sign_negative());
461
    /// // NaN can be either positive or negative
462
    /// assert!(nan.is_sign_positive() != nan.is_sign_negative());
463
    /// ```
464
    #[inline]
465
    #[must_use]
466
0
    pub const fn is_sign_negative(self) -> bool {
467
0
        self.0 & 0x8000u16 != 0
468
0
    }
469
470
    /// Returns a number composed of the magnitude of `self` and the sign of `sign`.
471
    ///
472
    /// Equal to `self` if the sign of `self` and `sign` are the same, otherwise equal to `-self`.
473
    /// If `self` is NaN, then NaN with the sign of `sign` is returned.
474
    ///
475
    /// # Examples
476
    ///
477
    /// ```
478
    /// # use half::prelude::*;
479
    /// let f = bf16::from_f32(3.5);
480
    ///
481
    /// assert_eq!(f.copysign(bf16::from_f32(0.42)), bf16::from_f32(3.5));
482
    /// assert_eq!(f.copysign(bf16::from_f32(-0.42)), bf16::from_f32(-3.5));
483
    /// assert_eq!((-f).copysign(bf16::from_f32(0.42)), bf16::from_f32(3.5));
484
    /// assert_eq!((-f).copysign(bf16::from_f32(-0.42)), bf16::from_f32(-3.5));
485
    ///
486
    /// assert!(bf16::NAN.copysign(bf16::from_f32(1.0)).is_nan());
487
    /// ```
488
    #[inline]
489
    #[must_use]
490
0
    pub const fn copysign(self, sign: bf16) -> bf16 {
491
0
        bf16((sign.0 & 0x8000u16) | (self.0 & 0x7FFFu16))
492
0
    }
493
494
    /// Returns the maximum of the two numbers.
495
    ///
496
    /// If one of the arguments is NaN, then the other argument is returned.
497
    ///
498
    /// # Examples
499
    ///
500
    /// ```
501
    /// # use half::prelude::*;
502
    /// let x = bf16::from_f32(1.0);
503
    /// let y = bf16::from_f32(2.0);
504
    ///
505
    /// assert_eq!(x.max(y), y);
506
    /// ```
507
    #[inline]
508
    #[must_use]
509
0
    pub fn max(self, other: bf16) -> bf16 {
510
0
        if self.is_nan() || other > self {
511
0
            other
512
        } else {
513
0
            self
514
        }
515
0
    }
516
517
    /// Returns the minimum of the two numbers.
518
    ///
519
    /// If one of the arguments is NaN, then the other argument is returned.
520
    ///
521
    /// # Examples
522
    ///
523
    /// ```
524
    /// # use half::prelude::*;
525
    /// let x = bf16::from_f32(1.0);
526
    /// let y = bf16::from_f32(2.0);
527
    ///
528
    /// assert_eq!(x.min(y), x);
529
    /// ```
530
    #[inline]
531
    #[must_use]
532
0
    pub fn min(self, other: bf16) -> bf16 {
533
0
        if self.is_nan() || other < self {
534
0
            other
535
        } else {
536
0
            self
537
        }
538
0
    }
539
540
    /// Restrict a value to a certain interval unless it is NaN.
541
    ///
542
    /// Returns `max` if `self` is greater than `max`, and `min` if `self` is less than `min`.
543
    /// Otherwise this returns `self`.
544
    ///
545
    /// Note that this function returns NaN if the initial value was NaN as well.
546
    ///
547
    /// # Panics
548
    /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
549
    ///
550
    /// # Examples
551
    ///
552
    /// ```
553
    /// # use half::prelude::*;
554
    /// assert!(bf16::from_f32(-3.0).clamp(bf16::from_f32(-2.0), bf16::from_f32(1.0)) == bf16::from_f32(-2.0));
555
    /// assert!(bf16::from_f32(0.0).clamp(bf16::from_f32(-2.0), bf16::from_f32(1.0)) == bf16::from_f32(0.0));
556
    /// assert!(bf16::from_f32(2.0).clamp(bf16::from_f32(-2.0), bf16::from_f32(1.0)) == bf16::from_f32(1.0));
557
    /// assert!(bf16::NAN.clamp(bf16::from_f32(-2.0), bf16::from_f32(1.0)).is_nan());
558
    /// ```
559
    #[inline]
560
    #[must_use]
561
0
    pub fn clamp(self, min: bf16, max: bf16) -> bf16 {
562
0
        assert!(min <= max);
563
0
        let mut x = self;
564
0
        if x < min {
565
0
            x = min;
566
0
        }
567
0
        if x > max {
568
0
            x = max;
569
0
        }
570
0
        x
571
0
    }
572
573
    /// Returns the ordering between `self` and `other`.
574
    ///
575
    /// Unlike the standard partial comparison between floating point numbers,
576
    /// this comparison always produces an ordering in accordance to
577
    /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
578
    /// floating point standard. The values are ordered in the following sequence:
579
    ///
580
    /// - negative quiet NaN
581
    /// - negative signaling NaN
582
    /// - negative infinity
583
    /// - negative numbers
584
    /// - negative subnormal numbers
585
    /// - negative zero
586
    /// - positive zero
587
    /// - positive subnormal numbers
588
    /// - positive numbers
589
    /// - positive infinity
590
    /// - positive signaling NaN
591
    /// - positive quiet NaN.
592
    ///
593
    /// The ordering established by this function does not always agree with the
594
    /// [`PartialOrd`] and [`PartialEq`] implementations of `bf16`. For example,
595
    /// they consider negative and positive zero equal, while `total_cmp`
596
    /// doesn't.
597
    ///
598
    /// The interpretation of the signaling NaN bit follows the definition in
599
    /// the IEEE 754 standard, which may not match the interpretation by some of
600
    /// the older, non-conformant (e.g. MIPS) hardware implementations.
601
    ///
602
    /// # Examples
603
    /// ```
604
    /// # use half::bf16;
605
    /// let mut v: Vec<bf16> = vec![];
606
    /// v.push(bf16::ONE);
607
    /// v.push(bf16::INFINITY);
608
    /// v.push(bf16::NEG_INFINITY);
609
    /// v.push(bf16::NAN);
610
    /// v.push(bf16::MAX_SUBNORMAL);
611
    /// v.push(-bf16::MAX_SUBNORMAL);
612
    /// v.push(bf16::ZERO);
613
    /// v.push(bf16::NEG_ZERO);
614
    /// v.push(bf16::NEG_ONE);
615
    /// v.push(bf16::MIN_POSITIVE);
616
    ///
617
    /// v.sort_by(|a, b| a.total_cmp(&b));
618
    ///
619
    /// assert!(v
620
    ///     .into_iter()
621
    ///     .zip(
622
    ///         [
623
    ///             bf16::NEG_INFINITY,
624
    ///             bf16::NEG_ONE,
625
    ///             -bf16::MAX_SUBNORMAL,
626
    ///             bf16::NEG_ZERO,
627
    ///             bf16::ZERO,
628
    ///             bf16::MAX_SUBNORMAL,
629
    ///             bf16::MIN_POSITIVE,
630
    ///             bf16::ONE,
631
    ///             bf16::INFINITY,
632
    ///             bf16::NAN
633
    ///         ]
634
    ///         .iter()
635
    ///     )
636
    ///     .all(|(a, b)| a.to_bits() == b.to_bits()));
637
    /// ```
638
    // Implementation based on: https://doc.rust-lang.org/std/primitive.f32.html#method.total_cmp
639
    #[inline]
640
    #[must_use]
641
0
    pub fn total_cmp(&self, other: &Self) -> Ordering {
642
0
        let mut left = self.to_bits() as i16;
643
0
        let mut right = other.to_bits() as i16;
644
0
        left ^= (((left >> 15) as u16) >> 1) as i16;
645
0
        right ^= (((right >> 15) as u16) >> 1) as i16;
646
0
        left.cmp(&right)
647
0
    }
648
649
    /// Alternate serialize adapter for serializing as a float.
650
    ///
651
    /// By default, [`struct@bf16`] serializes as a newtype of [`u16`]. This is an alternate serialize
652
    /// implementation that serializes as an [`f32`] value. It is designed for use with
653
    /// `serialize_with` serde attributes. Deserialization from `f32` values is already supported by
654
    /// the default deserialize implementation.
655
    ///
656
    /// # Examples
657
    ///
658
    /// A demonstration on how to use this adapater:
659
    ///
660
    /// ```
661
    /// use serde::{Serialize, Deserialize};
662
    /// use half::bf16;
663
    ///
664
    /// #[derive(Serialize, Deserialize)]
665
    /// struct MyStruct {
666
    ///     #[serde(serialize_with = "bf16::serialize_as_f32")]
667
    ///     value: bf16 // Will be serialized as f32 instead of u16
668
    /// }
669
    /// ```
670
    #[cfg(feature = "serde")]
671
    pub fn serialize_as_f32<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
672
        serializer.serialize_f32(self.to_f32())
673
    }
674
675
    /// Alternate serialize adapter for serializing as a string.
676
    ///
677
    /// By default, [`struct@bf16`] serializes as a newtype of [`u16`]. This is an alternate serialize
678
    /// implementation that serializes as a string value. It is designed for use with
679
    /// `serialize_with` serde attributes. Deserialization from string values is already supported
680
    /// by the default deserialize implementation.
681
    ///
682
    /// # Examples
683
    ///
684
    /// A demonstration on how to use this adapater:
685
    ///
686
    /// ```
687
    /// use serde::{Serialize, Deserialize};
688
    /// use half::bf16;
689
    ///
690
    /// #[derive(Serialize, Deserialize)]
691
    /// struct MyStruct {
692
    ///     #[serde(serialize_with = "bf16::serialize_as_string")]
693
    ///     value: bf16 // Will be serialized as a string instead of u16
694
    /// }
695
    /// ```
696
    #[cfg(all(feature = "serde", feature = "alloc"))]
697
    pub fn serialize_as_string<S: serde::Serializer>(
698
        &self,
699
        serializer: S,
700
    ) -> Result<S::Ok, S::Error> {
701
        serializer.serialize_str(&self.to_string())
702
    }
703
704
    /// Approximate number of [`struct@bf16`] significant digits in base 10
705
    pub const DIGITS: u32 = 2;
706
    /// [`struct@bf16`]
707
    /// [machine epsilon](https://en.wikipedia.org/wiki/Machine_epsilon) value
708
    ///
709
    /// This is the difference between 1.0 and the next largest representable number.
710
    pub const EPSILON: bf16 = bf16(0x3C00u16);
711
    /// [`struct@bf16`] positive Infinity (+∞)
712
    pub const INFINITY: bf16 = bf16(0x7F80u16);
713
    /// Number of [`struct@bf16`] significant digits in base 2
714
    pub const MANTISSA_DIGITS: u32 = 8;
715
    /// Largest finite [`struct@bf16`] value
716
    pub const MAX: bf16 = bf16(0x7F7F);
717
    /// Maximum possible [`struct@bf16`] power of 10 exponent
718
    pub const MAX_10_EXP: i32 = 38;
719
    /// Maximum possible [`struct@bf16`] power of 2 exponent
720
    pub const MAX_EXP: i32 = 128;
721
    /// Smallest finite [`struct@bf16`] value
722
    pub const MIN: bf16 = bf16(0xFF7F);
723
    /// Minimum possible normal [`struct@bf16`] power of 10 exponent
724
    pub const MIN_10_EXP: i32 = -37;
725
    /// One greater than the minimum possible normal [`struct@bf16`] power of 2 exponent
726
    pub const MIN_EXP: i32 = -125;
727
    /// Smallest positive normal [`struct@bf16`] value
728
    pub const MIN_POSITIVE: bf16 = bf16(0x0080u16);
729
    /// [`struct@bf16`] Not a Number (NaN)
730
    pub const NAN: bf16 = bf16(0x7FC0u16);
731
    /// [`struct@bf16`] negative infinity (-∞).
732
    pub const NEG_INFINITY: bf16 = bf16(0xFF80u16);
733
    /// The radix or base of the internal representation of [`struct@bf16`]
734
    pub const RADIX: u32 = 2;
735
736
    /// Minimum positive subnormal [`struct@bf16`] value
737
    pub const MIN_POSITIVE_SUBNORMAL: bf16 = bf16(0x0001u16);
738
    /// Maximum subnormal [`struct@bf16`] value
739
    pub const MAX_SUBNORMAL: bf16 = bf16(0x007Fu16);
740
741
    /// [`struct@bf16`] 1
742
    pub const ONE: bf16 = bf16(0x3F80u16);
743
    /// [`struct@bf16`] 0
744
    pub const ZERO: bf16 = bf16(0x0000u16);
745
    /// [`struct@bf16`] -0
746
    pub const NEG_ZERO: bf16 = bf16(0x8000u16);
747
    /// [`struct@bf16`] -1
748
    pub const NEG_ONE: bf16 = bf16(0xBF80u16);
749
750
    /// [`struct@bf16`] Euler's number (ℯ)
751
    pub const E: bf16 = bf16(0x402Eu16);
752
    /// [`struct@bf16`] Archimedes' constant (π)
753
    pub const PI: bf16 = bf16(0x4049u16);
754
    /// [`struct@bf16`] 1/π
755
    pub const FRAC_1_PI: bf16 = bf16(0x3EA3u16);
756
    /// [`struct@bf16`] 1/√2
757
    pub const FRAC_1_SQRT_2: bf16 = bf16(0x3F35u16);
758
    /// [`struct@bf16`] 2/π
759
    pub const FRAC_2_PI: bf16 = bf16(0x3F23u16);
760
    /// [`struct@bf16`] 2/√π
761
    pub const FRAC_2_SQRT_PI: bf16 = bf16(0x3F90u16);
762
    /// [`struct@bf16`] π/2
763
    pub const FRAC_PI_2: bf16 = bf16(0x3FC9u16);
764
    /// [`struct@bf16`] π/3
765
    pub const FRAC_PI_3: bf16 = bf16(0x3F86u16);
766
    /// [`struct@bf16`] π/4
767
    pub const FRAC_PI_4: bf16 = bf16(0x3F49u16);
768
    /// [`struct@bf16`] π/6
769
    pub const FRAC_PI_6: bf16 = bf16(0x3F06u16);
770
    /// [`struct@bf16`] π/8
771
    pub const FRAC_PI_8: bf16 = bf16(0x3EC9u16);
772
    /// [`struct@bf16`] 𝗅𝗇 10
773
    pub const LN_10: bf16 = bf16(0x4013u16);
774
    /// [`struct@bf16`] 𝗅𝗇 2
775
    pub const LN_2: bf16 = bf16(0x3F31u16);
776
    /// [`struct@bf16`] 𝗅𝗈𝗀₁₀ℯ
777
    pub const LOG10_E: bf16 = bf16(0x3EDEu16);
778
    /// [`struct@bf16`] 𝗅𝗈𝗀₁₀2
779
    pub const LOG10_2: bf16 = bf16(0x3E9Au16);
780
    /// [`struct@bf16`] 𝗅𝗈𝗀₂ℯ
781
    pub const LOG2_E: bf16 = bf16(0x3FB9u16);
782
    /// [`struct@bf16`] 𝗅𝗈𝗀₂10
783
    pub const LOG2_10: bf16 = bf16(0x4055u16);
784
    /// [`struct@bf16`] √2
785
    pub const SQRT_2: bf16 = bf16(0x3FB5u16);
786
}
787
788
impl From<bf16> for f32 {
789
    #[inline]
790
0
    fn from(x: bf16) -> f32 {
791
0
        x.to_f32()
792
0
    }
793
}
794
795
impl From<bf16> for f64 {
796
    #[inline]
797
0
    fn from(x: bf16) -> f64 {
798
0
        x.to_f64()
799
0
    }
800
}
801
802
impl From<i8> for bf16 {
803
    #[inline]
804
0
    fn from(x: i8) -> bf16 {
805
        // Convert to f32, then to bf16
806
0
        bf16::from_f32(f32::from(x))
807
0
    }
808
}
809
810
impl From<u8> for bf16 {
811
    #[inline]
812
0
    fn from(x: u8) -> bf16 {
813
        // Convert to f32, then to f16
814
0
        bf16::from_f32(f32::from(x))
815
0
    }
816
}
817
818
impl PartialEq for bf16 {
819
0
    fn eq(&self, other: &bf16) -> bool {
820
0
        if self.is_nan() || other.is_nan() {
821
0
            false
822
        } else {
823
0
            (self.0 == other.0) || ((self.0 | other.0) & 0x7FFFu16 == 0)
824
        }
825
0
    }
826
}
827
828
impl PartialOrd for bf16 {
829
0
    fn partial_cmp(&self, other: &bf16) -> Option<Ordering> {
830
0
        if self.is_nan() || other.is_nan() {
831
0
            None
832
        } else {
833
0
            let neg = self.0 & 0x8000u16 != 0;
834
0
            let other_neg = other.0 & 0x8000u16 != 0;
835
0
            match (neg, other_neg) {
836
0
                (false, false) => Some(self.0.cmp(&other.0)),
837
                (false, true) => {
838
0
                    if (self.0 | other.0) & 0x7FFFu16 == 0 {
839
0
                        Some(Ordering::Equal)
840
                    } else {
841
0
                        Some(Ordering::Greater)
842
                    }
843
                }
844
                (true, false) => {
845
0
                    if (self.0 | other.0) & 0x7FFFu16 == 0 {
846
0
                        Some(Ordering::Equal)
847
                    } else {
848
0
                        Some(Ordering::Less)
849
                    }
850
                }
851
0
                (true, true) => Some(other.0.cmp(&self.0)),
852
            }
853
        }
854
0
    }
855
856
0
    fn lt(&self, other: &bf16) -> bool {
857
0
        if self.is_nan() || other.is_nan() {
858
0
            false
859
        } else {
860
0
            let neg = self.0 & 0x8000u16 != 0;
861
0
            let other_neg = other.0 & 0x8000u16 != 0;
862
0
            match (neg, other_neg) {
863
0
                (false, false) => self.0 < other.0,
864
0
                (false, true) => false,
865
0
                (true, false) => (self.0 | other.0) & 0x7FFFu16 != 0,
866
0
                (true, true) => self.0 > other.0,
867
            }
868
        }
869
0
    }
870
871
0
    fn le(&self, other: &bf16) -> bool {
872
0
        if self.is_nan() || other.is_nan() {
873
0
            false
874
        } else {
875
0
            let neg = self.0 & 0x8000u16 != 0;
876
0
            let other_neg = other.0 & 0x8000u16 != 0;
877
0
            match (neg, other_neg) {
878
0
                (false, false) => self.0 <= other.0,
879
0
                (false, true) => (self.0 | other.0) & 0x7FFFu16 == 0,
880
0
                (true, false) => true,
881
0
                (true, true) => self.0 >= other.0,
882
            }
883
        }
884
0
    }
885
886
0
    fn gt(&self, other: &bf16) -> bool {
887
0
        if self.is_nan() || other.is_nan() {
888
0
            false
889
        } else {
890
0
            let neg = self.0 & 0x8000u16 != 0;
891
0
            let other_neg = other.0 & 0x8000u16 != 0;
892
0
            match (neg, other_neg) {
893
0
                (false, false) => self.0 > other.0,
894
0
                (false, true) => (self.0 | other.0) & 0x7FFFu16 != 0,
895
0
                (true, false) => false,
896
0
                (true, true) => self.0 < other.0,
897
            }
898
        }
899
0
    }
900
901
0
    fn ge(&self, other: &bf16) -> bool {
902
0
        if self.is_nan() || other.is_nan() {
903
0
            false
904
        } else {
905
0
            let neg = self.0 & 0x8000u16 != 0;
906
0
            let other_neg = other.0 & 0x8000u16 != 0;
907
0
            match (neg, other_neg) {
908
0
                (false, false) => self.0 >= other.0,
909
0
                (false, true) => true,
910
0
                (true, false) => (self.0 | other.0) & 0x7FFFu16 == 0,
911
0
                (true, true) => self.0 <= other.0,
912
            }
913
        }
914
0
    }
915
}
916
917
#[cfg(not(target_arch = "spirv"))]
918
impl FromStr for bf16 {
919
    type Err = ParseFloatError;
920
0
    fn from_str(src: &str) -> Result<bf16, ParseFloatError> {
921
0
        f32::from_str(src).map(bf16::from_f32)
922
0
    }
923
}
924
925
#[cfg(not(target_arch = "spirv"))]
926
impl Debug for bf16 {
927
0
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
928
0
        Debug::fmt(&self.to_f32(), f)
929
0
    }
930
}
931
932
#[cfg(not(target_arch = "spirv"))]
933
impl Display for bf16 {
934
0
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
935
0
        Display::fmt(&self.to_f32(), f)
936
0
    }
937
}
938
939
#[cfg(not(target_arch = "spirv"))]
940
impl LowerExp for bf16 {
941
0
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
942
0
        write!(f, "{:e}", self.to_f32())
943
0
    }
944
}
945
946
#[cfg(not(target_arch = "spirv"))]
947
impl UpperExp for bf16 {
948
0
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
949
0
        write!(f, "{:E}", self.to_f32())
950
0
    }
951
}
952
953
#[cfg(not(target_arch = "spirv"))]
954
impl Binary for bf16 {
955
0
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
956
0
        write!(f, "{:b}", self.0)
957
0
    }
958
}
959
960
#[cfg(not(target_arch = "spirv"))]
961
impl Octal for bf16 {
962
0
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
963
0
        write!(f, "{:o}", self.0)
964
0
    }
965
}
966
967
#[cfg(not(target_arch = "spirv"))]
968
impl LowerHex for bf16 {
969
0
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
970
0
        write!(f, "{:x}", self.0)
971
0
    }
972
}
973
974
#[cfg(not(target_arch = "spirv"))]
975
impl UpperHex for bf16 {
976
0
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
977
0
        write!(f, "{:X}", self.0)
978
0
    }
979
}
980
981
impl Neg for bf16 {
982
    type Output = Self;
983
984
0
    fn neg(self) -> Self::Output {
985
0
        Self(self.0 ^ 0x8000)
986
0
    }
987
}
988
989
impl Neg for &bf16 {
990
    type Output = <bf16 as Neg>::Output;
991
992
    #[inline]
993
0
    fn neg(self) -> Self::Output {
994
0
        Neg::neg(*self)
995
0
    }
996
}
997
998
impl Add for bf16 {
999
    type Output = Self;
1000
1001
0
    fn add(self, rhs: Self) -> Self::Output {
1002
0
        Self::from_f32(Self::to_f32(self) + Self::to_f32(rhs))
1003
0
    }
1004
}
1005
1006
impl Add<&bf16> for bf16 {
1007
    type Output = <bf16 as Add<bf16>>::Output;
1008
1009
    #[inline]
1010
0
    fn add(self, rhs: &bf16) -> Self::Output {
1011
0
        self.add(*rhs)
1012
0
    }
1013
}
1014
1015
impl Add<&bf16> for &bf16 {
1016
    type Output = <bf16 as Add<bf16>>::Output;
1017
1018
    #[inline]
1019
0
    fn add(self, rhs: &bf16) -> Self::Output {
1020
0
        (*self).add(*rhs)
1021
0
    }
1022
}
1023
1024
impl Add<bf16> for &bf16 {
1025
    type Output = <bf16 as Add<bf16>>::Output;
1026
1027
    #[inline]
1028
0
    fn add(self, rhs: bf16) -> Self::Output {
1029
0
        (*self).add(rhs)
1030
0
    }
1031
}
1032
1033
impl AddAssign for bf16 {
1034
    #[inline]
1035
0
    fn add_assign(&mut self, rhs: Self) {
1036
0
        *self = (*self).add(rhs);
1037
0
    }
1038
}
1039
1040
impl AddAssign<&bf16> for bf16 {
1041
    #[inline]
1042
0
    fn add_assign(&mut self, rhs: &bf16) {
1043
0
        *self = (*self).add(rhs);
1044
0
    }
1045
}
1046
1047
impl Sub for bf16 {
1048
    type Output = Self;
1049
1050
0
    fn sub(self, rhs: Self) -> Self::Output {
1051
0
        Self::from_f32(Self::to_f32(self) - Self::to_f32(rhs))
1052
0
    }
1053
}
1054
1055
impl Sub<&bf16> for bf16 {
1056
    type Output = <bf16 as Sub<bf16>>::Output;
1057
1058
    #[inline]
1059
0
    fn sub(self, rhs: &bf16) -> Self::Output {
1060
0
        self.sub(*rhs)
1061
0
    }
1062
}
1063
1064
impl Sub<&bf16> for &bf16 {
1065
    type Output = <bf16 as Sub<bf16>>::Output;
1066
1067
    #[inline]
1068
0
    fn sub(self, rhs: &bf16) -> Self::Output {
1069
0
        (*self).sub(*rhs)
1070
0
    }
1071
}
1072
1073
impl Sub<bf16> for &bf16 {
1074
    type Output = <bf16 as Sub<bf16>>::Output;
1075
1076
    #[inline]
1077
0
    fn sub(self, rhs: bf16) -> Self::Output {
1078
0
        (*self).sub(rhs)
1079
0
    }
1080
}
1081
1082
impl SubAssign for bf16 {
1083
    #[inline]
1084
0
    fn sub_assign(&mut self, rhs: Self) {
1085
0
        *self = (*self).sub(rhs);
1086
0
    }
1087
}
1088
1089
impl SubAssign<&bf16> for bf16 {
1090
    #[inline]
1091
0
    fn sub_assign(&mut self, rhs: &bf16) {
1092
0
        *self = (*self).sub(rhs);
1093
0
    }
1094
}
1095
1096
impl Mul for bf16 {
1097
    type Output = Self;
1098
1099
0
    fn mul(self, rhs: Self) -> Self::Output {
1100
0
        Self::from_f32(Self::to_f32(self) * Self::to_f32(rhs))
1101
0
    }
1102
}
1103
1104
impl Mul<&bf16> for bf16 {
1105
    type Output = <bf16 as Mul<bf16>>::Output;
1106
1107
    #[inline]
1108
0
    fn mul(self, rhs: &bf16) -> Self::Output {
1109
0
        self.mul(*rhs)
1110
0
    }
1111
}
1112
1113
impl Mul<&bf16> for &bf16 {
1114
    type Output = <bf16 as Mul<bf16>>::Output;
1115
1116
    #[inline]
1117
0
    fn mul(self, rhs: &bf16) -> Self::Output {
1118
0
        (*self).mul(*rhs)
1119
0
    }
1120
}
1121
1122
impl Mul<bf16> for &bf16 {
1123
    type Output = <bf16 as Mul<bf16>>::Output;
1124
1125
    #[inline]
1126
0
    fn mul(self, rhs: bf16) -> Self::Output {
1127
0
        (*self).mul(rhs)
1128
0
    }
1129
}
1130
1131
impl MulAssign for bf16 {
1132
    #[inline]
1133
0
    fn mul_assign(&mut self, rhs: Self) {
1134
0
        *self = (*self).mul(rhs);
1135
0
    }
1136
}
1137
1138
impl MulAssign<&bf16> for bf16 {
1139
    #[inline]
1140
0
    fn mul_assign(&mut self, rhs: &bf16) {
1141
0
        *self = (*self).mul(rhs);
1142
0
    }
1143
}
1144
1145
impl Div for bf16 {
1146
    type Output = Self;
1147
1148
0
    fn div(self, rhs: Self) -> Self::Output {
1149
0
        Self::from_f32(Self::to_f32(self) / Self::to_f32(rhs))
1150
0
    }
1151
}
1152
1153
impl Div<&bf16> for bf16 {
1154
    type Output = <bf16 as Div<bf16>>::Output;
1155
1156
    #[inline]
1157
0
    fn div(self, rhs: &bf16) -> Self::Output {
1158
0
        self.div(*rhs)
1159
0
    }
1160
}
1161
1162
impl Div<&bf16> for &bf16 {
1163
    type Output = <bf16 as Div<bf16>>::Output;
1164
1165
    #[inline]
1166
0
    fn div(self, rhs: &bf16) -> Self::Output {
1167
0
        (*self).div(*rhs)
1168
0
    }
1169
}
1170
1171
impl Div<bf16> for &bf16 {
1172
    type Output = <bf16 as Div<bf16>>::Output;
1173
1174
    #[inline]
1175
0
    fn div(self, rhs: bf16) -> Self::Output {
1176
0
        (*self).div(rhs)
1177
0
    }
1178
}
1179
1180
impl DivAssign for bf16 {
1181
    #[inline]
1182
0
    fn div_assign(&mut self, rhs: Self) {
1183
0
        *self = (*self).div(rhs);
1184
0
    }
1185
}
1186
1187
impl DivAssign<&bf16> for bf16 {
1188
    #[inline]
1189
0
    fn div_assign(&mut self, rhs: &bf16) {
1190
0
        *self = (*self).div(rhs);
1191
0
    }
1192
}
1193
1194
impl Rem for bf16 {
1195
    type Output = Self;
1196
1197
0
    fn rem(self, rhs: Self) -> Self::Output {
1198
0
        Self::from_f32(Self::to_f32(self) % Self::to_f32(rhs))
1199
0
    }
1200
}
1201
1202
impl Rem<&bf16> for bf16 {
1203
    type Output = <bf16 as Rem<bf16>>::Output;
1204
1205
    #[inline]
1206
0
    fn rem(self, rhs: &bf16) -> Self::Output {
1207
0
        self.rem(*rhs)
1208
0
    }
1209
}
1210
1211
impl Rem<&bf16> for &bf16 {
1212
    type Output = <bf16 as Rem<bf16>>::Output;
1213
1214
    #[inline]
1215
0
    fn rem(self, rhs: &bf16) -> Self::Output {
1216
0
        (*self).rem(*rhs)
1217
0
    }
1218
}
1219
1220
impl Rem<bf16> for &bf16 {
1221
    type Output = <bf16 as Rem<bf16>>::Output;
1222
1223
    #[inline]
1224
0
    fn rem(self, rhs: bf16) -> Self::Output {
1225
0
        (*self).rem(rhs)
1226
0
    }
1227
}
1228
1229
impl RemAssign for bf16 {
1230
    #[inline]
1231
0
    fn rem_assign(&mut self, rhs: Self) {
1232
0
        *self = (*self).rem(rhs);
1233
0
    }
1234
}
1235
1236
impl RemAssign<&bf16> for bf16 {
1237
    #[inline]
1238
0
    fn rem_assign(&mut self, rhs: &bf16) {
1239
0
        *self = (*self).rem(rhs);
1240
0
    }
1241
}
1242
1243
impl Product for bf16 {
1244
    #[inline]
1245
0
    fn product<I: Iterator<Item = Self>>(iter: I) -> Self {
1246
0
        bf16::from_f32(iter.map(|f| f.to_f32()).product())
1247
0
    }
1248
}
1249
1250
impl<'a> Product<&'a bf16> for bf16 {
1251
    #[inline]
1252
0
    fn product<I: Iterator<Item = &'a bf16>>(iter: I) -> Self {
1253
0
        bf16::from_f32(iter.map(|f| f.to_f32()).product())
1254
0
    }
1255
}
1256
1257
impl Sum for bf16 {
1258
    #[inline]
1259
0
    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
1260
0
        bf16::from_f32(iter.map(|f| f.to_f32()).sum())
1261
0
    }
1262
}
1263
1264
impl<'a> Sum<&'a bf16> for bf16 {
1265
    #[inline]
1266
0
    fn sum<I: Iterator<Item = &'a bf16>>(iter: I) -> Self {
1267
0
        bf16::from_f32(iter.map(|f| f.to_f32()).sum())
1268
0
    }
1269
}
1270
1271
#[cfg(feature = "serde")]
1272
struct Visitor;
1273
1274
#[cfg(feature = "serde")]
1275
impl<'de> Deserialize<'de> for bf16 {
1276
    fn deserialize<D>(deserializer: D) -> Result<bf16, D::Error>
1277
    where
1278
        D: serde::de::Deserializer<'de>,
1279
    {
1280
        deserializer.deserialize_newtype_struct("bf16", Visitor)
1281
    }
1282
}
1283
1284
#[cfg(feature = "serde")]
1285
impl<'de> serde::de::Visitor<'de> for Visitor {
1286
    type Value = bf16;
1287
1288
    fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
1289
        write!(formatter, "tuple struct bf16")
1290
    }
1291
1292
    fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1293
    where
1294
        D: serde::Deserializer<'de>,
1295
    {
1296
        Ok(bf16(<u16 as Deserialize>::deserialize(deserializer)?))
1297
    }
1298
1299
    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1300
    where
1301
        E: serde::de::Error,
1302
    {
1303
        v.parse().map_err(|_| {
1304
            serde::de::Error::invalid_value(serde::de::Unexpected::Str(v), &"a float string")
1305
        })
1306
    }
1307
1308
    fn visit_f32<E>(self, v: f32) -> Result<Self::Value, E>
1309
    where
1310
        E: serde::de::Error,
1311
    {
1312
        Ok(bf16::from_f32(v))
1313
    }
1314
1315
    fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
1316
    where
1317
        E: serde::de::Error,
1318
    {
1319
        Ok(bf16::from_f64(v))
1320
    }
1321
}
1322
1323
#[allow(
1324
    clippy::cognitive_complexity,
1325
    clippy::float_cmp,
1326
    clippy::neg_cmp_op_on_partial_ord
1327
)]
1328
#[cfg(test)]
1329
mod test {
1330
    use super::*;
1331
    #[allow(unused_imports)]
1332
    use core::cmp::Ordering;
1333
    #[cfg(feature = "num-traits")]
1334
    use num_traits::{AsPrimitive, FromBytes, FromPrimitive, ToBytes, ToPrimitive};
1335
    use quickcheck_macros::quickcheck;
1336
1337
    #[cfg(feature = "num-traits")]
1338
    #[test]
1339
    fn as_primitive() {
1340
        let two = bf16::from_f32(2.0);
1341
        assert_eq!(<i32 as AsPrimitive<bf16>>::as_(2), two);
1342
        assert_eq!(<bf16 as AsPrimitive<i32>>::as_(two), 2);
1343
1344
        assert_eq!(<f32 as AsPrimitive<bf16>>::as_(2.0), two);
1345
        assert_eq!(<bf16 as AsPrimitive<f32>>::as_(two), 2.0);
1346
1347
        assert_eq!(<f64 as AsPrimitive<bf16>>::as_(2.0), two);
1348
        assert_eq!(<bf16 as AsPrimitive<f64>>::as_(two), 2.0);
1349
    }
1350
1351
    #[cfg(feature = "num-traits")]
1352
    #[test]
1353
    fn to_primitive() {
1354
        let two = bf16::from_f32(2.0);
1355
        assert_eq!(ToPrimitive::to_i32(&two).unwrap(), 2i32);
1356
        assert_eq!(ToPrimitive::to_f32(&two).unwrap(), 2.0f32);
1357
        assert_eq!(ToPrimitive::to_f64(&two).unwrap(), 2.0f64);
1358
    }
1359
1360
    #[cfg(feature = "num-traits")]
1361
    #[test]
1362
    fn from_primitive() {
1363
        let two = bf16::from_f32(2.0);
1364
        assert_eq!(<bf16 as FromPrimitive>::from_i32(2).unwrap(), two);
1365
        assert_eq!(<bf16 as FromPrimitive>::from_f32(2.0).unwrap(), two);
1366
        assert_eq!(<bf16 as FromPrimitive>::from_f64(2.0).unwrap(), two);
1367
    }
1368
1369
    #[cfg(feature = "num-traits")]
1370
    #[test]
1371
    fn to_and_from_bytes() {
1372
        let two = bf16::from_f32(2.0);
1373
        assert_eq!(<bf16 as ToBytes>::to_le_bytes(&two), [0, 64]);
1374
        assert_eq!(<bf16 as FromBytes>::from_le_bytes(&[0, 64]), two);
1375
        assert_eq!(<bf16 as ToBytes>::to_be_bytes(&two), [64, 0]);
1376
        assert_eq!(<bf16 as FromBytes>::from_be_bytes(&[64, 0]), two);
1377
    }
1378
1379
    #[test]
1380
    fn test_bf16_consts_from_f32() {
1381
        let one = bf16::from_f32(1.0);
1382
        let zero = bf16::from_f32(0.0);
1383
        let neg_zero = bf16::from_f32(-0.0);
1384
        let neg_one = bf16::from_f32(-1.0);
1385
        let inf = bf16::from_f32(core::f32::INFINITY);
1386
        let neg_inf = bf16::from_f32(core::f32::NEG_INFINITY);
1387
        let nan = bf16::from_f32(core::f32::NAN);
1388
1389
        assert_eq!(bf16::ONE, one);
1390
        assert_eq!(bf16::ZERO, zero);
1391
        assert!(zero.is_sign_positive());
1392
        assert_eq!(bf16::NEG_ZERO, neg_zero);
1393
        assert!(neg_zero.is_sign_negative());
1394
        assert_eq!(bf16::NEG_ONE, neg_one);
1395
        assert!(neg_one.is_sign_negative());
1396
        assert_eq!(bf16::INFINITY, inf);
1397
        assert_eq!(bf16::NEG_INFINITY, neg_inf);
1398
        assert!(nan.is_nan());
1399
        assert!(bf16::NAN.is_nan());
1400
1401
        let e = bf16::from_f32(core::f32::consts::E);
1402
        let pi = bf16::from_f32(core::f32::consts::PI);
1403
        let frac_1_pi = bf16::from_f32(core::f32::consts::FRAC_1_PI);
1404
        let frac_1_sqrt_2 = bf16::from_f32(core::f32::consts::FRAC_1_SQRT_2);
1405
        let frac_2_pi = bf16::from_f32(core::f32::consts::FRAC_2_PI);
1406
        let frac_2_sqrt_pi = bf16::from_f32(core::f32::consts::FRAC_2_SQRT_PI);
1407
        let frac_pi_2 = bf16::from_f32(core::f32::consts::FRAC_PI_2);
1408
        let frac_pi_3 = bf16::from_f32(core::f32::consts::FRAC_PI_3);
1409
        let frac_pi_4 = bf16::from_f32(core::f32::consts::FRAC_PI_4);
1410
        let frac_pi_6 = bf16::from_f32(core::f32::consts::FRAC_PI_6);
1411
        let frac_pi_8 = bf16::from_f32(core::f32::consts::FRAC_PI_8);
1412
        let ln_10 = bf16::from_f32(core::f32::consts::LN_10);
1413
        let ln_2 = bf16::from_f32(core::f32::consts::LN_2);
1414
        let log10_e = bf16::from_f32(core::f32::consts::LOG10_E);
1415
        // core::f32::consts::LOG10_2 requires rustc 1.43.0
1416
        let log10_2 = bf16::from_f32(2f32.log10());
1417
        let log2_e = bf16::from_f32(core::f32::consts::LOG2_E);
1418
        // core::f32::consts::LOG2_10 requires rustc 1.43.0
1419
        let log2_10 = bf16::from_f32(10f32.log2());
1420
        let sqrt_2 = bf16::from_f32(core::f32::consts::SQRT_2);
1421
1422
        assert_eq!(bf16::E, e);
1423
        assert_eq!(bf16::PI, pi);
1424
        assert_eq!(bf16::FRAC_1_PI, frac_1_pi);
1425
        assert_eq!(bf16::FRAC_1_SQRT_2, frac_1_sqrt_2);
1426
        assert_eq!(bf16::FRAC_2_PI, frac_2_pi);
1427
        assert_eq!(bf16::FRAC_2_SQRT_PI, frac_2_sqrt_pi);
1428
        assert_eq!(bf16::FRAC_PI_2, frac_pi_2);
1429
        assert_eq!(bf16::FRAC_PI_3, frac_pi_3);
1430
        assert_eq!(bf16::FRAC_PI_4, frac_pi_4);
1431
        assert_eq!(bf16::FRAC_PI_6, frac_pi_6);
1432
        assert_eq!(bf16::FRAC_PI_8, frac_pi_8);
1433
        assert_eq!(bf16::LN_10, ln_10);
1434
        assert_eq!(bf16::LN_2, ln_2);
1435
        assert_eq!(bf16::LOG10_E, log10_e);
1436
        assert_eq!(bf16::LOG10_2, log10_2);
1437
        assert_eq!(bf16::LOG2_E, log2_e);
1438
        assert_eq!(bf16::LOG2_10, log2_10);
1439
        assert_eq!(bf16::SQRT_2, sqrt_2);
1440
    }
1441
1442
    #[test]
1443
    fn test_bf16_consts_from_f64() {
1444
        let one = bf16::from_f64(1.0);
1445
        let zero = bf16::from_f64(0.0);
1446
        let neg_zero = bf16::from_f64(-0.0);
1447
        let inf = bf16::from_f64(core::f64::INFINITY);
1448
        let neg_inf = bf16::from_f64(core::f64::NEG_INFINITY);
1449
        let nan = bf16::from_f64(core::f64::NAN);
1450
1451
        assert_eq!(bf16::ONE, one);
1452
        assert_eq!(bf16::ZERO, zero);
1453
        assert_eq!(bf16::NEG_ZERO, neg_zero);
1454
        assert_eq!(bf16::INFINITY, inf);
1455
        assert_eq!(bf16::NEG_INFINITY, neg_inf);
1456
        assert!(nan.is_nan());
1457
        assert!(bf16::NAN.is_nan());
1458
1459
        let e = bf16::from_f64(core::f64::consts::E);
1460
        let pi = bf16::from_f64(core::f64::consts::PI);
1461
        let frac_1_pi = bf16::from_f64(core::f64::consts::FRAC_1_PI);
1462
        let frac_1_sqrt_2 = bf16::from_f64(core::f64::consts::FRAC_1_SQRT_2);
1463
        let frac_2_pi = bf16::from_f64(core::f64::consts::FRAC_2_PI);
1464
        let frac_2_sqrt_pi = bf16::from_f64(core::f64::consts::FRAC_2_SQRT_PI);
1465
        let frac_pi_2 = bf16::from_f64(core::f64::consts::FRAC_PI_2);
1466
        let frac_pi_3 = bf16::from_f64(core::f64::consts::FRAC_PI_3);
1467
        let frac_pi_4 = bf16::from_f64(core::f64::consts::FRAC_PI_4);
1468
        let frac_pi_6 = bf16::from_f64(core::f64::consts::FRAC_PI_6);
1469
        let frac_pi_8 = bf16::from_f64(core::f64::consts::FRAC_PI_8);
1470
        let ln_10 = bf16::from_f64(core::f64::consts::LN_10);
1471
        let ln_2 = bf16::from_f64(core::f64::consts::LN_2);
1472
        let log10_e = bf16::from_f64(core::f64::consts::LOG10_E);
1473
        // core::f64::consts::LOG10_2 requires rustc 1.43.0
1474
        let log10_2 = bf16::from_f64(2f64.log10());
1475
        let log2_e = bf16::from_f64(core::f64::consts::LOG2_E);
1476
        // core::f64::consts::LOG2_10 requires rustc 1.43.0
1477
        let log2_10 = bf16::from_f64(10f64.log2());
1478
        let sqrt_2 = bf16::from_f64(core::f64::consts::SQRT_2);
1479
1480
        assert_eq!(bf16::E, e);
1481
        assert_eq!(bf16::PI, pi);
1482
        assert_eq!(bf16::FRAC_1_PI, frac_1_pi);
1483
        assert_eq!(bf16::FRAC_1_SQRT_2, frac_1_sqrt_2);
1484
        assert_eq!(bf16::FRAC_2_PI, frac_2_pi);
1485
        assert_eq!(bf16::FRAC_2_SQRT_PI, frac_2_sqrt_pi);
1486
        assert_eq!(bf16::FRAC_PI_2, frac_pi_2);
1487
        assert_eq!(bf16::FRAC_PI_3, frac_pi_3);
1488
        assert_eq!(bf16::FRAC_PI_4, frac_pi_4);
1489
        assert_eq!(bf16::FRAC_PI_6, frac_pi_6);
1490
        assert_eq!(bf16::FRAC_PI_8, frac_pi_8);
1491
        assert_eq!(bf16::LN_10, ln_10);
1492
        assert_eq!(bf16::LN_2, ln_2);
1493
        assert_eq!(bf16::LOG10_E, log10_e);
1494
        assert_eq!(bf16::LOG10_2, log10_2);
1495
        assert_eq!(bf16::LOG2_E, log2_e);
1496
        assert_eq!(bf16::LOG2_10, log2_10);
1497
        assert_eq!(bf16::SQRT_2, sqrt_2);
1498
    }
1499
1500
    #[test]
1501
    fn test_nan_conversion_to_smaller() {
1502
        let nan64 = f64::from_bits(0x7FF0_0000_0000_0001u64);
1503
        let neg_nan64 = f64::from_bits(0xFFF0_0000_0000_0001u64);
1504
        let nan32 = f32::from_bits(0x7F80_0001u32);
1505
        let neg_nan32 = f32::from_bits(0xFF80_0001u32);
1506
        let nan32_from_64 = nan64 as f32;
1507
        let neg_nan32_from_64 = neg_nan64 as f32;
1508
        let nan16_from_64 = bf16::from_f64(nan64);
1509
        let neg_nan16_from_64 = bf16::from_f64(neg_nan64);
1510
        let nan16_from_32 = bf16::from_f32(nan32);
1511
        let neg_nan16_from_32 = bf16::from_f32(neg_nan32);
1512
1513
        assert!(nan64.is_nan() && nan64.is_sign_positive());
1514
        assert!(neg_nan64.is_nan() && neg_nan64.is_sign_negative());
1515
        assert!(nan32.is_nan() && nan32.is_sign_positive());
1516
        assert!(neg_nan32.is_nan() && neg_nan32.is_sign_negative());
1517
1518
        // f32/f64 NaN conversion sign is non-deterministic: https://github.com/VoidStarKat/half-rs/issues/103
1519
        assert!(neg_nan32_from_64.is_nan());
1520
        assert!(nan32_from_64.is_nan());
1521
        assert!(nan16_from_64.is_nan());
1522
        assert!(neg_nan16_from_64.is_nan());
1523
        assert!(nan16_from_32.is_nan());
1524
        assert!(neg_nan16_from_32.is_nan());
1525
    }
1526
1527
    #[test]
1528
    fn test_nan_conversion_to_larger() {
1529
        let nan16 = bf16::from_bits(0x7F81u16);
1530
        let neg_nan16 = bf16::from_bits(0xFF81u16);
1531
        let nan32 = f32::from_bits(0x7F80_0001u32);
1532
        let neg_nan32 = f32::from_bits(0xFF80_0001u32);
1533
        let nan32_from_16 = f32::from(nan16);
1534
        let neg_nan32_from_16 = f32::from(neg_nan16);
1535
        let nan64_from_16 = f64::from(nan16);
1536
        let neg_nan64_from_16 = f64::from(neg_nan16);
1537
        let nan64_from_32 = f64::from(nan32);
1538
        let neg_nan64_from_32 = f64::from(neg_nan32);
1539
1540
        assert!(nan16.is_nan() && nan16.is_sign_positive());
1541
        assert!(neg_nan16.is_nan() && neg_nan16.is_sign_negative());
1542
        assert!(nan32.is_nan() && nan32.is_sign_positive());
1543
        assert!(neg_nan32.is_nan() && neg_nan32.is_sign_negative());
1544
1545
        // // f32/f64 NaN conversion sign is non-deterministic: https://github.com/VoidStarKat/half-rs/issues/103
1546
        assert!(nan32_from_16.is_nan());
1547
        assert!(neg_nan32_from_16.is_nan());
1548
        assert!(nan64_from_16.is_nan());
1549
        assert!(neg_nan64_from_16.is_nan());
1550
        assert!(nan64_from_32.is_nan());
1551
        assert!(neg_nan64_from_32.is_nan());
1552
    }
1553
1554
    #[test]
1555
    fn test_bf16_to_f32() {
1556
        let f = bf16::from_f32(7.0);
1557
        assert_eq!(f.to_f32(), 7.0f32);
1558
1559
        // 7.1 is NOT exactly representable in 16-bit, it's rounded
1560
        let f = bf16::from_f32(7.1);
1561
        let diff = (f.to_f32() - 7.1f32).abs();
1562
        // diff must be <= 4 * EPSILON, as 7 has two more significant bits than 1
1563
        assert!(diff <= 4.0 * bf16::EPSILON.to_f32());
1564
1565
        let tiny32 = f32::from_bits(0x0001_0000u32);
1566
        assert_eq!(bf16::from_bits(0x0001).to_f32(), tiny32);
1567
        assert_eq!(bf16::from_bits(0x0005).to_f32(), 5.0 * tiny32);
1568
1569
        assert_eq!(bf16::from_bits(0x0001), bf16::from_f32(tiny32));
1570
        assert_eq!(bf16::from_bits(0x0005), bf16::from_f32(5.0 * tiny32));
1571
    }
1572
1573
    #[test]
1574
    #[cfg_attr(miri, ignore)]
1575
    fn test_bf16_to_f64() {
1576
        let f = bf16::from_f64(7.0);
1577
        assert_eq!(f.to_f64(), 7.0f64);
1578
1579
        // 7.1 is NOT exactly representable in 16-bit, it's rounded
1580
        let f = bf16::from_f64(7.1);
1581
        let diff = (f.to_f64() - 7.1f64).abs();
1582
        // diff must be <= 4 * EPSILON, as 7 has two more significant bits than 1
1583
        assert!(diff <= 4.0 * bf16::EPSILON.to_f64());
1584
1585
        let tiny64 = 2.0f64.powi(-133);
1586
        assert_eq!(bf16::from_bits(0x0001).to_f64(), tiny64);
1587
        assert_eq!(bf16::from_bits(0x0005).to_f64(), 5.0 * tiny64);
1588
1589
        assert_eq!(bf16::from_bits(0x0001), bf16::from_f64(tiny64));
1590
        assert_eq!(bf16::from_bits(0x0005), bf16::from_f64(5.0 * tiny64));
1591
    }
1592
1593
    #[test]
1594
    fn test_comparisons() {
1595
        let zero = bf16::from_f64(0.0);
1596
        let one = bf16::from_f64(1.0);
1597
        let neg_zero = bf16::from_f64(-0.0);
1598
        let neg_one = bf16::from_f64(-1.0);
1599
1600
        assert_eq!(zero.partial_cmp(&neg_zero), Some(Ordering::Equal));
1601
        assert_eq!(neg_zero.partial_cmp(&zero), Some(Ordering::Equal));
1602
        assert!(zero == neg_zero);
1603
        assert!(neg_zero == zero);
1604
        assert!(!(zero != neg_zero));
1605
        assert!(!(neg_zero != zero));
1606
        assert!(!(zero < neg_zero));
1607
        assert!(!(neg_zero < zero));
1608
        assert!(zero <= neg_zero);
1609
        assert!(neg_zero <= zero);
1610
        assert!(!(zero > neg_zero));
1611
        assert!(!(neg_zero > zero));
1612
        assert!(zero >= neg_zero);
1613
        assert!(neg_zero >= zero);
1614
1615
        assert_eq!(one.partial_cmp(&neg_zero), Some(Ordering::Greater));
1616
        assert_eq!(neg_zero.partial_cmp(&one), Some(Ordering::Less));
1617
        assert!(!(one == neg_zero));
1618
        assert!(!(neg_zero == one));
1619
        assert!(one != neg_zero);
1620
        assert!(neg_zero != one);
1621
        assert!(!(one < neg_zero));
1622
        assert!(neg_zero < one);
1623
        assert!(!(one <= neg_zero));
1624
        assert!(neg_zero <= one);
1625
        assert!(one > neg_zero);
1626
        assert!(!(neg_zero > one));
1627
        assert!(one >= neg_zero);
1628
        assert!(!(neg_zero >= one));
1629
1630
        assert_eq!(one.partial_cmp(&neg_one), Some(Ordering::Greater));
1631
        assert_eq!(neg_one.partial_cmp(&one), Some(Ordering::Less));
1632
        assert!(!(one == neg_one));
1633
        assert!(!(neg_one == one));
1634
        assert!(one != neg_one);
1635
        assert!(neg_one != one);
1636
        assert!(!(one < neg_one));
1637
        assert!(neg_one < one);
1638
        assert!(!(one <= neg_one));
1639
        assert!(neg_one <= one);
1640
        assert!(one > neg_one);
1641
        assert!(!(neg_one > one));
1642
        assert!(one >= neg_one);
1643
        assert!(!(neg_one >= one));
1644
    }
1645
1646
    #[test]
1647
    #[allow(clippy::erasing_op, clippy::identity_op)]
1648
    #[cfg_attr(miri, ignore)]
1649
    fn round_to_even_f32() {
1650
        // smallest positive subnormal = 0b0.0000_001 * 2^-126 = 2^-133
1651
        let min_sub = bf16::from_bits(1);
1652
        let min_sub_f = (-133f32).exp2();
1653
        assert_eq!(bf16::from_f32(min_sub_f).to_bits(), min_sub.to_bits());
1654
        assert_eq!(f32::from(min_sub).to_bits(), min_sub_f.to_bits());
1655
1656
        // 0.0000000_011111 rounded to 0.0000000 (< tie, no rounding)
1657
        // 0.0000000_100000 rounded to 0.0000000 (tie and even, remains at even)
1658
        // 0.0000000_100001 rounded to 0.0000001 (> tie, rounds up)
1659
        assert_eq!(
1660
            bf16::from_f32(min_sub_f * 0.49).to_bits(),
1661
            min_sub.to_bits() * 0
1662
        );
1663
        assert_eq!(
1664
            bf16::from_f32(min_sub_f * 0.50).to_bits(),
1665
            min_sub.to_bits() * 0
1666
        );
1667
        assert_eq!(
1668
            bf16::from_f32(min_sub_f * 0.51).to_bits(),
1669
            min_sub.to_bits() * 1
1670
        );
1671
1672
        // 0.0000001_011111 rounded to 0.0000001 (< tie, no rounding)
1673
        // 0.0000001_100000 rounded to 0.0000010 (tie and odd, rounds up to even)
1674
        // 0.0000001_100001 rounded to 0.0000010 (> tie, rounds up)
1675
        assert_eq!(
1676
            bf16::from_f32(min_sub_f * 1.49).to_bits(),
1677
            min_sub.to_bits() * 1
1678
        );
1679
        assert_eq!(
1680
            bf16::from_f32(min_sub_f * 1.50).to_bits(),
1681
            min_sub.to_bits() * 2
1682
        );
1683
        assert_eq!(
1684
            bf16::from_f32(min_sub_f * 1.51).to_bits(),
1685
            min_sub.to_bits() * 2
1686
        );
1687
1688
        // 0.0000010_011111 rounded to 0.0000010 (< tie, no rounding)
1689
        // 0.0000010_100000 rounded to 0.0000010 (tie and even, remains at even)
1690
        // 0.0000010_100001 rounded to 0.0000011 (> tie, rounds up)
1691
        assert_eq!(
1692
            bf16::from_f32(min_sub_f * 2.49).to_bits(),
1693
            min_sub.to_bits() * 2
1694
        );
1695
        assert_eq!(
1696
            bf16::from_f32(min_sub_f * 2.50).to_bits(),
1697
            min_sub.to_bits() * 2
1698
        );
1699
        assert_eq!(
1700
            bf16::from_f32(min_sub_f * 2.51).to_bits(),
1701
            min_sub.to_bits() * 3
1702
        );
1703
1704
        assert_eq!(
1705
            bf16::from_f32(250.49f32).to_bits(),
1706
            bf16::from_f32(250.0).to_bits()
1707
        );
1708
        assert_eq!(
1709
            bf16::from_f32(250.50f32).to_bits(),
1710
            bf16::from_f32(250.0).to_bits()
1711
        );
1712
        assert_eq!(
1713
            bf16::from_f32(250.51f32).to_bits(),
1714
            bf16::from_f32(251.0).to_bits()
1715
        );
1716
        assert_eq!(
1717
            bf16::from_f32(251.49f32).to_bits(),
1718
            bf16::from_f32(251.0).to_bits()
1719
        );
1720
        assert_eq!(
1721
            bf16::from_f32(251.50f32).to_bits(),
1722
            bf16::from_f32(252.0).to_bits()
1723
        );
1724
        assert_eq!(
1725
            bf16::from_f32(251.51f32).to_bits(),
1726
            bf16::from_f32(252.0).to_bits()
1727
        );
1728
        assert_eq!(
1729
            bf16::from_f32(252.49f32).to_bits(),
1730
            bf16::from_f32(252.0).to_bits()
1731
        );
1732
        assert_eq!(
1733
            bf16::from_f32(252.50f32).to_bits(),
1734
            bf16::from_f32(252.0).to_bits()
1735
        );
1736
        assert_eq!(
1737
            bf16::from_f32(252.51f32).to_bits(),
1738
            bf16::from_f32(253.0).to_bits()
1739
        );
1740
    }
1741
1742
    #[test]
1743
    #[allow(clippy::erasing_op, clippy::identity_op)]
1744
    #[cfg_attr(miri, ignore)]
1745
    fn round_to_even_f64() {
1746
        // smallest positive subnormal = 0b0.0000_001 * 2^-126 = 2^-133
1747
        let min_sub = bf16::from_bits(1);
1748
        let min_sub_f = (-133f64).exp2();
1749
        assert_eq!(bf16::from_f64(min_sub_f).to_bits(), min_sub.to_bits());
1750
        assert_eq!(f64::from(min_sub).to_bits(), min_sub_f.to_bits());
1751
1752
        // 0.0000000_011111 rounded to 0.0000000 (< tie, no rounding)
1753
        // 0.0000000_100000 rounded to 0.0000000 (tie and even, remains at even)
1754
        // 0.0000000_100001 rounded to 0.0000001 (> tie, rounds up)
1755
        assert_eq!(
1756
            bf16::from_f64(min_sub_f * 0.49).to_bits(),
1757
            min_sub.to_bits() * 0
1758
        );
1759
        assert_eq!(
1760
            bf16::from_f64(min_sub_f * 0.50).to_bits(),
1761
            min_sub.to_bits() * 0
1762
        );
1763
        assert_eq!(
1764
            bf16::from_f64(min_sub_f * 0.51).to_bits(),
1765
            min_sub.to_bits() * 1
1766
        );
1767
1768
        // 0.0000001_011111 rounded to 0.0000001 (< tie, no rounding)
1769
        // 0.0000001_100000 rounded to 0.0000010 (tie and odd, rounds up to even)
1770
        // 0.0000001_100001 rounded to 0.0000010 (> tie, rounds up)
1771
        assert_eq!(
1772
            bf16::from_f64(min_sub_f * 1.49).to_bits(),
1773
            min_sub.to_bits() * 1
1774
        );
1775
        assert_eq!(
1776
            bf16::from_f64(min_sub_f * 1.50).to_bits(),
1777
            min_sub.to_bits() * 2
1778
        );
1779
        assert_eq!(
1780
            bf16::from_f64(min_sub_f * 1.51).to_bits(),
1781
            min_sub.to_bits() * 2
1782
        );
1783
1784
        // 0.0000010_011111 rounded to 0.0000010 (< tie, no rounding)
1785
        // 0.0000010_100000 rounded to 0.0000010 (tie and even, remains at even)
1786
        // 0.0000010_100001 rounded to 0.0000011 (> tie, rounds up)
1787
        assert_eq!(
1788
            bf16::from_f64(min_sub_f * 2.49).to_bits(),
1789
            min_sub.to_bits() * 2
1790
        );
1791
        assert_eq!(
1792
            bf16::from_f64(min_sub_f * 2.50).to_bits(),
1793
            min_sub.to_bits() * 2
1794
        );
1795
        assert_eq!(
1796
            bf16::from_f64(min_sub_f * 2.51).to_bits(),
1797
            min_sub.to_bits() * 3
1798
        );
1799
1800
        assert_eq!(
1801
            bf16::from_f64(250.49f64).to_bits(),
1802
            bf16::from_f64(250.0).to_bits()
1803
        );
1804
        assert_eq!(
1805
            bf16::from_f64(250.50f64).to_bits(),
1806
            bf16::from_f64(250.0).to_bits()
1807
        );
1808
        assert_eq!(
1809
            bf16::from_f64(250.51f64).to_bits(),
1810
            bf16::from_f64(251.0).to_bits()
1811
        );
1812
        assert_eq!(
1813
            bf16::from_f64(251.49f64).to_bits(),
1814
            bf16::from_f64(251.0).to_bits()
1815
        );
1816
        assert_eq!(
1817
            bf16::from_f64(251.50f64).to_bits(),
1818
            bf16::from_f64(252.0).to_bits()
1819
        );
1820
        assert_eq!(
1821
            bf16::from_f64(251.51f64).to_bits(),
1822
            bf16::from_f64(252.0).to_bits()
1823
        );
1824
        assert_eq!(
1825
            bf16::from_f64(252.49f64).to_bits(),
1826
            bf16::from_f64(252.0).to_bits()
1827
        );
1828
        assert_eq!(
1829
            bf16::from_f64(252.50f64).to_bits(),
1830
            bf16::from_f64(252.0).to_bits()
1831
        );
1832
        assert_eq!(
1833
            bf16::from_f64(252.51f64).to_bits(),
1834
            bf16::from_f64(253.0).to_bits()
1835
        );
1836
    }
1837
1838
    #[cfg(feature = "std")]
1839
    #[test]
1840
    fn formatting() {
1841
        let f = bf16::from_f32(0.1152344);
1842
1843
        assert_eq!(format!("{:.3}", f), "0.115");
1844
        assert_eq!(format!("{:.4}", f), "0.1152");
1845
        assert_eq!(format!("{:+.4}", f), "+0.1152");
1846
        assert_eq!(format!("{:>+10.4}", f), "   +0.1152");
1847
1848
        assert_eq!(format!("{:.3?}", f), "0.115");
1849
        assert_eq!(format!("{:.4?}", f), "0.1152");
1850
        assert_eq!(format!("{:+.4?}", f), "+0.1152");
1851
        assert_eq!(format!("{:>+10.4?}", f), "   +0.1152");
1852
    }
1853
1854
    impl quickcheck::Arbitrary for bf16 {
1855
        fn arbitrary(g: &mut quickcheck::Gen) -> Self {
1856
            bf16(u16::arbitrary(g))
1857
        }
1858
    }
1859
1860
    #[quickcheck]
1861
    fn qc_roundtrip_bf16_f32_is_identity(f: bf16) -> bool {
1862
        let roundtrip = bf16::from_f32(f.to_f32());
1863
        if f.is_nan() {
1864
            roundtrip.is_nan() && f.is_sign_negative() == roundtrip.is_sign_negative()
1865
        } else {
1866
            f.0 == roundtrip.0
1867
        }
1868
    }
1869
1870
    #[quickcheck]
1871
    fn qc_roundtrip_bf16_f64_is_identity(f: bf16) -> bool {
1872
        let roundtrip = bf16::from_f64(f.to_f64());
1873
        if f.is_nan() {
1874
            roundtrip.is_nan() && f.is_sign_negative() == roundtrip.is_sign_negative()
1875
        } else {
1876
            f.0 == roundtrip.0
1877
        }
1878
    }
1879
1880
    #[test]
1881
    fn test_max() {
1882
        let a = bf16::from_f32(0.0);
1883
        let b = bf16::from_f32(42.0);
1884
        assert_eq!(a.max(b), b);
1885
1886
        let a = bf16::from_f32(42.0);
1887
        let b = bf16::from_f32(0.0);
1888
        assert_eq!(a.max(b), a);
1889
1890
        let a = bf16::NAN;
1891
        let b = bf16::from_f32(42.0);
1892
        assert_eq!(a.max(b), b);
1893
1894
        let a = bf16::from_f32(42.0);
1895
        let b = bf16::NAN;
1896
        assert_eq!(a.max(b), a);
1897
1898
        let a = bf16::NAN;
1899
        let b = bf16::NAN;
1900
        assert!(a.max(b).is_nan());
1901
    }
1902
1903
    #[test]
1904
    fn test_min() {
1905
        let a = bf16::from_f32(0.0);
1906
        let b = bf16::from_f32(42.0);
1907
        assert_eq!(a.min(b), a);
1908
1909
        let a = bf16::from_f32(42.0);
1910
        let b = bf16::from_f32(0.0);
1911
        assert_eq!(a.min(b), b);
1912
1913
        let a = bf16::NAN;
1914
        let b = bf16::from_f32(42.0);
1915
        assert_eq!(a.min(b), b);
1916
1917
        let a = bf16::from_f32(42.0);
1918
        let b = bf16::NAN;
1919
        assert_eq!(a.min(b), a);
1920
1921
        let a = bf16::NAN;
1922
        let b = bf16::NAN;
1923
        assert!(a.min(b).is_nan());
1924
    }
1925
}